id stringlengths 25 30 | content stringlengths 14 942k | max_stars_repo_path stringlengths 49 55 |
|---|---|---|
crossvul-cpp_data_bad_1372_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;
if (pos + 5 > data_size) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Broken PMT! size %d but position %d and need at least 5 bytes to declare es\n", data_size, pos));
break;
}
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) {
if (pos + 2 > data_size) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Broken PMT descriptor! size %d but position %d and need at least 2 bytes to parse descritpor\n", data_size, pos));
break;
}
u8 tag = data[0];
u32 len = data[1];
if (pos + 2 + len > data_size) {
GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("Broken PMT descriptor! size %d, desc size %d but position %d\n", data_size, len, pos));
break;
}
if (es) {
switch (tag) {
case GF_M2TS_ISO_639_LANGUAGE_DESCRIPTOR:
if (pes && (len>=3) )
pes->lang = GF_4CC(' ', data[2], data[3], data[4]);
break;
case GF_M2TS_MPEG4_SL_DESCRIPTOR:
if (len>=2) {
es->mpeg4_es_id = ( (u32) data[2] & 0x1f) << 8 | data[3];
es->flags |= GF_M2TS_ES_IS_SL;
}
break;
case GF_M2TS_REGISTRATION_DESCRIPTOR:
if (len>=4) {
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:
if (len>=2) {
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 && (len>=8)) {
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:
if (len>=1) {
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 && (len>=4)) {
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-416/c/bad_1372_0 |
crossvul-cpp_data_bad_148_1 | /* radare - LGPL - Copyright 2009-2018 - pancake, maijin */
#include "r_util.h"
#include "r_core.h"
static const char *help_msg_a[] = {
"Usage:", "a", "[abdefFghoprxstc] [...]",
"aa", "[?]", "analyze all (fcns + bbs) (aa0 to avoid sub renaming)",
"a8", " [hexpairs]", "analyze bytes",
"ab", "[b] [addr]", "analyze block at given address",
"abb", " [len]", "analyze N basic blocks in [len] (section.size by default)",
"ac", " [cycles]", "analyze which op could be executed in [cycles]",
"ad", "[?]", "analyze data trampoline (wip)",
"ad", " [from] [to]", "analyze data pointers to (from-to)",
"ae", "[?] [expr]", "analyze opcode eval expression (see ao)",
"af", "[?]", "analyze Functions",
"aF", "", "same as above, but using anal.depth=1",
"ag", "[?] [options]", "output Graphviz code",
"ah", "[?]", "analysis hints (force opcode size, ...)",
"ai", " [addr]", "address information (show perms, stack, heap, ...)",
"an"," [name] [@addr]","show/rename/create whatever flag/function is used at addr",
"ao", "[?] [len]", "analyze Opcodes (or emulate it)",
"aO", "[?] [len]", "Analyze N instructions in M bytes",
"ap", "", "find prelude for current offset",
"ar", "[?]", "like 'dr' but for the esil vm. (registers)",
"as", "[?] [num]", "analyze syscall using dbg.reg",
"av", "[?] [.]", "show vtables",
"ax", "[?]", "manage refs/xrefs (see also afx?)",
NULL
};
static const char *help_msg_aa[] = {
"Usage:", "aa[0*?]", " # see also 'af' and 'afna'",
"aa", " ", "alias for 'af@@ sym.*;af@entry0;afva'", //;.afna @@ fcn.*'",
"aa*", "", "analyze all flags starting with sym. (af @@ sym.*)",
"aaa", "[?]", "autoname functions after aa (see afna)",
"aab", "", "aab across io.sections.text",
"aac", " [len]", "analyze function calls (af @@ `pi len~call[1]`)",
"aac*", " [len]", "flag function calls without performing a complete analysis",
"aad", " [len]", "analyze data references to code",
"aae", " [len] ([addr])", "analyze references with ESIL (optionally to address)",
"aaE", "", "run aef on all functions (same as aef @@f)",
"aaf", " ", "analyze all functions (e anal.hasnext=1;afr @@c:isq)",
"aai", "[j]", "show info of all analysis parameters",
"aan", "", "autoname functions that either start with fcn.* or sym.func.*",
"aap", "", "find and analyze function preludes",
"aar", "[?] [len]", "analyze len bytes of instructions for references",
"aas", " [len]", "analyze symbols (af @@= `isq~[0]`)",
"aat", " [len]", "analyze all consecutive functions in section",
"aaT", " [len]", "analyze code after trap-sleds",
"aau", " [len]", "list mem areas (larger than len bytes) not covered by functions",
"aav", " [sat]", "find values referencing a specific section or map",
NULL
};
static const char *help_msg_aar[] = {
"Usage:", "aar", "[j*] [sz] # search and analyze xrefs",
"aar", " [sz]", "analyze xrefs in current section or sz bytes of code",
"aar*", " [sz]", "list found xrefs in radare commands format",
"aarj", " [sz]", "list found xrefs in JSON format",
NULL
};
static const char *help_msg_ab[] = {
"Usage:", "ab", "",
"ab", " [addr]", "show basic block information at given address",
"abb", " [length]", "analyze N bytes and extract basic blocks",
"abj", "", "display basic block information in JSON",
"abx", " [hexpair-bytes]", "analyze N bytes",
NULL
};
static const char *help_msg_ad[] = {
"Usage:", "ad", "[kt] [...]",
"ad", " [N] [D]", "analyze N data words at D depth",
"ad4", " [N] [D]", "analyze N data words at D depth (asm.bits=32)",
"ad8", " [N] [D]", "analyze N data words at D depth (asm.bits=64)",
"adf", "", "analyze data in function (use like .adf @@=`afl~[0]`",
"adfg", "", "analyze data in function gaps",
"adt", "", "analyze data trampolines (wip)",
"adk", "", "analyze data kind (code, text, data, invalid, ...)",
NULL
};
static const char *help_msg_ae[] = {
"Usage:", "ae[idesr?] [arg]", "ESIL code emulation",
"ae", " [expr]", "evaluate ESIL expression",
"ae?", "", "show this help",
"ae??", "", "show ESIL help",
"ae[aA]", "[f] [count]", "analyse esil accesses (regs, mem..)",
"aec", "[?]", "continue until ^C",
"aecs", " [sn]", "continue until syscall number",
"aecu", " [addr]", "continue until address",
"aecue", " [esil]", "continue until esil expression match",
"aef", " [addr]", "emulate function",
"aei", "", "initialize ESIL VM state (aei- to deinitialize)",
"aeim", " [addr] [size] [name]", "initialize ESIL VM stack (aeim- remove)",
"aeip", "", "initialize ESIL program counter to curseek",
"aek", " [query]", "perform sdb query on ESIL.info",
"aek-", "", "resets the ESIL.info sdb instance",
"aep", "[?] [addr]", "manage esil pin hooks",
"aepc", " [addr]", "change esil PC to this address",
"aer", " [..]", "handle ESIL registers like 'ar' or 'dr' does",
"aets", "[?]", "ESIL Trace session",
"aes", "", "perform emulated debugger step",
"aesp", " [X] [N]", "evaluate N instr from offset X",
"aesb", "", "step back",
"aeso", " ", "step over",
"aesu", " [addr]", "step until given address",
"aesue", " [esil]", "step until esil expression match",
"aetr", "[esil]", "Convert an ESIL Expression to REIL",
"aex", " [hex]", "evaluate opcode expression",
NULL
};
static const char *help_detail_ae[] = {
"Examples:", "ESIL", " examples and documentation",
"+", "=", "A+=B => B,A,+=",
"+", "", "A=A+B => B,A,+,A,=",
"++", "", "increment, 2,A,++ == 3 (see rsi,--=[1], ... )",
"--", "", "decrement, 2,A,-- == 1",
"*", "=", "A*=B => B,A,*=",
"/", "=", "A/=B => B,A,/=",
"%", "=", "A%=B => B,A,%=",
"&", "=", "and ax, bx => bx,ax,&=",
"|", "", "or r0, r1, r2 => r2,r1,|,r0,=",
"!", "=", "negate all bits",
"^", "=", "xor ax, bx => bx,ax,^=",
"", "[]", "mov eax,[eax] => eax,[],eax,=",
"=", "[]", "mov [eax+3], 1 => 1,3,eax,+,=[]",
"=", "[1]", "mov byte[eax],1 => 1,eax,=[1]",
"=", "[8]", "mov [rax],1 => 1,rax,=[8]",
"[]", "", "peek from random position",
"[*]", "", "peek some from random position",
"=", "[*]", "poke some at random position",
"$", "", "int 0x80 => 0x80,$",
"$$", "", "simulate a hardware trap",
"==", "", "pops twice, compare and update esil flags",
"<", "", "compare for smaller",
"<", "=", "compare for smaller or equal",
">", "", "compare for bigger",
">", "=", "compare bigger for or equal",
">>", "=", "shr ax, bx => bx,ax,>>= # shift right",
"<<", "=", "shl ax, bx => bx,ax,<<= # shift left",
">>>", "=", "ror ax, bx => bx,ax,>>>= # rotate right",
"<<<", "=", "rol ax, bx => bx,ax,<<<= # rotate left",
"?{", "", "if popped value != 0 run the block until }",
"POP", "", "drops last element in the esil stack",
"DUP", "", "duplicate last value in stack",
"NUM", "", "evaluate last item in stack to number",
"PICK", "", "pick Nth element in stack",
"RPICK", "", "pick Nth element in reversed stack",
"SWAP", "", "swap last two values in stack",
"TRAP", "", "stop execution",
"BITS", "", "16,BITS # change bits, useful for arm/thumb",
"TODO", "", "the instruction is not yet esilized",
"STACK", "", "show contents of stack",
"CLEAR", "", "clears the esil stack",
"REPEAT", "", "repeat n times",
"BREAK", "", "terminates the string parsing",
"GOTO", "", "jump to the Nth word popped from the stack",
NULL
};
static const char *help_msg_aea[] = {
"Examples:", "aea", " show regs used in a range",
"aea", " [ops]", "Show regs used in N instructions (all,read,{no,}written,memreads,memwrites)",
"aea*", " [ops]", "Create mem.* flags for memory accesses",
"aeaf", "", "Show regs used in current function",
"aear", " [ops]", "Show regs read in N instructions",
"aeaw", " [ops]", "Show regs written in N instructions",
"aean", " [ops]", "Show regs not written in N instructions",
"aeaj", " [ops]", "Show aea output in JSON format",
"aeA", " [len]", "Show regs used in N bytes (subcommands are the same)",
NULL
};
static const char *help_msg_aec[] = {
"Examples:", "aec", " continue until ^c",
"aec", "", "Continue until exception",
"aecs", "", "Continue until syscall",
"aecu", "[addr]", "Continue until address",
"aecue", "[addr]", "Continue until esil expression",
NULL
};
static const char *help_msg_aep[] = {
"Usage:", "aep[-c] ", " [...]",
"aepc", " [addr]", "change program counter for esil",
"aep", "-[addr]", "remove pin",
"aep", " [name] @ [addr]", "set pin",
"aep", "", "list pins",
NULL
};
static const char *help_msg_aets[] = {
"Usage:", "aets ", " [...]",
"aets", "", "List all ESIL trace sessions",
"aets+", "", "Add ESIL trace session",
NULL
};
static const char *help_msg_af[] = {
"Usage:", "af", "",
"af", " ([name]) ([addr])", "analyze functions (start at addr or $$)",
"afr", " ([name]) ([addr])", "analyze functions recursively",
"af+", " addr name [type] [diff]", "hand craft a function (requires afb+)",
"af-", " [addr]", "clean all function analysis data (or function at addr)",
"afb+", " fcnA bbA sz [j] [f] ([t]( [d]))", "add bb to function @ fcnaddr",
"afb", "[?] [addr]", "List basic blocks of given function",
"afB", " 16", "set current function as thumb (change asm.bits)",
"afC[lc]", " ([addr])@[addr]", "calculate the Cycles (afC) or Cyclomatic Complexity (afCc)",
"afc", "[?] type @[addr]", "set calling convention for function",
"afd", "[addr]","show function + delta for given offset",
"aft", "[?]", "type matching, type propagation",
"aff", "", "re-adjust function boundaries to fit",
"afF", "[1|0|]", "fold/unfold/toggle",
"afi", " [addr|fcn.name]", "show function(s) information (verbose afl)",
"afl", "[?] [l*] [fcn name]", "list functions (addr, size, bbs, name) (see afll)",
"afo", " [fcn.name]", "show address for the function named like this",
"afm", " name", "merge two functions",
"afM", " name", "print functions map",
"afn", "[?] name [addr]", "rename name for function at address (change flag too)",
"afna", "", "suggest automatic name for current offset",
"afs", " [addr] [fcnsign]", "get/set function signature at current address",
"afS", "[stack_size]", "set stack frame size for function at current address",
"afu", " [addr]", "resize and analyze function from current address until addr",
"afv[bsra]", "?", "manipulate args, registers and variables in function",
"afx", "[cCd-] src dst", "add/remove code/Call/data/string reference",
NULL
};
static const char *help_msg_afb[] = {
"Usage:", "afb", " List basic blocks of given function",
".afbr-", "", "Set breakpoint on every return address of the function",
".afbr-*", "", "Remove breakpoint on every return address of the function",
"afb", " [addr]", "list basic blocks of function",
"afb.", " [addr]", "show info of current basic block",
"afb+", " fcn_at bbat bbsz [jump] [fail] ([type] ([diff]))", "add basic block by hand",
"afbr", "", "Show addresses of instructions which leave the function",
"afbi", "", "print current basic block information",
"afbj", "", "show basic blocks information in json",
"afbe", " bbfrom bbto", "add basic-block edge for switch-cases",
"afB", " [bits]", "define asm.bits for the given function",
NULL
};
static const char *help_msg_afc[] = {
"Usage:", "afc[agl?]", "",
"afc", " convention", "Manually set calling convention for current function",
"afc", "", "Show Calling convention for the Current function",
"afcr", "[j]", "Show register usage for the current function",
"afca", "", "Analyse function for finding the current calling convention",
"afcl", "", "List all available calling conventions",
"afco", " path", "Open Calling Convention sdb profile from given path",
NULL
};
static const char *help_msg_afC[] = {
"Usage:", "afC", " [addr]",
"afC", "", "function cycles cost",
"afCc", "", "cyclomatic complexity",
"afCl", "", "loop count (backward jumps)",
NULL
};
static const char *help_msg_afi[] = {
"Usage:", "afi[jl*]", " <addr>",
"afi", "", "show information of the function",
"afi.", "", "show function name in current offset",
"afi*", "", "function, variables and arguments",
"afij", "", "function info in json format",
"afil", "", "verbose function info",
NULL
};
static const char *help_msg_afl[] = {
"Usage:", "afl", " List all functions",
"afl", "", "list functions",
"aflc", "", "count of functions",
"aflj", "", "list functions in json",
"afll", "", "list functions in verbose mode",
"afllj", "", "list functions in verbose mode (alias to aflj)",
"aflq", "", "list functions in quiet mode",
"aflqj", "", "list functions in json quiet mode",
"afls", "", "print sum of sizes of all functions",
NULL
};
static const char *help_msg_afll[] = {
"Usage:", "", " List functions in verbose mode",
"", "", "",
"Table fields:", "", "",
"", "", "",
"address", "", "start address",
"size", "", "function size (realsize)",
"nbbs", "", "number of basic blocks",
"edges", "", "number of edges between basic blocks",
"cc", "", "cyclomatic complexity ( cc = edges - blocks + 2 * exit_blocks)",
"cost", "", "cyclomatic cost",
"min bound", "", "minimal address",
"range", "", "function size",
"max bound", "", "maximal address",
"calls", "", "number of caller functions",
"locals", "", "number of local variables",
"args", "", "number of function arguments",
"xref", "", "number of cross references",
"frame", "", "function stack size",
"name", "", "function name",
NULL
};
static const char *help_msg_afn[] = {
"Usage:", "afn[sa]", " Analyze function names",
"afn", " [name]", "rename the function",
"afna", "", "construct a function name for the current offset",
"afns", "", "list all strings associated with the current function",
NULL
};
static const char *help_msg_aft[] = {
"Usage:", "aftm", "",
"afta", "", "Setup memory and analyse do type matching analysis for all functions",
"aftm", "", "type matching analysis",
NULL
};
static const char *help_msg_afv[] = {
"Usage:", "afv","[rbs]",
"afvr", "[?]", "manipulate register based arguments",
"afvb", "[?]", "manipulate bp based arguments/locals",
"afvs", "[?]", "manipulate sp based arguments/locals",
"afvR", " [varname]", "list addresses where vars are accessed",
"afvW", " [varname]", "list addresses where vars are accessed",
"afva", "", "analyze function arguments/locals",
"afvd", " name", "output r2 command for displaying the value of args/locals in the debugger",
"afvn", " [old_name] [new_name]", "rename argument/local",
"afvt", " [name] [new_type]", "change type for given argument/local",
"afv-", "([name])", "remove all or given var",
NULL
};
static const char *help_msg_afvb[] = {
"Usage:", "afvb", " [idx] [name] ([type])",
"afvb", "", "list base pointer based arguments, locals",
"afvb*", "", "same as afvb but in r2 commands",
"afvb", " [idx] [name] ([type])", "define base pointer based arguments, locals",
"afvbj", "", "return list of base pointer based arguments, locals in JSON format",
"afvb-", " [name]", "delete argument/locals at the given name",
"afvbg", " [idx] [addr]", "define var get reference",
"afvbs", " [idx] [addr]", "define var set reference",
NULL
};
static const char *help_msg_afvr[] = {
"Usage:", "afvr", " [reg] [type] [name]",
"afvr", "", "list register based arguments",
"afvr*", "", "same as afvr but in r2 commands",
"afvr", " [reg] [name] ([type])", "define register arguments",
"afvrj", "", "return list of register arguments in JSON format",
"afvr-", " [name]", "delete register arguments at the given index",
"afvrg", " [reg] [addr]", "define argument get reference",
"afvrs", " [reg] [addr]", "define argument set reference",
NULL
};
static const char *help_msg_afvs[] = {
"Usage:", "afvs", " [idx] [type] [name]",
"afvs", "", "list stack based arguments and locals",
"afvs*", "", "same as afvs but in r2 commands",
"afvs", " [idx] [name] [type]", "define stack based arguments,locals",
"afvsj", "", "return list of stack based arguments and locals in JSON format",
"afvs-", " [name]", "delete stack based argument or locals with the given name",
"afvsg", " [idx] [addr]", "define var get reference",
"afvss", " [idx] [addr]", "define var set reference",
NULL
};
static const char *help_msg_afx[] = {
"Usage:", "afx[-cCd?] [src] [dst]", " manage function references (see also ar?)",
"afxc", " sym.main+0x38 sym.printf", "add code ref",
"afxC", " sym.main sym.puts", "add call ref",
"afxd", " sym.main str.helloworld", "add data ref",
"afx-", " sym.main str.helloworld", "remove reference",
NULL
};
static const char *help_msg_ag[] = {
"Usage:", "ag[?f]", " Graphviz/graph code",
"ag", " [addr]", "output graphviz code (bb at addr and children)",
"ag-", "", "Reset the current ASCII art graph (see agn, age, agg?)",
"aga", " [addr]", "idem, but only addresses",
"agr", "[j] [addr]", "output graphviz call graph of function",
"agg", "", "display current graph created with agn and age (see also ag-)",
"agc", "[*j] [addr]", "output graphviz call graph of function",
"agC", "[j]", "Same as agc -1. full program callgraph",
"agd", " [fcn name]", "output graphviz code of diffed function",
"age", "[?] title1 title2", "Add an edge to the current graph",
"agf", " [addr]", "Show ASCII art graph of given function",
"agg", "[?] [kdi*]", "Print graph in ASCII-Art, graphviz, k=v, r2 or visual",
"agj", " [addr]", "idem, but in JSON format",
"agJ", " [addr]", "idem, but in JSON format with formatted disassembly (like pdJ)",
"agk", " [addr]", "idem, but in SDB key-value format",
"agl", " [fcn name]", "output graphviz code using meta-data",
"agn", "[?] title body", "Add a node to the current graph",
"ags", " [addr]", "output simple graphviz call graph of function (only bb offset)",
"agt", " [addr]", "find paths from current offset to given address",
"agv", "", "Show function graph in web/png (see graph.web and cmd.graph) or agf for asciiart",
NULL
};
static const char *help_msg_age[] = {
"Usage:", "age [title1] [title2]", "",
"Examples:", "", "",
"age", " title1 title2", "Add an edge from the node with \"title1\" as title to the one with title \"title2\"",
"age", " \"title1 with spaces\" title2", "Add an edge from node \"title1 with spaces\" to node \"title2\"",
"age-", " title1 title2", "Remove an edge from the node with \"title1\" as title to the one with title \"title2\"",
"age?", "", "Show this help",
NULL
};
static const char *help_msg_agg[] = {
"Usage:", "agg[kid?*]", "print graph",
"agg", "", "show current graph in ascii art",
"aggk", "", "show graph in key=value form",
"aggi", "", "enter interactive mode for the current graph",
"aggd", "", "print the current graph in GRAPHVIZ dot format",
"aggv", "", "run graphviz + viewer (see 'e cmd.graph')",
"agg*", "", "in r2 commands, to save in projects, etc",
NULL
};
static const char *help_msg_agn[] = {
"Usage:", "agn [title] [body]", "",
"Examples:", "", "",
"agn", " title1 body1", "Add a node with title \"title1\" and body \"body1\"",
"agn", " \"title with space\" \"body with space\"", "Add a node with spaces in the title and in the body",
"agn", " title1 base64:Ym9keTE=", "Add a node with the body specified as base64",
"agn-", " title1", "Remove a node with title \"title1\"",
"agn?", "", "Show this help",
NULL
};
static const char *help_msg_ah[] = {
"Usage:", "ah[lba-]", "Analysis Hints",
"ah?", "", "show this help",
"ah?", " offset", "show hint of given offset",
"ah", "", "list hints in human-readable format",
"ah.", "", "list hints in human-readable format from current offset",
"ah-", "", "remove all hints",
"ah-", " offset [size]", "remove hints at given offset",
"ah*", " offset", "list hints in radare commands format",
"aha", " ppc 51", "set arch for a range of N bytes",
"ahb", " 16 @ $$", "force 16bit for current instruction",
"ahc", " 0x804804", "override call/jump address",
"ahe", " 3,eax,+=", "set vm analysis string",
"ahf", " 0x804840", "override fallback address for call",
"ahh", " 0x804840", "highlight this adrress offset in disasm",
"ahi", "[?] 10", "define numeric base for immediates (1, 8, 10, 16, s)",
"ahj", "", "list hints in JSON",
"aho", " foo a0,33", "replace opcode string",
"ahp", " addr", "set pointer hint",
"ahs", " 4", "set opcode size=4",
"ahS", " jz", "set asm.syntax=jz for this opcode",
NULL
};
static const char *help_msg_ahi[] = {
"Usage", "ahi [sbodh] [@ offset]", " Define numeric base",
"ahi", " [base]", "set numeric base (1, 2, 8, 10, 16)",
"ahi", " b", "set base to binary (2)",
"ahi", " d", "set base to decimal (10)",
"ahi", " h", "set base to hexadecimal (16)",
"ahi", " o", "set base to octal (8)",
"ahi", " p", "set base to htons(port) (3)",
"ahi", " i", "set base to IP address (32)",
"ahi", " S", "set base to syscall (80)",
"ahi", " s", "set base to string (1)",
NULL
};
static const char *help_msg_ao[] = {
"Usage:", "ao[e?] [len]", "Analyze Opcodes",
"aoj", " N", "display opcode analysis information in JSON for N opcodes",
"aoe", " N", "display esil form for N opcodes",
"aor", " N", "display reil form for N opcodes",
"aos", " N", "display size of N opcodes",
"ao", " 5", "display opcode analysis of 5 opcodes",
"ao*", "", "display opcode in r commands",
NULL
};
static const char *help_msg_ar[] = {
"Usage: ar", "", "# Analysis Registers",
"ar", "", "Show 'gpr' registers",
"ar0", "", "Reset register arenas to 0",
"ara", "[?]", "Manage register arenas",
"ar", " 16", "Show 16 bit registers",
"ar", " 32", "Show 32 bit registers",
"ar", " all", "Show all bit registers",
"ar", " <type>", "Show all registers of given type",
"arC", "", "Display register profile comments",
"arr", "", "Show register references (telescoping)",
"ar=", "([size])(:[regs])", "Show register values in columns",
"ar?", " <reg>", "Show register value",
"arb", " <type>", "Display hexdump of the given arena",
"arc", " <name>", "Conditional flag registers",
"ard", " <name>", "Show only different registers",
"arn", " <regalias>", "Get regname for pc,sp,bp,a0-3,zf,cf,of,sg",
"aro", "", "Show old (previous) register values",
"arp", "[?] <file>", "Load register profile from file",
"ars", "", "Stack register state",
"art", "", "List all register types",
"arw", " <hexnum>", "Set contents of the register arena",
".ar*", "", "Import register values as flags",
".ar-", "", "Unflag all registers",
NULL
};
static const char *help_msg_ara[] = {
"Usage:", "ara[+-s]", "Register Arena Push/Pop/Swap",
"ara", "", "show all register arenas allocated",
"ara", "+", "push a new register arena for each type",
"ara", "-", "pop last register arena",
"aras", "", "swap last two register arenas",
NULL
};
static const char *help_msg_arw[] = {
"Usage:", "arw ", "# Set contents of the register arena",
"arw", " <hexnum>", "Set contents of the register arena",
NULL
};
static const char *help_msg_as[] = {
"Usage: as[ljk?]", "", "syscall name <-> number utility",
"as", "", "show current syscall and arguments",
"as", " 4", "show syscall 4 based on asm.os and current regs/mem",
"asc[a]", " 4", "dump syscall info in .asm or .h",
"asf", " [k[=[v]]]", "list/set/unset pf function signatures (see fcnsign)",
"asj", "", "list of syscalls in JSON",
"asl", "", "list of syscalls by asm.os and asm.arch",
"asl", " close", "returns the syscall number for close",
"asl", " 4", "returns the name of the syscall number 4",
"ask", " [query]", "perform syscall/ queries",
NULL
};
static const char *help_msg_av[] = {
"Usage:", "av[?jr*]", " C++ vtables and RTTI",
"av", "", "search for vtables in data sections and show results",
"avj", "", "like av, but as json",
"av*", "", "like av, but as r2 commands",
"avr", "[j@addr]", "try to parse RTTI at vtable addr (see anal.cpp.abi)",
"avra", "[j]", "search for vtables and try to parse RTTI at each of them",
NULL
};
static const char *help_msg_ax[] = {
"Usage:", "ax[?d-l*]", " # see also 'afx?'",
"ax", "", "list refs",
"ax", " addr [at]", "add code ref pointing to addr (from curseek)",
"ax-", " [at]", "clean all refs (or refs from addr)",
"axc", " addr [at]", "add code jmp ref // unused?",
"axC", " addr [at]", "add code call ref",
"axg", " [addr]", "show xrefs graph to reach current function",
"axgj", " [addr]", "show xrefs graph to reach current function in json format",
"axd", " addr [at]", "add data ref",
"axq", "", "list refs in quiet/human-readable format",
"axj", "", "list refs in json format",
"axF", " [flg-glob]", "find data/code references of flags",
"axt", " [addr]", "find data/code references to this address",
"axf", " [addr]", "find data/code references from this address",
"axk", " [query]", "perform sdb query",
"ax*", "", "output radare commands",
NULL
};
static void cmd_anal_init(RCore *core) {
DEFINE_CMD_DESCRIPTOR (core, a);
DEFINE_CMD_DESCRIPTOR (core, aa);
DEFINE_CMD_DESCRIPTOR (core, aar);
DEFINE_CMD_DESCRIPTOR (core, ab);
DEFINE_CMD_DESCRIPTOR (core, ad);
DEFINE_CMD_DESCRIPTOR (core, ae);
DEFINE_CMD_DESCRIPTOR (core, aea);
DEFINE_CMD_DESCRIPTOR (core, aec);
DEFINE_CMD_DESCRIPTOR (core, aep);
DEFINE_CMD_DESCRIPTOR (core, af);
DEFINE_CMD_DESCRIPTOR (core, afb);
DEFINE_CMD_DESCRIPTOR (core, afc);
DEFINE_CMD_DESCRIPTOR (core, afC);
DEFINE_CMD_DESCRIPTOR (core, afi);
DEFINE_CMD_DESCRIPTOR (core, afl);
DEFINE_CMD_DESCRIPTOR (core, afll);
DEFINE_CMD_DESCRIPTOR (core, afn);
DEFINE_CMD_DESCRIPTOR (core, aft);
DEFINE_CMD_DESCRIPTOR (core, afv);
DEFINE_CMD_DESCRIPTOR (core, afvb);
DEFINE_CMD_DESCRIPTOR (core, afvr);
DEFINE_CMD_DESCRIPTOR (core, afvs);
DEFINE_CMD_DESCRIPTOR (core, afx);
DEFINE_CMD_DESCRIPTOR (core, ag);
DEFINE_CMD_DESCRIPTOR (core, age);
DEFINE_CMD_DESCRIPTOR (core, agg);
DEFINE_CMD_DESCRIPTOR (core, agn);
DEFINE_CMD_DESCRIPTOR (core, ah);
DEFINE_CMD_DESCRIPTOR (core, ahi);
DEFINE_CMD_DESCRIPTOR (core, ao);
DEFINE_CMD_DESCRIPTOR (core, ar);
DEFINE_CMD_DESCRIPTOR (core, ara);
DEFINE_CMD_DESCRIPTOR (core, arw);
DEFINE_CMD_DESCRIPTOR (core, as);
DEFINE_CMD_DESCRIPTOR (core, ax);
}
/* better aac for windows-x86-32 */
#define JAYRO_03 0
#if JAYRO_03
static bool anal_is_bad_call(RCore *core, ut64 from, ut64 to, ut64 addr, ut8 *buf, int bufi) {
ut64 align = R_ABS (addr % PE_ALIGN);
ut32 call_bytes;
// XXX this is x86 specific
if (align == 0) {
call_bytes = (ut32)((ut8*)buf)[bufi + 3] << 24;
call_bytes |= (ut32)((ut8*)buf)[bufi + 2] << 16;
call_bytes |= (ut32)((ut8*)buf)[bufi + 1] << 8;
call_bytes |= (ut32)((ut8*)buf)[bufi];
} else {
call_bytes = (ut32)((ut8*)buf)[bufi - align + 3] << 24;
call_bytes |= (ut32)((ut8*)buf)[bufi - align + 2] << 16;
call_bytes |= (ut32)((ut8*)buf)[bufi - align + 1] << 8;
call_bytes |= (ut32)((ut8*)buf)[bufi - align];
}
if (call_bytes >= from && call_bytes <= to) {
return true;
}
call_bytes = (ut32)((ut8*)buf)[bufi + 4] << 24;
call_bytes |= (ut32)((ut8*)buf)[bufi + 3] << 16;
call_bytes |= (ut32)((ut8*)buf)[bufi + 2] << 8;
call_bytes |= (ut32)((ut8*)buf)[bufi + 1];
call_bytes += addr + 5;
if (call_bytes >= from && call_bytes <= to) {
return false;
}
return false;
}
#endif
static void type_cmd(RCore *core, const char *input) {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
if (!fcn && *input != '?' && *input != 'a') {
eprintf ("cant find function here\n");
return;
}
RListIter *it;
ut64 seek;
bool io_cache = r_config_get_i (core->config, "io.cache");
r_cons_break_push (NULL, NULL);
switch (*input) {
case 'a': // "afta"
if (r_config_get_i (core->config, "cfg.debug")) {
eprintf ("TOFIX: afta can't run in debugger mode.\n");
break;
}
seek = core->offset;
r_core_cmd0 (core, "aei");
r_core_cmd0 (core, "aeim");
r_reg_arena_push (core->anal->reg);
r_list_foreach (core->anal->fcns, it, fcn) {
int ret = r_core_seek (core, fcn->addr, true);
if (!ret) {
continue;
}
r_anal_esil_set_pc (core->anal->esil, fcn->addr);
r_core_anal_type_match (core, fcn);
if (r_cons_is_breaked ()) {
break;
}
}
r_core_cmd0 (core, "aeim-");
r_core_cmd0 (core, "aei-");
r_core_seek (core, seek, true);
r_reg_arena_pop (core->anal->reg);
break;
case 'm': // "aftm"
r_config_set_i (core->config, "io.cache", true);
seek = core->offset;
r_anal_esil_set_pc (core->anal->esil, fcn? fcn->addr: core->offset);
r_core_anal_type_match (core, fcn);
r_core_seek (core, seek, true);
r_config_set_i (core->config, "io.cache", io_cache);
break;
case '?':
r_core_cmd_help (core, help_msg_aft);
break;
}
r_cons_break_pop ();
}
static int cc_print(void *p, const char *k, const char *v) {
if (!strcmp (v, "cc")) {
r_cons_println (k);
}
return 1;
}
static void find_refs(RCore *core, const char *glob) {
char cmd[128];
ut64 curseek = core->offset;
while (*glob == ' ') glob++;
if (!*glob) {
glob = "str.";
}
if (*glob == '?') {
eprintf ("Usage: arf [flag-str-filter]\n");
return;
}
eprintf ("Finding references of flags matching '%s'...\n", glob);
snprintf (cmd, sizeof (cmd) - 1, ".(findstref) @@= `f~%s[0]`", glob);
r_core_cmd0 (core, "(findstref,f here=$$,s entry0,/r here,f-here)");
r_core_cmd0 (core, cmd);
r_core_cmd0 (core, "(-findstref)");
r_core_seek (core, curseek, 1);
}
/* set flags for every function */
static void flag_every_function(RCore *core) {
RListIter *iter;
RAnalFunction *fcn;
r_flag_space_push (core->flags, "functions");
r_list_foreach (core->anal->fcns, iter, fcn) {
r_flag_set (core->flags, fcn->name,
fcn->addr, r_anal_fcn_size (fcn));
}
r_flag_space_pop (core->flags);
}
static void var_help(RCore *core, char ch) {
switch (ch) {
case 'b':
r_core_cmd_help (core, help_msg_afvb);
break;
case 's':
r_core_cmd_help (core, help_msg_afvs);
break;
case 'r':
r_core_cmd_help (core, help_msg_afvr);
break;
case '?':
r_core_cmd_help (core, help_msg_afv);
break;
default:
eprintf ("See afv?, afvb?, afvr? and afvs?\n");
}
}
static void var_accesses_list(RAnal *a, RAnalFunction *fcn, int delta, const char *typestr) {
const char *var_local = sdb_fmt ("var.0x%"PFMT64x".%d.%d.%s",
fcn->addr, 1, delta, typestr);
const char *xss = sdb_const_get (a->sdb_fcns, var_local, 0);
if (xss && *xss) {
r_cons_printf ("%s\n", xss);
} else {
r_cons_newline ();
}
}
static void list_vars(RCore *core, RAnalFunction *fcn, int type, const char *name) {
RAnalVar *var;
RListIter *iter;
RList *list = r_anal_var_list (core->anal, fcn, 0);
if (type == '*') {
const char *bp = r_reg_get_name (core->anal->reg, R_REG_NAME_BP);
r_cons_printf ("f-fcnvar*\n");
r_list_foreach (list, iter, var) {
r_cons_printf ("f fcnvar.%s @ %s%s%d\n", var->name, bp,
var->delta>=0? "+":"", var->delta);
}
return;
}
if (type != 'W' && type != 'R') {
return;
}
const char *typestr = type == 'R'?"reads":"writes";
r_list_foreach (list, iter, var) {
r_cons_printf ("%10s ", var->name);
var_accesses_list (core->anal, fcn, var->delta, typestr);
}
}
static int cmd_an(RCore *core, bool use_json, const char *name)
{
ut64 off = core->offset;
RAnalOp op;
char *q = NULL;
ut64 tgt_addr = UT64_MAX;
if (use_json) {
r_cons_print ("[");
}
r_anal_op (core->anal, &op, off,
core->block + off - core->offset, 32, R_ANAL_OP_MASK_ALL);
tgt_addr = op.jump != UT64_MAX ? op.jump : op.ptr;
if (op.var) {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, off, 0);
if (fcn) {
RAnalVar *bar = r_anal_var_get_byname (core->anal, fcn, op.var->name);
if (!bar) {
bar = r_anal_var_get_byname (core->anal, fcn, op.var->name);
if (!bar) {
bar = r_anal_var_get_byname (core->anal, fcn, op.var->name);
}
}
if (bar) {
if (name) {
r_anal_var_rename (core->anal, fcn->addr, bar->scope,
bar->kind, bar->name, name);
} else if (!use_json) {
r_cons_println (bar->name);
} else {
r_cons_printf ("{\"type\":\"var\",\"name\":\"%s\"}",
bar->name);
}
} else {
eprintf ("Cannot find variable\n");
}
} else {
eprintf ("Cannot find function\n");
}
} else if (tgt_addr != UT64_MAX) {
RAnalFunction *fcn = r_anal_get_fcn_at (core->anal, tgt_addr, R_ANAL_FCN_TYPE_NULL);
RFlagItem *f = r_flag_get_i (core->flags, tgt_addr);
if (fcn) {
if (name) {
q = r_str_newf ("afn %s 0x%"PFMT64x, name, tgt_addr);
} else if (!use_json) {
r_cons_println (fcn->name);
} else {
r_cons_printf ("{\"type\":\"function\",\"name\":\"%s\"}",
fcn->name);
}
} else if (f) {
if (name) {
q = r_str_newf ("fr %s %s", f->name, name);
} else if (!use_json) {
r_cons_println (f->name);
} else {
r_cons_printf ("{\"type\":\"flag\",\"name\":\"%s\"}",
f->name);
}
} else {
if (name) {
q = r_str_newf ("f %s @ 0x%"PFMT64x, name, tgt_addr);
} else if (!use_json) {
r_cons_printf ("0x%" PFMT64x "\n", tgt_addr);
} else {
r_cons_printf ("{\"type\":\"address\",\"offset\":"
"%" PFMT64d "}", tgt_addr);
}
}
}
if (use_json) {
r_cons_print ("]\n");
}
if (q) {
r_core_cmd0 (core, q);
free (q);
}
r_anal_op_fini (&op);
return 0;
}
static int var_cmd(RCore *core, const char *str) {
char *p, *ostr;
int delta, type = *str, res = true;
RAnalVar *v1;
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
ostr = p = NULL;
if (!str[0]) {
// "afv"
if (fcn) {
r_core_cmd0 (core, "afvs");
r_core_cmd0 (core, "afvb");
r_core_cmd0 (core, "afvr");
return true;
}
eprintf ("Cannot find function\n");
return false;
}
if (str[0] == 'j') {
// "afvj"
if (fcn) {
r_cons_printf ("{\"sp\":");
r_core_cmd0 (core, "afvsj");
r_cons_printf (",\"bp\":");
r_core_cmd0 (core, "afvbj");
r_cons_printf (",\"reg\":");
r_core_cmd0 (core, "afvrj");
r_cons_printf ("}\n");
return true;
}
eprintf ("Cannot find function\n");
return false;
}
if (!str[0] || str[1] == '?'|| str[0] == '?') {
var_help (core, *str);
return res;
}
if (!fcn) {
eprintf ("Cannot find function in 0x%08"PFMT64x"\n", core->offset);
return false;
}
ostr = p = strdup (str);
/* Variable access CFvs = set fun var */
switch (str[0]) {
case '-':
// "afv"
if (fcn) {
r_core_cmdf (core, "afvs-%s", str + 1);
r_core_cmdf (core, "afvb-%s", str + 1);
r_core_cmdf (core, "afvr-%s", str + 1);
return true;
}
eprintf ("Cannot find function\n");
return false;
case 'R': // "afvR"
case 'W': // "afvW"
case '*': // "afv*"
list_vars (core, fcn, str[0], str + 1);
break;
case 'a': // "afva"
r_anal_var_delete_all (core->anal, fcn->addr, R_ANAL_VAR_KIND_REG);
r_anal_var_delete_all (core->anal, fcn->addr, R_ANAL_VAR_KIND_BPV);
r_anal_var_delete_all (core->anal, fcn->addr, R_ANAL_VAR_KIND_SPV);
fcn_callconv (core, fcn);
free (p);
return true;
case 'n':
if (str[1]) { // "afvn"
char *old_name = r_str_trim_head (strchr (ostr, ' '));
if (!old_name) {
free (ostr);
return false;
}
char *new_name = strchr (old_name, ' ');
if (!new_name) {
free (ostr);
return false;
}
*new_name++ = 0;
r_str_trim (new_name);
v1 = r_anal_var_get_byname (core->anal, fcn, old_name);
if (v1) {
r_anal_var_rename (core->anal, fcn->addr, R_ANAL_VAR_SCOPE_LOCAL,
v1->kind, old_name, new_name);
r_anal_var_free (v1);
} else {
eprintf ("Cant find var by name\n");
}
free (ostr);
} else {
RListIter *iter;
RAnalVar *v;
RList *list = r_anal_var_list (core->anal, fcn, 0);
r_list_foreach (list, iter, v) {
r_cons_printf ("%s\n", v->name);
}
}
return true;
case 'd': // "afvd"
if (str[1]) {
p = r_str_trim (strchr (ostr, ' '));
if (!p) {
free (ostr);
return false;
}
v1 = r_anal_var_get_byname (core->anal, fcn, p);
if (!v1) {
free (ostr);
return false;
}
r_anal_var_display (core->anal, v1->delta, v1->kind, v1->type);
r_anal_var_free (v1);
free (ostr);
} else {
RListIter *iter;
RAnalVar *p;
RList *list = r_anal_var_list (core->anal, fcn, 0);
r_list_foreach (list, iter, p) {
char *a = r_core_cmd_strf (core, ".afvd %s", p->name);
if ((a && !*a) || !a) {
free (a);
a = strdup ("\n");
}
r_cons_printf ("var %s = %s", p->name, a);
free (a);
}
r_list_free (list);
// args
list = r_anal_var_list (core->anal, fcn, 1);
r_list_foreach (list, iter, p) {
char *a = r_core_cmd_strf (core, ".afvd %s", p->name);
if ((a && !*a) || !a) {
free (a);
a = strdup ("\n");
}
r_cons_printf ("arg %s = %s", p->name, a);
free (a);
}
r_list_free (list);
}
return true;
case 't':{ // "afvt"
p = strchr (ostr, ' ');
if (!p++) {
free (ostr);
return false;
}
char *type = strchr (p, ' ');
if (!type) {
free (ostr);
return false;
}
*type++ = 0;
v1 = r_anal_var_get_byname (core->anal, fcn, p);
if (!v1) {
eprintf ("Cant find get by name %s\n", p);
free (ostr);
return false;
}
r_anal_var_retype (core->anal, fcn->addr,
R_ANAL_VAR_SCOPE_LOCAL, -1, v1->kind, type, -1, p);
r_anal_var_free (v1);
free (ostr);
return true;
}
}
switch (str[1]) {
case '\0':
case '*':
case 'j':
r_anal_var_list_show (core->anal, fcn, type, str[1]);
break;
case '.':
r_anal_var_list_show (core->anal, fcn, core->offset, 0);
break;
case '-': // "afv[bsr]-"
if (str[2] == '*') {
r_anal_var_delete_all (core->anal, fcn->addr, type);
} else {
if (IS_DIGIT (str[2])) {
r_anal_var_delete (core->anal, fcn->addr,
type, 1, (int)r_num_math (core->num, str + 1));
} else {
char *name = r_str_trim ( strdup (str + 2));
r_anal_var_delete_byname (core->anal, fcn, type, name);
free (name);
}
}
break;
case 'd':
eprintf ("This command is deprecated, use afvd instead\n");
break;
case 't':
eprintf ("This command is deprecated use afvt instead\n");
break;
case 's':
case 'g':
if (str[2] != '\0') {
int rw = 0; // 0 = read, 1 = write
RAnalVar *var = r_anal_var_get (core->anal, fcn->addr,
(char)type, atoi (str + 2), R_ANAL_VAR_SCOPE_LOCAL);
if (!var) {
eprintf ("Cannot find variable in: '%s'\n", str);
res = false;
break;
}
if (var != NULL) {
int scope = (str[1] == 'g')? 0: 1;
r_anal_var_access (core->anal, fcn->addr, (char)type,
scope, atoi (str + 2), rw, core->offset);
r_anal_var_free (var);
break;
}
} else {
eprintf ("Missing argument\n");
}
break;
case ' ': {
const char *name;
char *vartype;
int size = 4;
int scope = 1;
for (str++; *str == ' ';) str++;
p = strchr (str, ' ');
if (!p) {
var_help (core, type);
break;
}
*p++ = 0;
if (type == 'r') { //registers
RRegItem *i = r_reg_get (core->anal->reg, str, -1);
if (!i) {
eprintf ("Register not found");
break;
}
delta = i->index;
} else {
delta = r_num_math (core->num, str);
}
name = p;
vartype = strchr (name, ' ');
if (vartype) {
*vartype++ = 0;
r_anal_var_add (core->anal, fcn->addr,
scope, delta, type,
vartype, size, name);
} else {
eprintf ("Missing name\n");
}
}
break;
};
free (ostr);
return res;
}
static void print_trampolines(RCore *core, ut64 a, ut64 b, size_t element_size) {
int i;
for (i = 0; i < core->blocksize; i += element_size) {
ut32 n;
memcpy (&n, core->block + i, sizeof (ut32));
if (n >= a && n <= b) {
if (element_size == 4) {
r_cons_printf ("f trampoline.%x @ 0x%" PFMT64x "\n", n, core->offset + i);
} else {
r_cons_printf ("f trampoline.%" PFMT64x " @ 0x%" PFMT64x "\n", n, core->offset + i);
}
r_cons_printf ("Cd %u @ 0x%" PFMT64x ":%u\n", element_size, core->offset + i, element_size);
// TODO: add data xrefs
}
}
}
static void cmd_anal_trampoline(RCore *core, const char *input) {
int bits = r_config_get_i (core->config, "asm.bits");
char *p, *inp = strdup (input);
p = strchr (inp, ' ');
if (p) {
*p = 0;
}
ut64 a = r_num_math (core->num, inp);
ut64 b = p? r_num_math (core->num, p + 1): 0;
free (inp);
switch (bits) {
case 32:
print_trampolines (core, a, b, 4);
break;
case 64:
print_trampolines (core, a, b, 8);
break;
}
}
R_API char *cmd_syscall_dostr(RCore *core, int n) {
char *res = NULL;
int i;
char str[64];
if (n == -1) {
n = (int)r_debug_reg_get (core->dbg, "oeax");
if (!n || n == -1) {
const char *a0 = r_reg_get_name (core->anal->reg, R_REG_NAME_SN);
n = (int)r_debug_reg_get (core->dbg, a0);
}
}
RSyscallItem *item = r_syscall_get (core->anal->syscall, n, -1);
if (!item) {
res = r_str_appendf (res, "%d = unknown ()", n);
return res;
}
res = r_str_appendf (res, "%d = %s (", item->num, item->name);
// TODO: move this to r_syscall
//TODO replace the hardcoded CC with the sdb ones
for (i = 0; i < item->args; i++) {
// XXX this is a hack to make syscall args work on x86-32 and x86-64
// we need to shift sn first.. which is bad, but needs to be redesigned
int regidx = i;
if (core->assembler->bits == 32) {
regidx++;
}
ut64 arg = r_debug_arg_get (core->dbg, R_ANAL_CC_TYPE_FASTCALL, regidx);
//r_cons_printf ("(%d:0x%"PFMT64x")\n", i, arg);
if (item->sargs) {
switch (item->sargs[i]) {
case 'p': // pointer
res = r_str_appendf (res, "0x%08" PFMT64x "", arg);
break;
case 'i':
res = r_str_appendf (res, "%" PFMT64d "", arg);
break;
case 'z':
memset (str, 0, sizeof (str));
r_io_read_at (core->io, arg, (ut8 *)str, sizeof (str) - 1);
r_str_filter (str, strlen (str));
res = r_str_appendf (res, "\"%s\"", str);
break;
case 'Z': {
//TODO replace the hardcoded CC with the sdb ones
ut64 len = r_debug_arg_get (core->dbg, R_ANAL_CC_TYPE_FASTCALL, i + 2);
len = R_MIN (len + 1, sizeof (str) - 1);
if (len == 0) {
len = 16; // override default
}
(void)r_io_read_at (core->io, arg, (ut8 *)str, len);
str[len] = 0;
r_str_filter (str, -1);
res = r_str_appendf (res, "\"%s\"", str);
} break;
default:
res = r_str_appendf (res, "0x%08" PFMT64x "", arg);
break;
}
} else {
res = r_str_appendf (res, "0x%08" PFMT64x "", arg);
}
if (i + 1 < item->args) {
res = r_str_appendf (res, ", ");
}
}
r_syscall_item_free (item);
res = r_str_appendf (res, ")");
return res;
}
static void cmd_syscall_do(RCore *core, int n) {
char *msg = cmd_syscall_dostr (core, n);
if (msg) {
r_cons_println (msg);
free (msg);
}
}
static void core_anal_bytes(RCore *core, const ut8 *buf, int len, int nops, int fmt) {
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
bool iotrap = r_config_get_i (core->config, "esil.iotrap");
bool romem = r_config_get_i (core->config, "esil.romem");
bool stats = r_config_get_i (core->config, "esil.stats");
bool be = core->print->big_endian;
bool use_color = core->print->flags & R_PRINT_FLAGS_COLOR;
core->parser->relsub = r_config_get_i (core->config, "asm.relsub");
int ret, i, j, idx, size;
const char *color = "";
const char *esilstr;
const char *opexstr;
RAnalHint *hint;
RAnalEsil *esil = NULL;
RAsmOp asmop;
RAnalOp op;
ut64 addr;
bool isFirst = true;
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
int totalsize = 0;
// Variables required for setting up ESIL to REIL conversion
if (use_color) {
color = core->cons->pal.label;
}
switch (fmt) {
case 'j':
r_cons_printf ("[");
break;
case 'r':
// Setup for ESIL to REIL conversion
esil = r_anal_esil_new (stacksize, iotrap, addrsize);
if (!esil) {
return;
}
r_anal_esil_to_reil_setup (esil, core->anal, romem, stats);
r_anal_esil_set_pc (esil, core->offset);
break;
}
for (i = idx = ret = 0; idx < len && (!nops || (nops && i < nops)); i++, idx += ret) {
addr = core->offset + idx;
// TODO: use more anal hints
hint = r_anal_hint_get (core->anal, addr);
r_asm_set_pc (core->assembler, addr);
ret = r_asm_disassemble (core->assembler, &asmop, buf + idx, len - idx);
ret = r_anal_op (core->anal, &op, core->offset + idx, buf + idx, len - idx, R_ANAL_OP_MASK_ALL);
esilstr = R_STRBUF_SAFEGET (&op.esil);
opexstr = R_STRBUF_SAFEGET (&op.opex);
char *mnem = strdup (asmop.buf_asm);
char *sp = strchr (mnem, ' ');
if (sp) {
*sp = 0;
}
if (ret < 1 && fmt != 'd') {
eprintf ("Oops at 0x%08" PFMT64x " (", core->offset + idx);
for (i = idx, j = 0; i < core->blocksize && j < 3; ++i, ++j) {
eprintf ("%02x ", buf[i]);
}
eprintf ("...)\n");
break;
}
size = (hint && hint->size)? hint->size: op.size;
if (fmt == 'd') {
char *opname = strdup (asmop.buf_asm);
r_str_split (opname, ' ');
char *d = r_asm_describe (core->assembler, opname);
if (d && *d) {
r_cons_printf ("%s: %s\n", opname, d);
free (d);
} else {
eprintf ("Unknown opcode\n");
}
free (opname);
} else if (fmt == 'e') {
if (*esilstr) {
if (use_color) {
r_cons_printf ("%s0x%" PFMT64x Color_RESET " %s\n", color, core->offset + idx, esilstr);
} else {
r_cons_printf ("0x%" PFMT64x " %s\n", core->offset + idx, esilstr);
}
}
} else if (fmt == 's') {
totalsize += op.size;
} else if (fmt == 'r') {
if (*esilstr) {
if (use_color) {
r_cons_printf ("%s0x%" PFMT64x Color_RESET "\n", color, core->offset + idx);
} else {
r_cons_printf ("0x%" PFMT64x "\n", core->offset + idx);
}
r_anal_esil_parse (esil, esilstr);
r_anal_esil_dumpstack (esil);
r_anal_esil_stack_free (esil);
}
} else if (fmt == 'j') {
if (isFirst) {
isFirst = false;
} else {
r_cons_print (",");
}
r_cons_printf ("{\"opcode\":\"%s\",", asmop.buf_asm);
{
char strsub[128] = { 0 };
// pc+33
r_parse_varsub (core->parser, NULL,
core->offset + idx,
asmop.size, asmop.buf_asm,
strsub, sizeof (strsub));
{
ut64 killme = UT64_MAX;
if (r_io_read_i (core->io, op.ptr, &killme, op.refptr, be)) {
core->parser->relsub_addr = killme;
}
}
// 0x33->sym.xx
char *p = strdup (strsub);
r_parse_filter (core->parser, core->flags, p,
strsub, sizeof (strsub), be);
free (p);
r_cons_printf ("\"disasm\":\"%s\",", strsub);
}
r_cons_printf ("\"mnemonic\":\"%s\",", mnem);
if (hint && hint->opcode) {
r_cons_printf ("\"ophint\":\"%s\",", hint->opcode);
}
r_cons_printf ("\"prefix\":%" PFMT64d ",", op.prefix);
r_cons_printf ("\"id\":%d,", op.id);
if (opexstr && *opexstr) {
r_cons_printf ("\"opex\":%s,", opexstr);
}
r_cons_printf ("\"addr\":%" PFMT64d ",", core->offset + idx);
r_cons_printf ("\"bytes\":\"");
for (j = 0; j < size; j++) {
r_cons_printf ("%02x", buf[j + idx]);
}
r_cons_printf ("\",");
if (op.val != UT64_MAX) {
r_cons_printf ("\"val\": %" PFMT64d ",", op.val);
}
if (op.ptr != UT64_MAX) {
r_cons_printf ("\"ptr\": %" PFMT64d ",", op.ptr);
}
r_cons_printf ("\"size\": %d,", size);
r_cons_printf ("\"type\": \"%s\",",
r_anal_optype_to_string (op.type));
if (op.reg) {
r_cons_printf ("\"reg\": \"%s\",", op.reg);
}
if (hint && hint->esil) {
r_cons_printf ("\"esil\": \"%s\",", hint->esil);
} else if (*esilstr) {
r_cons_printf ("\"esil\": \"%s\",", esilstr);
}
if (hint && hint->jump != UT64_MAX) {
op.jump = hint->jump;
}
if (op.jump != UT64_MAX) {
r_cons_printf ("\"jump\":%" PFMT64d ",", op.jump);
}
if (hint && hint->fail != UT64_MAX) {
op.fail = hint->fail;
}
if (op.refptr != -1) {
r_cons_printf ("\"refptr\":%d,", op.refptr);
}
if (op.fail != UT64_MAX) {
r_cons_printf ("\"fail\":%" PFMT64d ",", op.fail);
}
r_cons_printf ("\"cycles\":%d,", op.cycles);
if (op.failcycles) {
r_cons_printf ("\"failcycles\":%d,", op.failcycles);
}
r_cons_printf ("\"delay\":%d,", op.delay);
{
const char *p = r_anal_stackop_tostring (op.stackop);
if (p && *p && strcmp (p, "null"))
r_cons_printf ("\"stack\":\"%s\",", p);
}
if (op.stackptr) {
r_cons_printf ("\"stackptr\":%d,", op.stackptr);
}
{
const char *arg = (op.type & R_ANAL_OP_TYPE_COND)
? r_anal_cond_tostring (op.cond): NULL;
if (arg) {
r_cons_printf ("\"cond\":\"%s\",", arg);
}
}
r_cons_printf ("\"family\":\"%s\"}", r_anal_op_family_to_string (op.family));
} else {
#define printline(k, fmt, arg)\
{ \
if (use_color)\
r_cons_printf ("%s%s: " Color_RESET, color, k);\
else\
r_cons_printf ("%s: ", k);\
if (fmt) r_cons_printf (fmt, arg);\
}
printline ("address", "0x%" PFMT64x "\n", core->offset + idx);
printline ("opcode", "%s\n", asmop.buf_asm);
printline ("mnemonic", "%s\n", mnem);
if (hint) {
if (hint->opcode) {
printline ("ophint", "%s\n", hint->opcode);
}
#if 0
// addr should not override core->offset + idx.. its silly
if (hint->addr != UT64_MAX) {
printline ("addr", "0x%08" PFMT64x "\n", (hint->addr + idx));
}
#endif
}
printline ("prefix", "%" PFMT64d "\n", op.prefix);
printline ("id", "%d\n", op.id);
#if 0
// no opex here to avoid lot of tests broken..and having json in here is not much useful imho
if (opexstr && *opexstr) {
printline ("opex", "%s\n", opexstr);
}
#endif
printline ("bytes", NULL, 0);
for (j = 0; j < size; j++) {
r_cons_printf ("%02x", buf[j + idx]);
}
r_cons_newline ();
if (op.val != UT64_MAX)
printline ("val", "0x%08" PFMT64x "\n", op.val);
if (op.ptr != UT64_MAX)
printline ("ptr", "0x%08" PFMT64x "\n", op.ptr);
if (op.refptr != -1)
printline ("refptr", "%d\n", op.refptr);
printline ("size", "%d\n", size);
printline ("type", "%s\n", r_anal_optype_to_string (op.type));
{
const char *t2 = r_anal_optype_to_string (op.type2);
if (t2 && strcmp (t2, "null")) {
printline ("type2", "%s\n", t2);
}
}
if (op.reg) {
printline ("reg", "%s\n", op.reg);
}
if (hint && hint->esil) {
printline ("esil", "%s\n", hint->esil);
} else if (*esilstr) {
printline ("esil", "%s\n", esilstr);
}
if (hint && hint->jump != UT64_MAX) {
op.jump = hint->jump;
}
if (op.jump != UT64_MAX) {
printline ("jump", "0x%08" PFMT64x "\n", op.jump);
}
if (op.direction != 0) {
const char * dir = op.direction == 1 ? "read"
: op.direction == 2 ? "write"
: op.direction == 4 ? "exec"
: op.direction == 8 ? "ref": "none";
printline ("direction", "%s\n", dir);
}
if (hint && hint->fail != UT64_MAX) {
op.fail = hint->fail;
}
if (op.fail != UT64_MAX) {
printline ("fail", "0x%08" PFMT64x "\n", op.fail);
}
if (op.delay) {
printline ("delay", "%d\n", op.delay);
}
printline ("stack", "%s\n", r_anal_stackop_tostring (op.stackop));
{
const char *arg = (op.type & R_ANAL_OP_TYPE_COND)? r_anal_cond_tostring (op.cond): NULL;
if (arg) {
printline ("cond", "%s\n", arg);
}
}
printline ("family", "%s\n", r_anal_op_family_to_string (op.family));
printline ("stackop", "%s\n", r_anal_stackop_tostring (op.stackop));
if (op.stackptr) {
printline ("stackptr", "%"PFMT64d"\n", op.stackptr);
}
}
//r_cons_printf ("false: 0x%08"PFMT64x"\n", core->offset+idx);
//free (hint);
free (mnem);
r_anal_hint_free (hint);
}
if (fmt == 'j') {
r_cons_printf ("]");
r_cons_newline ();
} else if (fmt == 's') {
r_cons_printf ("%d\n", totalsize);
}
r_anal_esil_free (esil);
}
static int bb_cmp(const void *a, const void *b) {
const RAnalBlock *ba = a;
const RAnalBlock *bb = b;
return ba->addr - bb->addr;
}
static int anal_fcn_list_bb(RCore *core, const char *input, bool one) {
RDebugTracepoint *tp = NULL;
RListIter *iter;
RAnalBlock *b;
int mode = 0;
ut64 addr, bbaddr = UT64_MAX;
bool firstItem = true;
if (*input == '.') {
one = true;
input++;
}
if (*input) {
mode = *input;
input++;
}
if (*input == '.') {
one = true;
input++;
}
if (input && *input) {
addr = bbaddr = r_num_math (core->num, input);
} else {
addr = core->offset;
}
if (one) {
bbaddr = addr;
}
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (!fcn) {
return false;
}
switch (mode) {
case 'j':
r_cons_printf ("[");
break;
case '*':
r_cons_printf ("fs blocks\n");
break;
}
r_list_sort (fcn->bbs, bb_cmp);
r_list_foreach (fcn->bbs, iter, b) {
if (one) {
if (bbaddr != UT64_MAX && (bbaddr < b->addr || bbaddr >= (b->addr + b->size))) {
continue;
}
}
switch (mode) {
case 'r':
if (b->jump == UT64_MAX) {
ut64 retaddr = b->addr;
if (b->op_pos) {
retaddr += b->op_pos[b->ninstr - 2];
}
if (!strcmp (input, "*")) {
r_cons_printf ("db 0x%08"PFMT64x"\n", retaddr);
} else if (!strcmp (input, "-*")) {
r_cons_printf ("db-0x%08"PFMT64x"\n", retaddr);
} else {
r_cons_printf ("0x%08"PFMT64x"\n", retaddr);
}
}
break;
case '*':
r_cons_printf ("f bb.%05" PFMT64x " = 0x%08" PFMT64x "\n",
b->addr & 0xFFFFF, b->addr);
break;
case 'q':
r_cons_printf ("0x%08" PFMT64x "\n", b->addr);
break;
case 'j':
//r_cons_printf ("%" PFMT64d "%s", b->addr, iter->n? ",": "");
{
RListIter *iter2;
RAnalBlock *b2;
int inputs = 0;
int outputs = 0;
r_list_foreach (fcn->bbs, iter2, b2) {
if (b2->jump == b->addr) {
inputs++;
}
if (b2->fail == b->addr) {
inputs++;
}
}
if (b->jump != UT64_MAX) {
outputs ++;
}
if (b->fail != UT64_MAX) {
outputs ++;
}
r_cons_printf ("%s{", firstItem? "": ",");
firstItem = false;
if (b->jump != UT64_MAX) {
r_cons_printf ("\"jump\":%"PFMT64d",", b->jump);
}
if (b->fail != UT64_MAX) {
r_cons_printf ("\"fail\":%"PFMT64d",", b->fail);
}
r_cons_printf ("\"addr\":%" PFMT64d ",\"size\":%d,\"inputs\":%d,\"outputs\":%d,\"ninstr\":%d,\"traced\":%s}",
b->addr, b->size, inputs, outputs, b->ninstr, r_str_bool (b->traced));
}
break;
case 'i':
{
RListIter *iter2;
RAnalBlock *b2;
int inputs = 0;
int outputs = 0;
r_list_foreach (fcn->bbs, iter2, b2) {
if (b2->jump == b->addr) {
inputs++;
}
if (b2->fail == b->addr) {
inputs++;
}
}
if (b->jump != UT64_MAX) {
outputs ++;
}
if (b->fail != UT64_MAX) {
outputs ++;
}
firstItem = false;
if (b->jump != UT64_MAX) {
r_cons_printf ("jump: 0x%08"PFMT64x"\n", b->jump);
}
if (b->fail != UT64_MAX) {
r_cons_printf ("fail: 0x%08"PFMT64x"\n", b->fail);
}
r_cons_printf ("addr: 0x%08"PFMT64x"\nsize: %d\ninputs: %d\noutputs: %d\nninstr: %d\ntraced: %s\n",
b->addr, b->size, inputs, outputs, b->ninstr, r_str_bool (b->traced));
}
break;
default:
tp = r_debug_trace_get (core->dbg, b->addr);
r_cons_printf ("0x%08" PFMT64x " 0x%08" PFMT64x " %02X:%04X %d",
b->addr, b->addr + b->size,
tp? tp->times: 0, tp? tp->count: 0,
b->size);
if (b->jump != UT64_MAX) {
r_cons_printf (" j 0x%08" PFMT64x, b->jump);
}
if (b->fail != UT64_MAX) {
r_cons_printf (" f 0x%08" PFMT64x, b->fail);
}
r_cons_newline ();
break;
}
}
if (mode == 'j') {
r_cons_printf ("]\n");
}
return true;
}
static bool anal_bb_edge (RCore *core, const char *input) {
// "afbe" switch-bb-addr case-bb-addr
char *arg = strdup (r_str_trim_ro(input));
char *sp = strchr (arg, ' ');
if (sp) {
*sp++ = 0;
ut64 sw_at = r_num_math (core->num, arg);
ut64 cs_at = r_num_math (core->num, sp);
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, sw_at, 0);
if (fcn) {
RAnalBlock *bb;
RListIter *iter;
r_list_foreach (fcn->bbs, iter, bb) {
if (sw_at >= bb->addr && sw_at < (bb->addr + bb->size)) {
if (!bb->switch_op) {
bb->switch_op = r_anal_switch_op_new (
sw_at, 0, 0);
}
r_anal_switch_op_add_case (bb->switch_op, cs_at, 0, cs_at);
}
}
free (arg);
return true;
}
}
free (arg);
return false;
}
static bool anal_fcn_del_bb(RCore *core, const char *input) {
ut64 addr = r_num_math (core->num, input);
if (!addr) {
addr = core->offset;
}
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, -1);
if (fcn) {
if (!strcmp (input, "*")) {
r_list_free (fcn->bbs);
fcn->bbs = NULL;
} else {
RAnalBlock *b;
RListIter *iter;
r_list_foreach (fcn->bbs, iter, b) {
if (b->addr == addr) {
r_list_delete (fcn->bbs, iter);
return true;
}
}
eprintf ("Cannot find basic block\n");
}
} else {
eprintf ("Cannot find function\n");
}
return false;
}
static int anal_fcn_add_bb(RCore *core, const char *input) {
// fcn_addr bb_addr bb_size [jump] [fail]
char *ptr;
const char *ptr2 = NULL;
ut64 fcnaddr = -1LL, addr = -1LL;
ut64 size = 0LL;
ut64 jump = UT64_MAX;
ut64 fail = UT64_MAX;
int type = R_ANAL_BB_TYPE_NULL;
RAnalFunction *fcn = NULL;
RAnalDiff *diff = NULL;
while (*input == ' ') input++;
ptr = strdup (input);
switch (r_str_word_set0 (ptr)) {
case 7:
ptr2 = r_str_word_get0 (ptr, 6);
if (!(diff = r_anal_diff_new ())) {
eprintf ("error: Cannot init RAnalDiff\n");
free (ptr);
return false;
}
if (ptr2[0] == 'm') {
diff->type = R_ANAL_DIFF_TYPE_MATCH;
} else if (ptr2[0] == 'u') {
diff->type = R_ANAL_DIFF_TYPE_UNMATCH;
}
case 6:
ptr2 = r_str_word_get0 (ptr, 5);
if (strchr (ptr2, 'h')) {
type |= R_ANAL_BB_TYPE_HEAD;
}
if (strchr (ptr2, 'b')) {
type |= R_ANAL_BB_TYPE_BODY;
}
if (strchr (ptr2, 'l')) {
type |= R_ANAL_BB_TYPE_LAST;
}
if (strchr (ptr2, 'f')) {
type |= R_ANAL_BB_TYPE_FOOT;
}
case 5: // get fail
fail = r_num_math (core->num, r_str_word_get0 (ptr, 4));
case 4: // get jump
jump = r_num_math (core->num, r_str_word_get0 (ptr, 3));
case 3: // get size
size = r_num_math (core->num, r_str_word_get0 (ptr, 2));
case 2: // get addr
addr = r_num_math (core->num, r_str_word_get0 (ptr, 1));
case 1: // get fcnaddr
fcnaddr = r_num_math (core->num, r_str_word_get0 (ptr, 0));
}
fcn = r_anal_get_fcn_in (core->anal, fcnaddr, 0);
if (fcn) {
int ret = r_anal_fcn_add_bb (core->anal, fcn, addr, size, jump, fail, type, diff);
if (!ret) {
eprintf ("Cannot add basic block\n");
}
} else {
eprintf ("Cannot find function at 0x%" PFMT64x "\n", fcnaddr);
}
r_anal_diff_free (diff);
free (ptr);
return true;
}
static void r_core_anal_nofunclist (RCore *core, const char *input) {
int minlen = (int)(input[0]==' ') ? r_num_math (core->num, input + 1): 16;
ut64 code_size = r_num_get (core->num, "$SS");
ut64 base_addr = r_num_get (core->num, "$S");
ut64 chunk_size, chunk_offset, i;
RListIter *iter, *iter2;
RAnalFunction *fcn;
RAnalBlock *b;
char* bitmap;
int counter;
if (minlen < 1) {
minlen = 1;
}
if (code_size < 1) {
return;
}
bitmap = calloc (1, code_size+64);
if (!bitmap) {
return;
}
// for each function
r_list_foreach (core->anal->fcns, iter, fcn) {
// for each basic block in the function
r_list_foreach (fcn->bbs, iter2, b) {
// if it is not withing range, continue
if ((fcn->addr < base_addr) || (fcn->addr >= base_addr+code_size))
continue;
// otherwise mark each byte in the BB in the bitmap
for (counter = 0; counter < b->size; counter++) {
bitmap[b->addr+counter-base_addr] = '=';
}
// finally, add a special marker to show the beginning of a
// function
bitmap[fcn->addr-base_addr] = 'F';
}
}
// Now we print the list of memory regions that are not assigned to a function
chunk_size = 0;
chunk_offset = 0;
for (i = 0; i < code_size; i++) {
if (bitmap[i]){
// We only print a region is its size is bigger than 15 bytes
if (chunk_size >= minlen){
fcn = r_anal_get_fcn_in (core->anal, base_addr+chunk_offset, R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM);
if (fcn) {
r_cons_printf ("0x%08"PFMT64x" %6d %s\n", base_addr+chunk_offset, chunk_size, fcn->name);
} else {
r_cons_printf ("0x%08"PFMT64x" %6d\n", base_addr+chunk_offset, chunk_size);
}
}
chunk_size = 0;
chunk_offset = i+1;
continue;
}
chunk_size+=1;
}
if (chunk_size >= 16) {
fcn = r_anal_get_fcn_in (core->anal, base_addr+chunk_offset, R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM);
if (fcn) {
r_cons_printf ("0x%08"PFMT64x" %6d %s\n", base_addr+chunk_offset, chunk_size, fcn->name);
} else {
r_cons_printf ("0x%08"PFMT64x" %6d\n", base_addr+chunk_offset, chunk_size);
}
}
free(bitmap);
}
static void r_core_anal_fmap (RCore *core, const char *input) {
int show_color = r_config_get_i (core->config, "scr.color");
int cols = r_config_get_i (core->config, "hex.cols") * 4;
ut64 code_size = r_num_get (core->num, "$SS");
ut64 base_addr = r_num_get (core->num, "$S");
RListIter *iter, *iter2;
RAnalFunction *fcn;
RAnalBlock *b;
char* bitmap;
int assigned;
ut64 i;
if (code_size < 1) {
return;
}
bitmap = calloc (1, code_size+64);
if (!bitmap) {
return;
}
// for each function
r_list_foreach (core->anal->fcns, iter, fcn) {
// for each basic block in the function
r_list_foreach (fcn->bbs, iter2, b) {
// if it is not within range, continue
if ((fcn->addr < base_addr) || (fcn->addr >= base_addr+code_size))
continue;
// otherwise mark each byte in the BB in the bitmap
int counter = 1;
for (counter = 0; counter < b->size; counter++) {
bitmap[b->addr+counter-base_addr] = '=';
}
bitmap[fcn->addr-base_addr] = 'F';
}
}
// print the bitmap
assigned = 0;
if (cols < 1) {
cols = 1;
}
for (i = 0; i < code_size; i += 1) {
if (!(i % cols)) {
r_cons_printf ("\n0x%08"PFMT64x" ", base_addr+i);
}
if (bitmap[i]) {
assigned++;
}
if (show_color) {
if (bitmap[i]) {
r_cons_printf ("%s%c\x1b[0m", Color_GREEN, bitmap[i]);
} else {
r_cons_printf (".");
}
} else {
r_cons_printf ("%c", bitmap[i] ? bitmap[i] : '.' );
}
}
r_cons_printf ("\n%d / %d (%.2lf%%) bytes assigned to a function\n", assigned, code_size, 100.0*( (float) assigned) / code_size);
free(bitmap);
}
static bool fcnNeedsPrefix(const char *name) {
if (!strncmp (name, "entry", 5)) {
return false;
}
if (!strncmp (name, "main", 4)) {
return false;
}
return (!strchr (name, '.'));
}
/* TODO: move into r_anal_fcn_rename(); */
static bool setFunctionName(RCore *core, ut64 off, const char *_name, bool prefix) {
char *name, *oname, *nname = NULL;
RAnalFunction *fcn;
if (!core || !_name) {
return false;
}
const char *fcnpfx = r_config_get (core->config, "anal.fcnprefix");
if (!fcnpfx) {
fcnpfx = "fcn";
}
if (r_reg_get (core->anal->reg, _name, -1)) {
name = r_str_newf ("%s.%s", fcnpfx, _name);
} else {
name = strdup (_name);
}
fcn = r_anal_get_fcn_in (core->anal, off,
R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM | R_ANAL_FCN_TYPE_LOC);
if (!fcn) {
return false;
}
if (prefix && fcnNeedsPrefix (name)) {
nname = r_str_newf ("%s.%s", fcnpfx, name);
} else {
nname = strdup (name);
}
oname = fcn->name;
r_flag_rename (core->flags, r_flag_get (core->flags, fcn->name), nname);
fcn->name = strdup (nname);
if (core->anal->cb.on_fcn_rename) {
core->anal->cb.on_fcn_rename (core->anal,
core->anal->user, fcn, nname);
}
free (oname);
free (nname);
free (name);
return true;
}
static void afCc(RCore *core, const char *input) {
ut64 addr;
RAnalFunction *fcn;
if (*input == ' ') {
addr = r_num_math (core->num, input);
} else {
addr = core->offset;
}
if (addr == 0LL) {
fcn = r_anal_fcn_find_name (core->anal, input + 3);
} else {
fcn = r_anal_get_fcn_in (core->anal, addr, R_ANAL_FCN_TYPE_NULL);
}
if (fcn) {
ut32 totalCycles = r_anal_fcn_cost (core->anal, fcn);
// FIXME: This defeats the purpose of the function, but afC is used in project files.
// cf. canal.c
r_cons_printf ("%d\n", totalCycles);
} else {
eprintf ("Cannot find function\n");
}
}
static int cmd_anal_fcn(RCore *core, const char *input) {
char i;
r_cons_break_timeout (r_config_get_i (core->config, "anal.timeout"));
switch (input[1]) {
case 'f': // "aff"
r_anal_fcn_fit_overlaps (core->anal, NULL);
break;
case 'a':
if (input[2] == 'l') { // afal : list function call arguments
int show_args = r_config_get_i (core->config, "dbg.funcarg");
if (show_args) {
r_core_print_func_args (core);
}
break;
}
case 'd': // "afd"
{
ut64 addr = 0;
if (input[2] == '?') {
eprintf ("afd [offset]\n");
} else if (input[2] == ' ') {
addr = r_num_math (core->num, input + 2);
} else {
addr = core->offset;
}
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (fcn) {
if (fcn->addr != addr) {
r_cons_printf ("%s + %d\n", fcn->name,
(int)(addr - fcn->addr));
} else {
r_cons_println (fcn->name);
}
} else {
eprintf ("Cannot find function\n");
}
}
break;
case '-': // "af-"
if (!input[2] || !strcmp (input + 2, "*")) {
r_anal_fcn_del_locs (core->anal, UT64_MAX);
r_anal_fcn_del (core->anal, UT64_MAX);
} else {
ut64 addr = input[2]
? r_num_math (core->num, input + 2)
: core->offset;
r_anal_fcn_del_locs (core->anal, addr);
r_anal_fcn_del (core->anal, addr);
}
break;
case 'u': // "afu"
{
ut64 addr = core->offset;
ut64 addr_end = r_num_math (core->num, input + 2);
if (addr_end < addr) {
eprintf ("Invalid address ranges\n");
} else {
int depth = 1;
ut64 a, b;
const char *c;
a = r_config_get_i (core->config, "anal.from");
b = r_config_get_i (core->config, "anal.to");
c = r_config_get (core->config, "anal.limits");
r_config_set_i (core->config, "anal.from", addr);
r_config_set_i (core->config, "anal.to", addr_end);
r_config_set (core->config, "anal.limits", "true");
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (fcn) {
r_anal_fcn_resize (core->anal, fcn, addr_end - addr);
}
r_core_anal_fcn (core, addr, UT64_MAX,
R_ANAL_REF_TYPE_NULL, depth);
fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (fcn) {
r_anal_fcn_resize (core->anal, fcn, addr_end - addr);
}
r_config_set_i (core->config, "anal.from", a);
r_config_set_i (core->config, "anal.to", b);
r_config_set (core->config, "anal.limits", c? c: "");
}
}
break;
case '+': { // "af+"
if (input[2] != ' ') {
eprintf ("Missing arguments\n");
return false;
}
char *ptr = strdup (input + 3);
const char *ptr2;
int n = r_str_word_set0 (ptr);
const char *name = NULL;
ut64 addr = UT64_MAX;
ut64 size = 0LL;
RAnalDiff *diff = NULL;
int type = R_ANAL_FCN_TYPE_FCN;
if (n > 1) {
switch (n) {
case 5:
size = r_num_math (core->num, r_str_word_get0 (ptr, 4));
case 4:
ptr2 = r_str_word_get0 (ptr, 3);
if (!(diff = r_anal_diff_new ())) {
eprintf ("error: Cannot init RAnalDiff\n");
free (ptr);
return false;
}
if (ptr2[0] == 'm') {
diff->type = R_ANAL_DIFF_TYPE_MATCH;
} else if (ptr2[0] == 'u') {
diff->type = R_ANAL_DIFF_TYPE_UNMATCH;
}
case 3:
ptr2 = r_str_word_get0 (ptr, 2);
if (strchr (ptr2, 'l')) {
type = R_ANAL_FCN_TYPE_LOC;
} else if (strchr (ptr2, 'i')) {
type = R_ANAL_FCN_TYPE_IMP;
} else if (strchr (ptr2, 's')) {
type = R_ANAL_FCN_TYPE_SYM;
} else {
type = R_ANAL_FCN_TYPE_FCN;
}
case 2:
name = r_str_word_get0 (ptr, 1);
case 1:
addr = r_num_math (core->num, r_str_word_get0 (ptr, 0));
}
if (!r_anal_fcn_add (core->anal, addr, size, name, type, diff)) {
eprintf ("Cannot add function (duplicated)\n");
}
}
r_anal_diff_free (diff);
free (ptr);
}
break;
case 'o': // "afo"
{
RAnalFunction *fcn;
ut64 addr = core->offset;
if (input[2] == ' ')
addr = r_num_math (core->num, input + 3);
if (addr == 0LL) {
fcn = r_anal_fcn_find_name (core->anal, input + 3);
} else {
fcn = r_anal_get_fcn_in (core->anal, addr, R_ANAL_FCN_TYPE_NULL);
}
if (fcn) {
r_cons_printf ("0x%08" PFMT64x "\n", fcn->addr);
}
}
break;
case 'i': // "afi"
switch (input[2]) {
case '?':
r_core_cmd_help (core, help_msg_afi);
break;
case '.': // "afi."
{
ut64 addr = core->offset;
if (input[3] == ' ') {
addr = r_num_math (core->num, input + 3);
}
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, R_ANAL_FCN_TYPE_NULL);
if (fcn) {
r_cons_printf ("%s\n", fcn->name);
}
}
break;
case 'l': // "afil"
if (input[3] == '?') {
// TODO #7967 help refactor
help_msg_afll[1] = "afil";
r_core_cmd_help (core, help_msg_afll);
break;
}
/* fallthrough */
case 'j': // "afij"
case '*': // "afi*"
r_core_anal_fcn_list (core, input + 3, input + 2);
break;
default:
i = 1;
r_core_anal_fcn_list (core, input + 2, &i);
break;
}
break;
case 'l': // "afl"
switch (input[2]) {
case '?':
r_core_cmd_help (core, help_msg_afl);
break;
case 'l': // "afll"
if (input[3] == '?') {
// TODO #7967 help refactor
help_msg_afll[1] = "afll";
r_core_cmd_help (core, help_msg_afll);
break;
}
/* fallthrough */
case 'j': // "aflj"
case 'q': // "aflq"
case 's': // "afls"
case '*': // "afl*"
r_core_anal_fcn_list (core, NULL, input + 2);
break;
case 'c': // "aflc"
r_cons_printf ("%d\n", r_list_length (core->anal->fcns));
break;
default: // "afl "
r_core_anal_fcn_list (core, NULL, "o");
break;
}
break;
case 's': // "afs"
{
ut64 addr;
RAnalFunction *f;
const char *arg = input + 3;
if (input[2] && (addr = r_num_math (core->num, arg))) {
arg = strchr (arg, ' ');
if (arg) {
arg++;
}
} else {
addr = core->offset;
}
if ((f = r_anal_get_fcn_in (core->anal, addr, R_ANAL_FCN_TYPE_NULL))) {
if (arg && *arg) {
r_anal_str_to_fcn (core->anal, f, arg);
} else {
char *str = r_anal_fcn_to_string (core->anal, f);
r_cons_println (str);
free (str);
}
} else {
eprintf ("No function defined at 0x%08" PFMT64x "\n", addr);
}
}
break;
case 'm': // "afm" - merge two functions
r_core_anal_fcn_merge (core, core->offset, r_num_math (core->num, input + 2));
break;
case 'M': // "afM" - print functions map
r_core_anal_fmap (core, input + 1);
break;
case 'v': // "afv"
var_cmd (core, input + 2);
break;
case 't': // "aft"
type_cmd (core, input + 2);
break;
case 'C': // "afC"
if (input[2] == 'c') {
RAnalFunction *fcn;
if ((fcn = r_anal_get_fcn_in (core->anal, core->offset, 0)) != NULL) {
r_cons_printf ("%i\n", r_anal_fcn_cc (fcn));
} else {
eprintf ("Error: Cannot find function at 0x08%" PFMT64x "\n", core->offset);
}
} else if (input[2] == 'l') {
RAnalFunction *fcn;
if ((fcn = r_anal_get_fcn_in (core->anal, core->offset, 0)) != NULL) {
r_cons_printf ("%d\n", r_anal_fcn_loops (fcn));
} else {
eprintf ("Error: Cannot find function at 0x08%" PFMT64x "\n", core->offset);
}
} else if (input[2] == '?') {
r_core_cmd_help (core, help_msg_afC);
} else {
afCc (core, input + 3);
}
break;
case 'c':{ // "afc"
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, 0);
if (!fcn && !(input[2] == '?'|| input[2] == 'l' || input[2] == 'o')) {
eprintf ("Cannot find function here\n");
break;
}
switch (input[2]) {
case '\0': // "afc"
r_cons_println (fcn->cc);
break;
case ' ': { // "afc "
char *cc = r_str_trim (strdup (input + 3));
if (!r_anal_cc_exist (core->anal, cc)) {
eprintf ("Unknown calling convention '%s'\n"
"See afcl for available types\n", cc);
} else {
fcn->cc = r_str_const (r_anal_cc_to_constant (core->anal, cc));
}
break;
}
case 'a': // "afca""
eprintf ("Todo\n");
break;
case 'l': // "afcl" list all function Calling conventions.
sdb_foreach (core->anal->sdb_cc, cc_print, NULL);
break;
case 'o': { // "afco"
char *dbpath = r_str_trim (strdup (input + 3));
if (r_file_exists (dbpath)) {
Sdb *db = sdb_new (0, dbpath, 0);
sdb_merge (core->anal->sdb_cc, db);
sdb_close (db);
sdb_free (db);
}
free (dbpath);
break;
}
case 'r': { // "afcr"
int i;
char *out, *cmd, *regname, *tmp;
char *subvec_str = r_str_new ("");
char *json_str = r_str_new ("");
// if json_str initialize to NULL, it's possible for afcrj to output a (NULL)
// subvec_str and json_str should be valid until exiting this code block
bool json = input[3] == 'j'? true: false;
for (i = 0; i <= 11; i++) {
if (i == 0) {
cmd = r_str_newf ("cc.%s.ret", fcn->cc);
} else {
cmd = r_str_newf ("cc.%s.arg%d", fcn->cc, i);
}
if (i < 7) {
regname = r_str_new (cmd);
} else {
regname = r_str_newf ("cc.%s.float_arg%d", fcn->cc, i - 6);
}
out = sdb_querys (core->anal->sdb_cc, NULL, 0, cmd);
free (cmd);
if (out) {
out[strlen (out) - 1] = 0;
if (json) {
tmp = subvec_str;
subvec_str = r_str_newf ("%s,\"%s\"", subvec_str, out);
free (tmp);
} else {
r_cons_printf ("%s: %s\n", regname, out);
}
free (out);
}
free (regname);
if (!subvec_str[0]) {
continue;
}
switch (i) {
case 0: {
tmp = json_str;
json_str = r_str_newf ("%s,\"ret\":%s", json_str, subvec_str + 1);
free (tmp);
} break;
case 6: {
tmp = json_str;
json_str = r_str_newf ("%s,\"args\":[%s]", json_str, subvec_str + 1);
free (tmp);
} break;
case 11: {
tmp = json_str;
json_str = r_str_newf ("%s,\"float_args\":[%s]", json_str, subvec_str + 1);
free (tmp);
} break;
default:
continue;
}
free (subvec_str);
subvec_str = r_str_new ("");
}
if (json && json_str[0]) {
r_cons_printf ("{%s}\n", json_str + 1);
}
free (subvec_str);
free (json_str);
} break;
case '?': // "afc?"
default:
r_core_cmd_help (core, help_msg_afc);
}
}break;
case 'B': // "afB" // set function bits
if (input[2] == ' ') {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset,
R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM);
if (fcn) {
int bits = atoi (input + 3);
r_anal_hint_set_bits (core->anal, fcn->addr, bits);
r_anal_hint_set_bits (core->anal,
fcn->addr + r_anal_fcn_size (fcn),
core->anal->bits);
fcn->bits = bits;
} else {
eprintf ("Cannot find function to set bits\n");
}
} else {
eprintf ("Usage: afB [bits]\n");
}
break;
case 'b': // "afb"
switch (input[2]) {
case '-': // "afb-"
anal_fcn_del_bb (core, input + 3);
break;
case 'e': // "afbe"
anal_bb_edge (core, input + 3);
break;
case 0:
case ' ': // "afb "
case 'q': // "afbq"
case 'r': // "afbr"
case '*': // "afb*"
case 'j': // "afbj"
anal_fcn_list_bb (core, input + 2, false);
break;
case 'i': // "afbi"
anal_fcn_list_bb (core, input + 2, true);
break;
case '.': // "afb."
anal_fcn_list_bb (core, input[2]? " $$": input + 2, true);
break;
case '+': // "afb+"
anal_fcn_add_bb (core, input + 3);
break;
default:
case '?':
r_core_cmd_help (core, help_msg_afb);
break;
}
break;
case 'n': // "afn"
switch (input[2]) {
case 's': // "afns"
free (r_core_anal_fcn_autoname (core, core->offset, 1));
break;
case 'a': // "afna"
{
char *name = r_core_anal_fcn_autoname (core, core->offset, 0);
if (name) {
r_cons_printf ("afn %s 0x%08" PFMT64x "\n", name, core->offset);
free (name);
}
}
break;
case 0: // "afn"
{
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
if (fcn) {
r_cons_printf ("%s\n", fcn->name);
}
}
break;
case ' ': // "afn "
{
ut64 off = core->offset;
char *p, *name = strdup (input + 3);
if ((p = strchr (name, ' '))) {
*p++ = 0;
off = r_num_math (core->num, p);
}
if (*name) {
if (!setFunctionName (core, off, name, false)) {
eprintf ("Cannot find function '%s' at 0x%08" PFMT64x "\n", name, off);
}
free (name);
} else {
eprintf ("Usage: afn newname [off] # set new name to given function\n");
free (name);
}
}
break;
default:
r_core_cmd_help (core, help_msg_afn);
break;
}
break;
case 'S': // afS"
{
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
if (fcn) {
fcn->maxstack = r_num_math (core->num, input + 3);
//fcn->stack = fcn->maxstack;
}
}
break;
#if 0
/* this is undocumented and probably have no uses. plz discuss */
case 'e': // "afe"
{
RAnalFunction *fcn;
ut64 off = core->offset;
char *p, *name = strdup ((input[2]&&input[3])? input + 3: "");
if ((p = strchr (name, ' '))) {
*p = 0;
off = r_num_math (core->num, p + 1);
}
fcn = r_anal_get_fcn_in (core->anal, off, R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM);
if (fcn) {
RAnalBlock *b;
RListIter *iter;
RAnalRef *r;
r_list_foreach (fcn->refs, iter, r) {
r_cons_printf ("0x%08" PFMT64x " -%c 0x%08" PFMT64x "\n", r->at, r->type, r->addr);
}
r_list_foreach (fcn->bbs, iter, b) {
int ok = 0;
if (b->type == R_ANAL_BB_TYPE_LAST) ok = 1;
if (b->type == R_ANAL_BB_TYPE_FOOT) ok = 1;
if (b->jump == UT64_MAX && b->fail == UT64_MAX) ok = 1;
if (ok) {
r_cons_printf ("0x%08" PFMT64x " -r\n", b->addr);
// TODO: check if destination is outside the function boundaries
}
}
} else eprintf ("Cannot find function at 0x%08" PFMT64x "\n", core->offset);
free (name);
}
break;
#endif
case 'x': // "afx"
switch (input[2]) {
case '\0': // "afx"
case 'j': // "afxj"
case ' ': // "afx "
#if FCN_OLD
if (input[2] == 'j') {
r_cons_printf ("[");
}
// TODO: sdbize!
// list xrefs from current address
{
ut64 addr = input[2]==' '? r_num_math (core->num, input + 2): core->offset;
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, R_ANAL_FCN_TYPE_NULL);
if (fcn) {
RAnalRef *ref;
RListIter *iter;
RList *refs = r_anal_fcn_get_refs (core->anal, fcn);
r_list_foreach (refs, iter, ref) {
if (input[2] == 'j') {
r_cons_printf ("{\"type\":\"%c\",\"from\":%"PFMT64d",\"to\":%"PFMT64d"}%s",
ref->type, ref->at, ref->addr, iter->n? ",": "");
} else {
r_cons_printf ("%c 0x%08" PFMT64x " -> 0x%08" PFMT64x "\n",
ref->type, ref->at, ref->addr);
}
}
r_list_free (refs);
} else {
eprintf ("Cannot find function at 0x%08"PFMT64x"\n", addr);
}
}
if (input[2] == 'j') {
r_cons_printf ("]\n");
}
#else
#warning TODO_ FCNOLD sdbize xrefs here
eprintf ("TODO\n");
#endif
break;
case 'c': // "afxc" add code xref
case 'd': // "afxd"
case 's': // "afxs"
case 'C': { // "afxC"
char *p;
ut64 a, b;
char *mi = strdup (input);
if (mi && mi[3] == ' ' && (p = strchr (mi + 4, ' '))) {
*p = 0;
a = r_num_math (core->num, mi + 3);
b = r_num_math (core->num, p + 1);
r_anal_xrefs_set (core->anal, input[2], a, b);
} else {
r_core_cmd_help (core, help_msg_afx);
}
free (mi);
}
break;
case '-': // "afx-"
{
char *p;
ut64 a, b;
char *mi = strdup (input + 3);
if (mi && *mi == ' ' && (p = strchr (mi + 1, ' '))) {
*p = 0;
a = r_num_math (core->num, mi);
b = r_num_math (core->num, p + 1);
r_anal_xrefs_deln (core->anal, -1, a, b);
} else {
eprintf ("Usage: afx- [src] [dst]\n");
}
free (mi);
}
break;
default:
case '?': // "afx?"
r_core_cmd_help (core, help_msg_afx);
break;
}
break;
case 'F': // "afF"
{
int val = input[2] && r_num_math (core->num, input + 2);
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, R_ANAL_FCN_TYPE_NULL);
if (fcn) {
fcn->folded = input[2]? val: !fcn->folded;
}
}
break;
case '?': // "af?"
r_core_cmd_help (core, help_msg_af);
break;
case 'r': // "afr" // analyze function recursively
case ' ': // "af "
case '\0': // "af"
{
char *uaddr = NULL, *name = NULL;
int depth = r_config_get_i (core->config, "anal.depth");
bool analyze_recursively = r_config_get_i (core->config, "anal.calls");
RAnalFunction *fcn;
ut64 addr = core->offset;
if (input[1] == 'r') {
input++;
analyze_recursively = true;
}
// first undefine
if (input[0] && input[1] == ' ') {
name = strdup (input + 2);
uaddr = strchr (name, ' ');
if (uaddr) {
*uaddr++ = 0;
addr = r_num_math (core->num, uaddr);
}
// depth = 1; // or 1?
// disable hasnext
}
//r_core_anal_undefine (core, core->offset);
r_core_anal_fcn (core, addr, UT64_MAX, R_ANAL_REF_TYPE_NULL, depth);
fcn = r_anal_get_fcn_in (core->anal, addr, 0);
if (fcn && r_config_get_i (core->config, "anal.vars")) {
fcn_callconv (core, fcn);
}
if (fcn) {
/* ensure we use a proper name */
setFunctionName (core, addr, fcn->name, false);
}
if (analyze_recursively) {
fcn = r_anal_get_fcn_in (core->anal, addr, 0); /// XXX wrong in case of nopskip
if (fcn) {
RAnalRef *ref;
RListIter *iter;
RList *refs = r_anal_fcn_get_refs (core->anal, fcn);
r_list_foreach (refs, iter, ref) {
if (ref->addr == UT64_MAX) {
//eprintf ("Warning: ignore 0x%08"PFMT64x" call 0x%08"PFMT64x"\n", ref->at, ref->addr);
continue;
}
if (ref->type != 'c' && ref->type != 'C') {
/* only follow code/call references */
continue;
}
if (!r_io_is_valid_offset (core->io, ref->addr, !core->anal->opt.noncode)) {
continue;
}
r_core_anal_fcn (core, ref->addr, fcn->addr, R_ANAL_REF_TYPE_CALL, depth);
/* use recursivity here */
#if 1
RAnalFunction *f = r_anal_get_fcn_at (core->anal, ref->addr, 0);
if (f) {
RListIter *iter;
RAnalRef *ref;
RList *refs1 = r_anal_fcn_get_refs (core->anal, f);
r_list_foreach (refs1, iter, ref) {
if (!r_io_is_valid_offset (core->io, ref->addr, !core->anal->opt.noncode)) {
continue;
}
if (ref->type != 'c' && ref->type != 'C') {
continue;
}
r_core_anal_fcn (core, ref->addr, f->addr, R_ANAL_REF_TYPE_CALL, depth);
// recursively follow fcn->refs again and again
}
r_list_free (refs1);
} else {
f = r_anal_get_fcn_in (core->anal, fcn->addr, 0);
if (f) {
/* cut function */
r_anal_fcn_resize (core->anal, f, addr - fcn->addr);
r_core_anal_fcn (core, ref->addr, fcn->addr,
R_ANAL_REF_TYPE_CALL, depth);
f = r_anal_get_fcn_at (core->anal, fcn->addr, 0);
}
if (!f) {
eprintf ("Cannot find function at 0x%08" PFMT64x "\n", fcn->addr);
}
}
#endif
}
r_list_free (refs);
}
}
if (name) {
if (*name && !setFunctionName (core, addr, name, true)) {
eprintf ("Cannot find function '%s' at 0x%08" PFMT64x "\n", name, (ut64)addr);
}
free (name);
}
flag_every_function (core);
}
default:
return false;
break;
}
return true;
}
// size: 0: bits; -1: any; >0: exact size
static void __anal_reg_list(RCore *core, int type, int bits, char mode) {
RReg *hack = core->dbg->reg;
const char *use_color;
int use_colors = r_config_get_i (core->config, "scr.color");
if (use_colors) {
#undef ConsP
#define ConsP(x) (core->cons && core->cons->pal.x)? core->cons->pal.x
use_color = ConsP (creg) : Color_BWHITE;
} else {
use_color = NULL;
}
if (bits < 0) {
// TODO Change the `size` argument of r_debug_reg_list to use -1 for any and 0 for anal->bits
bits = 0;
} else if (!bits) {
bits = core->anal->bits;
}
if (core->anal) {
core->dbg->reg = core->anal->reg;
if (core->anal->cur && core->anal->cur->arch) {
/* workaround for thumb */
if (!strcmp (core->anal->cur->arch, "arm") && bits == 16) {
bits = 32;
}
/* workaround for 6502 */
if (!strcmp (core->anal->cur->arch, "6502") && bits == 8) {
r_debug_reg_list (core->dbg, R_REG_TYPE_GPR, 16, mode, use_color); // XXX detect which one is current usage
}
if (!strcmp (core->anal->cur->arch, "avr") && bits == 8) {
r_debug_reg_list (core->dbg, R_REG_TYPE_GPR, 16, mode, use_color); // XXX detect which one is current usage
}
}
}
if (mode == '=') {
int pcbits = 0;
const char *pcname = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
RRegItem *reg = r_reg_get (core->anal->reg, pcname, 0);
if (bits != reg->size) {
pcbits = reg->size;
}
if (pcbits) {
r_debug_reg_list (core->dbg, R_REG_TYPE_GPR, pcbits, 2, use_color); // XXX detect which one is current usage
}
}
r_debug_reg_list (core->dbg, type, bits, mode, use_color);
core->dbg->reg = hack;
}
// XXX dup from drp :OOO
void cmd_anal_reg(RCore *core, const char *str) {
int size = 0, i, type = R_REG_TYPE_GPR;
int bits = (core->anal->bits & R_SYS_BITS_64)? 64: 32;
int use_colors = r_config_get_i (core->config, "scr.color");
struct r_reg_item_t *r;
const char *use_color;
const char *name;
char *arg;
if (use_colors) {
#define ConsP(x) (core->cons && core->cons->pal.x)? core->cons->pal.x
use_color = ConsP (creg)
: Color_BWHITE;
} else {
use_color = NULL;
}
switch (str[0]) {
case 'l': // "arl"
{
RRegSet *rs = r_reg_regset_get (core->anal->reg, R_REG_TYPE_GPR);
if (rs) {
RRegItem *r;
RListIter *iter;
r_list_foreach (rs->regs, iter, r) {
r_cons_println (r->name);
}
}
} break;
case '0': // "ar0"
r_reg_arena_zero (core->anal->reg);
break;
case 'C': // "arC"
if (core->anal->reg->reg_profile_cmt) {
r_cons_println (core->anal->reg->reg_profile_cmt);
}
break;
case 'w': // "arw"
switch (str[1]) {
case '?': {
r_core_cmd_help (core, help_msg_arw);
break;
}
case ' ':
r_reg_arena_set_bytes (core->anal->reg, str + 1);
break;
default:
r_core_cmd_help (core, help_msg_arw);
break;
}
break;
case 'a': // "ara"
switch (str[1]) {
case '?': // "ara?"
r_core_cmd_help (core, help_msg_ara);
break;
case 's': // "aras"
r_reg_arena_swap (core->anal->reg, false);
break;
case '+': // "ara+"
r_reg_arena_push (core->anal->reg);
break;
case '-': // "ara-"
r_reg_arena_pop (core->anal->reg);
break;
default: {
int i, j;
RRegArena *a;
RListIter *iter;
for (i = 0; i < R_REG_TYPE_LAST; i++) {
RRegSet *rs = &core->anal->reg->regset[i];
j = 0;
r_list_foreach (rs->pool, iter, a) {
r_cons_printf ("%s %p %d %d %s %d\n",
(a == rs->arena)? "*": ".", a,
i, j, r_reg_get_type (i), a->size);
j++;
}
}
} break;
}
break;
case '?': // "ar?"
if (str[1]) {
ut64 off = r_reg_getv (core->anal->reg, str + 1);
r_cons_printf ("0x%08" PFMT64x "\n", off);
} else {
r_core_cmd_help (core, help_msg_ar);
}
break;
case 'r': // "arr"
r_core_debug_rr (core, core->anal->reg);
break;
case 'S': { // "arS"
int sz;
ut8 *buf = r_reg_get_bytes (
core->anal->reg, R_REG_TYPE_GPR, &sz);
r_cons_printf ("%d\n", sz);
free (buf);
} break;
case 'b': { // "arb" WORK IN PROGRESS // DEBUG COMMAND
int len, type = R_REG_TYPE_GPR;
arg = strchr (str, ' ');
if (arg) {
char *string = r_str_trim (strdup (arg + 1));
if (string) {
type = r_reg_type_by_name (string);
if (type == -1 && string[0] != 'a') {
type = R_REG_TYPE_GPR;
}
free (string);
}
}
ut8 *buf = r_reg_get_bytes (core->dbg->reg, type, &len);
if (buf) {
//r_print_hexdump (core->print, 0LL, buf, len, 16, 16);
r_print_hexdump (core->print, 0LL, buf, len, 32, 4, 1);
free (buf);
}
} break;
case 'c': // "arc"
// TODO: set flag values with drc zf=1
{
RRegItem *r;
const char *name = str + 1;
while (*name == ' ') name++;
if (*name && name[1]) {
r = r_reg_cond_get (core->dbg->reg, name);
if (r) {
r_cons_println (r->name);
} else {
int id = r_reg_cond_from_string (name);
RRegFlags *rf = r_reg_cond_retrieve (core->dbg->reg, NULL);
if (rf) {
int o = r_reg_cond_bits (core->dbg->reg, id, rf);
core->num->value = o;
// ORLY?
r_cons_printf ("%d\n", o);
free (rf);
} else {
eprintf ("unknown conditional or flag register\n");
}
}
} else {
RRegFlags *rf = r_reg_cond_retrieve (core->dbg->reg, NULL);
if (rf) {
r_cons_printf ("| s:%d z:%d c:%d o:%d p:%d\n",
rf->s, rf->z, rf->c, rf->o, rf->p);
if (*name == '=') {
for (i = 0; i < R_REG_COND_LAST; i++) {
r_cons_printf ("%s:%d ",
r_reg_cond_to_string (i),
r_reg_cond_bits (core->dbg->reg, i, rf));
}
r_cons_newline ();
} else {
for (i = 0; i < R_REG_COND_LAST; i++) {
r_cons_printf ("%d %s\n",
r_reg_cond_bits (core->dbg->reg, i, rf),
r_reg_cond_to_string (i));
}
}
free (rf);
}
}
}
break;
case 's': // "ars"
switch (str[1]) {
case '-': // "ars-"
r_reg_arena_pop (core->dbg->reg);
// restore debug registers if in debugger mode
r_debug_reg_sync (core->dbg, R_REG_TYPE_GPR, true);
break;
case '+': // "ars+"
r_reg_arena_push (core->dbg->reg);
break;
case '?': { // "ars?"
// TODO #7967 help refactor: dup from drp
const char *help_msg[] = {
"Usage:", "drs", " # Register states commands",
"drs", "", "List register stack",
"drs+", "", "Push register state",
"drs-", "", "Pop register state",
NULL };
r_core_cmd_help (core, help_msg);
} break;
default:
r_cons_printf ("%d\n", r_list_length (
core->dbg->reg->regset[0].pool));
break;
}
break;
case 'p': // "arp"
// XXX we have to break out .h for these cmd_xxx files.
cmd_reg_profile (core, 'a', str);
break;
case 't': // "art"
for (i = 0; (name = r_reg_get_type (i)); i++)
r_cons_println (name);
break;
case 'n': // "arn"
if (*(str + 1) == '\0') {
eprintf ("Oops. try arn [PC|SP|BP|A0|A1|A2|A3|A4|R0|R1|ZF|SF|NF|OF]\n");
break;
}
name = r_reg_get_name (core->dbg->reg, r_reg_get_name_idx (str + 2));
if (name && *name) {
r_cons_println (name);
} else {
eprintf ("Oops. try arn [PC|SP|BP|A0|A1|A2|A3|A4|R0|R1|ZF|SF|NF|OF]\n");
}
break;
case 'd': // "ard"
r_debug_reg_list (core->dbg, R_REG_TYPE_GPR, bits, 3, use_color); // XXX detect which one is current usage
break;
case 'o': // "aro"
r_reg_arena_swap (core->dbg->reg, false);
r_debug_reg_list (core->dbg, R_REG_TYPE_GPR, bits, 0, use_color); // XXX detect which one is current usage
r_reg_arena_swap (core->dbg->reg, false);
break;
case '=': // "ar="
{
char *p = NULL;
char *bits = NULL;
if (str[1]) {
p = strdup (str + 1);
if (str[1] != ':') {
// Bits were specified
bits = strtok (p, ":");
if (r_str_isnumber (bits)) {
st64 sz = r_num_math (core->num, bits);
if (sz > 0) {
size = sz;
}
} else {
r_core_cmd_help (core, help_msg_ar);
break;
}
}
int len = bits ? strlen (bits) : 0;
if (str[len + 1] == ':') {
// We have some regs
char *regs = bits ? strtok (NULL, ":") : strtok ((char *)str + 1, ":");
char *reg = strtok (regs, " ");
RList *q_regs = r_list_new ();
if (q_regs) {
while (reg) {
r_list_append (q_regs, reg);
reg = strtok (NULL, " ");
}
core->dbg->q_regs = q_regs;
}
}
}
__anal_reg_list (core, type, size, 2);
if (!r_list_empty (core->dbg->q_regs)) {
r_list_free (core->dbg->q_regs);
}
core->dbg->q_regs = NULL;
free (p);
}
break;
case '-': // "ar-"
case '*': // "ar*"
case 'R': // "arR"
case 'j': // "arj"
case '\0': // "ar"
__anal_reg_list (core, type, size, str[0]);
break;
case ' ': { // "ar "
arg = strchr (str + 1, '=');
if (arg) {
char *ostr, *regname;
*arg = 0;
ostr = r_str_trim (strdup (str + 1));
regname = r_str_trim_nc (ostr);
r = r_reg_get (core->dbg->reg, regname, -1);
if (!r) {
int role = r_reg_get_name_idx (regname);
if (role != -1) {
const char *alias = r_reg_get_name (core->dbg->reg, role);
r = r_reg_get (core->dbg->reg, alias, -1);
}
}
if (r) {
//eprintf ("%s 0x%08"PFMT64x" -> ", str,
// r_reg_get_value (core->dbg->reg, r));
r_reg_set_value (core->dbg->reg, r,
r_num_math (core->num, arg + 1));
r_debug_reg_sync (core->dbg, R_REG_TYPE_ALL, true);
//eprintf ("0x%08"PFMT64x"\n",
// r_reg_get_value (core->dbg->reg, r));
r_core_cmdf (core, ".dr*%d", bits);
} else {
eprintf ("ar: Unknown register '%s'\n", regname);
}
free (ostr);
return;
}
char name[32];
int i = 1, j;
while (str[i]) {
if (str[i] == ',') {
i++;
} else {
for (j = i; str[++j] && str[j] != ','; );
if (j - i + 1 <= sizeof name) {
r_str_ncpy (name, str + i, j - i + 1);
if (IS_DIGIT (name[0])) { // e.g. ar 32
__anal_reg_list (core, R_REG_TYPE_GPR, atoi (name), '\0');
} else if (showreg (core, name) > 0) { // e.g. ar rax
} else { // e.g. ar gpr ; ar all
type = r_reg_type_by_name (name);
// TODO differentiate ALL and illegal register types and print error message for the latter
__anal_reg_list (core, type, -1, '\0');
}
}
i = j;
}
}
}
}
}
static ut64 initializeEsil(RCore *core) {
const char *name = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
RAnalEsil *esil = core->anal->esil;
int romem = r_config_get_i (core->config, "esil.romem");
int stats = r_config_get_i (core->config, "esil.stats");
int iotrap = r_config_get_i (core->config, "esil.iotrap");
int exectrap = r_config_get_i (core->config, "esil.exectrap");
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
int noNULL = r_config_get_i (core->config, "esil.noNULL");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
if (!(core->anal->esil = r_anal_esil_new (stacksize, iotrap, addrsize))) {
return UT64_MAX;
}
ut64 addr;
esil = core->anal->esil;
r_anal_esil_setup (esil, core->anal, romem, stats, noNULL); // setup io
esil->exectrap = exectrap;
RList *entries = r_bin_get_entries (core->bin);
RBinAddr *entry = NULL;
RBinInfo *info = NULL;
if (entries && !r_list_empty (entries)) {
entry = (RBinAddr *)r_list_pop (entries);
info = r_bin_get_info (core->bin);
addr = info->has_va? entry->vaddr: entry->paddr;
r_list_push (entries, entry);
} else {
addr = core->offset;
}
r_reg_setv (core->anal->reg, name, addr);
// set memory read only
return addr;
}
R_API int r_core_esil_step(RCore *core, ut64 until_addr, const char *until_expr, ut64 *prev_addr) {
#define return_tail(x) { tail_return_value = x; goto tail_return; }
int tail_return_value = 0;
int ret;
ut8 code[32];
RAnalOp op = {0};
RAnalEsil *esil = core->anal->esil;
const char *name = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
if (!esil) {
// TODO inititalizeEsil (core);
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
int iotrap = r_config_get_i (core->config, "esil.iotrap");
int romem = r_config_get_i (core->config, "esil.romem");
int stats = r_config_get_i (core->config, "esil.stats");
int noNULL = r_config_get_i (core->config, "esil.noNULL");
int verbose = r_config_get_i (core->config, "esil.verbose");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
if (!(esil = r_anal_esil_new (stacksize, iotrap, addrsize))) {
return 0;
}
r_anal_esil_setup (esil, core->anal, romem, stats, noNULL); // setup io
core->anal->esil = esil;
esil->verbose = verbose;
{
const char *s = r_config_get (core->config, "cmd.esil.intr");
if (s) {
char *my = strdup (s);
if (my) {
r_config_set (core->config, "cmd.esil.intr", my);
free (my);
}
}
}
}
esil->cmd = r_core_esil_cmd;
ut64 addr = r_reg_getv (core->anal->reg, name);
r_cons_break_push (NULL, NULL);
repeat:
if (r_cons_is_breaked ()) {
eprintf ("[+] ESIL emulation interrupted at 0x%08" PFMT64x "\n", addr);
return_tail (0);
}
if (!esil) {
addr = initializeEsil (core);
esil = core->anal->esil;
if (!esil) {
return_tail (0);
}
} else {
esil->trap = 0;
addr = r_reg_getv (core->anal->reg, name);
//eprintf ("PC=0x%"PFMT64x"\n", (ut64)addr);
}
if (prev_addr) {
*prev_addr = addr;
}
if (esil->exectrap) {
if (!r_io_is_valid_offset (core->io, addr, R_IO_EXEC)) {
esil->trap = R_ANAL_TRAP_EXEC_ERR;
esil->trap_code = addr;
eprintf ("[ESIL] Trap, trying to execute on non-executable memory\n");
return_tail (1);
}
}
r_asm_set_pc (core->assembler, addr);
// run esil pin command here
const char *pincmd = r_anal_pin_call (core->anal, addr);
if (pincmd) {
r_core_cmd0 (core, pincmd);
ut64 pc = r_debug_reg_get (core->dbg, "PC");
if (addr != pc) {
return_tail (1);
}
}
(void)r_io_read_at (core->io, addr, code, sizeof (code));
// TODO: sometimes this is dupe
ret = r_anal_op (core->anal, &op, addr, code, sizeof (code), R_ANAL_OP_MASK_ALL);
// if type is JMP then we execute the next N instructions
// update the esil pointer because RAnal.op() can change it
esil = core->anal->esil;
if (op.size < 1 || ret < 0) {
if (esil->cmd && esil->cmd_todo) {
esil->cmd (esil, esil->cmd_todo, addr, 0);
}
op.size = 1; // avoid inverted stepping
}
{
/* apply hint */
RAnalHint *hint = r_anal_hint_get (core->anal, addr);
r_anal_op_hint (&op, hint);
r_anal_hint_free (hint);
}
r_reg_setv (core->anal->reg, name, addr + op.size);
if (ret) {
r_anal_esil_set_pc (esil, addr);
if (core->dbg->trace->enabled) {
RReg *reg = core->dbg->reg;
core->dbg->reg = core->anal->reg;
r_debug_trace_pc (core->dbg, addr);
core->dbg->reg = reg;
} else {
r_anal_esil_parse (esil, R_STRBUF_SAFEGET (&op.esil));
if (core->anal->cur && core->anal->cur->esil_post_loop) {
core->anal->cur->esil_post_loop (esil, &op);
}
r_anal_esil_stack_free (esil);
}
// only support 1 slot for now
if (op.delay) {
ut8 code2[32];
ut64 naddr = addr + op.size;
RAnalOp op2 = {0};
// emulate only 1 instruction
r_anal_esil_set_pc (esil, naddr);
(void)r_io_read_at (core->io, naddr, code2, sizeof (code2));
// TODO: sometimes this is dupe
ret = r_anal_op (core->anal, &op2, naddr, code2, sizeof (code2), R_ANAL_OP_MASK_ALL);
switch (op2.type) {
case R_ANAL_OP_TYPE_CJMP:
case R_ANAL_OP_TYPE_JMP:
case R_ANAL_OP_TYPE_CRET:
case R_ANAL_OP_TYPE_RET:
// branches are illegal in a delay slot
esil->trap = R_ANAL_TRAP_EXEC_ERR;
esil->trap_code = addr;
eprintf ("[ESIL] Trap, trying to execute a branch in a delay slot\n");
return_tail (1);
break;
}
r_anal_esil_parse (esil, R_STRBUF_SAFEGET (&op2.esil));
r_anal_op_fini (&op2);
}
tail_return_value = 1;
}
st64 follow = (st64)r_config_get_i (core->config, "dbg.follow");
ut64 pc = r_debug_reg_get (core->dbg, "PC");
if (follow > 0) {
if ((pc < core->offset) || (pc > (core->offset + follow))) {
r_core_cmd0 (core, "sr PC");
}
}
// check addr
if (until_addr != UT64_MAX) {
if (r_reg_getv (core->anal->reg, name) == until_addr) {
return_tail (0);
}
goto repeat;
}
// check esil
if (esil && esil->trap) {
if (core->anal->esil->verbose) {
eprintf ("TRAP\n");
}
return_tail (0);
}
if (until_expr) {
if (r_anal_esil_condition (core->anal->esil, until_expr)) {
if (core->anal->esil->verbose) {
eprintf ("ESIL BREAK!\n");
}
return_tail (0);
}
goto repeat;
}
tail_return:
r_anal_op_fini (&op);
r_cons_break_pop ();
return tail_return_value;
}
R_API int r_core_esil_step_back(RCore *core) {
RAnalEsil *esil = core->anal->esil;
RListIter *tail;
const char *name = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
ut64 prev = 0;
ut64 end = r_reg_getv (core->anal->reg, name);
if (!esil || !(tail = r_list_tail (esil->sessions))) {
return 0;
}
RAnalEsilSession *before = (RAnalEsilSession *) tail->data;
if (!before) {
eprintf ("Cannot find any previous state here\n");
return 0;
}
eprintf ("NOTE: step back in esil is setting an initial state and stepping into pc is the same.\n");
eprintf ("NOTE: this is extremely wrong and poorly efficient. so don't use this feature unless\n");
eprintf ("NOTE: you are going to fix it by making it consistent with dts, which is also broken as hell\n");
eprintf ("Execute until 0x%08"PFMT64x"\n", end);
r_anal_esil_session_set (esil, before);
r_core_esil_step (core, end, NULL, &prev);
eprintf ("Before 0x%08"PFMT64x"\n", prev);
r_anal_esil_session_set (esil, before);
r_core_esil_step (core, prev, NULL, NULL);
return 1;
}
static void cmd_address_info(RCore *core, const char *addrstr, int fmt) {
ut64 addr, type;
if (!addrstr || !*addrstr) {
addr = core->offset;
} else {
addr = r_num_math (core->num, addrstr);
}
type = r_core_anal_address (core, addr);
int isp = 0;
switch (fmt) {
case 'j':
#define COMMA isp++? ",": ""
r_cons_printf ("{");
if (type & R_ANAL_ADDR_TYPE_PROGRAM)
r_cons_printf ("%s\"program\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_LIBRARY)
r_cons_printf ("%s\"library\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_EXEC)
r_cons_printf ("%s\"exec\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_READ)
r_cons_printf ("%s\"read\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_WRITE)
r_cons_printf ("%s\"write\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_FLAG)
r_cons_printf ("%s\"flag\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_FUNC)
r_cons_printf ("%s\"func\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_STACK)
r_cons_printf ("%s\"stack\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_HEAP)
r_cons_printf ("%s\"heap\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_REG)
r_cons_printf ("%s\"reg\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_ASCII)
r_cons_printf ("%s\"ascii\":true", COMMA);
if (type & R_ANAL_ADDR_TYPE_SEQUENCE)
r_cons_printf ("%s\"sequence\":true", COMMA);
r_cons_print ("}");
break;
default:
if (type & R_ANAL_ADDR_TYPE_PROGRAM)
r_cons_printf ("program\n");
if (type & R_ANAL_ADDR_TYPE_LIBRARY)
r_cons_printf ("library\n");
if (type & R_ANAL_ADDR_TYPE_EXEC)
r_cons_printf ("exec\n");
if (type & R_ANAL_ADDR_TYPE_READ)
r_cons_printf ("read\n");
if (type & R_ANAL_ADDR_TYPE_WRITE)
r_cons_printf ("write\n");
if (type & R_ANAL_ADDR_TYPE_FLAG)
r_cons_printf ("flag\n");
if (type & R_ANAL_ADDR_TYPE_FUNC)
r_cons_printf ("func\n");
if (type & R_ANAL_ADDR_TYPE_STACK)
r_cons_printf ("stack\n");
if (type & R_ANAL_ADDR_TYPE_HEAP)
r_cons_printf ("heap\n");
if (type & R_ANAL_ADDR_TYPE_REG)
r_cons_printf ("reg\n");
if (type & R_ANAL_ADDR_TYPE_ASCII)
r_cons_printf ("ascii\n");
if (type & R_ANAL_ADDR_TYPE_SEQUENCE)
r_cons_printf ("sequence\n");
}
}
static void cmd_anal_info(RCore *core, const char *input) {
switch (input[0]) {
case '?':
eprintf ("Usage: ai @ rsp\n");
break;
case ' ':
cmd_address_info (core, input, 0);
break;
case 'j': // "aij"
cmd_address_info (core, input + 1, 'j');
break;
default:
cmd_address_info (core, NULL, 0);
break;
}
}
static void initialize_stack (RCore *core, ut64 addr, ut64 size) {
const char *mode = r_config_get (core->config, "esil.fillstack");
if (mode && *mode && *mode != '0') {
const int bs = 4096 * 32;
ut64 i;
for (i = 0; i < size; i += bs) {
int left = R_MIN (bs, size - i);
// r_core_cmdf (core, "wx 10203040 @ 0x%llx", addr);
switch (*mode) {
case 'd': // "debrujn"
r_core_cmdf (core, "wopD %"PFMT64d" @ 0x%"PFMT64x, left, addr + i);
break;
case 's': // "seq"
r_core_cmdf (core, "woe 1 0xff 1 4 @ 0x%"PFMT64x"!0x%"PFMT64x, addr + i, left);
break;
case 'r': // "random"
r_core_cmdf (core, "woR %"PFMT64d" @ 0x%"PFMT64x"!0x%"PFMT64x, left, addr + i, left);
break;
case 'z': // "zero"
case '0':
r_core_cmdf (core, "wow 00 @ 0x%"PFMT64x"!0x%"PFMT64x, addr + i, left);
break;
}
}
// eprintf ("[*] Initializing ESIL stack with pattern\n");
// r_core_cmdf (core, "woe 0 10 4 @ 0x%"PFMT64x, size, addr);
}
}
static void cmd_esil_mem(RCore *core, const char *input) {
RAnalEsil *esil = core->anal->esil;
RIOMap *stack_map;
ut64 curoff = core->offset;
const char *patt = "";
ut64 addr = 0x100000;
ut32 size = 0xf0000;
char name[128];
RFlagItem *fi;
const char *sp, *pc;
char uri[32];
char nomalloc[256];
char *p;
if (!esil) {
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
int iotrap = r_config_get_i (core->config, "esil.iotrap");
int romem = r_config_get_i (core->config, "esil.romem");
int stats = r_config_get_i (core->config, "esil.stats");
int noNULL = r_config_get_i (core->config, "esil.noNULL");
int verbose = r_config_get_i (core->config, "esil.verbose");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
if (!(esil = r_anal_esil_new (stacksize, iotrap, addrsize))) {
return;
}
r_anal_esil_setup (esil, core->anal, romem, stats, noNULL); // setup io
core->anal->esil = esil;
esil->verbose = verbose;
{
const char *s = r_config_get (core->config, "cmd.esil.intr");
if (s) {
char *my = strdup (s);
if (my) {
r_config_set (core->config, "cmd.esil.intr", my);
free (my);
}
}
}
}
if (*input == '?') {
eprintf ("Usage: aeim [addr] [size] [name] - initialize ESIL VM stack\n");
eprintf ("Default: 0x100000 0xf0000\n");
eprintf ("See ae? for more help\n");
return;
}
if (input[0] == 'p') {
fi = r_flag_get (core->flags, "aeim.stack");
if (fi) {
addr = fi->offset;
size = fi->size;
} else {
cmd_esil_mem (core, "");
}
if (esil) {
esil->stack_addr = addr;
esil->stack_size = size;
}
initialize_stack (core, addr, size);
return;
}
if (!*input) {
RFlagItem *fi = r_flag_get (core->flags, "aeim.fd");
if (fi) {
// Close the fd associated with the aeim stack
(void)r_io_fd_close (core->io, fi->offset);
}
}
addr = r_config_get_i (core->config, "esil.stack.addr");
size = r_config_get_i (core->config, "esil.stack.size");
patt = r_config_get (core->config, "esil.stack.pattern");
p = strncpy (nomalloc, input, 255);
if ((p = strchr (p, ' '))) {
while (*p == ' ') p++;
addr = r_num_math (core->num, p);
if ((p = strchr (p, ' '))) {
while (*p == ' ') p++;
size = (ut32)r_num_math (core->num, p);
if (size < 1) {
size = 0xf0000;
}
if ((p = strchr (p, ' '))) {
while (*p == ' ') p++;
snprintf (name, sizeof (name), "mem.%s", p);
} else {
snprintf (name, sizeof (name), "mem.0x%" PFMT64x "_0x%x", addr, size);
}
} else {
snprintf (name, sizeof (name), "mem.0x%" PFMT64x "_0x%x", addr, size);
}
} else {
snprintf (name, sizeof (name), "mem.0x%" PFMT64x "_0x%x", addr, size);
}
if (*input == '-') {
if (esil->stack_fd > 2) { //0, 1, 2 are reserved for stdio/stderr
r_io_fd_close (core->io, esil->stack_fd);
// no need to kill the maps, r_io_map_cleanup does that for us in the close
esil->stack_fd = 0;
} else {
eprintf ("Cannot deinitialize %s\n", name);
}
r_flag_unset_name (core->flags, name);
// eprintf ("Deinitialized %s\n", name);
return;
}
snprintf (uri, sizeof (uri), "malloc://%d", (int)size);
esil->stack_fd = r_io_fd_open (core->io, uri, R_IO_RW, 0);
if (!(stack_map = r_io_map_add (core->io, esil->stack_fd,
R_IO_RW, 0LL, addr, size, true))) {
r_io_fd_close (core->io, esil->stack_fd);
eprintf ("Cannot create map for tha stack, fd %d got closed again\n", esil->stack_fd);
esil->stack_fd = 0;
return;
}
r_io_map_set_name (stack_map, name);
// r_flag_set (core->flags, name, addr, size); //why is this here?
r_flag_set (core->flags, "aeim.stack", addr, size);
r_flag_set (core->flags, "aeim.fd", esil->stack_fd, 1);
r_config_set_i (core->config, "io.va", true);
if (patt && *patt) {
switch (*patt) {
case '0':
// do nothing
break;
case 'd':
r_core_cmdf (core, "wopD %d @ 0x%"PFMT64x, size, addr);
break;
case 'i':
r_core_cmdf (core, "woe 0 255 1 @ 0x%"PFMT64x"!%d",addr, size);
break;
case 'w':
r_core_cmdf (core, "woe 0 0xffff 1 4 @ 0x%"PFMT64x"!%d",addr, size);
break;
}
}
// SP
sp = r_reg_get_name (core->dbg->reg, R_REG_NAME_SP);
r_debug_reg_set (core->dbg, sp, addr + (size / 2));
// BP
sp = r_reg_get_name (core->dbg->reg, R_REG_NAME_BP);
r_debug_reg_set (core->dbg, sp, addr + (size / 2));
// PC
pc = r_reg_get_name (core->dbg->reg, R_REG_NAME_PC);
r_debug_reg_set (core->dbg, pc, curoff);
r_core_cmd0 (core, ".ar*");
#if 0
if (!r_io_section_get_name (core->io, ESIL_STACK_NAME)) {
r_core_cmdf (core, "om %d 0x%"PFMT64x, cf->fd, addr);
r_core_cmdf (core, "S 0x%"PFMT64x" 0x%"PFMT64x" %d %d "
ESIL_STACK_NAME, addr, addr, size, size);
}
#endif
if (esil) {
esil->stack_addr = addr;
esil->stack_size = size;
}
initialize_stack (core, addr, size);
r_core_seek (core, curoff, 0);
}
#if 0
static ut64 opc = UT64_MAX;
static ut8 *regstate = NULL;
static void esil_init (RCore *core) {
const char *pc = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
int noNULL = r_config_get_i (core->config, "esil.noNULL");
opc = r_reg_getv (core->anal->reg, pc);
if (!opc || opc==UT64_MAX) {
opc = core->offset;
}
if (!core->anal->esil) {
int iotrap = r_config_get_i (core->config, "esil.iotrap");
ut64 stackSize = r_config_get_i (core->config, "esil.stack.size");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
if (!(core->anal->esil = r_anal_esil_new (stackSize, iotrap, addrsize))) {
R_FREE (regstate);
return;
}
r_anal_esil_setup (core->anal->esil, core->anal, 0, 0, noNULL);
}
free (regstate);
regstate = r_reg_arena_peek (core->anal->reg);
}
static void esil_fini(RCore *core) {
const char *pc = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
r_reg_arena_poke (core->anal->reg, regstate);
r_reg_setv (core->anal->reg, pc, opc);
R_FREE (regstate);
}
#endif
typedef struct {
RList *regs;
RList *regread;
RList *regwrite;
RList *inputregs;
} AeaStats;
static void aea_stats_init (AeaStats *stats) {
stats->regs = r_list_newf (free);
stats->regread = r_list_newf (free);
stats->regwrite = r_list_newf (free);
stats->inputregs = r_list_newf (free);
}
static void aea_stats_fini (AeaStats *stats) {
R_FREE (stats->regs);
R_FREE (stats->regread);
R_FREE (stats->regwrite);
R_FREE (stats->inputregs);
}
static bool contains(RList *list, const char *name) {
RListIter *iter;
const char *n;
r_list_foreach (list, iter, n) {
if (!strcmp (name, n))
return true;
}
return false;
}
static char *oldregread = NULL;
static RList *mymemxsr = NULL;
static RList *mymemxsw = NULL;
#define R_NEW_DUP(x) memcpy((void*)malloc(sizeof(x)), &(x), sizeof(x))
typedef struct {
ut64 addr;
int size;
} AeaMemItem;
static int mymemwrite(RAnalEsil *esil, ut64 addr, const ut8 *buf, int len) {
RListIter *iter;
AeaMemItem *n;
r_list_foreach (mymemxsw, iter, n) {
if (addr == n->addr) {
return len;
}
}
if (!r_io_is_valid_offset (esil->anal->iob.io, addr, 0)) {
return false;
}
n = R_NEW (AeaMemItem);
if (n) {
n->addr = addr;
n->size = len;
r_list_push (mymemxsw, n);
}
return len;
}
static int mymemread(RAnalEsil *esil, ut64 addr, ut8 *buf, int len) {
RListIter *iter;
AeaMemItem *n;
r_list_foreach (mymemxsr, iter, n) {
if (addr == n->addr) {
return len;
}
}
if (!r_io_is_valid_offset (esil->anal->iob.io, addr, 0)) {
return false;
}
n = R_NEW (AeaMemItem);
if (n) {
n->addr = addr;
n->size = len;
r_list_push (mymemxsr, n);
}
return len;
}
static int myregwrite(RAnalEsil *esil, const char *name, ut64 *val) {
AeaStats *stats = esil->user;
if (oldregread && !strcmp (name, oldregread)) {
r_list_pop (stats->regread);
R_FREE (oldregread)
}
if (!IS_DIGIT (*name)) {
if (!contains (stats->regs, name)) {
r_list_push (stats->regs, strdup (name));
}
if (!contains (stats->regwrite, name)) {
r_list_push (stats->regwrite, strdup (name));
}
}
return 0;
}
static int myregread(RAnalEsil *esil, const char *name, ut64 *val, int *len) {
AeaStats *stats = esil->user;
if (!IS_DIGIT (*name)) {
if (!contains (stats->inputregs, name)) {
if (!contains (stats->regwrite, name)) {
r_list_push (stats->inputregs, strdup (name));
}
}
if (!contains (stats->regs, name)) {
r_list_push (stats->regs, strdup (name));
}
if (!contains (stats->regread, name)) {
r_list_push (stats->regread, strdup (name));
}
}
return 0;
}
static void showregs (RList *list) {
if (!r_list_empty (list)) {
char *reg;
RListIter *iter;
r_list_foreach (list, iter, reg) {
r_cons_print (reg);
if (iter->n) {
r_cons_printf (" ");
}
}
}
r_cons_newline();
}
static void showregs_json (RList *list) {
r_cons_printf ("[");
if (!r_list_empty (list)) {
char *reg;
RListIter *iter;
r_list_foreach (list, iter, reg) {
r_cons_printf ("\"%s\"", reg);
if (iter->n) {
r_cons_printf (",");
}
}
}
r_cons_printf ("]");
}
static bool cmd_aea(RCore* core, int mode, ut64 addr, int length) {
RAnalEsil *esil;
int ptr, ops, ops_end = 0, len, buf_sz, maxopsize;
ut64 addr_end;
AeaStats stats;
const char *esilstr;
RAnalOp aop = R_EMPTY;
ut8 *buf;
RList* regnow;
if (!core) {
return false;
}
maxopsize = r_anal_archinfo (core->anal, R_ANAL_ARCHINFO_MAX_OP_SIZE);
if (maxopsize < 1) {
maxopsize = 16;
}
if (mode & 1) {
// number of bytes / length
buf_sz = length;
} else {
// number of instructions / opcodes
ops_end = length;
if (ops_end < 1) {
ops_end = 1;
}
buf_sz = ops_end * maxopsize;
}
if (buf_sz < 1) {
buf_sz = maxopsize;
}
addr_end = addr + buf_sz;
buf = malloc (buf_sz);
if (!buf) {
return false;
}
(void)r_io_read_at (core->io, addr, (ut8 *)buf, buf_sz);
aea_stats_init (&stats);
//esil_init (core);
//esil = core->anal->esil;
r_reg_arena_push (core->anal->reg);
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
bool iotrap = r_config_get_i (core->config, "esil.iotrap");
int romem = r_config_get_i (core->config, "esil.romem");
int stats1 = r_config_get_i (core->config, "esil.stats");
int noNULL = r_config_get_i (core->config, "esil.noNULL");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
esil = r_anal_esil_new (stacksize, iotrap, addrsize);
r_anal_esil_setup (esil, core->anal, romem, stats1, noNULL); // setup io
# define hasNext(x) (x&1) ? (addr<addr_end) : (ops<ops_end)
mymemxsr = r_list_new ();
mymemxsw = r_list_new ();
esil->user = &stats;
esil->cb.hook_reg_write = myregwrite;
esil->cb.hook_reg_read = myregread;
esil->cb.hook_mem_write = mymemwrite;
esil->cb.hook_mem_read = mymemread;
esil->nowrite = true;
for (ops = ptr = 0; ptr < buf_sz && hasNext (mode); ops++, ptr += len) {
len = r_anal_op (core->anal, &aop, addr + ptr, buf + ptr, buf_sz - ptr, R_ANAL_OP_MASK_ALL);
esilstr = R_STRBUF_SAFEGET (&aop.esil);
if (len < 1) {
eprintf ("Invalid 0x%08"PFMT64x" instruction %02x %02x\n",
addr + ptr, buf[ptr], buf[ptr + 1]);
break;
}
r_anal_esil_parse (esil, esilstr);
r_anal_esil_stack_free (esil);
}
esil->nowrite = false;
esil->cb.hook_reg_write = NULL;
esil->cb.hook_reg_read = NULL;
//esil_fini (core);
r_anal_esil_free (esil);
r_reg_arena_pop (core->anal->reg);
regnow = r_list_newf (free);
{
RListIter *iter;
char *reg;
r_list_foreach (stats.regs, iter, reg) {
if (!contains (stats.regwrite, reg)) {
r_list_push (regnow, strdup (reg));
}
}
}
if ((mode >> 5) & 1) {
RListIter *iter;
AeaMemItem *n;
int c = 0;
r_cons_printf ("f-mem.*\n");
r_list_foreach (mymemxsr, iter, n) {
r_cons_printf ("f mem.read.%d 0x%08x @ 0x%08"PFMT64x"\n", c++, n->size, n->addr);
}
c = 0;
r_list_foreach (mymemxsw, iter, n) {
r_cons_printf ("f mem.write.%d 0x%08x @ 0x%08"PFMT64x"\n", c++, n->size, n->addr);
}
}
/* show registers used */
if ((mode >> 1) & 1) {
showregs (stats.regread);
} else if ((mode >> 2) & 1) {
showregs (stats.regwrite);
} else if ((mode >> 3) & 1) {
showregs (regnow);
} else if ((mode >> 4) & 1) {
r_cons_printf ("{\"A\":");
showregs_json (stats.regs);
r_cons_printf (",\"I\":");
showregs_json (stats.inputregs);
r_cons_printf (",\"R\":");
showregs_json (stats.regread);
r_cons_printf (",\"W\":");
showregs_json (stats.regwrite);
r_cons_printf (",\"N\":");
showregs_json (regnow);
r_cons_printf ("}");
r_cons_newline();
} else if ((mode >> 5) & 1) {
// nothing
} else {
r_cons_printf (" I: ");
showregs (stats.inputregs);
r_cons_printf (" A: ");
showregs (stats.regs);
r_cons_printf (" R: ");
showregs (stats.regread);
r_cons_printf (" W: ");
showregs (stats.regwrite);
r_cons_printf ("NW: ");
if (r_list_length (regnow)) {
showregs (regnow);
} else {
r_cons_newline();
}
RListIter *iter;
ut64 *n;
if (!r_list_empty (mymemxsr)) {
r_cons_printf ("@R:");
r_list_foreach (mymemxsr, iter, n) {
r_cons_printf (" 0x%08"PFMT64x, *n);
}
r_cons_newline ();
}
if (!r_list_empty (mymemxsw)) {
r_cons_printf ("@W:");
r_list_foreach (mymemxsw, iter, n) {
r_cons_printf (" 0x%08"PFMT64x, *n);
}
r_cons_newline ();
}
}
r_list_free (mymemxsr);
r_list_free (mymemxsw);
mymemxsr = NULL;
mymemxsw = NULL;
aea_stats_fini (&stats);
free (buf);
R_FREE (regnow);
return true;
}
static void cmd_aespc(RCore *core, ut64 addr, int off) {
RAnalEsil *esil = core->anal->esil;
int i, j = 0;
int instr_size = 0;
ut8 *buf;
RAnalOp aop = {0};
int ret , bsize = R_MAX (64, core->blocksize);
const int mininstrsz = r_anal_archinfo (core->anal, R_ANAL_ARCHINFO_MIN_OP_SIZE);
const int minopcode = R_MAX (1, mininstrsz);
const char *pc = r_reg_get_name (core->dbg->reg, R_REG_NAME_PC);
RRegItem *r = r_reg_get (core->dbg->reg, pc, -1);
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
int iotrap = r_config_get_i (core->config, "esil.iotrap");
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
if (!esil) {
if (!(esil = r_anal_esil_new (stacksize, iotrap, addrsize))) {
return;
}
}
buf = malloc (bsize);
if (!buf) {
eprintf ("Cannot allocate %d byte(s)\n", bsize);
free (buf);
return;
}
if (addr == -1) {
addr = r_debug_reg_get (core->dbg, pc);
}
ut64 curpc = addr;
ut64 oldoff = core->offset;
for (i = 0, j = 0; j < off ; i++, j++) {
if (r_cons_is_breaked ()) {
break;
}
if (i >= (bsize - 32)) {
i = 0;
}
if (!i) {
r_core_read_at (core, addr, buf, bsize);
}
ret = r_anal_op (core->anal, &aop, addr, buf + i, bsize - i, R_ANAL_OP_MASK_ALL);
instr_size += ret;
int inc = (core->search->align > 0)? core->search->align - 1: ret - 1;
if (inc < 0) {
inc = minopcode;
}
i += inc;
addr += inc;
r_anal_op_fini (&aop);
}
r_reg_set_value (core->dbg->reg, r, curpc);
r_core_esil_step (core, curpc + instr_size, NULL, NULL);
r_core_seek (core, oldoff, 1);
}
static void cmd_anal_esil(RCore *core, const char *input) {
RAnalEsil *esil = core->anal->esil;
ut64 addr = core->offset;
ut64 adr ;
char *n, *n1;
int off;
int stacksize = r_config_get_i (core->config, "esil.stack.depth");
int iotrap = r_config_get_i (core->config, "esil.iotrap");
int romem = r_config_get_i (core->config, "esil.romem");
int stats = r_config_get_i (core->config, "esil.stats");
int noNULL = r_config_get_i (core->config, "esil.noNULL");
ut64 until_addr = UT64_MAX;
unsigned int addrsize = r_config_get_i (core->config, "esil.addr.size");
const char *until_expr = NULL;
RAnalOp *op;
switch (input[0]) {
case 'p': // "aep"
switch (input[1]) {
case 'c':
if (input[2] == ' ') {
// seek to this address
r_core_cmdf (core, "ar PC=%s", input + 3);
r_core_cmd0 (core, ".ar*");
} else {
eprintf ("Missing argument\n");
}
break;
case 0:
r_anal_pin_list (core->anal);
break;
case '-':
if (input[2])
addr = r_num_math (core->num, input + 2);
r_anal_pin_unset (core->anal, addr);
break;
case ' ':
r_anal_pin (core->anal, addr, input + 2);
break;
default:
r_core_cmd_help (core, help_msg_aep);
break;
}
break;
case 'r': // "aer"
// 'aer' is an alias for 'ar'
cmd_anal_reg (core, input + 1);
break;
case '*':
// XXX: this is wip, not working atm
if (core->anal->esil) {
r_cons_printf ("trap: %d\n", core->anal->esil->trap);
r_cons_printf ("trap-code: %d\n", core->anal->esil->trap_code);
} else {
eprintf ("esil vm not initialized. run `aei`\n");
}
break;
case ' ':
//r_anal_esil_eval (core->anal, input+1);
if (!esil) {
if (!(core->anal->esil = esil = r_anal_esil_new (stacksize, iotrap, addrsize)))
return;
}
r_anal_esil_setup (esil, core->anal, romem, stats, noNULL); // setup io
r_anal_esil_set_pc (esil, core->offset);
r_anal_esil_parse (esil, input + 1);
r_anal_esil_dumpstack (esil);
r_anal_esil_stack_free (esil);
break;
case 's': // "aes"
// "aes" "aeso" "aesu" "aesue"
// aes -> single step
// aesb -> single step back
// aeso -> single step over
// aesu -> until address
// aesue -> until esil expression
switch (input[1]) {
case '?':
eprintf ("See: ae?~aes\n");
break;
case 'l': // "aesl"
{
ut64 pc = r_debug_reg_get (core->dbg, "PC");
RAnalOp *op = r_core_anal_op (core, pc);
// TODO: honor hint
if (!op) {
break;
}
r_core_esil_step (core, UT64_MAX, NULL, NULL);
r_debug_reg_set (core->dbg, "PC", pc + op->size);
r_anal_esil_set_pc (esil, pc + op->size);
r_core_cmd0 (core, ".ar*");
} break;
case 'b': // "aesb"
if (!r_core_esil_step_back (core)) {
eprintf ("cannnot step back\n");
}
r_core_cmd0 (core, ".ar*");
break;
case 'u': // "aesu"
if (input[2] == 'e') {
until_expr = input + 3;
} else {
until_addr = r_num_math (core->num, input + 2);
}
r_core_esil_step (core, until_addr, until_expr, NULL);
r_core_cmd0 (core, ".ar*");
break;
case 'o': // "aeso"
// step over
op = r_core_anal_op (core, r_reg_getv (core->anal->reg,
r_reg_get_name (core->anal->reg, R_REG_NAME_PC)));
if (op && op->type == R_ANAL_OP_TYPE_CALL) {
until_addr = op->addr + op->size;
}
r_core_esil_step (core, until_addr, until_expr, NULL);
r_anal_op_free (op);
r_core_cmd0 (core, ".ar*");
break;
case 'p': //"aesp"
n = strchr (input, ' ');
n1 = n ? strchr (n + 1, ' ') : NULL;
if ((!n || !n1) || (!(n + 1) || !(n1 + 1))) {
eprintf ("aesp [offset] [num]\n");
break;
}
adr = r_num_math (core->num, n + 1);
off = r_num_math (core->num, n1 + 1);
cmd_aespc (core, adr, off);
break;
case ' ':
n = strchr (input, ' ');
if (!(n + 1)) {
r_core_esil_step (core, until_addr, until_expr, NULL);
break;
}
off = r_num_math (core->num, n + 1);
cmd_aespc (core, -1, off);
break;
default:
r_core_esil_step (core, until_addr, until_expr, NULL);
r_core_cmd0 (core, ".ar*");
break;
}
break;
case 'c': // "aec"
if (input[1] == '?') { // "aec?"
r_core_cmd_help (core, help_msg_aec);
} else if (input[1] == 's') { // "aecs"
const char *pc = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
ut64 newaddr;
int ret;
for (;;) {
op = r_core_anal_op (core, addr);
if (!op) {
break;
}
if (op->type == R_ANAL_OP_TYPE_SWI) {
eprintf ("syscall at 0x%08" PFMT64x "\n", addr);
break;
}
if (op->type == R_ANAL_OP_TYPE_TRAP) {
eprintf ("trap at 0x%08" PFMT64x "\n", addr);
break;
}
ret = r_core_esil_step (core, UT64_MAX, NULL, NULL);
r_anal_op_free (op);
op = NULL;
if (core->anal->esil->trap || core->anal->esil->trap_code) {
break;
}
if (!ret)
break;
r_core_cmd0 (core, ".ar*");
newaddr = r_num_get (core->num, pc);
if (addr == newaddr) {
addr++;
break;
} else {
addr = newaddr;
}
}
if (op) {
r_anal_op_free (op);
}
} else {
// "aec" -> continue until ^C
// "aecu" -> until address
// "aecue" -> until esil expression
if (input[1] == 'u' && input[2] == 'e')
until_expr = input + 3;
else if (input[1] == 'u')
until_addr = r_num_math (core->num, input + 2);
else until_expr = "0";
r_core_esil_step (core, until_addr, until_expr, NULL);
r_core_cmd0 (core, ".ar*");
}
break;
case 'i': // "aei"
switch (input[1]) {
case 's':
case 'm': // "aeim"
cmd_esil_mem (core, input + 2);
break;
case 'p': // initialize pc = $$
r_core_cmd0 (core, "ar PC=$$");
break;
case '?':
cmd_esil_mem (core, "?");
break;
case '-':
if (esil) {
sdb_reset (esil->stats);
}
r_anal_esil_free (esil);
core->anal->esil = NULL;
break;
case 0: //lolololol
r_anal_esil_free (esil);
// reinitialize
{
const char *pc = r_reg_get_name (core->anal->reg, R_REG_NAME_PC);
if (r_reg_getv (core->anal->reg, pc) == 0LL) {
r_core_cmd0 (core, "ar PC=$$");
}
}
if (!(esil = core->anal->esil = r_anal_esil_new (stacksize, iotrap, addrsize))) {
return;
}
r_anal_esil_setup (esil, core->anal, romem, stats, noNULL); // setup io
esil->verbose = (int)r_config_get_i (core->config, "esil.verbose");
/* restore user settings for interrupt handling */
{
const char *s = r_config_get (core->config, "cmd.esil.intr");
if (s) {
char *my = strdup (s);
if (my) {
r_config_set (core->config, "cmd.esil.intr", my);
free (my);
}
}
}
break;
}
break;
case 'k': // "aek"
switch (input[1]) {
case '\0':
input = "123*";
/* fall through */
case ' ':
if (esil && esil->stats) {
char *out = sdb_querys (esil->stats, NULL, 0, input + 2);
if (out) {
r_cons_println (out);
free (out);
}
} else {
eprintf ("esil.stats is empty. Run 'aei'\n");
}
break;
case '-':
if (esil) {
sdb_reset (esil->stats);
}
break;
}
break;
case 'f': // "aef"
{
RListIter *iter;
RAnalBlock *bb;
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal,
core->offset, R_ANAL_FCN_TYPE_FCN | R_ANAL_FCN_TYPE_SYM);
if (fcn) {
// emulate every instruction in the function recursively across all the basic blocks
r_list_foreach (fcn->bbs, iter, bb) {
ut64 pc = bb->addr;
ut64 end = bb->addr + bb->size;
RAnalOp op;
ut8 *buf;
int ret, bbs = end - pc;
if (bbs < 1 || bbs > 0xfffff) {
eprintf ("Invalid block size\n");
}
// eprintf ("[*] Emulating 0x%08"PFMT64x" basic block 0x%08" PFMT64x " - 0x%08" PFMT64x "\r[", fcn->addr, pc, end);
buf = calloc (1, bbs + 1);
r_io_read_at (core->io, pc, buf, bbs);
int left;
while (pc < end) {
left = R_MIN (end - pc, 32);
r_asm_set_pc (core->assembler, pc);
ret = r_anal_op (core->anal, &op, addr, buf, left, R_ANAL_OP_MASK_ALL); // read overflow
if (ret) {
r_reg_set_value_by_role (core->anal->reg, R_REG_NAME_PC, pc);
r_anal_esil_parse (esil, R_STRBUF_SAFEGET (&op.esil));
r_anal_esil_dumpstack (esil);
r_anal_esil_stack_free (esil);
pc += op.size;
} else {
pc += 4; // XXX
}
}
}
} else {
eprintf ("Cannot find function at 0x%08" PFMT64x "\n", core->offset);
}
} break;
case 't': // "aet"
switch (input[1]) {
case 'r': // "aetr"
{
// anal ESIL to REIL.
RAnalEsil *esil = r_anal_esil_new (stacksize, iotrap, addrsize);
if (!esil)
return;
r_anal_esil_to_reil_setup (esil, core->anal, romem, stats);
r_anal_esil_set_pc (esil, core->offset);
r_anal_esil_parse (esil, input + 2);
r_anal_esil_dumpstack (esil);
r_anal_esil_free (esil);
break;
}
case 's': // "aets"
switch (input[2]) {
case 0:
r_anal_esil_session_list (esil);
break;
case '+':
r_anal_esil_session_add (esil);
break;
default:
r_core_cmd_help (core, help_msg_aets);
break;
}
break;
default:
eprintf ("Unknown command. Use `aetr`.\n");
break;
}
break;
case 'A': // "aeA"
if (input[1] == '?') {
r_core_cmd_help (core, help_msg_aea);
} else if (input[1] == 'r') {
cmd_aea (core, 1 + (1<<1), core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'w') {
cmd_aea (core, 1 + (1<<2), core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'n') {
cmd_aea (core, 1 + (1<<3), core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'j') {
cmd_aea (core, 1 + (1<<4), core->offset, r_num_math (core->num, input+2));
} else if (input[1] == '*') {
cmd_aea (core, 1 + (1<<5), core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'f') {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
if (fcn) {
cmd_aea (core, 1, fcn->addr, r_anal_fcn_size (fcn));
}
} else {
cmd_aea (core, 1, core->offset, (int)r_num_math (core->num, input+2));
}
break;
case 'a': // "aea"
if (input[1] == '?') {
r_core_cmd_help (core, help_msg_aea);
} else if (input[1] == 'r') {
cmd_aea (core, 1<<1, core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'w') {
cmd_aea (core, 1<<2, core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'n') {
cmd_aea (core, 1<<3, core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'j') {
cmd_aea (core, 1<<4, core->offset, r_num_math (core->num, input+2));
} else if (input[1] == '*') {
cmd_aea (core, 1<<5, core->offset, r_num_math (core->num, input+2));
} else if (input[1] == 'f') {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
// "aeafj"
if (fcn) {
switch (input[2]) {
case 'j': // "aeafj"
cmd_aea (core, 1<<4, fcn->addr, r_anal_fcn_size (fcn));
break;
default:
cmd_aea (core, 1, fcn->addr, r_anal_fcn_size (fcn));
break;
}
break;
}
} else {
const char *arg = input[1]? input + 2: "";
ut64 len = r_num_math (core->num, arg);
cmd_aea (core, 0, core->offset, len);
}
break;
case 'x': { // "aex"
char *hex;
int ret, bufsz;
input = r_str_trim_ro (input + 1);
hex = strdup (input);
if (!hex) {
break;
}
RAnalOp aop = R_EMPTY;
bufsz = r_hex_str2bin (hex, (ut8*)hex);
ret = r_anal_op (core->anal, &aop, core->offset,
(const ut8*)hex, bufsz, R_ANAL_OP_MASK_ALL);
if (ret>0) {
const char *str = R_STRBUF_SAFEGET (&aop.esil);
char *str2 = r_str_newf (" %s", str);
cmd_anal_esil (core, str2);
free (str2);
}
r_anal_op_fini (&aop);
break;
}
case '?': // "ae?"
if (input[1] == '?') {
r_core_cmd_help (core, help_detail_ae);
break;
}
/* fallthrough */
default:
r_core_cmd_help (core, help_msg_ae);
break;
}
}
static void cmd_anal_bytes(RCore *core, const char *input) {
int len = core->blocksize;
int tbs = len;
if (input[0]) {
len = (int)r_num_get (core->num, input + 1);
if (len > tbs) {
r_core_block_size (core, len);
}
}
core_anal_bytes (core, core->block, len, 0, input[0]);
if (tbs != core->blocksize) {
r_core_block_size (core, tbs);
}
}
static void cmd_anal_opcode(RCore *core, const char *input) {
int l, len = core->blocksize;
ut32 tbs = core->blocksize;
switch (input[0]) {
case '?':
r_core_cmd_help (core, help_msg_ao);
break;
case 's': // "aos"
case 'j': // "aoj"
case 'e': // "aoe"
case 'r': {
int count = 1;
if (input[1] && input[2]) {
l = (int)r_num_get (core->num, input + 1);
if (l > 0) {
count = l;
}
if (l > tbs) {
r_core_block_size (core, l * 4);
// len = l;
}
} else {
len = l = core->blocksize;
count = 1;
}
core_anal_bytes (core, core->block, len, count, input[0]);
}
break;
case '*':
r_core_anal_hint_list (core->anal, input[0]);
break;
default: {
int count = 0;
if (input[0]) {
l = (int)r_num_get (core->num, input + 1);
if (l > 0) {
count = l;
}
if (l > tbs) {
r_core_block_size (core, l * 4);
//len = l;
}
} else {
len = l = core->blocksize;
count = 1;
}
core_anal_bytes (core, core->block, len, count, 0);
break;
}
}
}
static void cmd_anal_jumps(RCore *core, const char *input) {
r_core_cmdf (core, "af @@= `ax~ref.code.jmp[1]`");
}
// TODO: cleanup to reuse code
static void cmd_anal_aftertraps(RCore *core, const char *input) {
int bufi, minop = 1; // 4
ut8 *buf;
RBinFile *binfile;
RAnalOp op;
ut64 addr, addr_end;
ut64 len = r_num_math (core->num, input);
if (len > 0xffffff) {
eprintf ("Too big\n");
return;
}
binfile = r_core_bin_cur (core);
if (!binfile) {
eprintf ("cur binfile NULL\n");
return;
}
addr = core->offset;
if (!len) {
// ignore search.in to avoid problems. analysis != search
RIOSection *sec = r_io_section_vget (core->io, addr);
if (sec && sec->flags & 1) {
// search in current section
if (sec->size > binfile->size) {
addr = sec->vaddr;
if (binfile->size > sec->paddr) {
len = binfile->size - sec->paddr;
} else {
eprintf ("Opps something went wrong aac\n");
return;
}
} else {
addr = sec->vaddr;
len = sec->size;
}
} else {
if (sec && sec->vaddr != sec->paddr && binfile->size > (core->offset - sec->vaddr + sec->paddr)) {
len = binfile->size - (core->offset - sec->vaddr + sec->paddr);
} else {
if (binfile->size > core->offset) {
len = binfile->size - core->offset;
} else {
eprintf ("Oops invalid range\n");
len = 0;
}
}
}
}
addr_end = addr + len;
if (!(buf = malloc (4096))) {
return;
}
bufi = 0;
int trapcount = 0;
int nopcount = 0;
r_cons_break_push (NULL, NULL);
while (addr < addr_end) {
if (r_cons_is_breaked ()) {
break;
}
// TODO: too many ioreads here
if (bufi > 4000) {
bufi = 0;
}
if (!bufi) {
r_io_read_at (core->io, addr, buf, 4096);
}
if (r_anal_op (core->anal, &op, addr, buf + bufi, 4096 - bufi, R_ANAL_OP_MASK_ALL)) {
if (op.size < 1) {
// XXX must be +4 on arm/mips/.. like we do in disasm.c
op.size = minop;
}
if (op.type == R_ANAL_OP_TYPE_TRAP) {
trapcount ++;
} else if (op.type == R_ANAL_OP_TYPE_NOP) {
nopcount ++;
} else {
if (nopcount > 1) {
r_cons_printf ("af @ 0x%08"PFMT64x"\n", addr);
nopcount = 0;
}
if (trapcount > 0) {
r_cons_printf ("af @ 0x%08"PFMT64x"\n", addr);
trapcount = 0;
}
}
} else {
op.size = minop;
}
addr += (op.size > 0)? op.size : 1;
bufi += (op.size > 0)? op.size : 1;
r_anal_op_fini (&op);
}
r_cons_break_pop ();
free (buf);
}
static void cmd_anal_blocks(RCore *core, const char *input) {
ut64 from , to;
char *arg = strchr (input, ' ');
r_cons_break_push (NULL, NULL);
#if 0
ls_foreach (core->io->sections, iter, s) {
/* is executable */
if (!(s->flags & R_IO_EXEC)) {
continue;
}
min = s->vaddr;
max = s->vaddr + s->vsize;
r_core_cmdf (core, "abb%s 0x%08"PFMT64x" @ 0x%08"PFMT64x, input, (max - min), min);
if (r_cons_is_breaked ()) {
goto ctrl_c;
}
}
if (ls_empty (core->io->sections)) {
min = core->offset;
max = 0xffff + min;
r_core_cmdf (core, "abb%s 0x%08"PFMT64x" @ 0x%08"PFMT64x, input, (max - min), min);
if (r_cons_is_breaked ()) {
goto ctrl_c;
}
}
#endif
if (!arg) {
RList *list = r_core_get_boundaries_prot (core, R_IO_EXEC, NULL, "anal");
RListIter *iter;
RIOMap* map;
r_list_foreach (list, iter, map) {
from = map->itv.addr;
to = r_itv_end (map->itv);
if (r_cons_is_breaked ()) {
goto ctrl_c;
}
if (!from && !to) {
eprintf ("Cannot determine search boundaries\n");
} else if (to - from > UT32_MAX) {
eprintf ("Skipping huge range\n");
} else {
r_core_cmdf (core, "abb 0x%08"PFMT64x" @ 0x%08"PFMT64x, (to - from), from);
}
}
} else {
int sz = r_num_math (core->num, arg + 1);
r_core_cmdf (core, "abb 0x%08"PFMT64x" @ 0x%08"PFMT64x, sz, core->offset);
}
ctrl_c:
r_cons_break_pop ();
}
static void _anal_calls(RCore *core, ut64 addr, ut64 addr_end) {
RAnalOp op;
int bufi;
int depth = r_config_get_i (core->config, "anal.depth");
const int addrbytes = core->io->addrbytes;
const int bsz = 4096;
ut8 *buf;
ut8 *block;
bufi = 0;
if (addr_end - addr > UT32_MAX) {
return;
}
buf = malloc (bsz);
block = malloc (bsz);
if (!buf || !block) {
eprintf ("Error: cannot allocate buf or block\n");
free (buf);
free (block);
return;
}
int minop = r_anal_archinfo (core->anal, R_ANAL_ARCHINFO_MIN_OP_SIZE);
if (minop < 1) {
minop = 1;
}
while (addr < addr_end) {
if (r_cons_is_breaked ()) {
break;
}
// TODO: too many ioreads here
if (bufi > 4000) {
bufi = 0;
}
if (!bufi) {
r_io_read_at (core->io, addr, buf, bsz);
}
memset (block, -1, bsz);
if (!memcmp (buf, block, bsz)) {
//eprintf ("Error: skipping uninitialized block \n");
addr += bsz;
continue;
}
memset (block, 0, bsz);
if (!memcmp (buf, block, bsz)) {
//eprintf ("Error: skipping uninitialized block \n");
addr += bsz;
continue;
}
if (r_anal_op (core->anal, &op, addr, buf + bufi, bsz - bufi, 0) > 0) {
if (op.size < 1) {
op.size = minop;
}
if (op.type == R_ANAL_OP_TYPE_CALL) {
#if JAYRO_03
#error FUCK
if (!anal_is_bad_call (core, from, to, addr, buf, bufi)) {
fcn = r_anal_get_fcn_in (core->anal, op.jump, R_ANAL_FCN_TYPE_ROOT);
if (!fcn) {
r_core_anal_fcn (core, op.jump, addr,
R_ANAL_REF_TYPE_NULL, depth);
}
}
#else
// add xref here
r_anal_xrefs_set (core->anal, R_ANAL_REF_TYPE_CALL, addr, op.jump);
if (r_io_is_valid_offset (core->io, op.jump, 1)) {
r_core_anal_fcn (core, op.jump, addr, R_ANAL_REF_TYPE_NULL, depth);
}
#endif
}
} else {
op.size = minop;
}
if ((int)op.size < 1) {
op.size = minop;
}
addr += op.size;
bufi += addrbytes * op.size;
r_anal_op_fini (&op);
}
free (buf);
free (block);
}
static void cmd_anal_calls(RCore *core, const char *input, bool only_print_flag) {
RList *ranges = NULL;
RIOMap *r;
RBinFile *binfile;
ut64 addr;
ut64 len = r_num_math (core->num, input);
if (len > 0xffffff) {
eprintf ("Too big\n");
return;
}
binfile = r_core_bin_cur (core);
addr = core->offset;
if (binfile) {
if (len) {
RIOMap *m = R_NEW0 (RIOMap);
m->itv.addr = addr;
m->itv.size = len;
r_list_append (ranges, m);
} else {
ranges = r_core_get_boundaries_prot (core, R_IO_EXEC, NULL, "anal");
}
}
r_cons_break_push (NULL, NULL);
if (!binfile || !r_list_length (ranges)) {
RListIter *iter;
RIOMap *map;
r_list_free (ranges);
ranges = r_core_get_boundaries_prot (core, 0, NULL, "anal");
r_list_foreach (ranges, iter, map) {
ut64 addr = map->itv.addr;
if (only_print_flag) {
r_cons_printf ("f fcn.0x%08"PFMT64x" %d 0x%08"PFMT64x"\n",
addr, map->itv.size, addr);
} else {
_anal_calls (core, addr, r_itv_end (map->itv));
}
}
} else {
RListIter *iter;
if (binfile) {
r_list_foreach (ranges, iter, r) {
addr = r->itv.addr;
//this normally will happen on fuzzed binaries, dunno if with huge
//binaries as well
if (r_cons_is_breaked ()) {
break;
}
if (only_print_flag) {
r_cons_printf ("f fcn.0x%08"PFMT64x" %d 0x%08"PFMT64x"\n",
addr, r->itv.size, addr);
} else {
_anal_calls (core, addr, r_itv_end (r->itv));
}
}
}
}
r_cons_break_pop ();
r_list_free (ranges);
}
static void cmd_asf(RCore *core, const char *input) {
char *ret;
if (input[0] == ' ') {
ret = sdb_querys (core->anal->sdb_fcnsign, NULL, 0, input + 1);
} else {
ret = sdb_querys (core->anal->sdb_fcnsign, NULL, 0, "*");
}
if (ret && *ret) {
r_cons_println (ret);
}
free (ret);
}
static void cmd_anal_syscall(RCore *core, const char *input) {
RSyscallItem *si;
RListIter *iter;
RList *list;
RNum *num = NULL;
char *out;
int n;
switch (input[0]) {
case 'c': // "asc"
if (input[1] == 'a') {
if (input[2] == ' ') {
if (!isalpha (input[3]) && (n = r_num_math (num, input + 3)) >= 0 ) {
si = r_syscall_get (core->anal->syscall, n, -1);
if (si)
r_cons_printf (".equ SYS_%s %d\n", si->name, n);
else eprintf ("Unknown syscall number\n");
} else {
n = r_syscall_get_num (core->anal->syscall, input + 3);
if (n != -1) {
r_cons_printf (".equ SYS_%s %d\n", input + 3, n);
} else {
eprintf ("Unknown syscall name\n");
}
}
} else {
list = r_syscall_list (core->anal->syscall);
r_list_foreach (list, iter, si) {
r_cons_printf (".equ SYS_%s %d\n",
si->name, (ut32)si->num);
}
r_list_free (list);
}
} else {
if (input[1] == ' ') {
if (!isalpha (input[2]) && (n = r_num_math (num, input + 2)) >= 0 ) {
si = r_syscall_get (core->anal->syscall, n, -1);
if (si)
r_cons_printf ("#define SYS_%s %d\n", si->name, n);
else eprintf ("Unknown syscall number\n");
} else {
n = r_syscall_get_num (core->anal->syscall, input + 2);
if (n != -1) {
r_cons_printf ("#define SYS_%s %d\n", input + 2, n);
} else {
eprintf ("Unknown syscall name\n");
}
}
} else {
list = r_syscall_list (core->anal->syscall);
r_list_foreach (list, iter, si) {
r_cons_printf ("#define SYS_%s %d\n",
si->name, (ut32)si->num);
}
r_list_free (list);
}
}
break;
case 'f': // "asf"
cmd_asf (core, input + 1);
break;
case 'l': // "asl"
if (input[1] == ' ') {
if (!isalpha (input[2]) && (n = r_num_math (num, input + 2)) >= 0 ) {
si = r_syscall_get (core->anal->syscall, n, -1);
if (si)
r_cons_println (si->name);
else eprintf ("Unknown syscall number\n");
} else {
n = r_syscall_get_num (core->anal->syscall, input + 2);
if (n != -1) {
r_cons_printf ("%d\n", n);
} else {
eprintf ("Unknown syscall name\n");
}
}
} else {
list = r_syscall_list (core->anal->syscall);
r_list_foreach (list, iter, si) {
r_cons_printf ("%s = 0x%02x.%u\n",
si->name, (ut32)si->swi, (ut32)si->num);
}
r_list_free (list);
}
break;
case 'j': // "asj"
list = r_syscall_list (core->anal->syscall);
r_cons_printf ("[");
r_list_foreach (list, iter, si) {
r_cons_printf ("{\"name\":\"%s\","
"\"swi\":\"%d\",\"num\":\"%d\"}",
si->name, si->swi, si->num);
if (iter->n) {
r_cons_printf (",");
}
}
r_cons_printf ("]\n");
r_list_free (list);
// JSON support
break;
case '\0':
cmd_syscall_do (core, -1); //n);
break;
case ' ':
cmd_syscall_do (core, (int)r_num_get (core->num, input + 1));
break;
case 'k': // "ask"
if (input[1] == ' ') {
out = sdb_querys (core->anal->syscall->db, NULL, 0, input + 2);
if (out) {
r_cons_println (out);
free (out);
}
} else eprintf ("|ERROR| Usage: ask [query]\n");
break;
default:
case '?':
r_core_cmd_help (core, help_msg_as);
break;
}
}
static void anal_axg (RCore *core, const char *input, int level, Sdb *db, int opts) {
char arg[32], pre[128];
RList *xrefs;
RListIter *iter;
RAnalRef *ref;
ut64 addr = core->offset;
int is_json = opts & R_CORE_ANAL_JSON;
if (input && *input) {
addr = r_num_math (core->num, input);
}
int spaces = (level + 1) * 2;
if (spaces > sizeof (pre) - 4) {
spaces = sizeof (pre) - 4;
}
memset (pre, ' ', sizeof (pre));
strcpy (pre+spaces, "- ");
xrefs = r_anal_xrefs_get (core->anal, addr);
if (!r_list_empty (xrefs)) {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, -1);
if (fcn) {
if (is_json) {
r_cons_printf ("{\"%"PFMT64d"\":{\"type\":\"fcn\","
"\"fcn_addr\":%"PFMT64d",\"name\":\"%s\",\"refs\":[",
addr, fcn->addr, fcn->name);
} else {
//if (sdb_add (db, fcn->name, "1", 0)) {
r_cons_printf ("%s0x%08"PFMT64x" fcn 0x%08"PFMT64x" %s\n",
pre + 2, addr, fcn->addr, fcn->name);
//}
}
} else {
if (is_json) {
r_cons_printf ("{\"%"PFMT64d"\":{\"refs\":[", addr);
} else {
//snprintf (arg, sizeof (arg), "0x%08"PFMT64x, addr);
//if (sdb_add (db, arg, "1", 0)) {
r_cons_printf ("%s0x%08"PFMT64x"\n", pre+2, addr);
//}
}
}
}
r_list_foreach (xrefs, iter, ref) {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, ref->addr, -1);
if (fcn) {
if (is_json) {
if (level == 0) {
r_cons_printf ("{\"%"PFMT64d"\":{\"type\":\"fcn\",\"fcn_addr\": %"PFMT64d",\"name\":\"%s\",\"refs\":[", ref->addr, fcn->addr, fcn->name);
} else {
r_cons_printf ("]}},{\"%"PFMT64d"\":{\"type\":\"fcn\",\"fcn_addr\": %"PFMT64d",\"name\":\"%s\",\"refs\":[", ref->addr, fcn->addr, fcn->name);
}
} else {
r_cons_printf ("%s0x%08"PFMT64x" fcn 0x%08"PFMT64x" %s\n", pre, ref->addr, fcn->addr, fcn->name);
}
if (sdb_add (db, fcn->name, "1", 0)) {
snprintf (arg, sizeof (arg), "0x%08"PFMT64x, fcn->addr);
anal_axg (core, arg, level+1, db, opts);
} else {
if (is_json) {
r_cons_printf("]}}");
}
}
if (is_json) {
if (iter->n) {
r_cons_printf (",");
}
}
} else {
if (is_json) {
r_cons_printf ("{\"%"PFMT64d"\":{\"type\":\"???\",\"refs\":[", ref->addr);
} else {
r_cons_printf ("%s0x%08"PFMT64x" ???\n", pre, ref->addr);
}
snprintf (arg, sizeof (arg), "0x%08"PFMT64x, ref->addr);
if (sdb_add (db, arg, "1", 0)) {
anal_axg (core, arg, level +1, db, opts);
} else {
if (is_json) {
r_cons_printf("]}}");
}
}
if (is_json) {
if (iter->n) {
r_cons_printf (",");
}
}
}
}
if (is_json) {
r_cons_printf("]}}");
if (level == 0) {
r_cons_printf("\n");
}
}
r_list_free (xrefs);
}
static void cmd_anal_ucall_ref (RCore *core, ut64 addr) {
RAnalFunction * fcn = r_anal_get_fcn_at (core->anal, addr, R_ANAL_FCN_TYPE_NULL);
if (fcn) {
r_cons_printf (" ; %s", fcn->name);
} else {
r_cons_printf (" ; 0x%" PFMT64x, addr);
}
}
static bool cmd_anal_refs(RCore *core, const char *input) {
ut64 addr = core->offset;
switch (input[0]) {
case '-': { // "ax-"
RList *list;
RListIter *iter;
RAnalRef *ref;
char *cp_inp = strdup (input + 1);
char *ptr = r_str_trim_head (cp_inp);
if (!strcmp (ptr, "*")) {
r_anal_xrefs_init (core->anal);
} else {
int n = r_str_word_set0 (ptr);
ut64 from = UT64_MAX, to = UT64_MAX;
switch (n) {
case 2:
from = r_num_math (core->num, r_str_word_get0 (ptr, 1));
//fall through
case 1: // get addr
to = r_num_math (core->num, r_str_word_get0 (ptr, 0));
break;
default:
to = core->offset;
break;
}
list = r_anal_xrefs_get (core->anal, to);
if (list) {
r_list_foreach (list, iter, ref) {
if (from != UT64_MAX && from == ref->addr) {
r_anal_ref_del (core->anal, ref->addr, ref->at);
}
if (from == UT64_MAX) {
r_anal_ref_del (core->anal, ref->addr, ref->at);
}
}
r_list_free (list);
}
}
free (cp_inp);
} break;
case 'g': // "axg"
{
Sdb *db = sdb_new0 ();
if(input[1] == '\0') {
anal_axg (core, input[1] ? input + 2 : NULL, 0, db, 0);
} else if(input[1] == 'j') {
anal_axg (core, input[1] ? input + 2 : NULL, 0, db, R_CORE_ANAL_JSON);
}
sdb_free (db);
}
break;
case 'k': // "axk"
if (input[1] == '?') {
eprintf ("Usage: axk [query]\n");
} else if (input[1] == ' ') {
sdb_query (core->anal->sdb_xrefs, input + 2);
} else {
r_core_anal_ref_list (core, 'k');
}
break;
case '\0': // "ax"
case 'j': // "axj"
case 'q': // "axq"
case '*': // "ax*"
r_core_anal_ref_list (core, input[0]);
break;
case 't': { // "axt"
const int size = 12;
RList *list;
RAnalFunction *fcn;
RAnalRef *ref;
RListIter *iter;
ut8 buf[12];
RAsmOp asmop;
char *buf_asm = NULL;
char *space = strchr (input, ' ');
if (space) {
addr = r_num_math (core->num, space + 1);
} else {
addr = core->offset;
}
list = r_anal_xrefs_get (core->anal, addr);
if (list) {
if (input[1] == 'q') { // "axtq"
r_list_foreach (list, iter, ref) {
r_cons_printf ("0x%" PFMT64x "\n", ref->addr);
}
} else if (input[1] == 'j') { // "axtj"
bool asm_varsub = r_config_get_i (core->config, "asm.varsub");
core->parser->relsub = r_config_get_i (core->config, "asm.relsub");
core->parser->localvar_only = r_config_get_i (core->config, "asm.varsub_only");
r_cons_printf ("[");
r_list_foreach (list, iter, ref) {
r_core_read_at (core, ref->addr, buf, size);
r_asm_set_pc (core->assembler, ref->addr);
r_asm_disassemble (core->assembler, &asmop, buf, size);
char str[512];
fcn = r_anal_get_fcn_in (core->anal, ref->addr, 0);
if (asm_varsub) {
r_parse_varsub (core->parser, fcn, ref->addr, asmop.size,
asmop.buf_asm, asmop.buf_asm, sizeof (asmop.buf_asm));
}
r_parse_filter (core->parser, core->flags,
asmop.buf_asm, str, sizeof (str), core->print->big_endian);
r_cons_printf ("{\"from\":%" PFMT64u ",\"type\":\"%s\",\"opcode\":\"%s\"", ref->addr, r_anal_ref_to_string (ref->type), str);
if (fcn) {
r_cons_printf (",\"fcn_addr\":%"PFMT64d",\"fcn_name\":\"%s\"", fcn->addr, fcn->name);
}
RFlagItem *fi = r_flag_get_at (core->flags, fcn? fcn->addr: ref->addr, true);
if (fi) {
if (fcn && strcmp (fcn->name, fi->name)) {
r_cons_printf (",\"flag\":\"%s\"", fi->name);
}
if (fi->realname && strcmp (fi->name, fi->realname)) {
r_cons_printf (",\"realname\":\"%s\"", fi->realname);
}
}
r_cons_printf ("}%s", iter->n? ",": "");
}
r_cons_printf ("]");
r_cons_newline ();
} else if (input[1] == 'g') { // axtg
r_list_foreach (list, iter, ref) {
char *str = r_core_cmd_strf (core, "fd 0x%"PFMT64x, ref->addr);
if (!str) {
str = strdup ("?\n");
}
r_str_trim_tail (str);
r_cons_printf ("agn 0x%" PFMT64x " \"%s\"\n", ref->addr, str);
free (str);
}
if (input[2] != '*') {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, addr, 0);
r_cons_printf ("agn 0x%" PFMT64x " \"%s\"\n", addr, fcn?fcn->name: "$$");
}
r_list_foreach (list, iter, ref) {
r_cons_printf ("age 0x%" PFMT64x " 0x%"PFMT64x"\n", ref->addr, addr);
}
} else if (input[1] == '*') { // axt*
// TODO: implement multi-line comments
r_list_foreach (list, iter, ref)
r_cons_printf ("CCa 0x%" PFMT64x " \"XREF type %d at 0x%" PFMT64x"%s\n",
ref->addr, ref->type, addr, iter->n? ",": "");
} else { // axt
int has_color = core->print->flags & R_PRINT_FLAGS_COLOR;
char str[512];
RAnalFunction *fcn;
char *comment;
bool asm_varsub = r_config_get_i (core->config, "asm.varsub");
core->parser->relsub = r_config_get_i (core->config, "asm.relsub");
core->parser->localvar_only = r_config_get_i (core->config, "asm.varsub_only");
if (core->parser->relsub) {
core->parser->relsub_addr = addr;
}
r_list_foreach (list, iter, ref) {
r_core_read_at (core, ref->addr, buf, size);
r_asm_set_pc (core->assembler, ref->addr);
r_asm_disassemble (core->assembler, &asmop, buf, size);
fcn = r_anal_get_fcn_in (core->anal, ref->addr, 0);
if (asm_varsub) {
r_parse_varsub (core->parser, fcn, ref->addr, asmop.size,
asmop.buf_asm, asmop.buf_asm, sizeof (asmop.buf_asm));
}
r_parse_filter (core->parser, core->flags,
asmop.buf_asm, str, sizeof (str), core->print->big_endian);
if (has_color) {
buf_asm = r_print_colorize_opcode (core->print, str,
core->cons->pal.reg, core->cons->pal.num, false);
} else {
buf_asm = r_str_new (str);
}
comment = r_meta_get_string (core->anal, R_META_TYPE_COMMENT, ref->addr);
char *buf_fcn = comment
? r_str_newf ("%s; %s", fcn ? fcn->name : "(nofunc)", strtok (comment, "\n"))
: r_str_newf ("%s", fcn ? fcn->name : "(nofunc)");
r_cons_printf ("%s 0x%" PFMT64x " [%s] %s\n",
buf_fcn, ref->addr, r_anal_ref_to_string (ref->type), buf_asm);
free (buf_asm);
free (buf_fcn);
}
}
r_list_free (list);
} else {
if (input[1] == 'j') { // "axtj"
r_cons_print ("[]\n");
}
}
} break;
case 'f': { // "axf"
ut8 buf[12];
RAsmOp asmop;
char *buf_asm = NULL;
RList *list, *list_ = NULL;
RAnalRef *ref;
RListIter *iter;
char *space = strchr (input, ' ');
if (space) {
addr = r_num_math (core->num, space + 1);
} else {
addr = core->offset;
}
if (input[1] == '.') { // axf.
list = list_ = r_anal_xrefs_get_from (core->anal, addr);
if (!list) {
RAnalFunction * fcn = r_anal_get_fcn_in (core->anal, addr, 0);
list = r_anal_fcn_get_refs (core->anal, fcn);
}
} else {
list = r_anal_refs_get (core->anal, addr);
}
if (list) {
if (input[1] == 'q') { // axfq
r_list_foreach (list, iter, ref) {
r_cons_printf ("0x%" PFMT64x "\n", ref->at);
}
} else if (input[1] == 'j') { // axfj
r_cons_print ("[");
r_list_foreach (list, iter, ref) {
r_core_read_at (core, ref->at, buf, 12);
r_asm_set_pc (core->assembler, ref->at);
r_asm_disassemble (core->assembler, &asmop, buf, 12);
r_cons_printf ("{\"from\":%" PFMT64d ",\"to\":%" PFMT64d ",\"type\":\"%s\",\"opcode\":\"%s\"}%s",
ref->at, ref->addr, r_anal_ref_to_string (ref->type), asmop.buf_asm, iter->n? ",": "");
}
r_cons_print ("]\n");
} else if (input[1] == '*') { // axf*
// TODO: implement multi-line comments
r_list_foreach (list, iter, ref) {
r_cons_printf ("CCa 0x%" PFMT64x " \"XREF from 0x%" PFMT64x "\n",
ref->at, ref->type, asmop.buf_asm, iter->n? ",": "");
}
} else { // axf
char str[512];
int has_color = core->print->flags & R_PRINT_FLAGS_COLOR;
r_list_foreach (list, iter, ref) {
r_core_read_at (core, ref->at, buf, 12);
r_asm_set_pc (core->assembler, ref->at);
r_asm_disassemble (core->assembler, &asmop, buf, 12);
r_parse_filter (core->parser, core->flags,
asmop.buf_asm, str, sizeof (str), core->print->big_endian);
if (has_color) {
buf_asm = r_print_colorize_opcode (core->print, str,
core->cons->pal.reg, core->cons->pal.num, false);
} else {
buf_asm = r_str_new (str);
}
r_cons_printf ("%c 0x%" PFMT64x " %s",
ref->type, ref->at, buf_asm);
if (ref->type == R_ANAL_REF_TYPE_CALL) {
RAnalOp aop;
r_anal_op (core->anal, &aop, ref->at, buf, 12, R_ANAL_OP_MASK_ALL);
if (aop.type == R_ANAL_OP_TYPE_UCALL) {
cmd_anal_ucall_ref (core, ref->addr);
}
}
r_cons_newline ();
free (buf_asm);
}
}
r_list_free (list_);
r_list_free (list);
} else {
if (input[1] == 'j') { // axfj
r_cons_print ("[]\n");
}
}
} break;
case 'F':
find_refs (core, input + 1);
break;
case 'C': // "axC"
case 'c': // "axc"
case 'd': // "axd"
case ' ': // "ax "
{
char *ptr = strdup (r_str_trim_head ((char *)input + 1));
int n = r_str_word_set0 (ptr);
ut64 at = core->offset;
ut64 addr = UT64_MAX;
switch (n) {
case 2: // get at
at = r_num_math (core->num, r_str_word_get0 (ptr, 1));
/* fall through */
case 1: // get addr
addr = r_num_math (core->num, r_str_word_get0 (ptr, 0));
break;
default:
free (ptr);
return false;
}
r_anal_xrefs_set (core->anal, input[0], at, addr);
free (ptr);
}
break;
default:
case '?':
r_core_cmd_help (core, help_msg_ax);
break;
}
return true;
}
static void cmd_anal_hint(RCore *core, const char *input) {
switch (input[0]) {
case '?':
if (input[1]) {
ut64 addr = r_num_math (core->num, input + 1);
r_core_anal_hint_print (core->anal, addr, 0);
} else {
r_core_cmd_help (core, help_msg_ah);
}
break;
case '.': // "ah."
r_core_anal_hint_print (core->anal, core->offset, 0);
break;
case 'a': // "aha" set arch
if (input[1]) {
int i;
char *ptr = strdup (input + 2);
i = r_str_word_set0 (ptr);
if (i == 2) {
r_num_math (core->num, r_str_word_get0 (ptr, 1));
}
r_anal_hint_set_arch (core->anal, core->offset, r_str_word_get0 (ptr, 0));
free (ptr);
} else if (input[1] == '-') {
r_anal_hint_unset_arch (core->anal, core->offset);
} else {
eprintf ("Missing argument\n");
}
break;
case 'b': // "ahb" set bits
if (input[1]) {
char *ptr = strdup (input + 2);
int bits;
int i = r_str_word_set0 (ptr);
if (i == 2) {
r_num_math (core->num, r_str_word_get0 (ptr, 1));
}
bits = r_num_math (core->num, r_str_word_get0 (ptr, 0));
r_anal_hint_set_bits (core->anal, core->offset, bits);
free (ptr);
} else if (input[1] == '-') {
r_anal_hint_unset_bits (core->anal, core->offset);
} else {
eprintf ("Missing argument\n");
}
break;
case 'i': // "ahi"
if (input[1] == '?') {
r_core_cmd_help (core, help_msg_ahi);
} else if (input[1] == ' ') {
// You can either specify immbase with letters, or numbers
const int base =
(input[2] == 's') ? 1 :
(input[2] == 'b') ? 2 :
(input[2] == 'p') ? 3 :
(input[2] == 'o') ? 8 :
(input[2] == 'd') ? 10 :
(input[2] == 'h') ? 16 :
(input[2] == 'i') ? 32 : // ip address
(input[2] == 'S') ? 80 : // syscall
(int) r_num_math (core->num, input + 1);
r_anal_hint_set_immbase (core->anal, core->offset, base);
} else if (input[1] == '-') { // "ahi-"
r_anal_hint_set_immbase (core->anal, core->offset, 0);
} else {
eprintf ("|ERROR| Usage: ahi [base]\n");
}
break;
case 'h': // "ahh"
if (input[1] == '-') {
r_anal_hint_unset_high (core->anal, core->offset);
} else if (input[1] == ' ') {
r_anal_hint_set_high (core->anal, r_num_math (core->num, input + 1));
} else {
r_anal_hint_set_high (core->anal, core->offset);
}
break;
case 'c': // "ahc"
if (input[1] == ' ') {
r_anal_hint_set_jump (
core->anal, core->offset,
r_num_math (core->num, input + 1));
} else if (input[1] == '-') {
r_anal_hint_unset_jump (core->anal, core->offset);
}
break;
case 'f': // "ahf"
if (input[1] == ' ') {
r_anal_hint_set_fail (
core->anal, core->offset,
r_num_math (core->num, input + 1));
} else if (input[1] == '-') {
r_anal_hint_unset_fail (core->anal, core->offset);
}
break;
case 's': // "ahs" set size (opcode length)
if (input[1] == ' ') {
r_anal_hint_set_size (core->anal, core->offset, atoi (input + 1));
} else if (input[1] == '-') {
r_anal_hint_unset_size (core->anal, core->offset);
} else {
eprintf ("Usage: ahs 16\n");
}
break;
case 'S': // "ahS" set size (opcode length)
if (input[1] == ' ') {
r_anal_hint_set_syntax (core->anal, core->offset, input + 2);
} else if (input[1] == '-') {
r_anal_hint_unset_syntax (core->anal, core->offset);
} else {
eprintf ("Usage: ahS att\n");
}
break;
case 'o': // "aho" set opcode string
if (input[1] == ' ') {
r_anal_hint_set_opcode (core->anal, core->offset, input + 2);
} else if (input[1] == '-') {
r_anal_hint_unset_opcode (core->anal, core->offset);
} else {
eprintf ("Usage: aho popall\n");
}
break;
case 'e': // "ahe" set ESIL string
if (input[1] == ' ') {
r_anal_hint_set_esil (core->anal, core->offset, input + 2);
} else if (input[1] == '-') {
r_anal_hint_unset_esil (core->anal, core->offset);
} else {
eprintf ("Usage: ahe r0,pc,=\n");
}
break;
#if 0
case 'e': // set endian
if (input[1] == ' ') {
r_anal_hint_set_opcode (core->anal, core->offset, atoi (input + 1));
} else if (input[1] == '-') {
r_anal_hint_unset_opcode (core->anal, core->offset);
}
break;
#endif
case 'p': // "ahp"
if (input[1] == ' ') {
r_anal_hint_set_pointer (core->anal, core->offset, r_num_math (core->num, input + 1));
} else if (input[1] == '-') { // "ahp-"
r_anal_hint_unset_pointer (core->anal, core->offset);
}
break;
case '*': // "ah*"
if (input[1] == ' ') {
char *ptr = strdup (r_str_trim_ro (input + 2));
r_str_word_set0 (ptr);
ut64 addr = r_num_math (core->num, r_str_word_get0 (ptr, 0));
r_core_anal_hint_print (core->anal, addr, '*');
} else {
r_core_anal_hint_list (core->anal, input[0]);
}
break;
case 'j': // "ahj"
case '\0': // "ah"
r_core_anal_hint_list (core->anal, input[0]);
break;
case '-': // "ah-"
if (input[1]) {
if (input[1] == '*') {
r_anal_hint_clear (core->anal);
} else {
char *ptr = strdup (r_str_trim_ro (input + 1));
ut64 addr;
int size = 1;
int i = r_str_word_set0 (ptr);
if (i == 2) {
size = r_num_math (core->num, r_str_word_get0 (ptr, 1));
}
const char *a0 = r_str_word_get0 (ptr, 0);
if (a0 && *a0) {
addr = r_num_math (core->num, a0);
} else {
addr = core->offset;
}
r_anal_hint_del (core->anal, addr, size);
free (ptr);
}
} else {
r_anal_hint_clear (core->anal);
}
break;
}
}
static void agraph_print_node_dot(RANode *n, void *user) {
char *label = strdup (n->body);
//label = r_str_replace (label, "\n", "\\l", 1);
if (!label || !*label) {
r_cons_printf ("\"%s\" [URL=\"%s\", color=\"lightgray\", label=\"%s\"]\n",
n->title, n->title, n->title);
} else {
r_cons_printf ("\"%s\" [URL=\"%s\", color=\"lightgray\", label=\"%s\\n%s\"]\n",
n->title, n->title, n->title, label);
}
free (label);
}
static void agraph_print_node(RANode *n, void *user) {
char *encbody, *cmd;
int len = strlen (n->body);
if (n->body[len - 1] == '\n') {
len--;
}
encbody = r_base64_encode_dyn (n->body, len);
cmd = r_str_newf ("agn \"%s\" base64:%s\n", n->title, encbody);
r_cons_printf (cmd);
free (cmd);
free (encbody);
}
static void agraph_print_edge_dot(RANode *from, RANode *to, void *user) {
r_cons_printf ("\"%s\" -> \"%s\"\n", from->title, to->title);
}
static void agraph_print_edge(RANode *from, RANode *to, void *user) {
r_cons_printf ("age \"%s\" \"%s\"\n", from->title, to->title);
}
static void cmd_agraph_node(RCore *core, const char *input) {
switch (*input) {
case ' ': { // "agn"
char *newbody = NULL;
char **args, *body;
int n_args, B_LEN = strlen ("base64:");
input++;
args = r_str_argv (input, &n_args);
if (n_args < 1 || n_args > 2) {
r_cons_printf ("Wrong arguments\n");
r_str_argv_free (args);
break;
}
// strdup cause there is double free in r_str_argv_free due to a realloc call
if (n_args > 1) {
body = strdup (args[1]);
if (strncmp (body, "base64:", B_LEN) == 0) {
body = r_str_replace (body, "\\n", "", true);
newbody = (char *)r_base64_decode_dyn (body + B_LEN, -1);
free (body);
if (!newbody) {
eprintf ("Cannot allocate buffer\n");
r_str_argv_free (args);
break;
}
body = newbody;
}
body = r_str_append (body, "\n");
} else {
body = strdup ("");
}
r_agraph_add_node (core->graph, args[0], body);
r_str_argv_free (args);
free (body);
//free newbody it's not necessary since r_str_append reallocate the space
break;
}
case '-': { // "agn-"
char **args;
int n_args;
input++;
args = r_str_argv (input, &n_args);
if (n_args != 1) {
r_cons_printf ("Wrong arguments\n");
r_str_argv_free (args);
break;
}
r_agraph_del_node (core->graph, args[0]);
r_str_argv_free (args);
break;
}
case '?':
default:
r_core_cmd_help (core, help_msg_agn);
break;
}
}
static void cmd_agraph_edge(RCore *core, const char *input) {
switch (*input) {
case ' ': // "age"
case '-': { // "age-"
RANode *u, *v;
char **args;
int n_args;
args = r_str_argv (input + 1, &n_args);
if (n_args != 2) {
r_cons_printf ("Wrong arguments\n");
r_str_argv_free (args);
break;
}
u = r_agraph_get_node (core->graph, args[0]);
v = r_agraph_get_node (core->graph, args[1]);
if (!u || !v) {
if (!u) {
r_cons_printf ("Node %s not found!\n", args[0]);
} else {
r_cons_printf ("Node %s not found!\n", args[1]);
}
r_str_argv_free (args);
break;
}
if (*input == ' ') {
r_agraph_add_edge (core->graph, u, v);
} else {
r_agraph_del_edge (core->graph, u, v);
}
r_str_argv_free (args);
break;
}
case '?':
default:
r_core_cmd_help (core, help_msg_age);
break;
}
}
static void cmd_agraph_print(RCore *core, const char *input) {
switch (*input) {
case 'k': // "aggk"
{
Sdb *db = r_agraph_get_sdb (core->graph);
char *o = sdb_querys (db, "null", 0, "*");
r_cons_print (o);
free (o);
break;
}
case 'v': // "aggv"
{
const char *cmd = r_config_get (core->config, "cmd.graph");
if (cmd && *cmd) {
char *newCmd = strdup (cmd);
if (newCmd) {
newCmd = r_str_replace (newCmd, "ag $$", "aggd", 0);
r_core_cmd0 (core, newCmd);
free (newCmd);
}
} else {
r_core_cmd0 (core, "agf");
}
break;
}
case 'i': // "aggi" - open current core->graph in interactive mode
{
RANode *ran = r_agraph_get_first_node (core->graph);
if (ran) {
r_agraph_set_title (core->graph, r_config_get (core->config, "graph.title"));
r_agraph_set_curnode (core->graph, ran);
core->graph->force_update_seek = true;
core->graph->need_set_layout = true;
core->graph->layout = r_config_get_i (core->config, "graph.layout");
int ov = r_config_get_i (core->config, "scr.interactive");
core->graph->need_update_dim = true;
r_core_visual_graph (core, core->graph, NULL, true);
r_config_set_i (core->config, "scr.interactive", ov);
r_cons_show_cursor (true);
} else {
eprintf ("This graph contains no nodes\n");
}
break;
}
case 'd': // "aggd" - dot format
r_cons_printf ("digraph code {\ngraph [bgcolor=white];\n"
"node [color=lightgray, style=filled shape=box "
"fontname=\"Courier\" fontsize=\"8\"];\n");
r_agraph_foreach (core->graph, agraph_print_node_dot, NULL);
r_agraph_foreach_edge (core->graph, agraph_print_edge_dot, NULL);
r_cons_printf ("}\n");
break;
case '*': // "agg*" -
r_agraph_foreach (core->graph, agraph_print_node, NULL);
r_agraph_foreach_edge (core->graph, agraph_print_edge, NULL);
break;
case '?':
r_core_cmd_help (core, help_msg_agg);
break;
default:
core->graph->can->linemode = r_config_get_i (core->config, "graph.linemode");
core->graph->can->color = r_config_get_i (core->config, "scr.color");
r_agraph_set_title (core->graph,
r_config_get (core->config, "graph.title"));
r_agraph_print (core->graph);
break;
}
}
static void cmd_anal_graph(RCore *core, const char *input) {
RList *list;
const char *arg;
switch (input[0]) {
case 'f': // "agf"
switch (input[1]) {
case 't':// "agft" - tiny graph
r_core_visual_graph (core, NULL, NULL, 2);
break;
case 0:
r_core_visual_graph (core, NULL, NULL, false);
break;
default:
eprintf ("Usage: agf or agft (for tiny)\n");
break;
}
break;
case '-': // "ag-"
r_agraph_reset (core->graph);
break;
case 'n': // "agn"
cmd_agraph_node (core, input + 1);
break;
case 'e': // "age"
cmd_agraph_edge (core, input + 1);
break;
case 'g': // "agg"
cmd_agraph_print (core, input + 1);
break;
case 's': // "ags"
r_core_anal_graph (core, r_num_math (core->num, input + 1), 0);
break;
case 't': // "agt"
list = r_core_anal_graph_to (core, r_num_math (core->num, input + 1), 0);
if (list) {
RListIter *iter, *iter2;
RList *list2;
RAnalBlock *bb;
r_list_foreach (list, iter, list2) {
r_list_foreach (list2, iter2, bb) {
r_cons_printf ("-> 0x%08" PFMT64x "\n", bb->addr);
}
}
r_list_purge (list);
free (list);
}
break;
case 'C': // "agC"
r_core_anal_coderefs (core, UT64_MAX, input[1] == 'j'? 2: 1);
break;
case 'r': // "refs"
switch (input[1]) {
case '*':
case 'j':
case ' ':
case 0:
{
ut64 addr = input[2]? r_num_math (core->num, input + 2): core->offset;
r_core_anal_codexrefs (core, addr, '*');
}
break;
default:
eprintf ("|ERROR| Usage: agr[*j]\n");
break;
}
break;
case 'c': // "agc"
if (input[1] == '*') {
ut64 addr = input[2]? r_num_math (core->num, input + 2): UT64_MAX;
r_core_anal_coderefs (core, addr, '*');
} else if (input[1] == 'j') {
ut64 addr = input[2]? r_num_math (core->num, input + 2): UT64_MAX;
r_core_anal_coderefs (core, addr, 2);
} else if (input[1] == ' ') {
ut64 addr = input[2]? r_num_math (core->num, input + 1): UT64_MAX;
r_core_anal_coderefs (core, addr, 1);
} else {
eprintf ("|ERROR| Usage: agc[j*] ([addr])\n");
}
break;
case 'j': // "agj"
r_core_anal_graph (core, r_num_math (core->num, input + 1), R_CORE_ANAL_JSON);
break;
case 'J': // "agJ"
r_core_anal_graph (core, r_num_math (core->num, input + 1), R_CORE_ANAL_JSON | R_CORE_ANAL_JSON_FORMAT_DISASM);
break;
case 'k': // "agk"
r_core_anal_graph (core, r_num_math (core->num, input + 1), R_CORE_ANAL_KEYVALUE);
break;
case 'l': // "agl"
r_core_anal_graph (core, r_num_math (core->num, input + 1), R_CORE_ANAL_GRAPHLINES);
break;
case 'a': // "aga"
r_core_anal_graph (core, r_num_math (core->num, input + 1), 0);
break;
case 'd': // "agd"
r_core_anal_graph (core, r_num_math (core->num, input + 1),
R_CORE_ANAL_GRAPHBODY | R_CORE_ANAL_GRAPHDIFF);
break;
case 'v': // "agv"
if (r_config_get_i (core->config, "graph.web")) {
r_core_cmd0 (core, "=H /graph/");
} else {
const char *cmd = r_config_get (core->config, "cmd.graph");
if (cmd && *cmd) {
r_core_cmd0 (core, cmd);
} else {
r_core_cmd0 (core, "agf");
}
}
break;
case '?': // "ag?"
r_core_cmd_help (core, help_msg_ag);
break;
case ' ': // "ag"
arg = strchr (input, ' ');
r_core_anal_graph (core, r_num_math (core->num, arg? arg + 1: NULL),
R_CORE_ANAL_GRAPHBODY);
break;
case 0:
eprintf ("|ERROR| Usage: ag [addr]\n");
break;
default:
eprintf ("See ag?\n");
break;
}
}
R_API int r_core_anal_refs(RCore *core, const char *input) {
int cfg_debug = r_config_get_i (core->config, "cfg.debug");
ut64 from, to;
char *ptr;
int rad, n;
if (*input == '?') {
r_core_cmd_help (core, help_msg_aar);
return 0;
}
if (*input == 'j' || *input == '*') {
rad = *input;
input++;
} else {
rad = 0;
}
from = to = 0;
ptr = r_str_trim_head (strdup (input));
n = r_str_word_set0 (ptr);
if (!n) {
// get boundaries of current memory map, section or io map
if (cfg_debug) {
RDebugMap *map = r_debug_map_get (core->dbg, core->offset);
if (map) {
from = map->addr;
to = map->addr_end;
}
} else {
RList *list = r_core_get_boundaries_prot (core, R_IO_EXEC, NULL, "anal");
RListIter *iter;
RIOMap* map;
r_list_foreach (list, iter, map) {
from = map->itv.addr;
to = r_itv_end (map->itv);
if (r_cons_is_breaked ()) {
break;
}
if (!from && !to) {
eprintf ("Cannot determine xref search boundaries\n");
} else if (to - from > UT32_MAX) {
eprintf ("Skipping huge range\n");
} else {
r_core_anal_search_xrefs (core, from, to, rad);
}
}
free (ptr);
return 1;
}
} else if (n == 1) {
from = core->offset;
to = core->offset + r_num_math (core->num, r_str_word_get0 (ptr, 0));
} else {
eprintf ("Invalid number of arguments\n");
}
free (ptr);
if (from == UT64_MAX && to == UT64_MAX) {
return false;
}
if (!from && !to) {
return false;
}
if (to - from > r_io_size (core->io)) {
return false;
}
return r_core_anal_search_xrefs (core, from, to, rad);
}
static const char *oldstr = NULL;
static void rowlog(RCore *core, const char *str) {
int use_color = core->print->flags & R_PRINT_FLAGS_COLOR;
bool verbose = r_config_get_i (core->config, "scr.prompt");
oldstr = str;
if (!verbose) {
return;
}
if (use_color) {
eprintf ("[ ] "Color_YELLOW"%s\r["Color_RESET, str);
} else {
eprintf ("[ ] %s\r[", str);
}
}
static void rowlog_done(RCore *core) {
int use_color = core->print->flags & R_PRINT_FLAGS_COLOR;
bool verbose = r_config_get_i (core->config, "scr.prompt");
if (verbose) {
if (use_color)
eprintf ("\r"Color_GREEN"[x]"Color_RESET" %s\n", oldstr);
else eprintf ("\r[x] %s\n", oldstr);
}
}
static int compute_coverage(RCore *core) {
RListIter *iter;
SdbListIter *iter2;
RAnalFunction *fcn;
RIOSection *sec;
int cov = 0;
r_list_foreach (core->anal->fcns, iter, fcn) {
ls_foreach (core->io->sections, iter2, sec) {
if (sec->flags & 1) {
ut64 section_end = sec->vaddr + sec->vsize;
ut64 s = r_anal_fcn_realsize (fcn);
if (fcn->addr >= sec->vaddr && (fcn->addr + s) < section_end) {
cov += s;
}
}
}
}
return cov;
}
static int compute_code (RCore* core) {
int code = 0;
SdbListIter *iter;
RIOSection *sec;
ls_foreach (core->io->sections, iter, sec) {
if (sec->flags & 1) {
code += sec->vsize;
}
}
return code;
}
static int compute_calls(RCore *core) {
RListIter *iter;
RAnalFunction *fcn;
RList *xrefs;
int cov = 0;
r_list_foreach (core->anal->fcns, iter, fcn) {
xrefs = r_anal_fcn_get_xrefs (core->anal, fcn);
if (xrefs) {
cov += r_list_length (xrefs);
r_list_free (xrefs);
xrefs = NULL;
}
}
return cov;
}
static void r_core_anal_info (RCore *core, const char *input) {
int fcns = r_list_length (core->anal->fcns);
int strs = r_flag_count (core->flags, "str.*");
int syms = r_flag_count (core->flags, "sym.*");
int imps = r_flag_count (core->flags, "sym.imp.*");
int code = compute_code (core);
int covr = compute_coverage (core);
int call = compute_calls (core);
int xrfs = r_anal_xrefs_count (core->anal);
int cvpc = (code > 0)? (covr * 100 / code): 0;
if (*input == 'j') {
r_cons_printf ("{\"fcns\":%d", fcns);
r_cons_printf (",\"xrefs\":%d", xrfs);
r_cons_printf (",\"calls\":%d", call);
r_cons_printf (",\"strings\":%d", strs);
r_cons_printf (",\"symbols\":%d", syms);
r_cons_printf (",\"imports\":%d", imps);
r_cons_printf (",\"covrage\":%d", covr);
r_cons_printf (",\"codesz\":%d", code);
r_cons_printf (",\"percent\":%d}\n", cvpc);
} else {
r_cons_printf ("fcns %d\n", fcns);
r_cons_printf ("xrefs %d\n", xrfs);
r_cons_printf ("calls %d\n", call);
r_cons_printf ("strings %d\n", strs);
r_cons_printf ("symbols %d\n", syms);
r_cons_printf ("imports %d\n", imps);
r_cons_printf ("covrage %d\n", covr);
r_cons_printf ("codesz %d\n", code);
r_cons_printf ("percent %d%%\n", cvpc);
}
}
static void cmd_anal_aad(RCore *core, const char *input) {
RListIter *iter;
RAnalRef *ref;
RList *list = r_list_newf (NULL);
r_anal_xrefs_from (core->anal, list, "xref", R_ANAL_REF_TYPE_DATA, UT64_MAX);
r_list_foreach (list, iter, ref) {
if (r_io_is_valid_offset (core->io, ref->addr, false)) {
r_core_anal_fcn (core, ref->at, ref->addr, R_ANAL_REF_TYPE_NULL, 1);
}
}
r_list_free (list);
}
static bool archIsArmOrThumb(RCore *core) {
RAsm *as = core ? core->assembler : NULL;
if (as && as->cur && as->cur->arch) {
if (r_str_startswith (as->cur->arch, "mips")) {
return true;
}
if (r_str_startswith (as->cur->arch, "arm")) {
if (as->bits < 64) {
return true;
}
}
}
return false;
}
const bool archIsMips (RCore *core) {
return strstr (core->assembler->cur->name, "mips");
}
void _CbInRangeAav(RCore *core, ut64 from, ut64 to, int vsize, bool asterisk, int count) {
bool isarm = archIsArmOrThumb (core);
if (isarm) {
if (to & 1) {
// .dword 0x000080b9 in reality is 0x000080b8
to--;
r_anal_hint_set_bits (core->anal, to, 16);
// can we assume is gonna be always a function?
} else {
r_core_seek_archbits (core, from);
ut64 bits = r_config_get_i (core->config, "asm.bits");
r_anal_hint_set_bits (core->anal, from, bits);
}
} else {
bool ismips = archIsMips (core);
if (ismips) {
if (from % 4 || to % 4) {
eprintf ("False positive\n");
return;
}
}
}
if (asterisk) {
r_cons_printf ("ax 0x%"PFMT64x " 0x%"PFMT64x "\n", to, from);
r_cons_printf ("Cd %d @ 0x%"PFMT64x "\n", vsize, from);
r_cons_printf ("f+ aav.0x%08"PFMT64x "= 0x%08"PFMT64x, to, to);
} else {
#if 1
r_anal_ref_add (core->anal, to, from, ' ');
r_meta_add (core->anal, 'd', from, from + vsize, NULL);
if (!r_flag_get_at (core->flags, to, false)) {
char *name = r_str_newf ("aav.0x%08"PFMT64x, to);
r_flag_set (core->flags, name, to, vsize);
free (name);
}
#else
r_core_cmdf (core, "ax 0x%"PFMT64x " 0x%"PFMT64x, to, from);
r_core_cmdf (core, "Cd %d @ 0x%"PFMT64x, vsize, from);
r_core_cmdf (core, "f+ aav.0x%08"PFMT64x "= 0x%08"PFMT64x, to, to);
#endif
}
}
static void cmd_anal_aav(RCore *core, const char *input) {
#define seti(x,y) r_config_set_i(core->config, x, y);
#define geti(x) r_config_get_i(core->config, x);
ut64 o_align = geti ("search.align");
bool asterisk = strchr (input, '*');;
bool is_debug = r_config_get_i (core->config, "cfg.debug");
// pre
int archAlign = r_anal_archinfo (core->anal, R_ANAL_ARCHINFO_ALIGN);
seti ("search.align", archAlign);
int vsize = 4; // 32bit dword
if (core->assembler->bits == 64) {
vsize = 8;
}
// body
r_cons_break_push (NULL, NULL);
if (is_debug) {
RList *list = r_core_get_boundaries_prot (core, 0, "dbg.map", "anal");
RListIter *iter;
RIOMap *map;
r_list_foreach (list, iter, map) {
if (r_cons_is_breaked ()) {
break;
}
eprintf ("aav: from 0x%"PFMT64x" to 0x%"PFMT64x"\n", map->itv.addr, r_itv_end (map->itv));
(void)r_core_search_value_in_range (core, map->itv,
map->itv.addr, r_itv_end (map->itv), vsize, asterisk, _CbInRangeAav);
}
r_list_free (list);
} else {
RList *list = r_core_get_boundaries_prot (core, 0, NULL, "anal");
RListIter *iter, *iter2;
RIOMap *map, *map2;
ut64 from = UT64_MAX;
ut64 to = UT64_MAX;
// find values pointing to non-executable regions
r_list_foreach (list, iter2, map2) {
if (r_cons_is_breaked ()) {
break;
}
//TODO: Reduce multiple hits for same addr
from = r_itv_begin (map2->itv);
to = r_itv_end (map2->itv);
eprintf ("Value from 0x%08"PFMT64x " to 0x%08" PFMT64x "\n", from, to);
r_list_foreach (list, iter, map) {
ut64 begin = map->itv.addr;
ut64 end = r_itv_end (map->itv);
if (r_cons_is_breaked ()) {
break;
}
if (end - begin > UT32_MAX) {
eprintf ("Skipping huge range\n");
continue;
}
eprintf ("aav: 0x%08"PFMT64x"-0x%08"PFMT64x" in 0x%"PFMT64x"-0x%"PFMT64x"\n", from, to, begin, end);
(void)r_core_search_value_in_range (core, map->itv, from, to, vsize, asterisk, _CbInRangeAav);
}
}
r_list_free (list);
}
r_cons_break_pop ();
// end
seti ("search.align", o_align);
}
static bool should_aav(RCore *core) {
// Don't aav on x86 for now
if (r_str_startswith (r_config_get (core->config, "asm.arch"), "x86")) {
return false;
}
return true;
}
static int cmd_anal_all(RCore *core, const char *input) {
switch (*input) {
case '?': r_core_cmd_help (core, help_msg_aa); break;
case 'b': // "aab"
cmd_anal_blocks (core, input + 1);
break; // "aab"
case 'f': // "aaf"
{
int analHasnext = r_config_get_i (core->config, "anal.hasnext");
r_config_set_i (core->config, "anal.hasnext", true);
r_core_cmd0 (core, "afr@@c:isq");
r_config_set_i (core->config, "anal.hasnext", analHasnext);
}
break;
case 'c': // "aac"
switch (input[1]) {
case '*':
cmd_anal_calls (core, input + 1, true); break; // "aac*"
default:
cmd_anal_calls (core, input + 1, false); break; // "aac"
}
case 'j': cmd_anal_jumps (core, input + 1); break; // "aaj"
case '*': // "aa*"
r_core_cmd0 (core, "af @@ sym.*");
r_core_cmd0 (core, "af @@ entry*");
break;
case 'd': // "aad"
cmd_anal_aad (core, input);
break;
case 'v': // "aav"
cmd_anal_aav (core, input);
break;
case 'u': // "aau" - print areas not covered by functions
r_core_anal_nofunclist (core, input + 1);
break;
case 'i': // "aai"
r_core_anal_info (core, input + 1);
break;
case 's': // "aas"
r_core_cmd0 (core, "af @@= `isq~[0]`");
r_core_cmd0 (core, "af @@ entry*");
break;
case 'n': // "aan"
r_core_anal_autoname_all_fcns (core);
break; //aan
case 'p': // "aap"
if (*input == '?') {
// TODO: accept parameters for ranges
eprintf ("Usage: /aap ; find in memory for function preludes");
} else {
r_core_search_preludes (core);
}
break;
case '\0': // "aa"
case 'a':
if (input[0] && (input[1] == '?' || (input[1] && input[2] == '?'))) {
r_cons_println ("Usage: See aa? for more help");
} else {
char *dh_orig = NULL;
if (!strncmp (input, "aaaaa", 5)) {
eprintf ("An r2 developer is coming to your place to manually analyze this program. Please wait for it\n");
if (r_config_get_i (core->config, "scr.interactive")) {
r_cons_any_key (NULL);
}
goto jacuzzi;
}
ut64 curseek = core->offset;
rowlog (core, "Analyze all flags starting with sym. and entry0 (aa)");
r_cons_break_push (NULL, NULL);
r_cons_break_timeout (r_config_get_i (core->config, "anal.timeout"));
r_core_anal_all (core);
rowlog_done (core);
dh_orig = core->dbg->h
? strdup (core->dbg->h->name)
: strdup ("esil");
if (core->io && core->io->desc && core->io->desc->plugin && !core->io->desc->plugin->isdbg) {
//use dh_origin if we are debugging
R_FREE (dh_orig);
}
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
r_cons_clear_line (1);
if (*input == 'a') { // "aaa"
if (dh_orig && strcmp (dh_orig, "esil")) {
r_core_cmd0 (core, "dL esil");
}
int c = r_config_get_i (core->config, "anal.calls");
if (should_aav (core)) {
rowlog (core, "\nAnalyze value pointers (aav)");
r_core_cmd0 (core, "aav");
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
}
r_config_set_i (core->config, "anal.calls", 1);
r_core_cmd0 (core, "s $S");
rowlog (core, "Analyze len bytes of instructions for references (aar)");
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
(void)r_core_anal_refs (core, ""); // "aar"
rowlog_done (core);
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
rowlog (core, "Analyze function calls (aac)");
(void) cmd_anal_calls (core, "", false); // "aac"
r_core_seek (core, curseek, 1);
// rowlog (core, "Analyze data refs as code (LEA)");
// (void) cmd_anal_aad (core, NULL); // "aad"
rowlog_done (core);
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
if (input[1] == 'a') { // "aaaa"
bool ioCache = r_config_get_i (core->config, "io.pcache");
r_config_set_i (core->config, "io.pcache", 1);
rowlog (core, "Emulate code to find computed references (aae)");
r_core_cmd0 (core, "aae $SS @ $S");
rowlog_done (core);
rowlog (core, "Analyze consecutive function (aat)");
r_core_cmd0 (core, "aat");
rowlog_done (core);
// drop cache writes is no cache was
if (!ioCache) {
r_core_cmd0 (core, "wc-*");
}
r_config_set_i (core->config, "io.pcache", ioCache);
} else {
rowlog (core, "Use -AA or aaaa to perform additional experimental analysis.");
rowlog_done (core);
}
r_config_set_i (core->config, "anal.calls", c);
rowlog (core, "Constructing a function name for fcn.* and sym.func.* functions (aan)");
if (r_cons_is_breaked ()) {
goto jacuzzi;
}
if (r_config_get_i (core->config, "anal.autoname")) {
r_core_anal_autoname_all_fcns (core);
rowlog_done (core);
}
if (input[1] == 'a') { // "aaaa"
bool ioCache = r_config_get_i (core->config, "io.pcache");
r_config_set_i (core->config, "io.pcache", 1);
if (sdb_count (core->anal->sdb_zigns) > 0) {
rowlog (core, "Check for zignature from zigns folder (z/)");
r_core_cmd0 (core, "z/");
}
rowlog (core, "Type matching analysis for all functions (afta)");
r_core_cmd0 (core, "afta");
rowlog_done (core);
if (!ioCache) {
r_core_cmd0 (core, "wc-*");
}
r_config_set_i (core->config, "io.pcache", ioCache);
}
r_core_cmd0 (core, "s-");
if (dh_orig) {
r_core_cmdf (core, "dL %s;dpa", dh_orig);
}
}
r_core_seek (core, curseek, 1);
jacuzzi:
flag_every_function (core);
r_cons_break_pop ();
R_FREE (dh_orig);
}
break;
case 't': { // "aat"
ut64 cur = core->offset;
bool hasnext = r_config_get_i (core->config, "anal.hasnext");
RListIter *iter;
RIOMap* map;
RList *list = r_core_get_boundaries_prot (core, R_IO_EXEC, NULL, "anal");
r_list_foreach (list, iter, map) {
r_core_seek (core, map->itv.addr, 1);
r_config_set_i (core->config, "anal.hasnext", 1);
r_core_cmd0 (core, "afr");
r_config_set_i (core->config, "anal.hasnext", hasnext);
}
r_core_seek (core, cur, 1);
break;
}
case 'T': // "aaT"
cmd_anal_aftertraps (core, input + 1);
break;
case 'E': // "aaE"
r_core_cmd0 (core, "aef @@f");
break;
case 'e': // "aae"
if (input[1]) {
const char *len = (char *) input + 1;
char *addr = strchr (input + 2, ' ');
if (addr) {
*addr++ = 0;
}
r_core_anal_esil (core, len, addr);
} else {
ut64 at = core->offset;
RIOMap* map;
RListIter *iter;
RList *list = r_core_get_boundaries_prot (core, -1, NULL, "anal");
r_list_foreach (list, iter, map) {
r_core_seek (core, map->itv.addr, 1);
r_core_anal_esil (core, "$SS", NULL);
}
r_core_seek (core, at, 1);
}
break;
case 'r':
(void)r_core_anal_refs (core, input + 1);
break;
default:
r_core_cmd_help (core, help_msg_aa);
break;
}
return true;
}
static bool anal_fcn_data (RCore *core, const char *input) {
RAnalFunction *fcn = r_anal_get_fcn_in (core->anal, core->offset, -1);
ut32 fcn_size = r_anal_fcn_size (fcn);
if (fcn) {
int i;
bool gap = false;
ut64 gap_addr = UT64_MAX;
char *bitmap = calloc (1, fcn_size);
if (bitmap) {
RAnalBlock *b;
RListIter *iter;
r_list_foreach (fcn->bbs, iter, b) {
int f = b->addr - fcn->addr;
int t = R_MIN (f + b->size, fcn_size);
if (f >= 0) {
while (f < t) {
bitmap[f++] = 1;
}
}
}
}
for (i = 0; i < fcn_size; i++) {
ut64 here = fcn->addr + i;
if (bitmap && bitmap[i]) {
if (gap) {
r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", here - gap_addr, gap_addr);
gap = false;
}
gap_addr = UT64_MAX;
} else {
if (!gap) {
gap = true;
gap_addr = here;
}
}
}
if (gap) {
r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", fcn->addr + fcn_size - gap_addr, gap_addr);
gap = false;
}
free (bitmap);
return true;
}
return false;
}
static int cmpaddr (const void *_a, const void *_b) {
const RAnalFunction *a = _a, *b = _b;
return a->addr - b->addr;
}
static bool anal_fcn_data_gaps (RCore *core, const char *input) {
ut64 end = UT64_MAX;
RAnalFunction *fcn;
RListIter *iter;
int i, wordsize = (core->assembler->bits == 64)? 8: 4;
r_list_sort (core->anal->fcns, cmpaddr);
r_list_foreach (core->anal->fcns, iter, fcn) {
if (end != UT64_MAX) {
int range = fcn->addr - end;
if (range > 0) {
for (i = 0; i + wordsize < range; i+= wordsize) {
r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", wordsize, end + i);
}
r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", range - i, end + i);
//r_cons_printf ("Cd %d @ 0x%08"PFMT64x"\n", range, end);
}
}
end = fcn->addr + r_anal_fcn_size (fcn);
}
return true;
}
static void cmd_anal_rtti(RCore *core, const char *input) {
switch (input[0]) {
case '\0': // "avr"
case 'j': // "avrj"
r_anal_rtti_print_at_vtable (core->anal, core->offset, input[0]);
break;
case 'a': // "avra"
r_anal_rtti_print_all (core->anal, input[1]);
break;
default :
r_core_cmd_help (core, help_msg_av);
break;
}
}
static void cmd_anal_virtual_functions(RCore *core, const char* input) {
switch (input[0]) {
case '\0': // "av"
case '*': // "av*"
case 'j': // "avj"
r_anal_list_vtables (core->anal, input[0]);
break;
case 'r': // "avr"
cmd_anal_rtti (core, input + 1);
break;
default :
r_core_cmd_help (core, help_msg_av);
break;
}
}
static int cmd_anal(void *data, const char *input) {
const char *r;
RCore *core = (RCore *)data;
ut32 tbs = core->blocksize;
switch (input[0]) {
case 'p': // "ap"
{
const ut8 *prelude = (const ut8*)"\xe9\x2d"; //:fffff000";
const int prelude_sz = 2;
const int bufsz = 4096;
ut8 *buf = calloc (1, bufsz);
ut64 off = core->offset;
if (input[1] == ' ') {
off = r_num_math (core->num, input+1);
r_io_read_at (core->io, off - bufsz + prelude_sz, buf, bufsz);
} else {
r_io_read_at (core->io, off - bufsz + prelude_sz, buf, bufsz);
}
//const char *prelude = "\x2d\xe9\xf0\x47"; //:fffff000";
r_mem_reverse (buf, bufsz);
//r_print_hexdump (NULL, off, buf, bufsz, 16, -16);
const ut8 *pos = r_mem_mem (buf, bufsz, prelude, prelude_sz);
if (pos) {
int delta = (size_t)(pos - buf);
eprintf ("POS = %d\n", delta);
eprintf ("HIT = 0x%"PFMT64x"\n", off - delta);
r_cons_printf ("0x%08"PFMT64x"\n", off - delta);
} else {
eprintf ("Cannot find prelude\n");
}
free (buf);
}
break;
case '8':
{
ut8 *buf = malloc (strlen (input) + 1);
if (buf) {
int len = r_hex_str2bin (input + 1, buf);
if (len > 0) {
core_anal_bytes (core, buf, len, 0, input[1]);
}
free (buf);
}
}
break;
case 'b':
if (input[1] == 'b') { // "abb"
core_anal_bbs (core, input + 2);
} else if (input[1] == 'r') { // "abr"
core_anal_bbs_range (core, input + 2);
} else if (input[1] == ' ' || !input[1]) {
// find block
ut64 addr = core->offset;
if (input[1]) {
addr = r_num_math (core->num, input + 1);
}
r_core_cmdf (core, "afbi @ 0x%"PFMT64x, addr);
} else {
r_core_cmd_help (core, help_msg_ab);
}
break;
case 'i': cmd_anal_info (core, input + 1); break; // "ai"
case 'r': cmd_anal_reg (core, input + 1); break; // "ar"
case 'e': cmd_anal_esil (core, input + 1); break; // "ae"
case 'o': cmd_anal_opcode (core, input + 1); break; // "ao"
case 'O': cmd_anal_bytes (core, input + 1); break; // "aO"
case 'F': // "aF"
r_core_anal_fcn (core, core->offset, UT64_MAX, R_ANAL_REF_TYPE_NULL, 1);
break;
case 'f': // "af"
{
int res = cmd_anal_fcn (core, input);
if (!res) {
return false;
}
}
break;
case 'n': // 'an'
{
const char *name = NULL;
bool use_json = false;
if (input[1] == 'j') {
use_json = true;
input++;
}
if (input[1] == ' ') {
name = input + 1;
while (name[0] == ' ') {
name++;
}
char *end = strchr (name, ' ');
if (end) {
*end = '\0';
}
if (*name == '\0') {
name = NULL;
}
}
cmd_an (core, use_json, name);
}
break;
case 'g': // "ag"
cmd_anal_graph (core, input + 1);
break;
case 's': // "as"
cmd_anal_syscall (core, input + 1);
break;
case 'v': // "av"
cmd_anal_virtual_functions (core, input + 1);
break;
case 'x': // "ax"
if (!cmd_anal_refs (core, input + 1)) {
return false;
}
break;
case 'a': // "aa"
if (!cmd_anal_all (core, input + 1))
return false;
break;
case 'c': // "ac"
{
RList *hooks;
RListIter *iter;
RAnalCycleHook *hook;
char *instr_tmp = NULL;
int ccl = input[1]? r_num_math (core->num, &input[2]): 0; //get cycles to look for
int cr = r_config_get_i (core->config, "asm.cmt.right");
int fun = r_config_get_i (core->config, "asm.functions");
int li = r_config_get_i (core->config, "asm.lines");
int xr = r_config_get_i (core->config, "asm.xrefs");
r_config_set_i (core->config, "asm.cmt.right", true);
r_config_set_i (core->config, "asm.functions", false);
r_config_set_i (core->config, "asm.lines", false);
r_config_set_i (core->config, "asm.xrefs", false);
hooks = r_core_anal_cycles (core, ccl); //analyse
r_cons_clear_line (1);
r_list_foreach (hooks, iter, hook) {
instr_tmp = r_core_disassemble_instr (core, hook->addr, 1);
r_cons_printf ("After %4i cycles:\t%s", (ccl - hook->cycles), instr_tmp);
r_cons_flush ();
free (instr_tmp);
}
r_list_free (hooks);
r_config_set_i (core->config, "asm.cmt.right", cr); //reset settings
r_config_set_i (core->config, "asm.functions", fun);
r_config_set_i (core->config, "asm.lines", li);
r_config_set_i (core->config, "asm.xrefs", xr);
}
break;
case 'd': // "ad"
switch (input[1]) {
case 'f': // "adf"
if (input[2] == 'g') {
anal_fcn_data_gaps (core, input + 1);
} else {
anal_fcn_data (core, input + 1);
}
break;
case 't': // "adt"
cmd_anal_trampoline (core, input + 2);
break;
case ' ': { // "ad"
const int default_depth = 1;
const char *p;
int a, b;
a = r_num_math (core->num, input + 2);
p = strchr (input + 2, ' ');
b = p? r_num_math (core->num, p + 1): default_depth;
if (a < 1) {
a = 1;
}
if (b < 1) {
b = 1;
}
r_core_anal_data (core, core->offset, a, b, 0);
} break;
case 'k': // "adk"
r = r_anal_data_kind (core->anal,
core->offset, core->block, core->blocksize);
r_cons_println (r);
break;
case '\0': // "ad"
r_core_anal_data (core, core->offset, 2 + (core->blocksize / 4), 1, 0);
break;
case '4': // "ad4"
r_core_anal_data (core, core->offset, 2 + (core->blocksize / 4), 1, 4);
break;
case '8': // "ad8"
r_core_anal_data (core, core->offset, 2 + (core->blocksize / 4), 1, 8);
break;
default:
r_core_cmd_help (core, help_msg_ad);
break;
}
break;
case 'h': // "ah"
cmd_anal_hint (core, input + 1);
break;
case '!': // "a!"
if (core->anal && core->anal->cur && core->anal->cur->cmd_ext) {
return core->anal->cur->cmd_ext (core->anal, input + 1);
} else {
r_cons_printf ("No plugins for this analysis plugin\n");
}
break;
default:
r_core_cmd_help (core, help_msg_a);
#if 0
r_cons_printf ("Examples:\n"
" f ts @ `S*~text:0[3]`; f t @ section..text\n"
" f ds @ `S*~data:0[3]`; f d @ section..data\n"
" .ad t t+ts @ d:ds\n",
NULL);
#endif
break;
}
if (tbs != core->blocksize) {
r_core_block_size (core, tbs);
}
if (r_cons_is_breaked ()) {
r_cons_clear_line (1);
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_148_1 |
crossvul-cpp_data_bad_2566_0 | /*
* POSIX message queues filesystem for Linux.
*
* Copyright (C) 2003,2004 Krzysztof Benedyczak (golbi@mat.uni.torun.pl)
* Michal Wronski (michal.wronski@gmail.com)
*
* Spinlocks: Mohamed Abbas (abbas.mohamed@intel.com)
* Lockless receive & send, fd based notify:
* Manfred Spraul (manfred@colorfullife.com)
*
* Audit: George Wilson (ltcgcw@us.ibm.com)
*
* This file is released under the GPL.
*/
#include <linux/capability.h>
#include <linux/init.h>
#include <linux/pagemap.h>
#include <linux/file.h>
#include <linux/mount.h>
#include <linux/namei.h>
#include <linux/sysctl.h>
#include <linux/poll.h>
#include <linux/mqueue.h>
#include <linux/msg.h>
#include <linux/skbuff.h>
#include <linux/vmalloc.h>
#include <linux/netlink.h>
#include <linux/syscalls.h>
#include <linux/audit.h>
#include <linux/signal.h>
#include <linux/mutex.h>
#include <linux/nsproxy.h>
#include <linux/pid.h>
#include <linux/ipc_namespace.h>
#include <linux/user_namespace.h>
#include <linux/slab.h>
#include <linux/sched/wake_q.h>
#include <linux/sched/signal.h>
#include <linux/sched/user.h>
#include <net/sock.h>
#include "util.h"
#define MQUEUE_MAGIC 0x19800202
#define DIRENT_SIZE 20
#define FILENT_SIZE 80
#define SEND 0
#define RECV 1
#define STATE_NONE 0
#define STATE_READY 1
struct posix_msg_tree_node {
struct rb_node rb_node;
struct list_head msg_list;
int priority;
};
struct ext_wait_queue { /* queue of sleeping tasks */
struct task_struct *task;
struct list_head list;
struct msg_msg *msg; /* ptr of loaded message */
int state; /* one of STATE_* values */
};
struct mqueue_inode_info {
spinlock_t lock;
struct inode vfs_inode;
wait_queue_head_t wait_q;
struct rb_root msg_tree;
struct posix_msg_tree_node *node_cache;
struct mq_attr attr;
struct sigevent notify;
struct pid *notify_owner;
struct user_namespace *notify_user_ns;
struct user_struct *user; /* user who created, for accounting */
struct sock *notify_sock;
struct sk_buff *notify_cookie;
/* for tasks waiting for free space and messages, respectively */
struct ext_wait_queue e_wait_q[2];
unsigned long qsize; /* size of queue in memory (sum of all msgs) */
};
static const struct inode_operations mqueue_dir_inode_operations;
static const struct file_operations mqueue_file_operations;
static const struct super_operations mqueue_super_ops;
static void remove_notification(struct mqueue_inode_info *info);
static struct kmem_cache *mqueue_inode_cachep;
static struct ctl_table_header *mq_sysctl_table;
static inline struct mqueue_inode_info *MQUEUE_I(struct inode *inode)
{
return container_of(inode, struct mqueue_inode_info, vfs_inode);
}
/*
* This routine should be called with the mq_lock held.
*/
static inline struct ipc_namespace *__get_ns_from_inode(struct inode *inode)
{
return get_ipc_ns(inode->i_sb->s_fs_info);
}
static struct ipc_namespace *get_ns_from_inode(struct inode *inode)
{
struct ipc_namespace *ns;
spin_lock(&mq_lock);
ns = __get_ns_from_inode(inode);
spin_unlock(&mq_lock);
return ns;
}
/* Auxiliary functions to manipulate messages' list */
static int msg_insert(struct msg_msg *msg, struct mqueue_inode_info *info)
{
struct rb_node **p, *parent = NULL;
struct posix_msg_tree_node *leaf;
p = &info->msg_tree.rb_node;
while (*p) {
parent = *p;
leaf = rb_entry(parent, struct posix_msg_tree_node, rb_node);
if (likely(leaf->priority == msg->m_type))
goto insert_msg;
else if (msg->m_type < leaf->priority)
p = &(*p)->rb_left;
else
p = &(*p)->rb_right;
}
if (info->node_cache) {
leaf = info->node_cache;
info->node_cache = NULL;
} else {
leaf = kmalloc(sizeof(*leaf), GFP_ATOMIC);
if (!leaf)
return -ENOMEM;
INIT_LIST_HEAD(&leaf->msg_list);
}
leaf->priority = msg->m_type;
rb_link_node(&leaf->rb_node, parent, p);
rb_insert_color(&leaf->rb_node, &info->msg_tree);
insert_msg:
info->attr.mq_curmsgs++;
info->qsize += msg->m_ts;
list_add_tail(&msg->m_list, &leaf->msg_list);
return 0;
}
static inline struct msg_msg *msg_get(struct mqueue_inode_info *info)
{
struct rb_node **p, *parent = NULL;
struct posix_msg_tree_node *leaf;
struct msg_msg *msg;
try_again:
p = &info->msg_tree.rb_node;
while (*p) {
parent = *p;
/*
* During insert, low priorities go to the left and high to the
* right. On receive, we want the highest priorities first, so
* walk all the way to the right.
*/
p = &(*p)->rb_right;
}
if (!parent) {
if (info->attr.mq_curmsgs) {
pr_warn_once("Inconsistency in POSIX message queue, "
"no tree element, but supposedly messages "
"should exist!\n");
info->attr.mq_curmsgs = 0;
}
return NULL;
}
leaf = rb_entry(parent, struct posix_msg_tree_node, rb_node);
if (unlikely(list_empty(&leaf->msg_list))) {
pr_warn_once("Inconsistency in POSIX message queue, "
"empty leaf node but we haven't implemented "
"lazy leaf delete!\n");
rb_erase(&leaf->rb_node, &info->msg_tree);
if (info->node_cache) {
kfree(leaf);
} else {
info->node_cache = leaf;
}
goto try_again;
} else {
msg = list_first_entry(&leaf->msg_list,
struct msg_msg, m_list);
list_del(&msg->m_list);
if (list_empty(&leaf->msg_list)) {
rb_erase(&leaf->rb_node, &info->msg_tree);
if (info->node_cache) {
kfree(leaf);
} else {
info->node_cache = leaf;
}
}
}
info->attr.mq_curmsgs--;
info->qsize -= msg->m_ts;
return msg;
}
static struct inode *mqueue_get_inode(struct super_block *sb,
struct ipc_namespace *ipc_ns, umode_t mode,
struct mq_attr *attr)
{
struct user_struct *u = current_user();
struct inode *inode;
int ret = -ENOMEM;
inode = new_inode(sb);
if (!inode)
goto err;
inode->i_ino = get_next_ino();
inode->i_mode = mode;
inode->i_uid = current_fsuid();
inode->i_gid = current_fsgid();
inode->i_mtime = inode->i_ctime = inode->i_atime = current_time(inode);
if (S_ISREG(mode)) {
struct mqueue_inode_info *info;
unsigned long mq_bytes, mq_treesize;
inode->i_fop = &mqueue_file_operations;
inode->i_size = FILENT_SIZE;
/* mqueue specific info */
info = MQUEUE_I(inode);
spin_lock_init(&info->lock);
init_waitqueue_head(&info->wait_q);
INIT_LIST_HEAD(&info->e_wait_q[0].list);
INIT_LIST_HEAD(&info->e_wait_q[1].list);
info->notify_owner = NULL;
info->notify_user_ns = NULL;
info->qsize = 0;
info->user = NULL; /* set when all is ok */
info->msg_tree = RB_ROOT;
info->node_cache = NULL;
memset(&info->attr, 0, sizeof(info->attr));
info->attr.mq_maxmsg = min(ipc_ns->mq_msg_max,
ipc_ns->mq_msg_default);
info->attr.mq_msgsize = min(ipc_ns->mq_msgsize_max,
ipc_ns->mq_msgsize_default);
if (attr) {
info->attr.mq_maxmsg = attr->mq_maxmsg;
info->attr.mq_msgsize = attr->mq_msgsize;
}
/*
* We used to allocate a static array of pointers and account
* the size of that array as well as one msg_msg struct per
* possible message into the queue size. That's no longer
* accurate as the queue is now an rbtree and will grow and
* shrink depending on usage patterns. We can, however, still
* account one msg_msg struct per message, but the nodes are
* allocated depending on priority usage, and most programs
* only use one, or a handful, of priorities. However, since
* this is pinned memory, we need to assume worst case, so
* that means the min(mq_maxmsg, max_priorities) * struct
* posix_msg_tree_node.
*/
mq_treesize = info->attr.mq_maxmsg * sizeof(struct msg_msg) +
min_t(unsigned int, info->attr.mq_maxmsg, MQ_PRIO_MAX) *
sizeof(struct posix_msg_tree_node);
mq_bytes = mq_treesize + (info->attr.mq_maxmsg *
info->attr.mq_msgsize);
spin_lock(&mq_lock);
if (u->mq_bytes + mq_bytes < u->mq_bytes ||
u->mq_bytes + mq_bytes > rlimit(RLIMIT_MSGQUEUE)) {
spin_unlock(&mq_lock);
/* mqueue_evict_inode() releases info->messages */
ret = -EMFILE;
goto out_inode;
}
u->mq_bytes += mq_bytes;
spin_unlock(&mq_lock);
/* all is ok */
info->user = get_uid(u);
} else if (S_ISDIR(mode)) {
inc_nlink(inode);
/* Some things misbehave if size == 0 on a directory */
inode->i_size = 2 * DIRENT_SIZE;
inode->i_op = &mqueue_dir_inode_operations;
inode->i_fop = &simple_dir_operations;
}
return inode;
out_inode:
iput(inode);
err:
return ERR_PTR(ret);
}
static int mqueue_fill_super(struct super_block *sb, void *data, int silent)
{
struct inode *inode;
struct ipc_namespace *ns = sb->s_fs_info;
sb->s_iflags |= SB_I_NOEXEC | SB_I_NODEV;
sb->s_blocksize = PAGE_SIZE;
sb->s_blocksize_bits = PAGE_SHIFT;
sb->s_magic = MQUEUE_MAGIC;
sb->s_op = &mqueue_super_ops;
inode = mqueue_get_inode(sb, ns, S_IFDIR | S_ISVTX | S_IRWXUGO, NULL);
if (IS_ERR(inode))
return PTR_ERR(inode);
sb->s_root = d_make_root(inode);
if (!sb->s_root)
return -ENOMEM;
return 0;
}
static struct dentry *mqueue_mount(struct file_system_type *fs_type,
int flags, const char *dev_name,
void *data)
{
struct ipc_namespace *ns;
if (flags & MS_KERNMOUNT) {
ns = data;
data = NULL;
} else {
ns = current->nsproxy->ipc_ns;
}
return mount_ns(fs_type, flags, data, ns, ns->user_ns, mqueue_fill_super);
}
static void init_once(void *foo)
{
struct mqueue_inode_info *p = (struct mqueue_inode_info *) foo;
inode_init_once(&p->vfs_inode);
}
static struct inode *mqueue_alloc_inode(struct super_block *sb)
{
struct mqueue_inode_info *ei;
ei = kmem_cache_alloc(mqueue_inode_cachep, GFP_KERNEL);
if (!ei)
return NULL;
return &ei->vfs_inode;
}
static void mqueue_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
kmem_cache_free(mqueue_inode_cachep, MQUEUE_I(inode));
}
static void mqueue_destroy_inode(struct inode *inode)
{
call_rcu(&inode->i_rcu, mqueue_i_callback);
}
static void mqueue_evict_inode(struct inode *inode)
{
struct mqueue_inode_info *info;
struct user_struct *user;
unsigned long mq_bytes, mq_treesize;
struct ipc_namespace *ipc_ns;
struct msg_msg *msg;
clear_inode(inode);
if (S_ISDIR(inode->i_mode))
return;
ipc_ns = get_ns_from_inode(inode);
info = MQUEUE_I(inode);
spin_lock(&info->lock);
while ((msg = msg_get(info)) != NULL)
free_msg(msg);
kfree(info->node_cache);
spin_unlock(&info->lock);
/* Total amount of bytes accounted for the mqueue */
mq_treesize = info->attr.mq_maxmsg * sizeof(struct msg_msg) +
min_t(unsigned int, info->attr.mq_maxmsg, MQ_PRIO_MAX) *
sizeof(struct posix_msg_tree_node);
mq_bytes = mq_treesize + (info->attr.mq_maxmsg *
info->attr.mq_msgsize);
user = info->user;
if (user) {
spin_lock(&mq_lock);
user->mq_bytes -= mq_bytes;
/*
* get_ns_from_inode() ensures that the
* (ipc_ns = sb->s_fs_info) is either a valid ipc_ns
* to which we now hold a reference, or it is NULL.
* We can't put it here under mq_lock, though.
*/
if (ipc_ns)
ipc_ns->mq_queues_count--;
spin_unlock(&mq_lock);
free_uid(user);
}
if (ipc_ns)
put_ipc_ns(ipc_ns);
}
static int mqueue_create(struct inode *dir, struct dentry *dentry,
umode_t mode, bool excl)
{
struct inode *inode;
struct mq_attr *attr = dentry->d_fsdata;
int error;
struct ipc_namespace *ipc_ns;
spin_lock(&mq_lock);
ipc_ns = __get_ns_from_inode(dir);
if (!ipc_ns) {
error = -EACCES;
goto out_unlock;
}
if (ipc_ns->mq_queues_count >= ipc_ns->mq_queues_max &&
!capable(CAP_SYS_RESOURCE)) {
error = -ENOSPC;
goto out_unlock;
}
ipc_ns->mq_queues_count++;
spin_unlock(&mq_lock);
inode = mqueue_get_inode(dir->i_sb, ipc_ns, mode, attr);
if (IS_ERR(inode)) {
error = PTR_ERR(inode);
spin_lock(&mq_lock);
ipc_ns->mq_queues_count--;
goto out_unlock;
}
put_ipc_ns(ipc_ns);
dir->i_size += DIRENT_SIZE;
dir->i_ctime = dir->i_mtime = dir->i_atime = current_time(dir);
d_instantiate(dentry, inode);
dget(dentry);
return 0;
out_unlock:
spin_unlock(&mq_lock);
if (ipc_ns)
put_ipc_ns(ipc_ns);
return error;
}
static int mqueue_unlink(struct inode *dir, struct dentry *dentry)
{
struct inode *inode = d_inode(dentry);
dir->i_ctime = dir->i_mtime = dir->i_atime = current_time(dir);
dir->i_size -= DIRENT_SIZE;
drop_nlink(inode);
dput(dentry);
return 0;
}
/*
* This is routine for system read from queue file.
* To avoid mess with doing here some sort of mq_receive we allow
* to read only queue size & notification info (the only values
* that are interesting from user point of view and aren't accessible
* through std routines)
*/
static ssize_t mqueue_read_file(struct file *filp, char __user *u_data,
size_t count, loff_t *off)
{
struct mqueue_inode_info *info = MQUEUE_I(file_inode(filp));
char buffer[FILENT_SIZE];
ssize_t ret;
spin_lock(&info->lock);
snprintf(buffer, sizeof(buffer),
"QSIZE:%-10lu NOTIFY:%-5d SIGNO:%-5d NOTIFY_PID:%-6d\n",
info->qsize,
info->notify_owner ? info->notify.sigev_notify : 0,
(info->notify_owner &&
info->notify.sigev_notify == SIGEV_SIGNAL) ?
info->notify.sigev_signo : 0,
pid_vnr(info->notify_owner));
spin_unlock(&info->lock);
buffer[sizeof(buffer)-1] = '\0';
ret = simple_read_from_buffer(u_data, count, off, buffer,
strlen(buffer));
if (ret <= 0)
return ret;
file_inode(filp)->i_atime = file_inode(filp)->i_ctime = current_time(file_inode(filp));
return ret;
}
static int mqueue_flush_file(struct file *filp, fl_owner_t id)
{
struct mqueue_inode_info *info = MQUEUE_I(file_inode(filp));
spin_lock(&info->lock);
if (task_tgid(current) == info->notify_owner)
remove_notification(info);
spin_unlock(&info->lock);
return 0;
}
static unsigned int mqueue_poll_file(struct file *filp, struct poll_table_struct *poll_tab)
{
struct mqueue_inode_info *info = MQUEUE_I(file_inode(filp));
int retval = 0;
poll_wait(filp, &info->wait_q, poll_tab);
spin_lock(&info->lock);
if (info->attr.mq_curmsgs)
retval = POLLIN | POLLRDNORM;
if (info->attr.mq_curmsgs < info->attr.mq_maxmsg)
retval |= POLLOUT | POLLWRNORM;
spin_unlock(&info->lock);
return retval;
}
/* Adds current to info->e_wait_q[sr] before element with smaller prio */
static void wq_add(struct mqueue_inode_info *info, int sr,
struct ext_wait_queue *ewp)
{
struct ext_wait_queue *walk;
ewp->task = current;
list_for_each_entry(walk, &info->e_wait_q[sr].list, list) {
if (walk->task->static_prio <= current->static_prio) {
list_add_tail(&ewp->list, &walk->list);
return;
}
}
list_add_tail(&ewp->list, &info->e_wait_q[sr].list);
}
/*
* Puts current task to sleep. Caller must hold queue lock. After return
* lock isn't held.
* sr: SEND or RECV
*/
static int wq_sleep(struct mqueue_inode_info *info, int sr,
ktime_t *timeout, struct ext_wait_queue *ewp)
__releases(&info->lock)
{
int retval;
signed long time;
wq_add(info, sr, ewp);
for (;;) {
__set_current_state(TASK_INTERRUPTIBLE);
spin_unlock(&info->lock);
time = schedule_hrtimeout_range_clock(timeout, 0,
HRTIMER_MODE_ABS, CLOCK_REALTIME);
if (ewp->state == STATE_READY) {
retval = 0;
goto out;
}
spin_lock(&info->lock);
if (ewp->state == STATE_READY) {
retval = 0;
goto out_unlock;
}
if (signal_pending(current)) {
retval = -ERESTARTSYS;
break;
}
if (time == 0) {
retval = -ETIMEDOUT;
break;
}
}
list_del(&ewp->list);
out_unlock:
spin_unlock(&info->lock);
out:
return retval;
}
/*
* Returns waiting task that should be serviced first or NULL if none exists
*/
static struct ext_wait_queue *wq_get_first_waiter(
struct mqueue_inode_info *info, int sr)
{
struct list_head *ptr;
ptr = info->e_wait_q[sr].list.prev;
if (ptr == &info->e_wait_q[sr].list)
return NULL;
return list_entry(ptr, struct ext_wait_queue, list);
}
static inline void set_cookie(struct sk_buff *skb, char code)
{
((char *)skb->data)[NOTIFY_COOKIE_LEN-1] = code;
}
/*
* The next function is only to split too long sys_mq_timedsend
*/
static void __do_notify(struct mqueue_inode_info *info)
{
/* notification
* invoked when there is registered process and there isn't process
* waiting synchronously for message AND state of queue changed from
* empty to not empty. Here we are sure that no one is waiting
* synchronously. */
if (info->notify_owner &&
info->attr.mq_curmsgs == 1) {
struct siginfo sig_i;
switch (info->notify.sigev_notify) {
case SIGEV_NONE:
break;
case SIGEV_SIGNAL:
/* sends signal */
sig_i.si_signo = info->notify.sigev_signo;
sig_i.si_errno = 0;
sig_i.si_code = SI_MESGQ;
sig_i.si_value = info->notify.sigev_value;
/* map current pid/uid into info->owner's namespaces */
rcu_read_lock();
sig_i.si_pid = task_tgid_nr_ns(current,
ns_of_pid(info->notify_owner));
sig_i.si_uid = from_kuid_munged(info->notify_user_ns, current_uid());
rcu_read_unlock();
kill_pid_info(info->notify.sigev_signo,
&sig_i, info->notify_owner);
break;
case SIGEV_THREAD:
set_cookie(info->notify_cookie, NOTIFY_WOKENUP);
netlink_sendskb(info->notify_sock, info->notify_cookie);
break;
}
/* after notification unregisters process */
put_pid(info->notify_owner);
put_user_ns(info->notify_user_ns);
info->notify_owner = NULL;
info->notify_user_ns = NULL;
}
wake_up(&info->wait_q);
}
static int prepare_timeout(const struct timespec __user *u_abs_timeout,
struct timespec *ts)
{
if (copy_from_user(ts, u_abs_timeout, sizeof(struct timespec)))
return -EFAULT;
if (!timespec_valid(ts))
return -EINVAL;
return 0;
}
static void remove_notification(struct mqueue_inode_info *info)
{
if (info->notify_owner != NULL &&
info->notify.sigev_notify == SIGEV_THREAD) {
set_cookie(info->notify_cookie, NOTIFY_REMOVED);
netlink_sendskb(info->notify_sock, info->notify_cookie);
}
put_pid(info->notify_owner);
put_user_ns(info->notify_user_ns);
info->notify_owner = NULL;
info->notify_user_ns = NULL;
}
static int mq_attr_ok(struct ipc_namespace *ipc_ns, struct mq_attr *attr)
{
int mq_treesize;
unsigned long total_size;
if (attr->mq_maxmsg <= 0 || attr->mq_msgsize <= 0)
return -EINVAL;
if (capable(CAP_SYS_RESOURCE)) {
if (attr->mq_maxmsg > HARD_MSGMAX ||
attr->mq_msgsize > HARD_MSGSIZEMAX)
return -EINVAL;
} else {
if (attr->mq_maxmsg > ipc_ns->mq_msg_max ||
attr->mq_msgsize > ipc_ns->mq_msgsize_max)
return -EINVAL;
}
/* check for overflow */
if (attr->mq_msgsize > ULONG_MAX/attr->mq_maxmsg)
return -EOVERFLOW;
mq_treesize = attr->mq_maxmsg * sizeof(struct msg_msg) +
min_t(unsigned int, attr->mq_maxmsg, MQ_PRIO_MAX) *
sizeof(struct posix_msg_tree_node);
total_size = attr->mq_maxmsg * attr->mq_msgsize;
if (total_size + mq_treesize < total_size)
return -EOVERFLOW;
return 0;
}
/*
* Invoked when creating a new queue via sys_mq_open
*/
static struct file *do_create(struct ipc_namespace *ipc_ns, struct inode *dir,
struct path *path, int oflag, umode_t mode,
struct mq_attr *attr)
{
const struct cred *cred = current_cred();
int ret;
if (attr) {
ret = mq_attr_ok(ipc_ns, attr);
if (ret)
return ERR_PTR(ret);
/* store for use during create */
path->dentry->d_fsdata = attr;
} else {
struct mq_attr def_attr;
def_attr.mq_maxmsg = min(ipc_ns->mq_msg_max,
ipc_ns->mq_msg_default);
def_attr.mq_msgsize = min(ipc_ns->mq_msgsize_max,
ipc_ns->mq_msgsize_default);
ret = mq_attr_ok(ipc_ns, &def_attr);
if (ret)
return ERR_PTR(ret);
}
mode &= ~current_umask();
ret = vfs_create(dir, path->dentry, mode, true);
path->dentry->d_fsdata = NULL;
if (ret)
return ERR_PTR(ret);
return dentry_open(path, oflag, cred);
}
/* Opens existing queue */
static struct file *do_open(struct path *path, int oflag)
{
static const int oflag2acc[O_ACCMODE] = { MAY_READ, MAY_WRITE,
MAY_READ | MAY_WRITE };
int acc;
if ((oflag & O_ACCMODE) == (O_RDWR | O_WRONLY))
return ERR_PTR(-EINVAL);
acc = oflag2acc[oflag & O_ACCMODE];
if (inode_permission(d_inode(path->dentry), acc))
return ERR_PTR(-EACCES);
return dentry_open(path, oflag, current_cred());
}
static int do_mq_open(const char __user *u_name, int oflag, umode_t mode,
struct mq_attr *attr)
{
struct path path;
struct file *filp;
struct filename *name;
int fd, error;
struct ipc_namespace *ipc_ns = current->nsproxy->ipc_ns;
struct vfsmount *mnt = ipc_ns->mq_mnt;
struct dentry *root = mnt->mnt_root;
int ro;
audit_mq_open(oflag, mode, attr);
if (IS_ERR(name = getname(u_name)))
return PTR_ERR(name);
fd = get_unused_fd_flags(O_CLOEXEC);
if (fd < 0)
goto out_putname;
ro = mnt_want_write(mnt); /* we'll drop it in any case */
error = 0;
inode_lock(d_inode(root));
path.dentry = lookup_one_len(name->name, root, strlen(name->name));
if (IS_ERR(path.dentry)) {
error = PTR_ERR(path.dentry);
goto out_putfd;
}
path.mnt = mntget(mnt);
if (oflag & O_CREAT) {
if (d_really_is_positive(path.dentry)) { /* entry already exists */
audit_inode(name, path.dentry, 0);
if (oflag & O_EXCL) {
error = -EEXIST;
goto out;
}
filp = do_open(&path, oflag);
} else {
if (ro) {
error = ro;
goto out;
}
audit_inode_parent_hidden(name, root);
filp = do_create(ipc_ns, d_inode(root), &path,
oflag, mode, attr);
}
} else {
if (d_really_is_negative(path.dentry)) {
error = -ENOENT;
goto out;
}
audit_inode(name, path.dentry, 0);
filp = do_open(&path, oflag);
}
if (!IS_ERR(filp))
fd_install(fd, filp);
else
error = PTR_ERR(filp);
out:
path_put(&path);
out_putfd:
if (error) {
put_unused_fd(fd);
fd = error;
}
inode_unlock(d_inode(root));
if (!ro)
mnt_drop_write(mnt);
out_putname:
putname(name);
return fd;
}
SYSCALL_DEFINE4(mq_open, const char __user *, u_name, int, oflag, umode_t, mode,
struct mq_attr __user *, u_attr)
{
struct mq_attr attr;
if (u_attr && copy_from_user(&attr, u_attr, sizeof(struct mq_attr)))
return -EFAULT;
return do_mq_open(u_name, oflag, mode, u_attr ? &attr : NULL);
}
SYSCALL_DEFINE1(mq_unlink, const char __user *, u_name)
{
int err;
struct filename *name;
struct dentry *dentry;
struct inode *inode = NULL;
struct ipc_namespace *ipc_ns = current->nsproxy->ipc_ns;
struct vfsmount *mnt = ipc_ns->mq_mnt;
name = getname(u_name);
if (IS_ERR(name))
return PTR_ERR(name);
audit_inode_parent_hidden(name, mnt->mnt_root);
err = mnt_want_write(mnt);
if (err)
goto out_name;
inode_lock_nested(d_inode(mnt->mnt_root), I_MUTEX_PARENT);
dentry = lookup_one_len(name->name, mnt->mnt_root,
strlen(name->name));
if (IS_ERR(dentry)) {
err = PTR_ERR(dentry);
goto out_unlock;
}
inode = d_inode(dentry);
if (!inode) {
err = -ENOENT;
} else {
ihold(inode);
err = vfs_unlink(d_inode(dentry->d_parent), dentry, NULL);
}
dput(dentry);
out_unlock:
inode_unlock(d_inode(mnt->mnt_root));
if (inode)
iput(inode);
mnt_drop_write(mnt);
out_name:
putname(name);
return err;
}
/* Pipelined send and receive functions.
*
* If a receiver finds no waiting message, then it registers itself in the
* list of waiting receivers. A sender checks that list before adding the new
* message into the message array. If there is a waiting receiver, then it
* bypasses the message array and directly hands the message over to the
* receiver. The receiver accepts the message and returns without grabbing the
* queue spinlock:
*
* - Set pointer to message.
* - Queue the receiver task for later wakeup (without the info->lock).
* - Update its state to STATE_READY. Now the receiver can continue.
* - Wake up the process after the lock is dropped. Should the process wake up
* before this wakeup (due to a timeout or a signal) it will either see
* STATE_READY and continue or acquire the lock to check the state again.
*
* The same algorithm is used for senders.
*/
/* pipelined_send() - send a message directly to the task waiting in
* sys_mq_timedreceive() (without inserting message into a queue).
*/
static inline void pipelined_send(struct wake_q_head *wake_q,
struct mqueue_inode_info *info,
struct msg_msg *message,
struct ext_wait_queue *receiver)
{
receiver->msg = message;
list_del(&receiver->list);
wake_q_add(wake_q, receiver->task);
/*
* Rely on the implicit cmpxchg barrier from wake_q_add such
* that we can ensure that updating receiver->state is the last
* write operation: As once set, the receiver can continue,
* and if we don't have the reference count from the wake_q,
* yet, at that point we can later have a use-after-free
* condition and bogus wakeup.
*/
receiver->state = STATE_READY;
}
/* pipelined_receive() - if there is task waiting in sys_mq_timedsend()
* gets its message and put to the queue (we have one free place for sure). */
static inline void pipelined_receive(struct wake_q_head *wake_q,
struct mqueue_inode_info *info)
{
struct ext_wait_queue *sender = wq_get_first_waiter(info, SEND);
if (!sender) {
/* for poll */
wake_up_interruptible(&info->wait_q);
return;
}
if (msg_insert(sender->msg, info))
return;
list_del(&sender->list);
wake_q_add(wake_q, sender->task);
sender->state = STATE_READY;
}
static int do_mq_timedsend(mqd_t mqdes, const char __user *u_msg_ptr,
size_t msg_len, unsigned int msg_prio,
struct timespec *ts)
{
struct fd f;
struct inode *inode;
struct ext_wait_queue wait;
struct ext_wait_queue *receiver;
struct msg_msg *msg_ptr;
struct mqueue_inode_info *info;
ktime_t expires, *timeout = NULL;
struct posix_msg_tree_node *new_leaf = NULL;
int ret = 0;
DEFINE_WAKE_Q(wake_q);
if (unlikely(msg_prio >= (unsigned long) MQ_PRIO_MAX))
return -EINVAL;
if (ts) {
expires = timespec_to_ktime(*ts);
timeout = &expires;
}
audit_mq_sendrecv(mqdes, msg_len, msg_prio, ts);
f = fdget(mqdes);
if (unlikely(!f.file)) {
ret = -EBADF;
goto out;
}
inode = file_inode(f.file);
if (unlikely(f.file->f_op != &mqueue_file_operations)) {
ret = -EBADF;
goto out_fput;
}
info = MQUEUE_I(inode);
audit_file(f.file);
if (unlikely(!(f.file->f_mode & FMODE_WRITE))) {
ret = -EBADF;
goto out_fput;
}
if (unlikely(msg_len > info->attr.mq_msgsize)) {
ret = -EMSGSIZE;
goto out_fput;
}
/* First try to allocate memory, before doing anything with
* existing queues. */
msg_ptr = load_msg(u_msg_ptr, msg_len);
if (IS_ERR(msg_ptr)) {
ret = PTR_ERR(msg_ptr);
goto out_fput;
}
msg_ptr->m_ts = msg_len;
msg_ptr->m_type = msg_prio;
/*
* msg_insert really wants us to have a valid, spare node struct so
* it doesn't have to kmalloc a GFP_ATOMIC allocation, but it will
* fall back to that if necessary.
*/
if (!info->node_cache)
new_leaf = kmalloc(sizeof(*new_leaf), GFP_KERNEL);
spin_lock(&info->lock);
if (!info->node_cache && new_leaf) {
/* Save our speculative allocation into the cache */
INIT_LIST_HEAD(&new_leaf->msg_list);
info->node_cache = new_leaf;
new_leaf = NULL;
} else {
kfree(new_leaf);
}
if (info->attr.mq_curmsgs == info->attr.mq_maxmsg) {
if (f.file->f_flags & O_NONBLOCK) {
ret = -EAGAIN;
} else {
wait.task = current;
wait.msg = (void *) msg_ptr;
wait.state = STATE_NONE;
ret = wq_sleep(info, SEND, timeout, &wait);
/*
* wq_sleep must be called with info->lock held, and
* returns with the lock released
*/
goto out_free;
}
} else {
receiver = wq_get_first_waiter(info, RECV);
if (receiver) {
pipelined_send(&wake_q, info, msg_ptr, receiver);
} else {
/* adds message to the queue */
ret = msg_insert(msg_ptr, info);
if (ret)
goto out_unlock;
__do_notify(info);
}
inode->i_atime = inode->i_mtime = inode->i_ctime =
current_time(inode);
}
out_unlock:
spin_unlock(&info->lock);
wake_up_q(&wake_q);
out_free:
if (ret)
free_msg(msg_ptr);
out_fput:
fdput(f);
out:
return ret;
}
static int do_mq_timedreceive(mqd_t mqdes, char __user *u_msg_ptr,
size_t msg_len, unsigned int __user *u_msg_prio,
struct timespec *ts)
{
ssize_t ret;
struct msg_msg *msg_ptr;
struct fd f;
struct inode *inode;
struct mqueue_inode_info *info;
struct ext_wait_queue wait;
ktime_t expires, *timeout = NULL;
struct posix_msg_tree_node *new_leaf = NULL;
if (ts) {
expires = timespec_to_ktime(*ts);
timeout = &expires;
}
audit_mq_sendrecv(mqdes, msg_len, 0, ts);
f = fdget(mqdes);
if (unlikely(!f.file)) {
ret = -EBADF;
goto out;
}
inode = file_inode(f.file);
if (unlikely(f.file->f_op != &mqueue_file_operations)) {
ret = -EBADF;
goto out_fput;
}
info = MQUEUE_I(inode);
audit_file(f.file);
if (unlikely(!(f.file->f_mode & FMODE_READ))) {
ret = -EBADF;
goto out_fput;
}
/* checks if buffer is big enough */
if (unlikely(msg_len < info->attr.mq_msgsize)) {
ret = -EMSGSIZE;
goto out_fput;
}
/*
* msg_insert really wants us to have a valid, spare node struct so
* it doesn't have to kmalloc a GFP_ATOMIC allocation, but it will
* fall back to that if necessary.
*/
if (!info->node_cache)
new_leaf = kmalloc(sizeof(*new_leaf), GFP_KERNEL);
spin_lock(&info->lock);
if (!info->node_cache && new_leaf) {
/* Save our speculative allocation into the cache */
INIT_LIST_HEAD(&new_leaf->msg_list);
info->node_cache = new_leaf;
} else {
kfree(new_leaf);
}
if (info->attr.mq_curmsgs == 0) {
if (f.file->f_flags & O_NONBLOCK) {
spin_unlock(&info->lock);
ret = -EAGAIN;
} else {
wait.task = current;
wait.state = STATE_NONE;
ret = wq_sleep(info, RECV, timeout, &wait);
msg_ptr = wait.msg;
}
} else {
DEFINE_WAKE_Q(wake_q);
msg_ptr = msg_get(info);
inode->i_atime = inode->i_mtime = inode->i_ctime =
current_time(inode);
/* There is now free space in queue. */
pipelined_receive(&wake_q, info);
spin_unlock(&info->lock);
wake_up_q(&wake_q);
ret = 0;
}
if (ret == 0) {
ret = msg_ptr->m_ts;
if ((u_msg_prio && put_user(msg_ptr->m_type, u_msg_prio)) ||
store_msg(u_msg_ptr, msg_ptr, msg_ptr->m_ts)) {
ret = -EFAULT;
}
free_msg(msg_ptr);
}
out_fput:
fdput(f);
out:
return ret;
}
SYSCALL_DEFINE5(mq_timedsend, mqd_t, mqdes, const char __user *, u_msg_ptr,
size_t, msg_len, unsigned int, msg_prio,
const struct timespec __user *, u_abs_timeout)
{
struct timespec ts, *p = NULL;
if (u_abs_timeout) {
int res = prepare_timeout(u_abs_timeout, &ts);
if (res)
return res;
p = &ts;
}
return do_mq_timedsend(mqdes, u_msg_ptr, msg_len, msg_prio, p);
}
SYSCALL_DEFINE5(mq_timedreceive, mqd_t, mqdes, char __user *, u_msg_ptr,
size_t, msg_len, unsigned int __user *, u_msg_prio,
const struct timespec __user *, u_abs_timeout)
{
struct timespec ts, *p = NULL;
if (u_abs_timeout) {
int res = prepare_timeout(u_abs_timeout, &ts);
if (res)
return res;
p = &ts;
}
return do_mq_timedreceive(mqdes, u_msg_ptr, msg_len, u_msg_prio, p);
}
/*
* Notes: the case when user wants us to deregister (with NULL as pointer)
* and he isn't currently owner of notification, will be silently discarded.
* It isn't explicitly defined in the POSIX.
*/
static int do_mq_notify(mqd_t mqdes, const struct sigevent *notification)
{
int ret;
struct fd f;
struct sock *sock;
struct inode *inode;
struct mqueue_inode_info *info;
struct sk_buff *nc;
audit_mq_notify(mqdes, notification);
nc = NULL;
sock = NULL;
if (notification != NULL) {
if (unlikely(notification->sigev_notify != SIGEV_NONE &&
notification->sigev_notify != SIGEV_SIGNAL &&
notification->sigev_notify != SIGEV_THREAD))
return -EINVAL;
if (notification->sigev_notify == SIGEV_SIGNAL &&
!valid_signal(notification->sigev_signo)) {
return -EINVAL;
}
if (notification->sigev_notify == SIGEV_THREAD) {
long timeo;
/* create the notify skb */
nc = alloc_skb(NOTIFY_COOKIE_LEN, GFP_KERNEL);
if (!nc) {
ret = -ENOMEM;
goto out;
}
if (copy_from_user(nc->data,
notification->sigev_value.sival_ptr,
NOTIFY_COOKIE_LEN)) {
ret = -EFAULT;
goto out;
}
/* TODO: add a header? */
skb_put(nc, NOTIFY_COOKIE_LEN);
/* and attach it to the socket */
retry:
f = fdget(notification->sigev_signo);
if (!f.file) {
ret = -EBADF;
goto out;
}
sock = netlink_getsockbyfilp(f.file);
fdput(f);
if (IS_ERR(sock)) {
ret = PTR_ERR(sock);
sock = NULL;
goto out;
}
timeo = MAX_SCHEDULE_TIMEOUT;
ret = netlink_attachskb(sock, nc, &timeo, NULL);
if (ret == 1)
goto retry;
if (ret) {
sock = NULL;
nc = NULL;
goto out;
}
}
}
f = fdget(mqdes);
if (!f.file) {
ret = -EBADF;
goto out;
}
inode = file_inode(f.file);
if (unlikely(f.file->f_op != &mqueue_file_operations)) {
ret = -EBADF;
goto out_fput;
}
info = MQUEUE_I(inode);
ret = 0;
spin_lock(&info->lock);
if (notification == NULL) {
if (info->notify_owner == task_tgid(current)) {
remove_notification(info);
inode->i_atime = inode->i_ctime = current_time(inode);
}
} else if (info->notify_owner != NULL) {
ret = -EBUSY;
} else {
switch (notification->sigev_notify) {
case SIGEV_NONE:
info->notify.sigev_notify = SIGEV_NONE;
break;
case SIGEV_THREAD:
info->notify_sock = sock;
info->notify_cookie = nc;
sock = NULL;
nc = NULL;
info->notify.sigev_notify = SIGEV_THREAD;
break;
case SIGEV_SIGNAL:
info->notify.sigev_signo = notification->sigev_signo;
info->notify.sigev_value = notification->sigev_value;
info->notify.sigev_notify = SIGEV_SIGNAL;
break;
}
info->notify_owner = get_pid(task_tgid(current));
info->notify_user_ns = get_user_ns(current_user_ns());
inode->i_atime = inode->i_ctime = current_time(inode);
}
spin_unlock(&info->lock);
out_fput:
fdput(f);
out:
if (sock)
netlink_detachskb(sock, nc);
else if (nc)
dev_kfree_skb(nc);
return ret;
}
SYSCALL_DEFINE2(mq_notify, mqd_t, mqdes,
const struct sigevent __user *, u_notification)
{
struct sigevent n, *p = NULL;
if (u_notification) {
if (copy_from_user(&n, u_notification, sizeof(struct sigevent)))
return -EFAULT;
p = &n;
}
return do_mq_notify(mqdes, p);
}
static int do_mq_getsetattr(int mqdes, struct mq_attr *new, struct mq_attr *old)
{
struct fd f;
struct inode *inode;
struct mqueue_inode_info *info;
if (new && (new->mq_flags & (~O_NONBLOCK)))
return -EINVAL;
f = fdget(mqdes);
if (!f.file)
return -EBADF;
if (unlikely(f.file->f_op != &mqueue_file_operations)) {
fdput(f);
return -EBADF;
}
inode = file_inode(f.file);
info = MQUEUE_I(inode);
spin_lock(&info->lock);
if (old) {
*old = info->attr;
old->mq_flags = f.file->f_flags & O_NONBLOCK;
}
if (new) {
audit_mq_getsetattr(mqdes, new);
spin_lock(&f.file->f_lock);
if (new->mq_flags & O_NONBLOCK)
f.file->f_flags |= O_NONBLOCK;
else
f.file->f_flags &= ~O_NONBLOCK;
spin_unlock(&f.file->f_lock);
inode->i_atime = inode->i_ctime = current_time(inode);
}
spin_unlock(&info->lock);
fdput(f);
return 0;
}
SYSCALL_DEFINE3(mq_getsetattr, mqd_t, mqdes,
const struct mq_attr __user *, u_mqstat,
struct mq_attr __user *, u_omqstat)
{
int ret;
struct mq_attr mqstat, omqstat;
struct mq_attr *new = NULL, *old = NULL;
if (u_mqstat) {
new = &mqstat;
if (copy_from_user(new, u_mqstat, sizeof(struct mq_attr)))
return -EFAULT;
}
if (u_omqstat)
old = &omqstat;
ret = do_mq_getsetattr(mqdes, new, old);
if (ret || !old)
return ret;
if (copy_to_user(u_omqstat, old, sizeof(struct mq_attr)))
return -EFAULT;
return 0;
}
#ifdef CONFIG_COMPAT
struct compat_mq_attr {
compat_long_t mq_flags; /* message queue flags */
compat_long_t mq_maxmsg; /* maximum number of messages */
compat_long_t mq_msgsize; /* maximum message size */
compat_long_t mq_curmsgs; /* number of messages currently queued */
compat_long_t __reserved[4]; /* ignored for input, zeroed for output */
};
static inline int get_compat_mq_attr(struct mq_attr *attr,
const struct compat_mq_attr __user *uattr)
{
struct compat_mq_attr v;
if (copy_from_user(&v, uattr, sizeof(*uattr)))
return -EFAULT;
memset(attr, 0, sizeof(*attr));
attr->mq_flags = v.mq_flags;
attr->mq_maxmsg = v.mq_maxmsg;
attr->mq_msgsize = v.mq_msgsize;
attr->mq_curmsgs = v.mq_curmsgs;
return 0;
}
static inline int put_compat_mq_attr(const struct mq_attr *attr,
struct compat_mq_attr __user *uattr)
{
struct compat_mq_attr v;
memset(&v, 0, sizeof(v));
v.mq_flags = attr->mq_flags;
v.mq_maxmsg = attr->mq_maxmsg;
v.mq_msgsize = attr->mq_msgsize;
v.mq_curmsgs = attr->mq_curmsgs;
if (copy_to_user(uattr, &v, sizeof(*uattr)))
return -EFAULT;
return 0;
}
COMPAT_SYSCALL_DEFINE4(mq_open, const char __user *, u_name,
int, oflag, compat_mode_t, mode,
struct compat_mq_attr __user *, u_attr)
{
struct mq_attr attr, *p = NULL;
if (u_attr && oflag & O_CREAT) {
p = &attr;
if (get_compat_mq_attr(&attr, u_attr))
return -EFAULT;
}
return do_mq_open(u_name, oflag, mode, p);
}
static int compat_prepare_timeout(const struct compat_timespec __user *p,
struct timespec *ts)
{
if (compat_get_timespec(ts, p))
return -EFAULT;
if (!timespec_valid(ts))
return -EINVAL;
return 0;
}
COMPAT_SYSCALL_DEFINE5(mq_timedsend, mqd_t, mqdes,
const char __user *, u_msg_ptr,
compat_size_t, msg_len, unsigned int, msg_prio,
const struct compat_timespec __user *, u_abs_timeout)
{
struct timespec ts, *p = NULL;
if (u_abs_timeout) {
int res = compat_prepare_timeout(u_abs_timeout, &ts);
if (res)
return res;
p = &ts;
}
return do_mq_timedsend(mqdes, u_msg_ptr, msg_len, msg_prio, p);
}
COMPAT_SYSCALL_DEFINE5(mq_timedreceive, mqd_t, mqdes,
char __user *, u_msg_ptr,
compat_size_t, msg_len, unsigned int __user *, u_msg_prio,
const struct compat_timespec __user *, u_abs_timeout)
{
struct timespec ts, *p = NULL;
if (u_abs_timeout) {
int res = compat_prepare_timeout(u_abs_timeout, &ts);
if (res)
return res;
p = &ts;
}
return do_mq_timedreceive(mqdes, u_msg_ptr, msg_len, u_msg_prio, p);
}
COMPAT_SYSCALL_DEFINE2(mq_notify, mqd_t, mqdes,
const struct compat_sigevent __user *, u_notification)
{
struct sigevent n, *p = NULL;
if (u_notification) {
if (get_compat_sigevent(&n, u_notification))
return -EFAULT;
if (n.sigev_notify == SIGEV_THREAD)
n.sigev_value.sival_ptr = compat_ptr(n.sigev_value.sival_int);
p = &n;
}
return do_mq_notify(mqdes, p);
}
COMPAT_SYSCALL_DEFINE3(mq_getsetattr, mqd_t, mqdes,
const struct compat_mq_attr __user *, u_mqstat,
struct compat_mq_attr __user *, u_omqstat)
{
int ret;
struct mq_attr mqstat, omqstat;
struct mq_attr *new = NULL, *old = NULL;
if (u_mqstat) {
new = &mqstat;
if (get_compat_mq_attr(new, u_mqstat))
return -EFAULT;
}
if (u_omqstat)
old = &omqstat;
ret = do_mq_getsetattr(mqdes, new, old);
if (ret || !old)
return ret;
if (put_compat_mq_attr(old, u_omqstat))
return -EFAULT;
return 0;
}
#endif
static const struct inode_operations mqueue_dir_inode_operations = {
.lookup = simple_lookup,
.create = mqueue_create,
.unlink = mqueue_unlink,
};
static const struct file_operations mqueue_file_operations = {
.flush = mqueue_flush_file,
.poll = mqueue_poll_file,
.read = mqueue_read_file,
.llseek = default_llseek,
};
static const struct super_operations mqueue_super_ops = {
.alloc_inode = mqueue_alloc_inode,
.destroy_inode = mqueue_destroy_inode,
.evict_inode = mqueue_evict_inode,
.statfs = simple_statfs,
};
static struct file_system_type mqueue_fs_type = {
.name = "mqueue",
.mount = mqueue_mount,
.kill_sb = kill_litter_super,
.fs_flags = FS_USERNS_MOUNT,
};
int mq_init_ns(struct ipc_namespace *ns)
{
ns->mq_queues_count = 0;
ns->mq_queues_max = DFLT_QUEUESMAX;
ns->mq_msg_max = DFLT_MSGMAX;
ns->mq_msgsize_max = DFLT_MSGSIZEMAX;
ns->mq_msg_default = DFLT_MSG;
ns->mq_msgsize_default = DFLT_MSGSIZE;
ns->mq_mnt = kern_mount_data(&mqueue_fs_type, ns);
if (IS_ERR(ns->mq_mnt)) {
int err = PTR_ERR(ns->mq_mnt);
ns->mq_mnt = NULL;
return err;
}
return 0;
}
void mq_clear_sbinfo(struct ipc_namespace *ns)
{
ns->mq_mnt->mnt_sb->s_fs_info = NULL;
}
void mq_put_mnt(struct ipc_namespace *ns)
{
kern_unmount(ns->mq_mnt);
}
static int __init init_mqueue_fs(void)
{
int error;
mqueue_inode_cachep = kmem_cache_create("mqueue_inode_cache",
sizeof(struct mqueue_inode_info), 0,
SLAB_HWCACHE_ALIGN|SLAB_ACCOUNT, init_once);
if (mqueue_inode_cachep == NULL)
return -ENOMEM;
/* ignore failures - they are not fatal */
mq_sysctl_table = mq_register_sysctl_table();
error = register_filesystem(&mqueue_fs_type);
if (error)
goto out_sysctl;
spin_lock_init(&mq_lock);
error = mq_init_ns(&init_ipc_ns);
if (error)
goto out_filesystem;
return 0;
out_filesystem:
unregister_filesystem(&mqueue_fs_type);
out_sysctl:
if (mq_sysctl_table)
unregister_sysctl_table(mq_sysctl_table);
kmem_cache_destroy(mqueue_inode_cachep);
return error;
}
device_initcall(init_mqueue_fs);
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_2566_0 |
crossvul-cpp_data_good_1840_0 | /*
* DBD::mysql - DBI driver for the mysql database
*
* Copyright (c) 2004-2014 Patrick Galbraith
* Copyright (c) 2013-2014 Michiel Beijen
* Copyright (c) 2004-2007 Alexey Stroganov
* Copyright (c) 2003-2005 Rudolf Lippan
* Copyright (c) 1997-2003 Jochen Wiedmann
*
* You may distribute this under the terms of either the GNU General Public
* License or the Artistic License, as specified in the Perl README file.
*/
#ifdef WIN32
#include "windows.h"
#include "winsock.h"
#endif
#include "dbdimp.h"
#if defined(WIN32) && defined(WORD)
#undef WORD
typedef short WORD;
#endif
#ifdef WIN32
#define MIN min
#else
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
#endif
#if MYSQL_ASYNC
# include <poll.h>
# define ASYNC_CHECK_RETURN(h, value)\
if(imp_dbh->async_query_in_flight) {\
do_error(h, 2000, "Calling a synchronous function on an asynchronous handle", "HY000");\
return (value);\
}
#else
# define ASYNC_CHECK_RETURN(h, value)
#endif
static int parse_number(char *string, STRLEN len, char **end);
DBISTATE_DECLARE;
typedef struct sql_type_info_s
{
const char *type_name;
int data_type;
int column_size;
const char *literal_prefix;
const char *literal_suffix;
const char *create_params;
int nullable;
int case_sensitive;
int searchable;
int unsigned_attribute;
int fixed_prec_scale;
int auto_unique_value;
const char *local_type_name;
int minimum_scale;
int maximum_scale;
int num_prec_radix;
int sql_datatype;
int sql_datetime_sub;
int interval_precision;
int native_type;
int is_num;
} sql_type_info_t;
/*
This function manually counts the number of placeholders in an SQL statement,
used for emulated prepare statements < 4.1.3
*/
static int
count_params(imp_xxh_t *imp_xxh, pTHX_ char *statement, bool bind_comment_placeholders)
{
bool comment_end= false;
char* ptr= statement;
int num_params= 0;
int comment_length= 0;
char c;
if (DBIc_DBISTATE(imp_xxh)->debug >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), ">count_params statement %s\n", statement);
while ( (c = *ptr++) )
{
switch (c) {
/* so, this is a -- comment, so let's burn up characters */
case '-':
{
if (bind_comment_placeholders)
{
c = *ptr++;
break;
}
else
{
comment_length= 1;
/* let's see if the next one is a dash */
c = *ptr++;
if (c == '-') {
/* if two dashes, ignore everything until newline */
while ((c = *ptr))
{
if (DBIc_DBISTATE(imp_xxh)->debug >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%c\n", c);
ptr++;
comment_length++;
if (c == '\n')
{
comment_end= true;
break;
}
}
/*
if not comment_end, the comment never ended and we need to iterate
back to the beginning of where we started and let the database
handle whatever is in the statement
*/
if (! comment_end)
ptr-= comment_length;
}
/* otherwise, only one dash/hyphen, backtrack by one */
else
ptr--;
break;
}
}
/* c-type comments */
case '/':
{
if (bind_comment_placeholders)
{
c = *ptr++;
break;
}
else
{
c = *ptr++;
/* let's check if the next one is an asterisk */
if (c == '*')
{
comment_length= 0;
comment_end= false;
/* ignore everything until closing comment */
while ((c= *ptr))
{
ptr++;
comment_length++;
if (c == '*')
{
c = *ptr++;
/* alas, end of comment */
if (c == '/')
{
comment_end= true;
break;
}
/*
nope, just an asterisk, not so fast, not
end of comment, go back one
*/
else
ptr--;
}
}
/*
if the end of the comment was never found, we have
to backtrack to whereever we first started skipping
over the possible comment.
This means we will pass the statement to the database
to see its own fate and issue the error
*/
if (!comment_end)
ptr -= comment_length;
}
else
ptr--;
break;
}
}
case '`':
case '"':
case '\'':
/* Skip string */
{
char end_token = c;
while ((c = *ptr) && c != end_token)
{
if (c == '\\')
if (! *(++ptr))
continue;
++ptr;
}
if (c)
++ptr;
break;
}
case '?':
++num_params;
break;
default:
break;
}
}
return num_params;
}
/*
allocate memory in statement handle per number of placeholders
*/
static imp_sth_ph_t *alloc_param(int num_params)
{
imp_sth_ph_t *params;
if (num_params)
Newz(908, params, (unsigned int) num_params, imp_sth_ph_t);
else
params= NULL;
return params;
}
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
/*
allocate memory in MYSQL_BIND bind structure per
number of placeholders
*/
static MYSQL_BIND *alloc_bind(int num_params)
{
MYSQL_BIND *bind;
if (num_params)
Newz(908, bind, (unsigned int) num_params, MYSQL_BIND);
else
bind= NULL;
return bind;
}
/*
allocate memory in fbind imp_sth_phb_t structure per
number of placeholders
*/
static imp_sth_phb_t *alloc_fbind(int num_params)
{
imp_sth_phb_t *fbind;
if (num_params)
Newz(908, fbind, (unsigned int) num_params, imp_sth_phb_t);
else
fbind= NULL;
return fbind;
}
/*
alloc memory for imp_sth_fbh_t fbuffer per number of fields
*/
static imp_sth_fbh_t *alloc_fbuffer(int num_fields)
{
imp_sth_fbh_t *fbh;
if (num_fields)
Newz(908, fbh, (unsigned int) num_fields, imp_sth_fbh_t);
else
fbh= NULL;
return fbh;
}
/*
free MYSQL_BIND bind struct
*/
static void free_bind(MYSQL_BIND *bind)
{
if (bind)
Safefree(bind);
}
/*
free imp_sth_phb_t fbind structure
*/
static void free_fbind(imp_sth_phb_t *fbind)
{
if (fbind)
Safefree(fbind);
}
/*
free imp_sth_fbh_t fbh structure
*/
static void free_fbuffer(imp_sth_fbh_t *fbh)
{
if (fbh)
Safefree(fbh);
}
#endif
/*
free statement param structure per num_params
*/
static void
free_param(pTHX_ imp_sth_ph_t *params, int num_params)
{
if (params)
{
int i;
for (i= 0; i < num_params; i++)
{
imp_sth_ph_t *ph= params+i;
if (ph->value)
{
(void) SvREFCNT_dec(ph->value);
ph->value= NULL;
}
}
Safefree(params);
}
}
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
/*
Convert a MySQL type to a type that perl can handle
NOTE: In the future we may want to return a struct with a lot of
information for each type
*/
static enum enum_field_types mysql_to_perl_type(enum enum_field_types type)
{
static enum enum_field_types enum_type;
switch (type) {
case MYSQL_TYPE_DOUBLE:
case MYSQL_TYPE_FLOAT:
enum_type= MYSQL_TYPE_DOUBLE;
break;
case MYSQL_TYPE_SHORT:
case MYSQL_TYPE_TINY:
case MYSQL_TYPE_LONG:
case MYSQL_TYPE_INT24:
case MYSQL_TYPE_YEAR:
#if MYSQL_VERSION_ID > NEW_DATATYPE_VERSION
case MYSQL_TYPE_BIT:
#endif
enum_type= MYSQL_TYPE_LONG;
break;
#if MYSQL_VERSION_ID > NEW_DATATYPE_VERSION
case MYSQL_TYPE_NEWDECIMAL:
#endif
case MYSQL_TYPE_DECIMAL:
enum_type= MYSQL_TYPE_DECIMAL;
break;
case MYSQL_TYPE_LONGLONG: /* No longlong in perl */
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_TIME:
case MYSQL_TYPE_DATETIME:
case MYSQL_TYPE_NEWDATE:
case MYSQL_TYPE_TIMESTAMP:
case MYSQL_TYPE_VAR_STRING:
#if MYSQL_VERSION_ID > NEW_DATATYPE_VERSION
case MYSQL_TYPE_VARCHAR:
#endif
case MYSQL_TYPE_STRING:
enum_type= MYSQL_TYPE_STRING;
break;
#if MYSQL_VERSION_ID > GEO_DATATYPE_VERSION
case MYSQL_TYPE_GEOMETRY:
#endif
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_TINY_BLOB:
enum_type= MYSQL_TYPE_BLOB;
break;
default:
enum_type= MYSQL_TYPE_STRING; /* MySQL can handle all types as strings */
}
return(enum_type);
}
#endif
#if defined(DBD_MYSQL_EMBEDDED)
/*
count embedded options
*/
int count_embedded_options(char *st)
{
int rc;
char c;
char *ptr;
ptr= st;
rc= 0;
if (st)
{
while ((c= *ptr++))
{
if (c == ',')
rc++;
}
rc++;
}
return rc;
}
/*
Free embbedded options
*/
int free_embedded_options(char ** options_list, int options_count)
{
int i;
for (i= 0; i < options_count; i++)
{
if (options_list[i])
free(options_list[i]);
}
free(options_list);
return 1;
}
/*
Print out embbedded option settings
*/
int print_embedded_options(char ** options_list, int options_count)
{
int i;
for (i=0; i<options_count; i++)
{
if (options_list[i])
PerlIO_printf(DBILOGFP,
"Embedded server, parameter[%d]=%s\n",
i, options_list[i]);
}
return 1;
}
/*
*/
char **fill_out_embedded_options(char *options,
int options_type,
int slen, int cnt)
{
int ind, len;
char c;
char *ptr;
char **options_list= NULL;
if (!(options_list= (char **) calloc(cnt, sizeof(char *))))
{
PerlIO_printf(DBILOGFP,
"Initialize embedded server. Out of memory \n");
return NULL;
}
ptr= options;
ind= 0;
if (options_type == 0)
{
/* server_groups list NULL terminated */
options_list[cnt]= (char *) NULL;
}
if (options_type == 1)
{
/* first item in server_options list is ignored. fill it with \0 */
if (!(options_list[0]= calloc(1,sizeof(char))))
return NULL;
ind++;
}
while ((c= *ptr++))
{
slen--;
if (c == ',' || !slen)
{
len= ptr - options;
if (c == ',')
len--;
if (!(options_list[ind]=calloc(len+1,sizeof(char))))
return NULL;
strncpy(options_list[ind], options, len);
ind++;
options= ptr;
}
}
return options_list;
}
#endif
/*
constructs an SQL statement previously prepared with
actual values replacing placeholders
*/
static char *parse_params(
imp_xxh_t *imp_xxh,
pTHX_ MYSQL *sock,
char *statement,
STRLEN *slen_ptr,
imp_sth_ph_t* params,
int num_params,
bool bind_type_guessing,
bool bind_comment_placeholders)
{
bool comment_end= false;
char *salloc, *statement_ptr;
char *statement_ptr_end, *ptr, *valbuf;
char *cp, *end;
int alen, i;
int slen= *slen_ptr;
int limit_flag= 0;
int comment_length=0;
STRLEN vallen;
imp_sth_ph_t *ph;
if (DBIc_DBISTATE(imp_xxh)->debug >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), ">parse_params statement %s\n", statement);
if (num_params == 0)
return NULL;
while (isspace(*statement))
{
++statement;
--slen;
}
/* Calculate the number of bytes being allocated for the statement */
alen= slen;
for (i= 0, ph= params; i < num_params; i++, ph++)
{
int defined= 0;
if (ph->value)
{
if (SvMAGICAL(ph->value))
mg_get(ph->value);
if (SvOK(ph->value))
defined=1;
}
if (!defined)
alen+= 3; /* Erase '?', insert 'NULL' */
else
{
valbuf= SvPV(ph->value, vallen);
alen+= 2+vallen+1;
/* this will most likely not happen since line 214 */
/* of mysql.xs hardcodes all types to SQL_VARCHAR */
if (!ph->type)
{
if (bind_type_guessing)
{
valbuf= SvPV(ph->value, vallen);
ph->type= SQL_INTEGER;
if (parse_number(valbuf, vallen, &end) != 0)
{
ph->type= SQL_VARCHAR;
}
}
else
ph->type= SQL_VARCHAR;
}
}
}
/* Allocate memory, why *2, well, because we have ptr and statement_ptr */
New(908, salloc, alen*2, char);
ptr= salloc;
i= 0;
/* Now create the statement string; compare count_params above */
statement_ptr_end= (statement_ptr= statement)+ slen;
while (statement_ptr < statement_ptr_end)
{
/* LIMIT should be the last part of the query, in most cases */
if (! limit_flag)
{
/*
it would be good to be able to handle any number of cases and orders
*/
if ((*statement_ptr == 'l' || *statement_ptr == 'L') &&
(!strncmp(statement_ptr+1, "imit ?", 6) ||
!strncmp(statement_ptr+1, "IMIT ?", 6)))
{
limit_flag = 1;
}
}
switch (*statement_ptr)
{
/* comment detection. Anything goes in a comment */
case '-':
{
if (bind_comment_placeholders)
{
*ptr++= *statement_ptr++;
break;
}
else
{
comment_length= 1;
comment_end= false;
*ptr++ = *statement_ptr++;
if (*statement_ptr == '-')
{
/* ignore everything until newline or end of string */
while (*statement_ptr)
{
comment_length++;
*ptr++ = *statement_ptr++;
if (!*statement_ptr || *statement_ptr == '\n')
{
comment_end= true;
break;
}
}
/* if not end of comment, go back to where we started, no end found */
if (! comment_end)
{
statement_ptr -= comment_length;
ptr -= comment_length;
}
}
break;
}
}
/* c-type comments */
case '/':
{
if (bind_comment_placeholders)
{
*ptr++= *statement_ptr++;
break;
}
else
{
comment_length= 1;
comment_end= false;
*ptr++ = *statement_ptr++;
if (*statement_ptr == '*')
{
/* use up characters everything until newline */
while (*statement_ptr)
{
*ptr++ = *statement_ptr++;
comment_length++;
if (!strncmp(statement_ptr, "*/", 2))
{
comment_length += 2;
comment_end= true;
break;
}
}
/* Go back to where started if comment end not found */
if (! comment_end)
{
statement_ptr -= comment_length;
ptr -= comment_length;
}
}
break;
}
}
case '`':
case '\'':
case '"':
/* Skip string */
{
char endToken = *statement_ptr++;
*ptr++ = endToken;
while (statement_ptr != statement_ptr_end &&
*statement_ptr != endToken)
{
if (*statement_ptr == '\\')
{
*ptr++ = *statement_ptr++;
if (statement_ptr == statement_ptr_end)
break;
}
*ptr++= *statement_ptr++;
}
if (statement_ptr != statement_ptr_end)
*ptr++= *statement_ptr++;
}
break;
case '?':
/* Insert parameter */
statement_ptr++;
if (i >= num_params)
{
break;
}
ph = params+ (i++);
if (!ph->value || !SvOK(ph->value))
{
*ptr++ = 'N';
*ptr++ = 'U';
*ptr++ = 'L';
*ptr++ = 'L';
}
else
{
int is_num = FALSE;
valbuf= SvPV(ph->value, vallen);
if (valbuf)
{
switch (ph->type)
{
case SQL_NUMERIC:
case SQL_DECIMAL:
case SQL_INTEGER:
case SQL_SMALLINT:
case SQL_FLOAT:
case SQL_REAL:
case SQL_DOUBLE:
case SQL_BIGINT:
case SQL_TINYINT:
is_num = TRUE;
break;
}
/* (note this sets *end, which we use if is_num) */
if ( parse_number(valbuf, vallen, &end) != 0 && is_num)
{
if (bind_type_guessing) {
/* .. not a number, so apparerently we guessed wrong */
is_num = 0;
ph->type = SQL_VARCHAR;
}
}
/* we're at the end of the query, so any placeholders if */
/* after a LIMIT clause will be numbers and should not be quoted */
if (limit_flag == 1)
is_num = TRUE;
if (!is_num)
{
*ptr++ = '\'';
ptr += mysql_real_escape_string(sock, ptr, valbuf, vallen);
*ptr++ = '\'';
}
else
{
for (cp= valbuf; cp < end; cp++)
*ptr++= *cp;
}
}
}
break;
/* in case this is a nested LIMIT */
case ')':
limit_flag = 0;
*ptr++ = *statement_ptr++;
break;
default:
*ptr++ = *statement_ptr++;
break;
}
}
*slen_ptr = ptr - salloc;
*ptr++ = '\0';
return(salloc);
}
int bind_param(imp_sth_ph_t *ph, SV *value, IV sql_type)
{
dTHX;
if (ph->value)
{
if (SvMAGICAL(ph->value))
mg_get(ph->value);
(void) SvREFCNT_dec(ph->value);
}
ph->value= newSVsv(value);
if (sql_type)
ph->type = sql_type;
return TRUE;
}
static const sql_type_info_t SQL_GET_TYPE_INFO_values[]= {
{ "varchar", SQL_VARCHAR, 255, "'", "'", "max length",
1, 0, 3, 0, 0, 0, "variable length string",
0, 0, 0,
SQL_VARCHAR, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_VAR_STRING, 0,
#else
MYSQL_TYPE_STRING, 0,
#endif
},
{ "decimal", SQL_DECIMAL, 15, NULL, NULL, "precision,scale",
1, 0, 3, 0, 0, 0, "double",
0, 6, 2,
SQL_DECIMAL, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_DECIMAL, 1
#else
MYSQL_TYPE_DECIMAL, 1
#endif
},
{ "tinyint", SQL_TINYINT, 3, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "Tiny integer",
0, 0, 10,
SQL_TINYINT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_TINY, 1
#else
MYSQL_TYPE_TINY, 1
#endif
},
{ "smallint", SQL_SMALLINT, 5, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "Short integer",
0, 0, 10,
SQL_SMALLINT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_SHORT, 1
#else
MYSQL_TYPE_SHORT, 1
#endif
},
{ "integer", SQL_INTEGER, 10, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "integer",
0, 0, 10,
SQL_INTEGER, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_LONG, 1
#else
MYSQL_TYPE_LONG, 1
#endif
},
{ "float", SQL_REAL, 7, NULL, NULL, NULL,
1, 0, 0, 0, 0, 0, "float",
0, 2, 10,
SQL_FLOAT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_FLOAT, 1
#else
MYSQL_TYPE_FLOAT, 1
#endif
},
{ "double", SQL_FLOAT, 15, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "double",
0, 4, 2,
SQL_FLOAT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_DOUBLE, 1
#else
MYSQL_TYPE_DOUBLE, 1
#endif
},
{ "double", SQL_DOUBLE, 15, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "double",
0, 4, 10,
SQL_DOUBLE, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_DOUBLE, 1
#else
MYSQL_TYPE_DOUBLE, 1
#endif
},
/*
FIELD_TYPE_NULL ?
*/
{ "timestamp", SQL_TIMESTAMP, 14, "'", "'", NULL,
0, 0, 3, 0, 0, 0, "timestamp",
0, 0, 0,
SQL_TIMESTAMP, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_TIMESTAMP, 0
#else
MYSQL_TYPE_TIMESTAMP, 0
#endif
},
{ "bigint", SQL_BIGINT, 19, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "Longlong integer",
0, 0, 10,
SQL_BIGINT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_LONGLONG, 1
#else
MYSQL_TYPE_LONGLONG, 1
#endif
},
{ "mediumint", SQL_INTEGER, 8, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "Medium integer",
0, 0, 10,
SQL_INTEGER, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_INT24, 1
#else
MYSQL_TYPE_INT24, 1
#endif
},
{ "date", SQL_DATE, 10, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "date",
0, 0, 0,
SQL_DATE, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_DATE, 0
#else
MYSQL_TYPE_DATE, 0
#endif
},
{ "time", SQL_TIME, 6, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "time",
0, 0, 0,
SQL_TIME, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_TIME, 0
#else
MYSQL_TYPE_TIME, 0
#endif
},
{ "datetime", SQL_TIMESTAMP, 21, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "datetime",
0, 0, 0,
SQL_TIMESTAMP, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_DATETIME, 0
#else
MYSQL_TYPE_DATETIME, 0
#endif
},
{ "year", SQL_SMALLINT, 4, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "year",
0, 0, 10,
SQL_SMALLINT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_YEAR, 0
#else
MYSQL_TYPE_YEAR, 0
#endif
},
{ "date", SQL_DATE, 10, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "date",
0, 0, 0,
SQL_DATE, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_NEWDATE, 0
#else
MYSQL_TYPE_NEWDATE, 0
#endif
},
{ "enum", SQL_VARCHAR, 255, "'", "'", NULL,
1, 0, 1, 0, 0, 0, "enum(value1,value2,value3...)",
0, 0, 0,
0, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_ENUM, 0
#else
MYSQL_TYPE_ENUM, 0
#endif
},
{ "set", SQL_VARCHAR, 255, "'", "'", NULL,
1, 0, 1, 0, 0, 0, "set(value1,value2,value3...)",
0, 0, 0,
0, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_SET, 0
#else
MYSQL_TYPE_SET, 0
#endif
},
{ "blob", SQL_LONGVARBINARY, 65535, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "binary large object (0-65535)",
0, 0, 0,
SQL_LONGVARBINARY, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_BLOB, 0
#else
MYSQL_TYPE_BLOB, 0
#endif
},
{ "tinyblob", SQL_VARBINARY, 255, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "binary large object (0-255) ",
0, 0, 0,
SQL_VARBINARY, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_TINY_BLOB, 0
#else
FIELD_TYPE_TINY_BLOB, 0
#endif
},
{ "mediumblob", SQL_LONGVARBINARY, 16777215, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "binary large object",
0, 0, 0,
SQL_LONGVARBINARY, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_MEDIUM_BLOB, 0
#else
MYSQL_TYPE_MEDIUM_BLOB, 0
#endif
},
{ "longblob", SQL_LONGVARBINARY, 2147483647, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "binary large object, use mediumblob instead",
0, 0, 0,
SQL_LONGVARBINARY, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_LONG_BLOB, 0
#else
MYSQL_TYPE_LONG_BLOB, 0
#endif
},
{ "char", SQL_CHAR, 255, "'", "'", "max length",
1, 0, 3, 0, 0, 0, "string",
0, 0, 0,
SQL_CHAR, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_STRING, 0
#else
MYSQL_TYPE_STRING, 0
#endif
},
{ "decimal", SQL_NUMERIC, 15, NULL, NULL, "precision,scale",
1, 0, 3, 0, 0, 0, "double",
0, 6, 2,
SQL_NUMERIC, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_DECIMAL, 1
#else
MYSQL_TYPE_DECIMAL, 1
#endif
},
{ "tinyint unsigned", SQL_TINYINT, 3, NULL, NULL, NULL,
1, 0, 3, 1, 0, 0, "Tiny integer unsigned",
0, 0, 10,
SQL_TINYINT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_TINY, 1
#else
MYSQL_TYPE_TINY, 1
#endif
},
{ "smallint unsigned", SQL_SMALLINT, 5, NULL, NULL, NULL,
1, 0, 3, 1, 0, 0, "Short integer unsigned",
0, 0, 10,
SQL_SMALLINT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_SHORT, 1
#else
MYSQL_TYPE_SHORT, 1
#endif
},
{ "mediumint unsigned", SQL_INTEGER, 8, NULL, NULL, NULL,
1, 0, 3, 1, 0, 0, "Medium integer unsigned",
0, 0, 10,
SQL_INTEGER, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_INT24, 1
#else
MYSQL_TYPE_INT24, 1
#endif
},
{ "int unsigned", SQL_INTEGER, 10, NULL, NULL, NULL,
1, 0, 3, 1, 0, 0, "integer unsigned",
0, 0, 10,
SQL_INTEGER, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_LONG, 1
#else
MYSQL_TYPE_LONG, 1
#endif
},
{ "int", SQL_INTEGER, 10, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "integer",
0, 0, 10,
SQL_INTEGER, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_LONG, 1
#else
MYSQL_TYPE_LONG, 1
#endif
},
{ "integer unsigned", SQL_INTEGER, 10, NULL, NULL, NULL,
1, 0, 3, 1, 0, 0, "integer",
0, 0, 10,
SQL_INTEGER, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_LONG, 1
#else
MYSQL_TYPE_LONG, 1
#endif
},
{ "bigint unsigned", SQL_BIGINT, 20, NULL, NULL, NULL,
1, 0, 3, 1, 0, 0, "Longlong integer unsigned",
0, 0, 10,
SQL_BIGINT, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_LONGLONG, 1
#else
MYSQL_TYPE_LONGLONG, 1
#endif
},
{ "text", SQL_LONGVARCHAR, 65535, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "large text object (0-65535)",
0, 0, 0,
SQL_LONGVARCHAR, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_BLOB, 0
#else
MYSQL_TYPE_BLOB, 0
#endif
},
{ "mediumtext", SQL_LONGVARCHAR, 16777215, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "large text object",
0, 0, 0,
SQL_LONGVARCHAR, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
FIELD_TYPE_MEDIUM_BLOB, 0
#else
MYSQL_TYPE_MEDIUM_BLOB, 0
#endif
},
{ "mediumint unsigned auto_increment", SQL_INTEGER, 8, NULL, NULL, NULL,
0, 0, 3, 1, 0, 1, "Medium integer unsigned auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_INTEGER, 0, 0, FIELD_TYPE_INT24, 1,
#else
SQL_INTEGER, 0, 0, MYSQL_TYPE_INT24, 1,
#endif
},
{ "tinyint unsigned auto_increment", SQL_TINYINT, 3, NULL, NULL, NULL,
0, 0, 3, 1, 0, 1, "tinyint unsigned auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_TINYINT, 0, 0, FIELD_TYPE_TINY, 1
#else
SQL_TINYINT, 0, 0, MYSQL_TYPE_TINY, 1
#endif
},
{ "smallint auto_increment", SQL_SMALLINT, 5, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "smallint auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_SMALLINT, 0, 0, FIELD_TYPE_SHORT, 1
#else
SQL_SMALLINT, 0, 0, MYSQL_TYPE_SHORT, 1
#endif
},
{ "int unsigned auto_increment", SQL_INTEGER, 10, NULL, NULL, NULL,
0, 0, 3, 1, 0, 1, "integer unsigned auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_INTEGER, 0, 0, FIELD_TYPE_LONG, 1
#else
SQL_INTEGER, 0, 0, MYSQL_TYPE_LONG, 1
#endif
},
{ "mediumint", SQL_INTEGER, 7, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "Medium integer", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_INTEGER, 0, 0, FIELD_TYPE_INT24, 1
#else
SQL_INTEGER, 0, 0, MYSQL_TYPE_INT24, 1
#endif
},
{ "bit", SQL_BIT, 1, NULL, NULL, NULL,
1, 0, 3, 0, 0, 0, "char(1)", 0, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_BIT, 0, 0, FIELD_TYPE_TINY, 0
#else
SQL_BIT, 0, 0, MYSQL_TYPE_TINY, 0
#endif
},
{ "numeric", SQL_NUMERIC, 19, NULL, NULL, "precision,scale",
1, 0, 3, 0, 0, 0, "numeric", 0, 19, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_NUMERIC, 0, 0, FIELD_TYPE_DECIMAL, 1,
#else
SQL_NUMERIC, 0, 0, MYSQL_TYPE_DECIMAL, 1,
#endif
},
{ "integer unsigned auto_increment", SQL_INTEGER, 10, NULL, NULL, NULL,
0, 0, 3, 1, 0, 1, "integer unsigned auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_INTEGER, 0, 0, FIELD_TYPE_LONG, 1,
#else
SQL_INTEGER, 0, 0, MYSQL_TYPE_LONG, 1,
#endif
},
{ "mediumint unsigned", SQL_INTEGER, 8, NULL, NULL, NULL,
1, 0, 3, 1, 0, 0, "Medium integer unsigned", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_INTEGER, 0, 0, FIELD_TYPE_INT24, 1
#else
SQL_INTEGER, 0, 0, MYSQL_TYPE_INT24, 1
#endif
},
{ "smallint unsigned auto_increment", SQL_SMALLINT, 5, NULL, NULL, NULL,
0, 0, 3, 1, 0, 1, "smallint unsigned auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_SMALLINT, 0, 0, FIELD_TYPE_SHORT, 1
#else
SQL_SMALLINT, 0, 0, MYSQL_TYPE_SHORT, 1
#endif
},
{ "int auto_increment", SQL_INTEGER, 10, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "integer auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_INTEGER, 0, 0, FIELD_TYPE_LONG, 1
#else
SQL_INTEGER, 0, 0, MYSQL_TYPE_LONG, 1
#endif
},
{ "long varbinary", SQL_LONGVARBINARY, 16777215, "0x", NULL, NULL,
1, 0, 3, 0, 0, 0, "mediumblob", 0, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_LONGVARBINARY, 0, 0, FIELD_TYPE_LONG_BLOB, 0
#else
SQL_LONGVARBINARY, 0, 0, MYSQL_TYPE_LONG_BLOB, 0
#endif
},
{ "double auto_increment", SQL_FLOAT, 15, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "double auto_increment", 0, 4, 2,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_FLOAT, 0, 0, FIELD_TYPE_DOUBLE, 1
#else
SQL_FLOAT, 0, 0, MYSQL_TYPE_DOUBLE, 1
#endif
},
{ "double auto_increment", SQL_DOUBLE, 15, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "double auto_increment", 0, 4, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_DOUBLE, 0, 0, FIELD_TYPE_DOUBLE, 1
#else
SQL_DOUBLE, 0, 0, MYSQL_TYPE_DOUBLE, 1
#endif
},
{ "integer auto_increment", SQL_INTEGER, 10, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "integer auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_INTEGER, 0, 0, FIELD_TYPE_LONG, 1,
#else
SQL_INTEGER, 0, 0, MYSQL_TYPE_LONG, 1,
#endif
},
{ "bigint auto_increment", SQL_BIGINT, 19, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "bigint auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_BIGINT, 0, 0, FIELD_TYPE_LONGLONG, 1
#else
SQL_BIGINT, 0, 0, MYSQL_TYPE_LONGLONG, 1
#endif
},
{ "bit auto_increment", SQL_BIT, 1, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "char(1) auto_increment", 0, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_BIT, 0, 0, FIELD_TYPE_TINY, 1
#else
SQL_BIT, 0, 0, MYSQL_TYPE_TINY, 1
#endif
},
{ "mediumint auto_increment", SQL_INTEGER, 7, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "Medium integer auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_INTEGER, 0, 0, FIELD_TYPE_INT24, 1
#else
SQL_INTEGER, 0, 0, MYSQL_TYPE_INT24, 1
#endif
},
{ "float auto_increment", SQL_REAL, 7, NULL, NULL, NULL,
0, 0, 0, 0, 0, 1, "float auto_increment", 0, 2, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_FLOAT, 0, 0, FIELD_TYPE_FLOAT, 1
#else
SQL_FLOAT, 0, 0, MYSQL_TYPE_FLOAT, 1
#endif
},
{ "long varchar", SQL_LONGVARCHAR, 16777215, "'", "'", NULL,
1, 0, 3, 0, 0, 0, "mediumtext", 0, 0, 0,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_LONGVARCHAR, 0, 0, FIELD_TYPE_MEDIUM_BLOB, 1
#else
SQL_LONGVARCHAR, 0, 0, MYSQL_TYPE_MEDIUM_BLOB, 1
#endif
},
{ "tinyint auto_increment", SQL_TINYINT, 3, NULL, NULL, NULL,
0, 0, 3, 0, 0, 1, "tinyint auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_TINYINT, 0, 0, FIELD_TYPE_TINY, 1
#else
SQL_TINYINT, 0, 0, MYSQL_TYPE_TINY, 1
#endif
},
{ "bigint unsigned auto_increment", SQL_BIGINT, 20, NULL, NULL, NULL,
0, 0, 3, 1, 0, 1, "bigint unsigned auto_increment", 0, 0, 10,
#if MYSQL_VERSION_ID < MYSQL_VERSION_5_0
SQL_BIGINT, 0, 0, FIELD_TYPE_LONGLONG, 1
#else
SQL_BIGINT, 0, 0, MYSQL_TYPE_LONGLONG, 1
#endif
},
/* END MORE STUFF */
};
/*
static const sql_type_info_t* native2sql (int t)
*/
static const sql_type_info_t *native2sql(int t)
{
switch (t) {
case FIELD_TYPE_VAR_STRING: return &SQL_GET_TYPE_INFO_values[0];
case FIELD_TYPE_DECIMAL: return &SQL_GET_TYPE_INFO_values[1];
#ifdef FIELD_TYPE_NEWDECIMAL
case FIELD_TYPE_NEWDECIMAL: return &SQL_GET_TYPE_INFO_values[1];
#endif
case FIELD_TYPE_TINY: return &SQL_GET_TYPE_INFO_values[2];
case FIELD_TYPE_SHORT: return &SQL_GET_TYPE_INFO_values[3];
case FIELD_TYPE_LONG: return &SQL_GET_TYPE_INFO_values[4];
case FIELD_TYPE_FLOAT: return &SQL_GET_TYPE_INFO_values[5];
/* 6 */
case FIELD_TYPE_DOUBLE: return &SQL_GET_TYPE_INFO_values[7];
case FIELD_TYPE_TIMESTAMP: return &SQL_GET_TYPE_INFO_values[8];
case FIELD_TYPE_LONGLONG: return &SQL_GET_TYPE_INFO_values[9];
case FIELD_TYPE_INT24: return &SQL_GET_TYPE_INFO_values[10];
case FIELD_TYPE_DATE: return &SQL_GET_TYPE_INFO_values[11];
case FIELD_TYPE_TIME: return &SQL_GET_TYPE_INFO_values[12];
case FIELD_TYPE_DATETIME: return &SQL_GET_TYPE_INFO_values[13];
case FIELD_TYPE_YEAR: return &SQL_GET_TYPE_INFO_values[14];
case FIELD_TYPE_NEWDATE: return &SQL_GET_TYPE_INFO_values[15];
case FIELD_TYPE_ENUM: return &SQL_GET_TYPE_INFO_values[16];
case FIELD_TYPE_SET: return &SQL_GET_TYPE_INFO_values[17];
case FIELD_TYPE_BLOB: return &SQL_GET_TYPE_INFO_values[18];
case FIELD_TYPE_TINY_BLOB: return &SQL_GET_TYPE_INFO_values[19];
case FIELD_TYPE_MEDIUM_BLOB: return &SQL_GET_TYPE_INFO_values[20];
case FIELD_TYPE_LONG_BLOB: return &SQL_GET_TYPE_INFO_values[21];
case FIELD_TYPE_STRING: return &SQL_GET_TYPE_INFO_values[22];
default: return &SQL_GET_TYPE_INFO_values[0];
}
}
#define SQL_GET_TYPE_INFO_num \
(sizeof(SQL_GET_TYPE_INFO_values)/sizeof(sql_type_info_t))
/***************************************************************************
*
* Name: dbd_init
*
* Purpose: Called when the driver is installed by DBI
*
* Input: dbistate - pointer to the DBI state variable, used for some
* DBI internal things
*
* Returns: Nothing
*
**************************************************************************/
void dbd_init(dbistate_t* dbistate)
{
dTHX;
DBISTATE_INIT;
}
/**************************************************************************
*
* Name: do_error, do_warn
*
* Purpose: Called to associate an error code and an error message
* to some handle
*
* Input: h - the handle in error condition
* rc - the error code
* what - the error message
*
* Returns: Nothing
*
**************************************************************************/
void do_error(SV* h, int rc, const char* what, const char* sqlstate)
{
dTHX;
D_imp_xxh(h);
STRLEN lna;
SV *errstr;
SV *errstate;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\t--> do_error\n");
errstr= DBIc_ERRSTR(imp_xxh);
sv_setiv(DBIc_ERR(imp_xxh), (IV)rc); /* set err early */
sv_setpv(errstr, what);
#if MYSQL_VERSION_ID >= SQL_STATE_VERSION
if (sqlstate)
{
errstate= DBIc_STATE(imp_xxh);
sv_setpvn(errstate, sqlstate, 5);
}
#endif
/* NO EFFECT DBIh_EVENT2(h, ERROR_event, DBIc_ERR(imp_xxh), errstr); */
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%s error %d recorded: %s\n",
what, rc, SvPV(errstr,lna));
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\t<-- do_error\n");
}
/*
void do_warn(SV* h, int rc, char* what)
*/
void do_warn(SV* h, int rc, char* what)
{
dTHX;
D_imp_xxh(h);
STRLEN lna;
SV *errstr = DBIc_ERRSTR(imp_xxh);
sv_setiv(DBIc_ERR(imp_xxh), (IV)rc); /* set err early */
sv_setpv(errstr, what);
/* NO EFFECT DBIh_EVENT2(h, WARN_event, DBIc_ERR(imp_xxh), errstr);*/
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%s warning %d recorded: %s\n",
what, rc, SvPV(errstr,lna));
warn("%s", what);
}
#if defined(DBD_MYSQL_EMBEDDED)
#define DBD_MYSQL_NAMESPACE "DBD::mysqlEmb::QUIET";
#else
#define DBD_MYSQL_NAMESPACE "DBD::mysql::QUIET";
#endif
#define doquietwarn(s) \
{ \
SV* sv = perl_get_sv(DBD_MYSQL_NAMESPACE, FALSE); \
if (!sv || !SvTRUE(sv)) { \
warn s; \
} \
}
/***************************************************************************
*
* Name: mysql_dr_connect
*
* Purpose: Replacement for mysql_connect
*
* Input: MYSQL* sock - Pointer to a MYSQL structure being
* initialized
* char* mysql_socket - Name of a UNIX socket being used
* or NULL
* char* host - Host name being used or NULL for localhost
* char* port - Port number being used or NULL for default
* char* user - User name being used or NULL
* char* password - Password being used or NULL
* char* dbname - Database name being used or NULL
* char* imp_dbh - Pointer to internal dbh structure
*
* Returns: The sock argument for success, NULL otherwise;
* you have to call do_error in the latter case.
*
**************************************************************************/
MYSQL *mysql_dr_connect(
SV* dbh,
MYSQL* sock,
char* mysql_socket,
char* host,
char* port,
char* user,
char* password,
char* dbname,
imp_dbh_t *imp_dbh)
{
int portNr;
unsigned int client_flag;
MYSQL* result;
dTHX;
D_imp_xxh(dbh);
/* per Monty, already in client.c in API */
/* but still not exist in libmysqld.c */
#if defined(DBD_MYSQL_EMBEDDED)
if (host && !*host) host = NULL;
#endif
portNr= (port && *port) ? atoi(port) : 0;
/* already in client.c in API */
/* if (user && !*user) user = NULL; */
/* if (password && !*password) password = NULL; */
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: host = |%s|, port = %d," \
" uid = %s, pwd = %s\n",
host ? host : "NULL", portNr,
user ? user : "NULL",
password ? password : "NULL");
{
#if defined(DBD_MYSQL_EMBEDDED)
if (imp_dbh)
{
D_imp_drh_from_dbh;
SV* sv = DBIc_IMP_DATA(imp_dbh);
if (sv && SvROK(sv))
{
SV** svp;
STRLEN lna;
char * options;
int server_args_cnt= 0;
int server_groups_cnt= 0;
int rc= 0;
char ** server_args = NULL;
char ** server_groups = NULL;
HV* hv = (HV*) SvRV(sv);
if (SvTYPE(hv) != SVt_PVHV)
return NULL;
if (!imp_drh->embedded.state)
{
/* Init embedded server */
if ((svp = hv_fetch(hv, "mysql_embedded_groups", 21, FALSE)) &&
*svp && SvTRUE(*svp))
{
options = SvPV(*svp, lna);
imp_drh->embedded.groups=newSVsv(*svp);
if ((server_groups_cnt=count_embedded_options(options)))
{
/* number of server_groups always server_groups+1 */
server_groups=fill_out_embedded_options(options, 0,
(int)lna, ++server_groups_cnt);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
{
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"Groups names passed to embedded server:\n");
print_embedded_options(DBIc_LOGPIO(imp_xxh), server_groups, server_groups_cnt);
}
}
}
if ((svp = hv_fetch(hv, "mysql_embedded_options", 22, FALSE)) &&
*svp && SvTRUE(*svp))
{
options = SvPV(*svp, lna);
imp_drh->embedded.args=newSVsv(*svp);
if ((server_args_cnt=count_embedded_options(options)))
{
/* number of server_options always server_options+1 */
server_args=fill_out_embedded_options(options, 1, (int)lna, ++server_args_cnt);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
{
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Server options passed to embedded server:\n");
print_embedded_options(DBIc_LOGPIO(imp_xxh), server_args, server_args_cnt);
}
}
}
if (mysql_server_init(server_args_cnt, server_args, server_groups))
{
do_warn(dbh, AS_ERR_EMBEDDED, "Embedded server was not started. \
Could not initialize environment.");
return NULL;
}
imp_drh->embedded.state=1;
if (server_args_cnt)
free_embedded_options(server_args, server_args_cnt);
if (server_groups_cnt)
free_embedded_options(server_groups, server_groups_cnt);
}
else
{
/*
* Check if embedded parameters passed to connect() differ from
* first ones
*/
if ( ((svp = hv_fetch(hv, "mysql_embedded_groups", 21, FALSE)) &&
*svp && SvTRUE(*svp)))
rc =+ abs(sv_cmp(*svp, imp_drh->embedded.groups));
if ( ((svp = hv_fetch(hv, "mysql_embedded_options", 22, FALSE)) &&
*svp && SvTRUE(*svp)) )
rc =+ abs(sv_cmp(*svp, imp_drh->embedded.args));
if (rc)
{
do_warn(dbh, AS_ERR_EMBEDDED,
"Embedded server was already started. You cannot pass init\
parameters to embedded server once");
return NULL;
}
}
}
}
#endif
#ifdef MYSQL_NO_CLIENT_FOUND_ROWS
client_flag = 0;
#else
client_flag = CLIENT_FOUND_ROWS;
#endif
mysql_init(sock);
if (imp_dbh)
{
SV* sv = DBIc_IMP_DATA(imp_dbh);
DBIc_set(imp_dbh, DBIcf_AutoCommit, TRUE);
if (sv && SvROK(sv))
{
HV* hv = (HV*) SvRV(sv);
SV** svp;
STRLEN lna;
/* thanks to Peter John Edwards for mysql_init_command */
if ((svp = hv_fetch(hv, "mysql_init_command", 18, FALSE)) &&
*svp && SvTRUE(*svp))
{
char* df = SvPV(*svp, lna);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Setting" \
" init command (%s).\n", df);
mysql_options(sock, MYSQL_INIT_COMMAND, df);
}
if ((svp = hv_fetch(hv, "mysql_compression", 17, FALSE)) &&
*svp && SvTRUE(*svp))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Enabling" \
" compression.\n");
mysql_options(sock, MYSQL_OPT_COMPRESS, NULL);
}
if ((svp = hv_fetch(hv, "mysql_connect_timeout", 21, FALSE))
&& *svp && SvTRUE(*svp))
{
int to = SvIV(*svp);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Setting" \
" connect timeout (%d).\n",to);
mysql_options(sock, MYSQL_OPT_CONNECT_TIMEOUT,
(const char *)&to);
}
if ((svp = hv_fetch(hv, "mysql_write_timeout", 19, FALSE))
&& *svp && SvTRUE(*svp))
{
int to = SvIV(*svp);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Setting" \
" write timeout (%d).\n",to);
mysql_options(sock, MYSQL_OPT_WRITE_TIMEOUT,
(const char *)&to);
}
if ((svp = hv_fetch(hv, "mysql_read_timeout", 18, FALSE))
&& *svp && SvTRUE(*svp))
{
int to = SvIV(*svp);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Setting" \
" read timeout (%d).\n",to);
mysql_options(sock, MYSQL_OPT_READ_TIMEOUT,
(const char *)&to);
}
if ((svp = hv_fetch(hv, "mysql_skip_secure_auth", 22, FALSE)) &&
*svp && SvTRUE(*svp))
{
my_bool secauth = 0;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Skipping" \
" secure auth\n");
mysql_options(sock, MYSQL_SECURE_AUTH, &secauth);
}
if ((svp = hv_fetch(hv, "mysql_read_default_file", 23, FALSE)) &&
*svp && SvTRUE(*svp))
{
char* df = SvPV(*svp, lna);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Reading" \
" default file %s.\n", df);
mysql_options(sock, MYSQL_READ_DEFAULT_FILE, df);
}
if ((svp = hv_fetch(hv, "mysql_read_default_group", 24,
FALSE)) &&
*svp && SvTRUE(*svp)) {
char* gr = SvPV(*svp, lna);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Using" \
" default group %s.\n", gr);
mysql_options(sock, MYSQL_READ_DEFAULT_GROUP, gr);
}
#if (MYSQL_VERSION_ID >= 50606)
if ((svp = hv_fetch(hv, "mysql_conn_attrs", 16, FALSE)) && *svp) {
HV* attrs = (HV*) SvRV(*svp);
HE* entry = NULL;
I32 num_entries = hv_iterinit(attrs);
while (num_entries && (entry = hv_iternext(attrs))) {
I32 retlen = 0;
char *attr_name = hv_iterkey(entry, &retlen);
SV *sv_attr_val = hv_iterval(attrs, entry);
char *attr_val = SvPV(sv_attr_val, lna);
mysql_options4(sock, MYSQL_OPT_CONNECT_ATTR_ADD, attr_name, attr_val);
}
}
#endif
if ((svp = hv_fetch(hv, "mysql_client_found_rows", 23, FALSE)) && *svp)
{
if (SvTRUE(*svp))
client_flag |= CLIENT_FOUND_ROWS;
else
client_flag &= ~CLIENT_FOUND_ROWS;
}
if ((svp = hv_fetch(hv, "mysql_use_result", 16, FALSE)) && *svp)
{
imp_dbh->use_mysql_use_result = SvTRUE(*svp);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->use_mysql_use_result: %d\n",
imp_dbh->use_mysql_use_result);
}
if ((svp = hv_fetch(hv, "mysql_bind_type_guessing", 24, TRUE)) && *svp)
{
imp_dbh->bind_type_guessing= SvTRUE(*svp);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->bind_type_guessing: %d\n",
imp_dbh->bind_type_guessing);
}
if ((svp = hv_fetch(hv, "mysql_bind_comment_placeholders", 31, FALSE)) && *svp)
{
imp_dbh->bind_comment_placeholders = SvTRUE(*svp);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->bind_comment_placeholders: %d\n",
imp_dbh->bind_comment_placeholders);
}
if ((svp = hv_fetch(hv, "mysql_no_autocommit_cmd", 23, FALSE)) && *svp)
{
imp_dbh->no_autocommit_cmd= SvTRUE(*svp);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->no_autocommit_cmd: %d\n",
imp_dbh->no_autocommit_cmd);
}
#if FABRIC_SUPPORT
if ((svp = hv_fetch(hv, "mysql_use_fabric", 16, FALSE)) &&
*svp && SvTRUE(*svp))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->use_fabric: Enabling use of" \
" MySQL Fabric.\n");
mysql_options(sock, MYSQL_OPT_USE_FABRIC, NULL);
}
#endif
#if defined(CLIENT_MULTI_STATEMENTS)
if ((svp = hv_fetch(hv, "mysql_multi_statements", 22, FALSE)) && *svp)
{
if (SvTRUE(*svp))
client_flag |= CLIENT_MULTI_STATEMENTS;
else
client_flag &= ~CLIENT_MULTI_STATEMENTS;
}
#endif
#if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
/* took out client_flag |= CLIENT_PROTOCOL_41; */
/* because libmysql.c already sets this no matter what */
if ((svp = hv_fetch(hv, "mysql_server_prepare", 20, FALSE))
&& *svp)
{
if (SvTRUE(*svp))
{
client_flag |= CLIENT_PROTOCOL_41;
imp_dbh->use_server_side_prepare = TRUE;
}
else
{
client_flag &= ~CLIENT_PROTOCOL_41;
imp_dbh->use_server_side_prepare = FALSE;
}
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->use_server_side_prepare: %d\n",
imp_dbh->use_server_side_prepare);
#endif
/* HELMUT */
#if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
if ((svp = hv_fetch(hv, "mysql_enable_utf8mb4", 20, FALSE)) && *svp && SvTRUE(*svp)) {
mysql_options(sock, MYSQL_SET_CHARSET_NAME, "utf8mb4");
}
else if ((svp = hv_fetch(hv, "mysql_enable_utf8", 17, FALSE)) && *svp) {
/* Do not touch imp_dbh->enable_utf8 as we are called earlier
* than it is set and mysql_options() must be before:
* mysql_real_connect()
*/
mysql_options(sock, MYSQL_SET_CHARSET_NAME,
(SvTRUE(*svp) ? "utf8" : "latin1"));
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"mysql_options: MYSQL_SET_CHARSET_NAME=%s\n",
(SvTRUE(*svp) ? "utf8" : "latin1"));
}
#endif
#if defined(DBD_MYSQL_WITH_SSL) && !defined(DBD_MYSQL_EMBEDDED) && \
(defined(CLIENT_SSL) || (MYSQL_VERSION_ID >= 40000))
if ((svp = hv_fetch(hv, "mysql_ssl", 9, FALSE)) && *svp)
{
if (SvTRUE(*svp))
{
char *client_key = NULL;
char *client_cert = NULL;
char *ca_file = NULL;
char *ca_path = NULL;
char *cipher = NULL;
STRLEN lna;
#if MYSQL_VERSION_ID >= SSL_VERIFY_VERSION
/*
New code to utilise MySQLs new feature that verifies that the
server's hostname that the client connects to matches that of
the certificate
*/
my_bool ssl_verify_true = 0;
if ((svp = hv_fetch(hv, "mysql_ssl_verify_server_cert", 28, FALSE)) && *svp)
ssl_verify_true = SvTRUE(*svp);
#endif
if ((svp = hv_fetch(hv, "mysql_ssl_client_key", 20, FALSE)) && *svp)
client_key = SvPV(*svp, lna);
if ((svp = hv_fetch(hv, "mysql_ssl_client_cert", 21, FALSE)) &&
*svp)
client_cert = SvPV(*svp, lna);
if ((svp = hv_fetch(hv, "mysql_ssl_ca_file", 17, FALSE)) &&
*svp)
ca_file = SvPV(*svp, lna);
if ((svp = hv_fetch(hv, "mysql_ssl_ca_path", 17, FALSE)) &&
*svp)
ca_path = SvPV(*svp, lna);
if ((svp = hv_fetch(hv, "mysql_ssl_cipher", 16, FALSE)) &&
*svp)
cipher = SvPV(*svp, lna);
mysql_ssl_set(sock, client_key, client_cert, ca_file,
ca_path, cipher);
#if MYSQL_VERSION_ID >= SSL_VERIFY_VERSION
mysql_options(sock, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, &ssl_verify_true);
#endif
client_flag |= CLIENT_SSL;
}
}
#endif
#if (MYSQL_VERSION_ID >= 32349)
/*
* MySQL 3.23.49 disables LOAD DATA LOCAL by default. Use
* mysql_local_infile=1 in the DSN to enable it.
*/
if ((svp = hv_fetch( hv, "mysql_local_infile", 18, FALSE)) && *svp)
{
unsigned int flag = SvTRUE(*svp);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->mysql_dr_connect: Using" \
" local infile %u.\n", flag);
mysql_options(sock, MYSQL_OPT_LOCAL_INFILE, (const char *) &flag);
}
#endif
}
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: client_flags = %d\n",
client_flag);
#if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION
client_flag|= CLIENT_MULTI_RESULTS;
#endif
result = mysql_real_connect(sock, host, user, password, dbname,
portNr, mysql_socket, client_flag);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->mysql_dr_connect: <-");
if (result)
{
#if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
/* connection succeeded. */
/* imp_dbh == NULL when mysql_dr_connect() is called from mysql.xs
functions (_admin_internal(),_ListDBs()). */
if (!(result->client_flag & CLIENT_PROTOCOL_41) && imp_dbh)
imp_dbh->use_server_side_prepare = FALSE;
#endif
#if MYSQL_ASYNC
if(imp_dbh) {
imp_dbh->async_query_in_flight = NULL;
}
#endif
/*
we turn off Mysql's auto reconnect and handle re-connecting ourselves
so that we can keep track of when this happens.
*/
result->reconnect=0;
}
else {
/*
sock was allocated with mysql_init()
fixes: https://rt.cpan.org/Ticket/Display.html?id=86153
Safefree(sock);
rurban: No, we still need this handle later in mysql_dr_error().
RT #97625. It will be freed as imp_dbh->pmysql in dbd_db_destroy(),
which is called by the DESTROY handler.
*/
}
return result;
}
}
/*
safe_hv_fetch
*/
static char *safe_hv_fetch(pTHX_ HV *hv, const char *name, int name_length)
{
SV** svp;
STRLEN len;
char *res= NULL;
if ((svp= hv_fetch(hv, name, name_length, FALSE)))
{
res= SvPV(*svp, len);
if (!len)
res= NULL;
}
return res;
}
/*
Frontend for mysql_dr_connect
*/
static int my_login(pTHX_ SV* dbh, imp_dbh_t *imp_dbh)
{
SV* sv;
HV* hv;
char* dbname;
char* host;
char* port;
char* user;
char* password;
char* mysql_socket;
int result;
int fresh = 0;
D_imp_xxh(dbh);
/* TODO- resolve this so that it is set only if DBI is 1.607 */
#define TAKE_IMP_DATA_VERSION 1
#if TAKE_IMP_DATA_VERSION
if (DBIc_has(imp_dbh, DBIcf_IMPSET))
{ /* eg from take_imp_data() */
if (DBIc_has(imp_dbh, DBIcf_ACTIVE))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "my_login skip connect\n");
/* tell our parent we've adopted an active child */
++DBIc_ACTIVE_KIDS(DBIc_PARENT_COM(imp_dbh));
return TRUE;
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"my_login IMPSET but not ACTIVE so connect not skipped\n");
}
#endif
sv = DBIc_IMP_DATA(imp_dbh);
if (!sv || !SvROK(sv))
return FALSE;
hv = (HV*) SvRV(sv);
if (SvTYPE(hv) != SVt_PVHV)
return FALSE;
host= safe_hv_fetch(aTHX_ hv, "host", 4);
port= safe_hv_fetch(aTHX_ hv, "port", 4);
user= safe_hv_fetch(aTHX_ hv, "user", 4);
password= safe_hv_fetch(aTHX_ hv, "password", 8);
dbname= safe_hv_fetch(aTHX_ hv, "database", 8);
mysql_socket= safe_hv_fetch(aTHX_ hv, "mysql_socket", 12);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->my_login : dbname = %s, uid = %s, pwd = %s," \
"host = %s, port = %s\n",
dbname ? dbname : "NULL",
user ? user : "NULL",
password ? password : "NULL",
host ? host : "NULL",
port ? port : "NULL");
if (!imp_dbh->pmysql) {
fresh = 1;
Newz(908, imp_dbh->pmysql, 1, MYSQL);
}
result = mysql_dr_connect(dbh, imp_dbh->pmysql, mysql_socket, host, port, user,
password, dbname, imp_dbh) ? TRUE : FALSE;
return result;
}
/**************************************************************************
*
* Name: dbd_db_login
*
* Purpose: Called for connecting to a database and logging in.
*
* Input: dbh - database handle being initialized
* imp_dbh - drivers private database handle data
* dbname - the database we want to log into; may be like
* "dbname:host" or "dbname:host:port"
* user - user name to connect as
* password - passwort to connect with
*
* Returns: TRUE for success, FALSE otherwise; do_error has already
* been called in the latter case
*
**************************************************************************/
int dbd_db_login(SV* dbh, imp_dbh_t* imp_dbh, char* dbname, char* user,
char* password) {
#ifdef dTHR
dTHR;
#endif
dTHX;
D_imp_xxh(dbh);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"imp_dbh->connect: dsn = %s, uid = %s, pwd = %s\n",
dbname ? dbname : "NULL",
user ? user : "NULL",
password ? password : "NULL");
imp_dbh->stats.auto_reconnects_ok= 0;
imp_dbh->stats.auto_reconnects_failed= 0;
imp_dbh->bind_type_guessing= FALSE;
imp_dbh->bind_comment_placeholders= FALSE;
imp_dbh->has_transactions= TRUE;
/* Safer we flip this to TRUE perl side if we detect a mod_perl env. */
imp_dbh->auto_reconnect = FALSE;
/* HELMUT */
#if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
imp_dbh->enable_utf8 = FALSE; /* initialize mysql_enable_utf8 */
imp_dbh->enable_utf8mb4 = FALSE; /* initialize mysql_enable_utf8mb4 */
#endif
if (!my_login(aTHX_ dbh, imp_dbh))
{
if(imp_dbh->pmysql) {
do_error(dbh, mysql_errno(imp_dbh->pmysql),
mysql_error(imp_dbh->pmysql) ,mysql_sqlstate(imp_dbh->pmysql));
Safefree(imp_dbh->pmysql);
}
return FALSE;
}
/*
* Tell DBI, that dbh->disconnect should be called for this handle
*/
DBIc_ACTIVE_on(imp_dbh);
/* Tell DBI, that dbh->destroy should be called for this handle */
DBIc_on(imp_dbh, DBIcf_IMPSET);
return TRUE;
}
/***************************************************************************
*
* Name: dbd_db_commit
* dbd_db_rollback
*
* Purpose: You guess what they should do.
*
* Input: dbh - database handle being commited or rolled back
* imp_dbh - drivers private database handle data
*
* Returns: TRUE for success, FALSE otherwise; do_error has already
* been called in the latter case
*
**************************************************************************/
int
dbd_db_commit(SV* dbh, imp_dbh_t* imp_dbh)
{
if (DBIc_has(imp_dbh, DBIcf_AutoCommit))
return FALSE;
ASYNC_CHECK_RETURN(dbh, FALSE);
if (imp_dbh->has_transactions)
{
#if MYSQL_VERSION_ID < SERVER_PREPARE_VERSION
if (mysql_real_query(imp_dbh->pmysql, "COMMIT", 6))
#else
if (mysql_commit(imp_dbh->pmysql))
#endif
{
do_error(dbh, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql)
,mysql_sqlstate(imp_dbh->pmysql));
return FALSE;
}
}
else
do_warn(dbh, JW_ERR_NOT_IMPLEMENTED,
"Commit ineffective because transactions are not available");
return TRUE;
}
/*
dbd_db_rollback
*/
int
dbd_db_rollback(SV* dbh, imp_dbh_t* imp_dbh) {
/* croak, if not in AutoCommit mode */
if (DBIc_has(imp_dbh, DBIcf_AutoCommit))
return FALSE;
ASYNC_CHECK_RETURN(dbh, FALSE);
if (imp_dbh->has_transactions)
{
#if MYSQL_VERSION_ID < SERVER_PREPARE_VERSION
if (mysql_real_query(imp_dbh->pmysql, "ROLLBACK", 8))
#else
if (mysql_rollback(imp_dbh->pmysql))
#endif
{
do_error(dbh, mysql_errno(imp_dbh->pmysql),
mysql_error(imp_dbh->pmysql) ,mysql_sqlstate(imp_dbh->pmysql));
return FALSE;
}
}
else
do_error(dbh, JW_ERR_NOT_IMPLEMENTED,
"Rollback ineffective because transactions are not available" ,NULL);
return TRUE;
}
/*
***************************************************************************
*
* Name: dbd_db_disconnect
*
* Purpose: Disconnect a database handle from its database
*
* Input: dbh - database handle being disconnected
* imp_dbh - drivers private database handle data
*
* Returns: TRUE for success, FALSE otherwise; do_error has already
* been called in the latter case
*
**************************************************************************/
int dbd_db_disconnect(SV* dbh, imp_dbh_t* imp_dbh)
{
#ifdef dTHR
dTHR;
#endif
dTHX;
D_imp_xxh(dbh);
/* We assume that disconnect will always work */
/* since most errors imply already disconnected. */
DBIc_ACTIVE_off(imp_dbh);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "imp_dbh->pmysql: %lx\n",
(long) imp_dbh->pmysql);
mysql_close(imp_dbh->pmysql );
/* We don't free imp_dbh since a reference still exists */
/* The DESTROY method is the only one to 'free' memory. */
return TRUE;
}
/***************************************************************************
*
* Name: dbd_discon_all
*
* Purpose: Disconnect all database handles at shutdown time
*
* Input: dbh - database handle being disconnected
* imp_dbh - drivers private database handle data
*
* Returns: TRUE for success, FALSE otherwise; do_error has already
* been called in the latter case
*
**************************************************************************/
int dbd_discon_all (SV *drh, imp_drh_t *imp_drh) {
#if defined(dTHR)
dTHR;
#endif
dTHX;
D_imp_xxh(drh);
#if defined(DBD_MYSQL_EMBEDDED)
if (imp_drh->embedded.state)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Stop embedded server\n");
mysql_server_end();
if (imp_drh->embedded.groups)
{
(void) SvREFCNT_dec(imp_drh->embedded.groups);
imp_drh->embedded.groups = NULL;
}
if (imp_drh->embedded.args)
{
(void) SvREFCNT_dec(imp_drh->embedded.args);
imp_drh->embedded.args = NULL;
}
}
#else
mysql_server_end();
#endif
/* The disconnect_all concept is flawed and needs more work */
if (!PL_dirty && !SvTRUE(perl_get_sv("DBI::PERL_ENDING",0))) {
sv_setiv(DBIc_ERR(imp_drh), (IV)1);
sv_setpv(DBIc_ERRSTR(imp_drh),
(char*)"disconnect_all not implemented");
/* NO EFFECT DBIh_EVENT2(drh, ERROR_event,
DBIc_ERR(imp_drh), DBIc_ERRSTR(imp_drh)); */
return FALSE;
}
PL_perl_destruct_level = 0;
return FALSE;
}
/****************************************************************************
*
* Name: dbd_db_destroy
*
* Purpose: Our part of the dbh destructor
*
* Input: dbh - database handle being destroyed
* imp_dbh - drivers private database handle data
*
* Returns: Nothing
*
**************************************************************************/
void dbd_db_destroy(SV* dbh, imp_dbh_t* imp_dbh) {
/*
* Being on the safe side never hurts ...
*/
if (DBIc_ACTIVE(imp_dbh))
{
if (imp_dbh->has_transactions)
{
if (!DBIc_has(imp_dbh, DBIcf_AutoCommit))
#if MYSQL_VERSION_ID < SERVER_PREPARE_VERSION
if ( mysql_real_query(imp_dbh->pmysql, "ROLLBACK", 8))
#else
if (mysql_rollback(imp_dbh->pmysql))
#endif
do_error(dbh, TX_ERR_ROLLBACK,"ROLLBACK failed" ,NULL);
}
dbd_db_disconnect(dbh, imp_dbh);
}
Safefree(imp_dbh->pmysql);
/* Tell DBI, that dbh->destroy must no longer be called */
DBIc_off(imp_dbh, DBIcf_IMPSET);
}
/*
***************************************************************************
*
* Name: dbd_db_STORE_attrib
*
* Purpose: Function for storing dbh attributes; we currently support
* just nothing. :-)
*
* Input: dbh - database handle being modified
* imp_dbh - drivers private database handle data
* keysv - the attribute name
* valuesv - the attribute value
*
* Returns: TRUE for success, FALSE otherwise
*
**************************************************************************/
int
dbd_db_STORE_attrib(
SV* dbh,
imp_dbh_t* imp_dbh,
SV* keysv,
SV* valuesv
)
{
dTHX;
STRLEN kl;
char *key = SvPV(keysv, kl);
SV *cachesv = Nullsv;
int cacheit = FALSE;
const bool bool_value = SvTRUE(valuesv);
if (kl==10 && strEQ(key, "AutoCommit"))
{
if (imp_dbh->has_transactions)
{
bool oldval = DBIc_has(imp_dbh,DBIcf_AutoCommit) ? 1 : 0;
if (bool_value == oldval)
return TRUE;
/* if setting AutoCommit on ... */
if (!imp_dbh->no_autocommit_cmd)
{
if (
#if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
mysql_autocommit(imp_dbh->pmysql, bool_value)
#else
mysql_real_query(imp_dbh->pmysql,
bool_value ? "SET AUTOCOMMIT=1" : "SET AUTOCOMMIT=0",
16)
#endif
)
{
do_error(dbh, TX_ERR_AUTOCOMMIT,
bool_value ?
"Turning on AutoCommit failed" :
"Turning off AutoCommit failed"
,NULL);
return TRUE; /* TRUE means we handled it - important to avoid spurious errors */
}
}
DBIc_set(imp_dbh, DBIcf_AutoCommit, bool_value);
}
else
{
/*
* We do support neither transactions nor "AutoCommit".
* But we stub it. :-)
*/
if (!bool_value)
{
do_error(dbh, JW_ERR_NOT_IMPLEMENTED,
"Transactions not supported by database" ,NULL);
croak("Transactions not supported by database");
}
}
}
else if (kl == 16 && strEQ(key,"mysql_use_result"))
imp_dbh->use_mysql_use_result = bool_value;
else if (kl == 20 && strEQ(key,"mysql_auto_reconnect"))
imp_dbh->auto_reconnect = bool_value;
else if (kl == 20 && strEQ(key, "mysql_server_prepare"))
imp_dbh->use_server_side_prepare = bool_value;
else if (kl == 23 && strEQ(key,"mysql_no_autocommit_cmd"))
imp_dbh->no_autocommit_cmd = bool_value;
else if (kl == 24 && strEQ(key,"mysql_bind_type_guessing"))
imp_dbh->bind_type_guessing = bool_value;
else if (kl == 31 && strEQ(key,"mysql_bind_comment_placeholders"))
imp_dbh->bind_type_guessing = bool_value;
#if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
else if (kl == 17 && strEQ(key, "mysql_enable_utf8"))
imp_dbh->enable_utf8 = bool_value;
else if (kl == 20 && strEQ(key, "mysql_enable_utf8mb4"))
imp_dbh->enable_utf8mb4 = bool_value;
#endif
#if FABRIC_SUPPORT
else if (kl == 22 && strEQ(key, "mysql_fabric_opt_group"))
mysql_options(imp_dbh->pmysql, FABRIC_OPT_GROUP, (void *)SvPVbyte_nolen(valuesv));
else if (kl == 29 && strEQ(key, "mysql_fabric_opt_default_mode"))
{
if (SvOK(valuesv)) {
STRLEN len;
const char *str = SvPVbyte(valuesv, len);
if ( len == 0 || ( len == 2 && (strnEQ(str, "ro", 3) || strnEQ(str, "rw", 3)) ) )
mysql_options(imp_dbh->pmysql, FABRIC_OPT_DEFAULT_MODE, len == 0 ? NULL : str);
else
croak("Valid settings for FABRIC_OPT_DEFAULT_MODE are 'ro', 'rw', or undef/empty string");
}
else {
mysql_options(imp_dbh->pmysql, FABRIC_OPT_DEFAULT_MODE, NULL);
}
}
else if (kl == 21 && strEQ(key, "mysql_fabric_opt_mode"))
{
STRLEN len;
const char *str = SvPVbyte(valuesv, len);
if (len != 2 || (strnNE(str, "ro", 3) && strnNE(str, "rw", 3)))
croak("Valid settings for FABRIC_OPT_MODE are 'ro' or 'rw'");
mysql_options(imp_dbh->pmysql, FABRIC_OPT_MODE, str);
}
else if (kl == 34 && strEQ(key, "mysql_fabric_opt_group_credentials"))
{
croak("'fabric_opt_group_credentials' is not supported");
}
#endif
else
return FALSE; /* Unknown key */
if (cacheit) /* cache value for later DBI 'quick' fetch? */
hv_store((HV*)SvRV(dbh), key, kl, cachesv, 0);
return TRUE;
}
/***************************************************************************
*
* Name: dbd_db_FETCH_attrib
*
* Purpose: Function for fetching dbh attributes
*
* Input: dbh - database handle being queried
* imp_dbh - drivers private database handle data
* keysv - the attribute name
*
* Returns: An SV*, if sucessfull; NULL otherwise
*
* Notes: Do not forget to call sv_2mortal in the former case!
*
**************************************************************************/
static SV*
my_ulonglong2str(pTHX_ my_ulonglong val)
{
char buf[64];
char *ptr = buf + sizeof(buf) - 1;
if (val == 0)
return newSVpv("0", 1);
*ptr = '\0';
while (val > 0)
{
*(--ptr) = ('0' + (val % 10));
val = val / 10;
}
return newSVpv(ptr, (buf+ sizeof(buf) - 1) - ptr);
}
SV* dbd_db_FETCH_attrib(SV *dbh, imp_dbh_t *imp_dbh, SV *keysv)
{
dTHX;
STRLEN kl;
char *key = SvPV(keysv, kl);
char* fine_key = NULL;
SV* result = NULL;
dbh= dbh;
switch (*key) {
case 'A':
if (strEQ(key, "AutoCommit"))
{
if (imp_dbh->has_transactions)
return sv_2mortal(boolSV(DBIc_has(imp_dbh,DBIcf_AutoCommit)));
/* Default */
return &PL_sv_yes;
}
break;
}
if (strncmp(key, "mysql_", 6) == 0) {
fine_key = key;
key = key+6;
kl = kl-6;
}
/* MONTY: Check if kl should not be used or used everywhere */
switch(*key) {
case 'a':
if (kl == strlen("auto_reconnect") && strEQ(key, "auto_reconnect"))
result= sv_2mortal(newSViv(imp_dbh->auto_reconnect));
break;
case 'b':
if (kl == strlen("bind_type_guessing") &&
strEQ(key, "bind_type_guessing"))
{
result = sv_2mortal(newSViv(imp_dbh->bind_type_guessing));
}
else if (kl == strlen("bind_comment_placeholders") &&
strEQ(key, "bind_comment_placeholders"))
{
result = sv_2mortal(newSViv(imp_dbh->bind_comment_placeholders));
}
break;
case 'c':
if (kl == 10 && strEQ(key, "clientinfo"))
{
const char* clientinfo = mysql_get_client_info();
result= clientinfo ?
sv_2mortal(newSVpv(clientinfo, strlen(clientinfo))) : &PL_sv_undef;
}
else if (kl == 13 && strEQ(key, "clientversion"))
{
result= sv_2mortal(my_ulonglong2str(aTHX_ mysql_get_client_version()));
}
break;
case 'e':
if (strEQ(key, "errno"))
result= sv_2mortal(newSViv((IV)mysql_errno(imp_dbh->pmysql)));
else if ( strEQ(key, "error") || strEQ(key, "errmsg"))
{
/* Note that errmsg is obsolete, as of 2.09! */
const char* msg = mysql_error(imp_dbh->pmysql);
result= sv_2mortal(newSVpv(msg, strlen(msg)));
}
/* HELMUT */
#if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
else if (kl == strlen("enable_utf8mb4") && strEQ(key, "enable_utf8mb4"))
result = sv_2mortal(newSViv(imp_dbh->enable_utf8mb4));
else if (kl == strlen("enable_utf8") && strEQ(key, "enable_utf8"))
result = sv_2mortal(newSViv(imp_dbh->enable_utf8));
#endif
break;
case 'd':
if (strEQ(key, "dbd_stats"))
{
HV* hv = newHV();
hv_store(
hv,
"auto_reconnects_ok",
strlen("auto_reconnects_ok"),
newSViv(imp_dbh->stats.auto_reconnects_ok),
0
);
hv_store(
hv,
"auto_reconnects_failed",
strlen("auto_reconnects_failed"),
newSViv(imp_dbh->stats.auto_reconnects_failed),
0
);
result= sv_2mortal((newRV_noinc((SV*)hv)));
}
case 'h':
if (strEQ(key, "hostinfo"))
{
const char* hostinfo = mysql_get_host_info(imp_dbh->pmysql);
result= hostinfo ?
sv_2mortal(newSVpv(hostinfo, strlen(hostinfo))) : &PL_sv_undef;
}
break;
case 'i':
if (strEQ(key, "info"))
{
const char* info = mysql_info(imp_dbh->pmysql);
result= info ? sv_2mortal(newSVpv(info, strlen(info))) : &PL_sv_undef;
}
else if (kl == 8 && strEQ(key, "insertid"))
/* We cannot return an IV, because the insertid is a long. */
result= sv_2mortal(my_ulonglong2str(aTHX_ mysql_insert_id(imp_dbh->pmysql)));
break;
case 'n':
if (kl == strlen("no_autocommit_cmd") &&
strEQ(key, "no_autocommit_cmd"))
result = sv_2mortal(newSViv(imp_dbh->no_autocommit_cmd));
break;
case 'p':
if (kl == 9 && strEQ(key, "protoinfo"))
result= sv_2mortal(newSViv(mysql_get_proto_info(imp_dbh->pmysql)));
break;
case 's':
if (kl == 10 && strEQ(key, "serverinfo")) {
const char* serverinfo = mysql_get_server_info(imp_dbh->pmysql);
result= serverinfo ?
sv_2mortal(newSVpv(serverinfo, strlen(serverinfo))) : &PL_sv_undef;
}
else if (kl == 13 && strEQ(key, "serverversion"))
result= sv_2mortal(my_ulonglong2str(aTHX_ mysql_get_server_version(imp_dbh->pmysql)));
else if (strEQ(key, "sock"))
result= sv_2mortal(newSViv((IV) imp_dbh->pmysql));
else if (strEQ(key, "sockfd"))
result= sv_2mortal(newSViv((IV) imp_dbh->pmysql->net.fd));
else if (strEQ(key, "stat"))
{
const char* stats = mysql_stat(imp_dbh->pmysql);
result= stats ?
sv_2mortal(newSVpv(stats, strlen(stats))) : &PL_sv_undef;
}
else if (strEQ(key, "stats"))
{
/* Obsolete, as of 2.09 */
const char* stats = mysql_stat(imp_dbh->pmysql);
result= stats ?
sv_2mortal(newSVpv(stats, strlen(stats))) : &PL_sv_undef;
}
else if (kl == 14 && strEQ(key,"server_prepare"))
result= sv_2mortal(newSViv((IV) imp_dbh->use_server_side_prepare));
break;
case 't':
if (kl == 9 && strEQ(key, "thread_id"))
result= sv_2mortal(newSViv(mysql_thread_id(imp_dbh->pmysql)));
break;
case 'w':
if (kl == 13 && strEQ(key, "warning_count"))
result= sv_2mortal(newSViv(mysql_warning_count(imp_dbh->pmysql)));
break;
case 'u':
if (strEQ(key, "use_result"))
{
result= sv_2mortal(newSViv((IV) imp_dbh->use_mysql_use_result));
}
break;
}
if (result== NULL)
return Nullsv;
return result;
}
/*
**************************************************************************
*
* Name: dbd_st_prepare
*
* Purpose: Called for preparing an SQL statement; our part of the
* statement handle constructor
*
* Input: sth - statement handle being initialized
* imp_sth - drivers private statement handle data
* statement - pointer to string with SQL statement
* attribs - statement attributes, currently not in use
*
* Returns: TRUE for success, FALSE otherwise; do_error will
* be called in the latter case
*
**************************************************************************/
int
dbd_st_prepare(
SV *sth,
imp_sth_t *imp_sth,
char *statement,
SV *attribs)
{
int i;
SV **svp;
dTHX;
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
#if MYSQL_VERSION_ID < CALL_PLACEHOLDER_VERSION
char *str_ptr, *str_last_ptr;
#endif
int col_type, prepare_retval, limit_flag=0;
MYSQL_BIND *bind, *bind_end;
imp_sth_phb_t *fbind;
#endif
D_imp_xxh(sth);
D_imp_dbh_from_sth;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t-> dbd_st_prepare MYSQL_VERSION_ID %d, SQL statement: %s\n",
MYSQL_VERSION_ID, statement);
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
/* Set default value of 'mysql_server_prepare' attribute for sth from dbh */
imp_sth->use_server_side_prepare= imp_dbh->use_server_side_prepare;
if (attribs)
{
svp= DBD_ATTRIB_GET_SVP(attribs, "mysql_server_prepare", 20);
imp_sth->use_server_side_prepare = (svp) ?
SvTRUE(*svp) : imp_dbh->use_server_side_prepare;
svp = DBD_ATTRIB_GET_SVP(attribs, "async", 5);
if(svp && SvTRUE(*svp)) {
#if MYSQL_ASYNC
imp_sth->is_async = TRUE;
imp_sth->use_server_side_prepare = FALSE;
#else
do_error(sth, 2000,
"Async support was not built into this version of DBD::mysql", "HY000");
return 0;
#endif
}
}
imp_sth->fetch_done= 0;
#endif
imp_sth->done_desc= 0;
imp_sth->result= NULL;
imp_sth->currow= 0;
/* Set default value of 'mysql_use_result' attribute for sth from dbh */
svp= DBD_ATTRIB_GET_SVP(attribs, "mysql_use_result", 16);
imp_sth->use_mysql_use_result= svp ?
SvTRUE(*svp) : imp_dbh->use_mysql_use_result;
for (i= 0; i < AV_ATTRIB_LAST; i++)
imp_sth->av_attr[i]= Nullav;
/*
Clean-up previous result set(s) for sth to prevent
'Commands out of sync' error
*/
mysql_st_free_result_sets(sth, imp_sth);
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION && MYSQL_VERSION_ID < CALL_PLACEHOLDER_VERSION
if (imp_sth->use_server_side_prepare)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tuse_server_side_prepare set, check restrictions\n");
/*
This code is here because placeholder support is not implemented for
statements with :-
1. LIMIT < 5.0.7
2. CALL < 5.5.3 (Added support for out & inout parameters)
In these cases we have to disable server side prepared statements
NOTE: These checks could cause a false possitive on statements which
include columns / table names that match "call " or " limit "
*/
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
#if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION
"\t\tneed to test for LIMIT & CALL\n");
#else
"\t\tneed to test for restrictions\n");
#endif
str_last_ptr = statement + strlen(statement);
for (str_ptr= statement; str_ptr < str_last_ptr; str_ptr++)
{
#if MYSQL_VERSION_ID < LIMIT_PLACEHOLDER_VERSION
/*
Place holders not supported in LIMIT's
*/
if (limit_flag)
{
if (*str_ptr == '?')
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tLIMIT and ? found, set to use_server_side_prepare=0\n");
/* ... then we do not want to try server side prepare (use emulation) */
imp_sth->use_server_side_prepare= 0;
break;
}
}
else if (str_ptr < str_last_ptr - 6 &&
isspace(*(str_ptr + 0)) &&
tolower(*(str_ptr + 1)) == 'l' &&
tolower(*(str_ptr + 2)) == 'i' &&
tolower(*(str_ptr + 3)) == 'm' &&
tolower(*(str_ptr + 4)) == 'i' &&
tolower(*(str_ptr + 5)) == 't' &&
isspace(*(str_ptr + 6)))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "LIMIT set limit flag to 1\n");
limit_flag= 1;
}
#endif
/*
Place holders not supported in CALL's
*/
if (str_ptr < str_last_ptr - 4 &&
tolower(*(str_ptr + 0)) == 'c' &&
tolower(*(str_ptr + 1)) == 'a' &&
tolower(*(str_ptr + 2)) == 'l' &&
tolower(*(str_ptr + 3)) == 'l' &&
isspace(*(str_ptr + 4)))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Disable PS mode for CALL()\n");
imp_sth->use_server_side_prepare= 0;
break;
}
}
}
#endif
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
if (imp_sth->use_server_side_prepare)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tuse_server_side_prepare set\n");
/* do we really need this? If we do, we should return, not just continue */
if (imp_sth->stmt)
fprintf(stderr,
"ERROR: Trying to prepare new stmt while we have \
already not closed one \n");
imp_sth->stmt= mysql_stmt_init(imp_dbh->pmysql);
if (! imp_sth->stmt)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tERROR: Unable to return MYSQL_STMT structure \
from mysql_stmt_init(): ERROR NO: %d ERROR MSG:%s\n",
mysql_errno(imp_dbh->pmysql),
mysql_error(imp_dbh->pmysql));
}
prepare_retval= mysql_stmt_prepare(imp_sth->stmt,
statement,
strlen(statement));
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tmysql_stmt_prepare returned %d\n",
prepare_retval);
if (prepare_retval)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tmysql_stmt_prepare %d %s\n",
mysql_stmt_errno(imp_sth->stmt),
mysql_stmt_error(imp_sth->stmt));
/* For commands that are not supported by server side prepared statement
mechanism lets try to pass them through regular API */
if (mysql_stmt_errno(imp_sth->stmt) == ER_UNSUPPORTED_PS)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tSETTING imp_sth->use_server_side_prepare to 0\n");
imp_sth->use_server_side_prepare= 0;
}
else
{
do_error(sth, mysql_stmt_errno(imp_sth->stmt),
mysql_stmt_error(imp_sth->stmt),
mysql_sqlstate(imp_dbh->pmysql));
mysql_stmt_close(imp_sth->stmt);
imp_sth->stmt= NULL;
return FALSE;
}
}
else
{
DBIc_NUM_PARAMS(imp_sth)= mysql_stmt_param_count(imp_sth->stmt);
/* mysql_stmt_param_count */
if (DBIc_NUM_PARAMS(imp_sth) > 0)
{
int has_statement_fields= imp_sth->stmt->fields != 0;
/* Allocate memory for bind variables */
imp_sth->bind= alloc_bind(DBIc_NUM_PARAMS(imp_sth));
imp_sth->fbind= alloc_fbind(DBIc_NUM_PARAMS(imp_sth));
imp_sth->has_been_bound= 0;
/* Initialize ph variables with NULL values */
for (i= 0,
bind= imp_sth->bind,
fbind= imp_sth->fbind,
bind_end= bind+DBIc_NUM_PARAMS(imp_sth);
bind < bind_end ;
bind++, fbind++, i++ )
{
/*
if this statement has a result set, field types will be
correctly identified. If there is no result set, such as
with an INSERT, fields will not be defined, and all buffer_type
will default to MYSQL_TYPE_VAR_STRING
*/
col_type= (has_statement_fields ?
imp_sth->stmt->fields[i].type : MYSQL_TYPE_STRING);
bind->buffer_type= mysql_to_perl_type(col_type);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tmysql_to_perl_type returned %d\n", col_type);
bind->buffer= NULL;
bind->length= &(fbind->length);
bind->is_null= (char*) &(fbind->is_null);
fbind->is_null= 1;
fbind->length= 0;
}
}
}
}
#endif
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
/* Count the number of parameters (driver, vs server-side) */
if (imp_sth->use_server_side_prepare == 0)
DBIc_NUM_PARAMS(imp_sth) = count_params((imp_xxh_t *)imp_dbh, aTHX_ statement,
imp_dbh->bind_comment_placeholders);
#else
DBIc_NUM_PARAMS(imp_sth) = count_params((imp_xxh_t *)imp_dbh, aTHX_ statement,
imp_dbh->bind_comment_placeholders);
#endif
/* Allocate memory for parameters */
imp_sth->params= alloc_param(DBIc_NUM_PARAMS(imp_sth));
DBIc_IMPSET_on(imp_sth);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_prepare\n");
return 1;
}
/***************************************************************************
* Name: dbd_st_free_result_sets
*
* Purpose: Clean-up single or multiple result sets (if any)
*
* Inputs: sth - Statement handle
* imp_sth - driver's private statement handle
*
* Returns: 1 ok
* 0 error
*************************************************************************/
int mysql_st_free_result_sets (SV * sth, imp_sth_t * imp_sth)
{
dTHX;
D_imp_dbh_from_sth;
D_imp_xxh(sth);
int next_result_rc= -1;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t>- dbd_st_free_result_sets\n");
#if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION
do
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_free_result_sets RC %d\n", next_result_rc);
if (next_result_rc == 0)
{
if (!(imp_sth->result = mysql_use_result(imp_dbh->pmysql)))
{
/* Check for possible error */
if (mysql_field_count(imp_dbh->pmysql))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_free_result_sets ERROR: %s\n",
mysql_error(imp_dbh->pmysql));
do_error(sth, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql),
mysql_sqlstate(imp_dbh->pmysql));
return 0;
}
}
}
if (imp_sth->result)
{
mysql_free_result(imp_sth->result);
imp_sth->result=NULL;
}
} while ((next_result_rc=mysql_next_result(imp_dbh->pmysql))==0);
if (next_result_rc > 0)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_free_result_sets: Error while processing multi-result set: %s\n",
mysql_error(imp_dbh->pmysql));
do_error(sth, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql),
mysql_sqlstate(imp_dbh->pmysql));
}
#else
if (imp_sth->result)
{
mysql_free_result(imp_sth->result);
imp_sth->result=NULL;
}
#endif
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_free_result_sets\n");
return 1;
}
#if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION
/***************************************************************************
* Name: dbd_st_more_results
*
* Purpose: Move onto the next result set (if any)
*
* Inputs: sth - Statement handle
* imp_sth - driver's private statement handle
*
* Returns: 1 if there are more results sets
* 0 if there are not
* -1 for errors.
*************************************************************************/
int dbd_st_more_results(SV* sth, imp_sth_t* imp_sth)
{
dTHX;
D_imp_dbh_from_sth;
D_imp_xxh(sth);
int use_mysql_use_result=imp_sth->use_mysql_use_result;
int next_result_return_code, i;
MYSQL* svsock= imp_dbh->pmysql;
if (!SvROK(sth) || SvTYPE(SvRV(sth)) != SVt_PVHV)
croak("Expected hash array");
if (!mysql_more_results(svsock))
{
/* No more pending result set(s)*/
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\n <- dbs_st_more_results no more results\n");
return 0;
}
if (imp_sth->use_server_side_prepare)
{
do_warn(sth, JW_ERR_NOT_IMPLEMENTED,
"Processing of multiple result set is not possible with server side prepare");
return 0;
}
/*
* Free cached array attributes
*/
for (i= 0; i < AV_ATTRIB_LAST; i++)
{
if (imp_sth->av_attr[i])
SvREFCNT_dec(imp_sth->av_attr[i]);
imp_sth->av_attr[i]= Nullav;
}
/* Release previous MySQL result*/
if (imp_sth->result)
mysql_free_result(imp_sth->result);
if (DBIc_ACTIVE(imp_sth))
DBIc_ACTIVE_off(imp_sth);
next_result_return_code= mysql_next_result(svsock);
imp_sth->warning_count = mysql_warning_count(imp_dbh->pmysql);
/*
mysql_next_result returns
0 if there are more results
-1 if there are no more results
>0 if there was an error
*/
if (next_result_return_code > 0)
{
do_error(sth, mysql_errno(svsock), mysql_error(svsock),
mysql_sqlstate(svsock));
return 0;
}
else if(next_result_return_code == -1)
{
return 0;
}
else
{
/* Store the result from the Query */
imp_sth->result = use_mysql_use_result ?
mysql_use_result(svsock) : mysql_store_result(svsock);
if (mysql_errno(svsock))
{
do_error(sth, mysql_errno(svsock), mysql_error(svsock),
mysql_sqlstate(svsock));
return 0;
}
imp_sth->row_num= mysql_affected_rows(imp_dbh->pmysql);
if (imp_sth->result == NULL)
{
/* No "real" rowset*/
DBIc_NUM_FIELDS(imp_sth)= 0; /* for DBI <= 1.53 */
DBIS->set_attr_k(sth, sv_2mortal(newSVpvn("NUM_OF_FIELDS",13)), 0,
sv_2mortal(newSViv(0)));
return 1;
}
else
{
/* We have a new rowset */
imp_sth->currow=0;
/* delete cached handle attributes */
/* XXX should be driven by a list to ease maintenance */
hv_delete((HV*)SvRV(sth), "NAME", 4, G_DISCARD);
hv_delete((HV*)SvRV(sth), "NULLABLE", 8, G_DISCARD);
hv_delete((HV*)SvRV(sth), "NUM_OF_FIELDS", 13, G_DISCARD);
hv_delete((HV*)SvRV(sth), "PRECISION", 9, G_DISCARD);
hv_delete((HV*)SvRV(sth), "SCALE", 5, G_DISCARD);
hv_delete((HV*)SvRV(sth), "TYPE", 4, G_DISCARD);
hv_delete((HV*)SvRV(sth), "mysql_insertid", 14, G_DISCARD);
hv_delete((HV*)SvRV(sth), "mysql_is_auto_increment", 23, G_DISCARD);
hv_delete((HV*)SvRV(sth), "mysql_is_blob", 13, G_DISCARD);
hv_delete((HV*)SvRV(sth), "mysql_is_key", 12, G_DISCARD);
hv_delete((HV*)SvRV(sth), "mysql_is_num", 12, G_DISCARD);
hv_delete((HV*)SvRV(sth), "mysql_is_pri_key", 16, G_DISCARD);
hv_delete((HV*)SvRV(sth), "mysql_length", 12, G_DISCARD);
hv_delete((HV*)SvRV(sth), "mysql_max_length", 16, G_DISCARD);
hv_delete((HV*)SvRV(sth), "mysql_table", 11, G_DISCARD);
hv_delete((HV*)SvRV(sth), "mysql_type", 10, G_DISCARD);
hv_delete((HV*)SvRV(sth), "mysql_type_name", 15, G_DISCARD);
hv_delete((HV*)SvRV(sth), "mysql_warning_count", 20, G_DISCARD);
/* Adjust NUM_OF_FIELDS - which also adjusts the row buffer size */
DBIc_NUM_FIELDS(imp_sth)= 0; /* for DBI <= 1.53 */
DBIc_DBISTATE(imp_sth)->set_attr_k(sth, sv_2mortal(newSVpvn("NUM_OF_FIELDS",13)), 0,
sv_2mortal(newSViv(mysql_num_fields(imp_sth->result)))
);
DBIc_ACTIVE_on(imp_sth);
imp_sth->done_desc = 0;
}
imp_dbh->pmysql->net.last_errno= 0;
return 1;
}
}
#endif
/**************************************************************************
*
* Name: mysql_st_internal_execute
*
* Purpose: Internal version for executing a statement, called both from
* within the "do" and the "execute" method.
*
* Inputs: h - object handle, for storing error messages
* statement - query being executed
* attribs - statement attributes, currently ignored
* num_params - number of parameters being bound
* params - parameter array
* result - where to store results, if any
* svsock - socket connected to the database
*
**************************************************************************/
my_ulonglong mysql_st_internal_execute(
SV *h, /* could be sth or dbh */
SV *statement,
SV *attribs,
int num_params,
imp_sth_ph_t *params,
MYSQL_RES **result,
MYSQL *svsock,
int use_mysql_use_result
)
{
dTHX;
bool bind_type_guessing= FALSE;
bool bind_comment_placeholders= TRUE;
STRLEN slen;
char *sbuf = SvPV(statement, slen);
char *table;
char *salloc;
int htype;
int errno;
#if MYSQL_ASYNC
bool async = FALSE;
#endif
my_ulonglong rows= 0;
/* thank you DBI.c for this info! */
D_imp_xxh(h);
attribs= attribs;
htype= DBIc_TYPE(imp_xxh);
/*
It is important to import imp_dbh properly according to the htype
that it is! Also, one might ask why bind_type_guessing is assigned
in each block. Well, it's because D_imp_ macros called in these
blocks make it so imp_dbh is not "visible" or defined outside of the
if/else (when compiled, it fails for imp_dbh not being defined).
*/
/* h is a dbh */
if (htype == DBIt_DB)
{
D_imp_dbh(h);
/* if imp_dbh is not available, it causes segfault (proper) on OpenBSD */
if (imp_dbh && imp_dbh->bind_type_guessing)
{
bind_type_guessing= imp_dbh->bind_type_guessing;
bind_comment_placeholders= bind_comment_placeholders;
}
#if MYSQL_ASYNC
async = (bool) (imp_dbh->async_query_in_flight != NULL);
#endif
}
/* h is a sth */
else
{
D_imp_sth(h);
D_imp_dbh_from_sth;
/* if imp_dbh is not available, it causes segfault (proper) on OpenBSD */
if (imp_dbh)
{
bind_type_guessing= imp_dbh->bind_type_guessing;
bind_comment_placeholders= imp_dbh->bind_comment_placeholders;
}
#if MYSQL_ASYNC
async = imp_sth->is_async;
if(async) {
imp_dbh->async_query_in_flight = imp_sth;
} else {
imp_dbh->async_query_in_flight = NULL;
}
#endif
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "mysql_st_internal_execute MYSQL_VERSION_ID %d\n",
MYSQL_VERSION_ID );
salloc= parse_params(imp_xxh,
aTHX_ svsock,
sbuf,
&slen,
params,
num_params,
bind_type_guessing,
bind_comment_placeholders);
if (salloc)
{
sbuf= salloc;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "Binding parameters: %s\n", sbuf);
}
if (slen >= 11 && (!strncmp(sbuf, "listfields ", 11) ||
!strncmp(sbuf, "LISTFIELDS ", 11)))
{
/* remove pre-space */
slen-= 10;
sbuf+= 10;
while (slen && isspace(*sbuf)) { --slen; ++sbuf; }
if (!slen)
{
do_error(h, JW_ERR_QUERY, "Missing table name" ,NULL);
return -2;
}
if (!(table= malloc(slen+1)))
{
do_error(h, JW_ERR_MEM, "Out of memory" ,NULL);
return -2;
}
strncpy(table, sbuf, slen);
sbuf= table;
while (slen && !isspace(*sbuf))
{
--slen;
++sbuf;
}
*sbuf++= '\0';
*result= mysql_list_fields(svsock, table, NULL);
free(table);
if (!(*result))
{
do_error(h, mysql_errno(svsock), mysql_error(svsock)
,mysql_sqlstate(svsock));
return -2;
}
return 0;
}
#if MYSQL_ASYNC
if(async) {
if((mysql_send_query(svsock, sbuf, slen)) &&
(!mysql_db_reconnect(h) ||
(mysql_send_query(svsock, sbuf, slen))))
{
rows = -2;
} else {
rows = 0;
}
} else {
#endif
if ((mysql_real_query(svsock, sbuf, slen)) &&
(!mysql_db_reconnect(h) ||
(mysql_real_query(svsock, sbuf, slen))))
{
rows = -2;
} else {
/** Store the result from the Query */
*result= use_mysql_use_result ?
mysql_use_result(svsock) : mysql_store_result(svsock);
if (mysql_errno(svsock))
do_error(h, mysql_errno(svsock), mysql_error(svsock)
,mysql_sqlstate(svsock));
if (!*result)
rows= mysql_affected_rows(svsock);
else
rows= mysql_num_rows(*result);
}
#if MYSQL_ASYNC
}
#endif
if (salloc)
Safefree(salloc);
if(rows == -2) {
do_error(h, mysql_errno(svsock), mysql_error(svsock),
mysql_sqlstate(svsock));
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "IGNORING ERROR errno %d\n", errno);
rows = -2;
}
return(rows);
}
/**************************************************************************
*
* Name: mysql_st_internal_execute41
*
* Purpose: Internal version for executing a prepared statement, called both
* from within the "do" and the "execute" method.
* MYSQL 4.1 API
*
*
* Inputs: h - object handle, for storing error messages
* statement - query being executed
* attribs - statement attributes, currently ignored
* num_params - number of parameters being bound
* params - parameter array
* result - where to store results, if any
* svsock - socket connected to the database
*
**************************************************************************/
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
my_ulonglong mysql_st_internal_execute41(
SV *sth,
int num_params,
MYSQL_RES **result,
MYSQL_STMT *stmt,
MYSQL_BIND *bind,
int *has_been_bound
)
{
int i;
enum enum_field_types enum_type;
dTHX;
int execute_retval;
my_ulonglong rows=0;
D_imp_xxh(sth);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t-> mysql_st_internal_execute41\n");
/* free result if exists */
if (*result)
{
mysql_free_result(*result);
*result= 0;
}
/*
If were performed any changes with ph variables
we have to rebind them
*/
if (num_params > 0 && !(*has_been_bound))
{
if (mysql_stmt_bind_param(stmt,bind))
goto error;
*has_been_bound= 1;
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tmysql_st_internal_execute41 calling mysql_execute with %d num_params\n",
num_params);
execute_retval= mysql_stmt_execute(stmt);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tmysql_stmt_execute returned %d\n",
execute_retval);
if (execute_retval)
goto error;
/*
This statement does not return a result set (INSERT, UPDATE...)
*/
if (!(*result= mysql_stmt_result_metadata(stmt)))
{
if (mysql_stmt_errno(stmt))
goto error;
rows= mysql_stmt_affected_rows(stmt);
}
/*
This statement returns a result set (SELECT...)
*/
else
{
for (i = mysql_stmt_field_count(stmt) - 1; i >=0; --i) {
enum_type = mysql_to_perl_type(stmt->fields[i].type);
if (enum_type != MYSQL_TYPE_DOUBLE && enum_type != MYSQL_TYPE_LONG)
{
/* mysql_stmt_store_result to update MYSQL_FIELD->max_length */
my_bool on = 1;
mysql_stmt_attr_set(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, &on);
break;
}
}
/* Get the total rows affected and return */
if (mysql_stmt_store_result(stmt))
goto error;
else
rows= mysql_stmt_num_rows(stmt);
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t<- mysql_internal_execute_41 returning %d rows\n",
(int) rows);
return(rows);
error:
if (*result)
{
mysql_free_result(*result);
*result= 0;
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" errno %d err message %s\n",
mysql_stmt_errno(stmt),
mysql_stmt_error(stmt));
do_error(sth, mysql_stmt_errno(stmt), mysql_stmt_error(stmt),
mysql_stmt_sqlstate(stmt));
mysql_stmt_reset(stmt);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t<- mysql_st_internal_execute41\n");
return -2;
}
#endif
/***************************************************************************
*
* Name: dbd_st_execute
*
* Purpose: Called for preparing an SQL statement; our part of the
* statement handle constructor
*
* Input: sth - statement handle being initialized
* imp_sth - drivers private statement handle data
*
* Returns: TRUE for success, FALSE otherwise; do_error will
* be called in the latter case
*
**************************************************************************/
int dbd_st_execute(SV* sth, imp_sth_t* imp_sth)
{
dTHX;
char actual_row_num[64];
int i;
SV **statement;
D_imp_dbh_from_sth;
D_imp_xxh(sth);
#if defined (dTHR)
dTHR;
#endif
ASYNC_CHECK_RETURN(sth, -2);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" -> dbd_st_execute for %08lx\n", (u_long) sth);
if (!SvROK(sth) || SvTYPE(SvRV(sth)) != SVt_PVHV)
croak("Expected hash array");
/* Free cached array attributes */
for (i= 0; i < AV_ATTRIB_LAST; i++)
{
if (imp_sth->av_attr[i])
SvREFCNT_dec(imp_sth->av_attr[i]);
imp_sth->av_attr[i]= Nullav;
}
statement= hv_fetch((HV*) SvRV(sth), "Statement", 9, FALSE);
/*
Clean-up previous result set(s) for sth to prevent
'Commands out of sync' error
*/
mysql_st_free_result_sets (sth, imp_sth);
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
if (imp_sth->use_server_side_prepare && ! imp_sth->use_mysql_use_result)
{
imp_sth->row_num= mysql_st_internal_execute41(
sth,
DBIc_NUM_PARAMS(imp_sth),
&imp_sth->result,
imp_sth->stmt,
imp_sth->bind,
&imp_sth->has_been_bound
);
}
else {
#endif
imp_sth->row_num= mysql_st_internal_execute(
sth,
*statement,
NULL,
DBIc_NUM_PARAMS(imp_sth),
imp_sth->params,
&imp_sth->result,
imp_dbh->pmysql,
imp_sth->use_mysql_use_result
);
#if MYSQL_ASYNC
if(imp_dbh->async_query_in_flight) {
DBIc_ACTIVE_on(imp_sth);
return 0;
}
#endif
}
if (imp_sth->row_num+1 != (my_ulonglong)-1)
{
if (!imp_sth->result)
{
imp_sth->insertid= mysql_insert_id(imp_dbh->pmysql);
#if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION
if (mysql_more_results(imp_dbh->pmysql))
DBIc_ACTIVE_on(imp_sth);
#endif
}
else
{
/** Store the result in the current statement handle */
DBIc_NUM_FIELDS(imp_sth)= mysql_num_fields(imp_sth->result);
DBIc_ACTIVE_on(imp_sth);
if (!imp_sth->use_server_side_prepare)
imp_sth->done_desc= 0;
imp_sth->fetch_done= 0;
}
}
imp_sth->warning_count = mysql_warning_count(imp_dbh->pmysql);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
{
/*
PerlIO_printf doesn't always handle imp_sth->row_num %llu
consistantly!!
*/
sprintf(actual_row_num, "%llu", imp_sth->row_num);
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" <- dbd_st_execute returning imp_sth->row_num %s\n",
actual_row_num);
}
return (int)imp_sth->row_num;
}
/**************************************************************************
*
* Name: dbd_describe
*
* Purpose: Called from within the fetch method to describe the result
*
* Input: sth - statement handle being initialized
* imp_sth - our part of the statement handle, there's no
* need for supplying both; Tim just doesn't remove it
*
* Returns: TRUE for success, FALSE otherwise; do_error will
* be called in the latter case
*
**************************************************************************/
int dbd_describe(SV* sth, imp_sth_t* imp_sth)
{
dTHX;
D_imp_xxh(sth);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t--> dbd_describe\n");
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
if (imp_sth->use_server_side_prepare)
{
int i;
int col_type;
int num_fields= DBIc_NUM_FIELDS(imp_sth);
imp_sth_fbh_t *fbh;
MYSQL_BIND *buffer;
MYSQL_FIELD *fields;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_describe() num_fields %d\n",
num_fields);
if (imp_sth->done_desc)
return TRUE;
if (!num_fields || !imp_sth->result)
{
/* no metadata */
do_error(sth, JW_ERR_SEQUENCE,
"no metadata information while trying describe result set",
NULL);
return 0;
}
/* allocate fields buffers */
if ( !(imp_sth->fbh= alloc_fbuffer(num_fields))
|| !(imp_sth->buffer= alloc_bind(num_fields)) )
{
/* Out of memory */
do_error(sth, JW_ERR_SEQUENCE,
"Out of memory in dbd_sescribe()",NULL);
return 0;
}
fields= mysql_fetch_fields(imp_sth->result);
for (
fbh= imp_sth->fbh, buffer= (MYSQL_BIND*)imp_sth->buffer, i= 0;
i < num_fields;
i++, fbh++, buffer++
)
{
/* get the column type */
col_type = fields ? fields[i].type : MYSQL_TYPE_STRING;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
{
PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\t\ti %d col_type %d fbh->length %d\n",
i, col_type, (int) fbh->length);
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tfields[i].length %lu fields[i].max_length %lu fields[i].type %d fields[i].charsetnr %d\n",
(long unsigned int) fields[i].length, (long unsigned int) fields[i].max_length, fields[i].type,
fields[i].charsetnr);
}
fbh->charsetnr = fields[i].charsetnr;
#if MYSQL_VERSION_ID < FIELD_CHARSETNR_VERSION
fbh->flags = fields[i].flags;
#endif
buffer->buffer_type= mysql_to_perl_type(col_type);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tmysql_to_perl_type returned %d\n",
col_type);
buffer->length= &(fbh->length);
buffer->is_null= (my_bool*) &(fbh->is_null);
buffer->error= (my_bool*) &(fbh->error);
switch (buffer->buffer_type) {
case MYSQL_TYPE_DOUBLE:
buffer->buffer_length= sizeof(fbh->ddata);
buffer->buffer= (char*) &fbh->ddata;
break;
case MYSQL_TYPE_LONG:
buffer->buffer_length= sizeof(fbh->ldata);
buffer->buffer= (char*) &fbh->ldata;
buffer->is_unsigned= (fields[i].flags & UNSIGNED_FLAG) ? 1 : 0;
break;
default:
buffer->buffer_length= fields[i].max_length ? fields[i].max_length : 1;
Newz(908, fbh->data, buffer->buffer_length, char);
buffer->buffer= (char *) fbh->data;
}
}
if (mysql_stmt_bind_result(imp_sth->stmt, imp_sth->buffer))
{
do_error(sth, mysql_stmt_errno(imp_sth->stmt),
mysql_stmt_error(imp_sth->stmt),
mysql_stmt_sqlstate(imp_sth->stmt));
return 0;
}
}
#endif
imp_sth->done_desc= 1;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_describe\n");
return TRUE;
}
/**************************************************************************
*
* Name: dbd_st_fetch
*
* Purpose: Called for fetching a result row
*
* Input: sth - statement handle being initialized
* imp_sth - drivers private statement handle data
*
* Returns: array of columns; the array is allocated by DBI via
* DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth), even the values
* of the array are prepared, we just need to modify them
* appropriately
*
**************************************************************************/
AV*
dbd_st_fetch(SV *sth, imp_sth_t* imp_sth)
{
dTHX;
int num_fields, ChopBlanks, i, rc;
unsigned long *lengths;
AV *av;
int av_length, av_readonly;
MYSQL_ROW cols;
D_imp_dbh_from_sth;
MYSQL* svsock= imp_dbh->pmysql;
imp_sth_fbh_t *fbh;
D_imp_xxh(sth);
#if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
MYSQL_BIND *buffer;
#endif
MYSQL_FIELD *fields;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t-> dbd_st_fetch\n");
#if MYSQL_ASYNC
if(imp_dbh->async_query_in_flight) {
if(mysql_db_async_result(sth, &imp_sth->result) <= 0) {
return Nullav;
}
}
#endif
#if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
if (imp_sth->use_server_side_prepare)
{
if (!DBIc_ACTIVE(imp_sth) )
{
do_error(sth, JW_ERR_SEQUENCE, "no statement executing\n",NULL);
return Nullav;
}
if (imp_sth->fetch_done)
{
do_error(sth, JW_ERR_SEQUENCE, "fetch() but fetch already done",NULL);
return Nullav;
}
if (!imp_sth->done_desc)
{
if (!dbd_describe(sth, imp_sth))
{
do_error(sth, JW_ERR_SEQUENCE, "Error while describe result set.",
NULL);
return Nullav;
}
}
}
#endif
ChopBlanks = DBIc_is(imp_sth, DBIcf_ChopBlanks);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tdbd_st_fetch for %08lx, chopblanks %d\n",
(u_long) sth, ChopBlanks);
if (!imp_sth->result)
{
do_error(sth, JW_ERR_SEQUENCE, "fetch() without execute()" ,NULL);
return Nullav;
}
/* fix from 2.9008 */
imp_dbh->pmysql->net.last_errno = 0;
#if MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
if (imp_sth->use_server_side_prepare)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_st_fetch calling mysql_fetch\n");
if ((rc= mysql_stmt_fetch(imp_sth->stmt)))
{
if (rc == 1)
do_error(sth, mysql_stmt_errno(imp_sth->stmt),
mysql_stmt_error(imp_sth->stmt),
mysql_stmt_sqlstate(imp_sth->stmt));
#if MYSQL_VERSION_ID >= MYSQL_VERSION_5_0
if (rc == MYSQL_DATA_TRUNCATED) {
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_st_fetch data truncated\n");
goto process;
}
#endif
if (rc == MYSQL_NO_DATA)
{
/* Update row_num to affected_rows value */
imp_sth->row_num= mysql_stmt_affected_rows(imp_sth->stmt);
imp_sth->fetch_done=1;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tdbd_st_fetch no data\n");
}
dbd_st_finish(sth, imp_sth);
return Nullav;
}
process:
imp_sth->currow++;
av= DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth);
num_fields=mysql_stmt_field_count(imp_sth->stmt);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tdbd_st_fetch called mysql_fetch, rc %d num_fields %d\n",
rc, num_fields);
for (
buffer= imp_sth->buffer,
fbh= imp_sth->fbh,
i= 0;
i < num_fields;
i++,
fbh++,
buffer++
)
{
SV *sv= AvARRAY(av)[i]; /* Note: we (re)use the SV in the AV */
STRLEN len;
/* This is wrong, null is not being set correctly
* This is not the way to determine length (this would break blobs!)
*/
if (fbh->is_null)
(void) SvOK_off(sv); /* Field is NULL, return undef */
else
{
/* In case of BLOB/TEXT fields we allocate only 8192 bytes
in dbd_describe() for data. Here we know real size of field
so we should increase buffer size and refetch column value
*/
if (fbh->length > buffer->buffer_length || fbh->error)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\tRefetch BLOB/TEXT column: %d, length: %lu, error: %d\n",
i, fbh->length, fbh->error);
Renew(fbh->data, fbh->length, char);
buffer->buffer_length= fbh->length;
buffer->buffer= (char *) fbh->data;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) {
int j;
int m = MIN(*buffer->length, buffer->buffer_length);
char *ptr = (char*)buffer->buffer;
PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\t\tbefore buffer->buffer: ");
for (j = 0; j < m; j++) {
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%c", *ptr++);
}
PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\n");
}
/*TODO: Use offset instead of 0 to fetch only remain part of data*/
if (mysql_stmt_fetch_column(imp_sth->stmt, buffer , i, 0))
do_error(sth, mysql_stmt_errno(imp_sth->stmt),
mysql_stmt_error(imp_sth->stmt),
mysql_stmt_sqlstate(imp_sth->stmt));
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2) {
int j;
int m = MIN(*buffer->length, buffer->buffer_length);
char *ptr = (char*)buffer->buffer;
PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\t\tafter buffer->buffer: ");
for (j = 0; j < m; j++) {
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "%c", *ptr++);
}
PerlIO_printf(DBIc_LOGPIO(imp_xxh),"\n");
}
}
/* This does look a lot like Georg's PHP driver doesn't it? --Brian */
/* Credit due to Georg - mysqli_api.c ;) --PMG */
switch (buffer->buffer_type) {
case MYSQL_TYPE_DOUBLE:
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tst_fetch double data %f\n", fbh->ddata);
sv_setnv(sv, fbh->ddata);
break;
case MYSQL_TYPE_LONG:
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tst_fetch int data %d, unsigned? %d\n",
(int) fbh->ldata, buffer->is_unsigned);
if (buffer->is_unsigned)
sv_setuv(sv, fbh->ldata);
else
sv_setiv(sv, fbh->ldata);
break;
default:
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tERROR IN st_fetch_string");
len= fbh->length;
/* ChopBlanks server-side prepared statement */
if (ChopBlanks)
{
/*
see bottom of:
http://www.mysql.org/doc/refman/5.0/en/c-api-datatypes.html
*/
if (fbh->charsetnr != 63)
while (len && fbh->data[len-1] == ' ') { --len; }
}
/* END OF ChopBlanks */
sv_setpvn(sv, fbh->data, len);
/* UTF8 */
/*HELMUT*/
#if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
#if MYSQL_VERSION_ID >= FIELD_CHARSETNR_VERSION
/* SHOW COLLATION WHERE Id = 63; -- 63 == charset binary, collation binary */
if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && fbh->charsetnr != 63)
#else
if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && !(fbh->flags & BINARY_FLAG))
#endif
sv_utf8_decode(sv);
#endif
/* END OF UTF8 */
break;
}
}
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_fetch, %d cols\n", num_fields);
return av;
}
else
{
#endif
imp_sth->currow++;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
{
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tdbd_st_fetch result set details\n");
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\timp_sth->result=%08lx\n",(long unsigned int) imp_sth->result);
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tmysql_num_fields=%llu\n",
(long long unsigned int) mysql_num_fields(imp_sth->result));
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tmysql_num_rows=%llu\n",
mysql_num_rows(imp_sth->result));
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tmysql_affected_rows=%llu\n",
mysql_affected_rows(imp_dbh->pmysql));
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tdbd_st_fetch for %08lx, currow= %d\n",
(u_long) sth,imp_sth->currow);
}
if (!(cols= mysql_fetch_row(imp_sth->result)))
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
{
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tdbd_st_fetch, no more rows to fetch");
}
if (mysql_errno(imp_dbh->pmysql))
do_error(sth, mysql_errno(imp_dbh->pmysql),
mysql_error(imp_dbh->pmysql),
mysql_sqlstate(imp_dbh->pmysql));
#if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION
if (!mysql_more_results(svsock))
#endif
dbd_st_finish(sth, imp_sth);
return Nullav;
}
num_fields= mysql_num_fields(imp_sth->result);
fields= mysql_fetch_fields(imp_sth->result);
lengths= mysql_fetch_lengths(imp_sth->result);
if ((av= DBIc_FIELDS_AV(imp_sth)) != Nullav)
{
av_length= av_len(av)+1;
if (av_length != num_fields) /* Resize array if necessary */
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_fetch, size of results array(%d) != num_fields(%d)\n",
av_length, num_fields);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_fetch, result fields(%d)\n",
DBIc_NUM_FIELDS(imp_sth));
av_readonly = SvREADONLY(av);
if (av_readonly)
SvREADONLY_off( av ); /* DBI sets this readonly */
while (av_length < num_fields)
{
av_store(av, av_length++, newSV(0));
}
while (av_length > num_fields)
{
SvREFCNT_dec(av_pop(av));
av_length--;
}
if (av_readonly)
SvREADONLY_on(av);
}
}
av= DBIc_DBISTATE(imp_sth)->get_fbav(imp_sth);
for (i= 0; i < num_fields; ++i)
{
char *col= cols[i];
SV *sv= AvARRAY(av)[i]; /* Note: we (re)use the SV in the AV */
if (col)
{
STRLEN len= lengths[i];
if (ChopBlanks)
{
while (len && col[len-1] == ' ')
{ --len; }
}
sv_setpvn(sv, col, len);
/* UTF8 */
/*HELMUT*/
#if defined(sv_utf8_decode) && MYSQL_VERSION_ID >=SERVER_PREPARE_VERSION
/* see bottom of: http://www.mysql.org/doc/refman/5.0/en/c-api-datatypes.html */
if ((imp_dbh->enable_utf8 || imp_dbh->enable_utf8mb4) && fields[i].charsetnr != 63)
sv_utf8_decode(sv);
#endif
/* END OF UTF8 */
}
else
(void) SvOK_off(sv); /* Field is NULL, return undef */
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t<- dbd_st_fetch, %d cols\n", num_fields);
return av;
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
}
#endif
}
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
/*
We have to fetch all data from stmt
There is may be usefull for 2 cases:
1. st_finish when we have undef statement
2. call st_execute again when we have some unfetched data in stmt
*/
int mysql_st_clean_cursor(SV* sth, imp_sth_t* imp_sth) {
if (DBIc_ACTIVE(imp_sth) && dbd_describe(sth, imp_sth) &&
!imp_sth->fetch_done)
mysql_stmt_free_result(imp_sth->stmt);
return 1;
}
#endif
/***************************************************************************
*
* Name: dbd_st_finish
*
* Purpose: Called for freeing a mysql result
*
* Input: sth - statement handle being finished
* imp_sth - drivers private statement handle data
*
* Returns: TRUE for success, FALSE otherwise; do_error() will
* be called in the latter case
*
**************************************************************************/
int dbd_st_finish(SV* sth, imp_sth_t* imp_sth) {
dTHX;
D_imp_xxh(sth);
#if defined (dTHR)
dTHR;
#endif
#if MYSQL_ASYNC
D_imp_dbh_from_sth;
if(imp_dbh->async_query_in_flight) {
mysql_db_async_result(sth, &imp_sth->result);
}
#endif
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
{
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\n--> dbd_st_finish\n");
}
if (imp_sth->use_server_side_prepare)
{
if (imp_sth && imp_sth->stmt)
{
if (!mysql_st_clean_cursor(sth, imp_sth))
{
do_error(sth, JW_ERR_SEQUENCE,
"Error happened while tried to clean up stmt",NULL);
return 0;
}
}
}
#endif
/*
Cancel further fetches from this cursor.
We don't close the cursor till DESTROY.
The application may re execute it.
*/
if (imp_sth && DBIc_ACTIVE(imp_sth))
{
/*
Clean-up previous result set(s) for sth to prevent
'Commands out of sync' error
*/
mysql_st_free_result_sets(sth, imp_sth);
}
DBIc_ACTIVE_off(imp_sth);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
{
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\n<-- dbd_st_finish\n");
}
return 1;
}
/**************************************************************************
*
* Name: dbd_st_destroy
*
* Purpose: Our part of the statement handles destructor
*
* Input: sth - statement handle being destroyed
* imp_sth - drivers private statement handle data
*
* Returns: Nothing
*
**************************************************************************/
void dbd_st_destroy(SV *sth, imp_sth_t *imp_sth) {
dTHX;
D_imp_xxh(sth);
#if defined (dTHR)
dTHR;
#endif
int i;
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
imp_sth_fbh_t *fbh;
int n;
n= DBIc_NUM_PARAMS(imp_sth);
if (n)
{
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\tFreeing %d parameters, bind %p fbind %p\n",
n, imp_sth->bind, imp_sth->fbind);
free_bind(imp_sth->bind);
free_fbind(imp_sth->fbind);
}
fbh= imp_sth->fbh;
if (fbh)
{
n = DBIc_NUM_FIELDS(imp_sth);
i = 0;
while (i < n)
{
if (fbh[i].data) Safefree(fbh[i].data);
++i;
}
free_fbuffer(fbh);
if (imp_sth->buffer)
free_bind(imp_sth->buffer);
}
if (imp_sth->stmt)
{
if (mysql_stmt_close(imp_sth->stmt))
{
do_error(DBIc_PARENT_H(imp_sth), mysql_stmt_errno(imp_sth->stmt),
mysql_stmt_error(imp_sth->stmt),
mysql_stmt_sqlstate(imp_sth->stmt));
}
}
#endif
/* dbd_st_finish has already been called by .xs code if needed. */
/* Free values allocated by dbd_bind_ph */
if (imp_sth->params)
{
free_param(aTHX_ imp_sth->params, DBIc_NUM_PARAMS(imp_sth));
imp_sth->params= NULL;
}
/* Free cached array attributes */
for (i= 0; i < AV_ATTRIB_LAST; i++)
{
if (imp_sth->av_attr[i])
SvREFCNT_dec(imp_sth->av_attr[i]);
imp_sth->av_attr[i]= Nullav;
}
/* let DBI know we've done it */
DBIc_IMPSET_off(imp_sth);
}
/*
**************************************************************************
*
* Name: dbd_st_STORE_attrib
*
* Purpose: Modifies a statement handles attributes; we currently
* support just nothing
*
* Input: sth - statement handle being destroyed
* imp_sth - drivers private statement handle data
* keysv - attribute name
* valuesv - attribute value
*
* Returns: TRUE for success, FALSE otrherwise; do_error will
* be called in the latter case
*
**************************************************************************/
int
dbd_st_STORE_attrib(
SV *sth,
imp_sth_t *imp_sth,
SV *keysv,
SV *valuesv
)
{
dTHX;
STRLEN(kl);
char *key= SvPV(keysv, kl);
int retval= FALSE;
D_imp_xxh(sth);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\t-> dbd_st_STORE_attrib for %08lx, key %s\n",
(u_long) sth, key);
if (strEQ(key, "mysql_use_result"))
{
imp_sth->use_mysql_use_result= SvTRUE(valuesv);
}
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
"\t\t<- dbd_st_STORE_attrib for %08lx, result %d\n",
(u_long) sth, retval);
return retval;
}
/*
**************************************************************************
*
* Name: dbd_st_FETCH_internal
*
* Purpose: Retrieves a statement handles array attributes; we use
* a separate function, because creating the array
* attributes shares much code and it aids in supporting
* enhanced features like caching.
*
* Input: sth - statement handle; may even be a database handle,
* in which case this will be used for storing error
* messages only. This is only valid, if cacheit (the
* last argument) is set to TRUE.
* what - internal attribute number
* res - pointer to a DBMS result
* cacheit - TRUE, if results may be cached in the sth.
*
* Returns: RV pointing to result array in case of success, NULL
* otherwise; do_error has already been called in the latter
* case.
*
**************************************************************************/
#ifndef IS_KEY
#define IS_KEY(A) (((A) & (PRI_KEY_FLAG | UNIQUE_KEY_FLAG | MULTIPLE_KEY_FLAG)) != 0)
#endif
#if !defined(IS_AUTO_INCREMENT) && defined(AUTO_INCREMENT_FLAG)
#define IS_AUTO_INCREMENT(A) (((A) & AUTO_INCREMENT_FLAG) != 0)
#endif
SV*
dbd_st_FETCH_internal(
SV *sth,
int what,
MYSQL_RES *res,
int cacheit
)
{
dTHX;
D_imp_sth(sth);
AV *av= Nullav;
MYSQL_FIELD *curField;
/* Are we asking for a legal value? */
if (what < 0 || what >= AV_ATTRIB_LAST)
do_error(sth, JW_ERR_NOT_IMPLEMENTED, "Not implemented", NULL);
/* Return cached value, if possible */
else if (cacheit && imp_sth->av_attr[what])
av= imp_sth->av_attr[what];
/* Does this sth really have a result? */
else if (!res)
do_error(sth, JW_ERR_NOT_ACTIVE,
"statement contains no result" ,NULL);
/* Do the real work. */
else
{
av= newAV();
mysql_field_seek(res, 0);
while ((curField= mysql_fetch_field(res)))
{
SV *sv;
switch(what) {
case AV_ATTRIB_NAME:
sv= newSVpv(curField->name, strlen(curField->name));
break;
case AV_ATTRIB_TABLE:
sv= newSVpv(curField->table, strlen(curField->table));
break;
case AV_ATTRIB_TYPE:
sv= newSViv((int) curField->type);
break;
case AV_ATTRIB_SQL_TYPE:
sv= newSViv((int) native2sql(curField->type)->data_type);
break;
case AV_ATTRIB_IS_PRI_KEY:
sv= boolSV(IS_PRI_KEY(curField->flags));
break;
case AV_ATTRIB_IS_NOT_NULL:
sv= boolSV(IS_NOT_NULL(curField->flags));
break;
case AV_ATTRIB_NULLABLE:
sv= boolSV(!IS_NOT_NULL(curField->flags));
break;
case AV_ATTRIB_LENGTH:
sv= newSViv((int) curField->length);
break;
case AV_ATTRIB_IS_NUM:
sv= newSViv((int) native2sql(curField->type)->is_num);
break;
case AV_ATTRIB_TYPE_NAME:
sv= newSVpv((char*) native2sql(curField->type)->type_name, 0);
break;
case AV_ATTRIB_MAX_LENGTH:
sv= newSViv((int) curField->max_length);
break;
case AV_ATTRIB_IS_AUTO_INCREMENT:
#if defined(AUTO_INCREMENT_FLAG)
sv= boolSV(IS_AUTO_INCREMENT(curField->flags));
break;
#else
croak("AUTO_INCREMENT_FLAG is not supported on this machine");
#endif
case AV_ATTRIB_IS_KEY:
sv= boolSV(IS_KEY(curField->flags));
break;
case AV_ATTRIB_IS_BLOB:
sv= boolSV(IS_BLOB(curField->flags));
break;
case AV_ATTRIB_SCALE:
sv= newSViv((int) curField->decimals);
break;
case AV_ATTRIB_PRECISION:
sv= newSViv((int) (curField->length > curField->max_length) ?
curField->length : curField->max_length);
break;
default:
sv= &PL_sv_undef;
break;
}
av_push(av, sv);
}
/* Ensure that this value is kept, decremented in
* dbd_st_destroy and dbd_st_execute. */
if (!cacheit)
return sv_2mortal(newRV_noinc((SV*)av));
imp_sth->av_attr[what]= av;
}
if (av == Nullav)
return &PL_sv_undef;
return sv_2mortal(newRV_inc((SV*)av));
}
/*
**************************************************************************
*
* Name: dbd_st_FETCH_attrib
*
* Purpose: Retrieves a statement handles attributes
*
* Input: sth - statement handle being destroyed
* imp_sth - drivers private statement handle data
* keysv - attribute name
*
* Returns: NULL for an unknown attribute, "undef" for error,
* attribute value otherwise.
*
**************************************************************************/
#define ST_FETCH_AV(what) \
dbd_st_FETCH_internal(sth, (what), imp_sth->result, TRUE)
SV* dbd_st_FETCH_attrib(
SV *sth,
imp_sth_t *imp_sth,
SV *keysv
)
{
dTHX;
STRLEN(kl);
char *key= SvPV(keysv, kl);
SV *retsv= Nullsv;
D_imp_xxh(sth);
if (kl < 2)
return Nullsv;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" -> dbd_st_FETCH_attrib for %08lx, key %s\n",
(u_long) sth, key);
switch (*key) {
case 'N':
if (strEQ(key, "NAME"))
retsv= ST_FETCH_AV(AV_ATTRIB_NAME);
else if (strEQ(key, "NULLABLE"))
retsv= ST_FETCH_AV(AV_ATTRIB_NULLABLE);
break;
case 'P':
if (strEQ(key, "PRECISION"))
retsv= ST_FETCH_AV(AV_ATTRIB_PRECISION);
if (strEQ(key, "ParamValues"))
{
HV *pvhv= newHV();
if (DBIc_NUM_PARAMS(imp_sth))
{
int n;
char key[100];
I32 keylen;
for (n= 0; n < DBIc_NUM_PARAMS(imp_sth); n++)
{
keylen= sprintf(key, "%d", n);
hv_store(pvhv, key,
keylen, newSVsv(imp_sth->params[n].value), 0);
}
}
retsv= sv_2mortal(newRV_noinc((SV*)pvhv));
}
break;
case 'S':
if (strEQ(key, "SCALE"))
retsv= ST_FETCH_AV(AV_ATTRIB_SCALE);
break;
case 'T':
if (strEQ(key, "TYPE"))
retsv= ST_FETCH_AV(AV_ATTRIB_SQL_TYPE);
break;
case 'm':
switch (kl) {
case 10:
if (strEQ(key, "mysql_type"))
retsv= ST_FETCH_AV(AV_ATTRIB_TYPE);
break;
case 11:
if (strEQ(key, "mysql_table"))
retsv= ST_FETCH_AV(AV_ATTRIB_TABLE);
break;
case 12:
if ( strEQ(key, "mysql_is_key"))
retsv= ST_FETCH_AV(AV_ATTRIB_IS_KEY);
else if (strEQ(key, "mysql_is_num"))
retsv= ST_FETCH_AV(AV_ATTRIB_IS_NUM);
else if (strEQ(key, "mysql_length"))
retsv= ST_FETCH_AV(AV_ATTRIB_LENGTH);
else if (strEQ(key, "mysql_result"))
retsv= sv_2mortal(newSViv((IV) imp_sth->result));
break;
case 13:
if (strEQ(key, "mysql_is_blob"))
retsv= ST_FETCH_AV(AV_ATTRIB_IS_BLOB);
break;
case 14:
if (strEQ(key, "mysql_insertid"))
{
/* We cannot return an IV, because the insertid is a long. */
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "INSERT ID %d\n", (int) imp_sth->insertid);
return sv_2mortal(my_ulonglong2str(aTHX_ imp_sth->insertid));
}
break;
case 15:
if (strEQ(key, "mysql_type_name"))
retsv = ST_FETCH_AV(AV_ATTRIB_TYPE_NAME);
break;
case 16:
if ( strEQ(key, "mysql_is_pri_key"))
retsv= ST_FETCH_AV(AV_ATTRIB_IS_PRI_KEY);
else if (strEQ(key, "mysql_max_length"))
retsv= ST_FETCH_AV(AV_ATTRIB_MAX_LENGTH);
else if (strEQ(key, "mysql_use_result"))
retsv= boolSV(imp_sth->use_mysql_use_result);
break;
case 19:
if (strEQ(key, "mysql_warning_count"))
retsv= sv_2mortal(newSViv((IV) imp_sth->warning_count));
break;
case 20:
if (strEQ(key, "mysql_server_prepare"))
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
retsv= sv_2mortal(newSViv((IV) imp_sth->use_server_side_prepare));
#else
retsv= boolSV(0);
#endif
break;
case 23:
if (strEQ(key, "mysql_is_auto_increment"))
retsv = ST_FETCH_AV(AV_ATTRIB_IS_AUTO_INCREMENT);
break;
}
break;
}
return retsv;
}
/***************************************************************************
*
* Name: dbd_st_blob_read
*
* Purpose: Used for blob reads if the statement handles "LongTruncOk"
* attribute (currently not supported by DBD::mysql)
*
* Input: SV* - statement handle from which a blob will be fetched
* imp_sth - drivers private statement handle data
* field - field number of the blob (note, that a row may
* contain more than one blob)
* offset - the offset of the field, where to start reading
* len - maximum number of bytes to read
* destrv - RV* that tells us where to store
* destoffset - destination offset
*
* Returns: TRUE for success, FALSE otrherwise; do_error will
* be called in the latter case
*
**************************************************************************/
int dbd_st_blob_read (
SV *sth,
imp_sth_t *imp_sth,
int field,
long offset,
long len,
SV *destrv,
long destoffset)
{
/* quell warnings */
sth= sth;
imp_sth=imp_sth;
field= field;
offset= offset;
len= len;
destrv= destrv;
destoffset= destoffset;
return FALSE;
}
/***************************************************************************
*
* Name: dbd_bind_ph
*
* Purpose: Binds a statement value to a parameter
*
* Input: sth - statement handle
* imp_sth - drivers private statement handle data
* param - parameter number, counting starts with 1
* value - value being inserted for parameter "param"
* sql_type - SQL type of the value
* attribs - bind parameter attributes, currently this must be
* one of the values SQL_CHAR, ...
* inout - TRUE, if parameter is an output variable (currently
* this is not supported)
* maxlen - ???
*
* Returns: TRUE for success, FALSE otherwise
*
**************************************************************************/
int dbd_bind_ph(SV *sth, imp_sth_t *imp_sth, SV *param, SV *value,
IV sql_type, SV *attribs, int is_inout, IV maxlen) {
dTHX;
int rc;
int param_num= SvIV(param);
int idx= param_num - 1;
char err_msg[64];
D_imp_xxh(sth);
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
STRLEN slen;
char *buffer= NULL;
int buffer_is_null= 0;
int buffer_length= slen;
unsigned int buffer_type= 0;
#endif
D_imp_dbh_from_sth;
ASYNC_CHECK_RETURN(sth, FALSE);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" Called: dbd_bind_ph\n");
attribs= attribs;
maxlen= maxlen;
if (param_num <= 0 || param_num > DBIc_NUM_PARAMS(imp_sth))
{
do_error(sth, JW_ERR_ILLEGAL_PARAM_NUM, "Illegal parameter number", NULL);
return FALSE;
}
/*
This fixes the bug whereby no warning was issued upone binding a
defined non-numeric as numeric
*/
if (SvOK(value) &&
(sql_type == SQL_NUMERIC ||
sql_type == SQL_DECIMAL ||
sql_type == SQL_INTEGER ||
sql_type == SQL_SMALLINT ||
sql_type == SQL_FLOAT ||
sql_type == SQL_REAL ||
sql_type == SQL_DOUBLE) )
{
if (! looks_like_number(value))
{
sprintf(err_msg,
"Binding non-numeric field %d, value %s as a numeric!",
param_num, neatsvpv(value,0));
do_error(sth, JW_ERR_ILLEGAL_PARAM_NUM, err_msg, NULL);
}
}
if (is_inout)
{
do_error(sth, JW_ERR_NOT_IMPLEMENTED, "Output parameters not implemented", NULL);
return FALSE;
}
rc = bind_param(&imp_sth->params[idx], value, sql_type);
#if MYSQL_VERSION_ID >= SERVER_PREPARE_VERSION
if (imp_sth->use_server_side_prepare)
{
switch(sql_type) {
case SQL_NUMERIC:
case SQL_INTEGER:
case SQL_SMALLINT:
case SQL_BIGINT:
case SQL_TINYINT:
buffer_type= MYSQL_TYPE_LONG;
break;
case SQL_DOUBLE:
case SQL_DECIMAL:
case SQL_FLOAT:
case SQL_REAL:
buffer_type= MYSQL_TYPE_DOUBLE;
break;
case SQL_CHAR:
case SQL_VARCHAR:
case SQL_DATE:
case SQL_TIME:
case SQL_TIMESTAMP:
case SQL_LONGVARCHAR:
case SQL_BINARY:
case SQL_VARBINARY:
case SQL_LONGVARBINARY:
buffer_type= MYSQL_TYPE_BLOB;
break;
default:
buffer_type= MYSQL_TYPE_STRING;
}
buffer_is_null = !(SvOK(imp_sth->params[idx].value) && imp_sth->params[idx].value);
if (! buffer_is_null) {
switch(buffer_type) {
case MYSQL_TYPE_LONG:
/* INT */
if (!SvIOK(imp_sth->params[idx].value) && DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tTRY TO BIND AN INT NUMBER\n");
buffer_length = sizeof imp_sth->fbind[idx].numeric_val.lval;
imp_sth->fbind[idx].numeric_val.lval= SvIV(imp_sth->params[idx].value);
buffer=(void*)&(imp_sth->fbind[idx].numeric_val.lval);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR type %d ->%ld<- IS A INT NUMBER\n",
(int) sql_type, (long) (*buffer));
break;
case MYSQL_TYPE_DOUBLE:
if (!SvNOK(imp_sth->params[idx].value) && DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh), "\t\tTRY TO BIND A FLOAT NUMBER\n");
buffer_length = sizeof imp_sth->fbind[idx].numeric_val.dval;
imp_sth->fbind[idx].numeric_val.dval= SvNV(imp_sth->params[idx].value);
buffer=(char*)&(imp_sth->fbind[idx].numeric_val.dval);
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR type %d ->%f<- IS A FLOAT NUMBER\n",
(int) sql_type, (double)(*buffer));
break;
case MYSQL_TYPE_BLOB:
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR type BLOB\n");
break;
case MYSQL_TYPE_STRING:
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR type STRING %d, buffertype=%d\n", (int) sql_type, buffer_type);
break;
default:
croak("Bug in DBD::Mysql file dbdimp.c#dbd_bind_ph: do not know how to handle unknown buffer type.");
}
if (buffer_type == MYSQL_TYPE_STRING || buffer_type == MYSQL_TYPE_BLOB)
{
buffer= SvPV(imp_sth->params[idx].value, slen);
buffer_length= slen;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR type %d ->length %d<- IS A STRING or BLOB\n",
(int) sql_type, buffer_length);
}
}
else
{
/*case: buffer_is_null != 0*/
buffer= NULL;
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" SCALAR NULL VALUE: buffer type is: %d\n", buffer_type);
}
/* Type of column was changed. Force to rebind */
if (imp_sth->bind[idx].buffer_type != buffer_type) {
/* Note: this looks like being another bug:
* if type of parameter N changes, then a bind is triggered
* with an only partially filled bind structure ??
*/
if (DBIc_TRACE_LEVEL(imp_xxh) >= 2)
PerlIO_printf(DBIc_LOGPIO(imp_xxh),
" FORCE REBIND: buffer type changed from %d to %d, sql-type=%d\n",
(int) imp_sth->bind[idx].buffer_type, buffer_type, (int) sql_type);
imp_sth->has_been_bound = 0;
}
/* prepare has not been called */
if (imp_sth->has_been_bound == 0)
{
imp_sth->bind[idx].buffer_type= buffer_type;
imp_sth->bind[idx].buffer= buffer;
imp_sth->bind[idx].buffer_length= buffer_length;
}
else /* prepare has been called */
{
imp_sth->stmt->params[idx].buffer= buffer;
imp_sth->stmt->params[idx].buffer_length= buffer_length;
}
imp_sth->fbind[idx].length= buffer_length;
imp_sth->fbind[idx].is_null= buffer_is_null;
}
#endif
return rc;
}
/***************************************************************************
*
* Name: mysql_db_reconnect
*
* Purpose: If the server has disconnected, try to reconnect.
*
* Input: h - database or statement handle
*
* Returns: TRUE for success, FALSE otherwise
*
**************************************************************************/
int mysql_db_reconnect(SV* h)
{
dTHX;
D_imp_xxh(h);
imp_dbh_t* imp_dbh;
MYSQL save_socket;
if (DBIc_TYPE(imp_xxh) == DBIt_ST)
{
imp_dbh = (imp_dbh_t*) DBIc_PARENT_COM(imp_xxh);
h = DBIc_PARENT_H(imp_xxh);
}
else
imp_dbh= (imp_dbh_t*) imp_xxh;
if (mysql_errno(imp_dbh->pmysql) != CR_SERVER_GONE_ERROR)
/* Other error */
return FALSE;
if (!DBIc_has(imp_dbh, DBIcf_AutoCommit) || !imp_dbh->auto_reconnect)
{
/* We never reconnect if AutoCommit is turned off.
* Otherwise we might get an inconsistent transaction
* state.
*/
return FALSE;
}
/* my_login will blow away imp_dbh->mysql so we save a copy of
* imp_dbh->mysql and put it back where it belongs if the reconnect
* fail. Think server is down & reconnect fails but the application eval{}s
* the execute, so next time $dbh->quote() gets called, instant SIGSEGV!
*/
save_socket= *(imp_dbh->pmysql);
memcpy (&save_socket, imp_dbh->pmysql,sizeof(save_socket));
memset (imp_dbh->pmysql,0,sizeof(*(imp_dbh->pmysql)));
/* we should disconnect the db handle before reconnecting, this will
* prevent my_login from thinking it's adopting an active child which
* would prevent the handle from actually reconnecting
*/
if (!dbd_db_disconnect(h, imp_dbh) || !my_login(aTHX_ h, imp_dbh))
{
do_error(h, mysql_errno(imp_dbh->pmysql), mysql_error(imp_dbh->pmysql),
mysql_sqlstate(imp_dbh->pmysql));
memcpy (imp_dbh->pmysql, &save_socket, sizeof(save_socket));
++imp_dbh->stats.auto_reconnects_failed;
return FALSE;
}
/*
* Tell DBI, that dbh->disconnect should be called for this handle
*/
DBIc_ACTIVE_on(imp_dbh);
++imp_dbh->stats.auto_reconnects_ok;
return TRUE;
}
/**************************************************************************
*
* Name: dbd_db_type_info_all
*
* Purpose: Implements $dbh->type_info_all
*
* Input: dbh - database handle
* imp_sth - drivers private database handle data
*
* Returns: RV to AV of types
*
**************************************************************************/
#define PV_PUSH(c) \
if (c) { \
sv= newSVpv((char*) (c), 0); \
SvREADONLY_on(sv); \
} else { \
sv= &PL_sv_undef; \
} \
av_push(row, sv);
#define IV_PUSH(i) sv= newSViv((i)); SvREADONLY_on(sv); av_push(row, sv);
AV *dbd_db_type_info_all(SV *dbh, imp_dbh_t *imp_dbh)
{
dTHX;
AV *av= newAV();
AV *row;
HV *hv;
SV *sv;
int i;
const char *cols[] = {
"TYPE_NAME",
"DATA_TYPE",
"COLUMN_SIZE",
"LITERAL_PREFIX",
"LITERAL_SUFFIX",
"CREATE_PARAMS",
"NULLABLE",
"CASE_SENSITIVE",
"SEARCHABLE",
"UNSIGNED_ATTRIBUTE",
"FIXED_PREC_SCALE",
"AUTO_UNIQUE_VALUE",
"LOCAL_TYPE_NAME",
"MINIMUM_SCALE",
"MAXIMUM_SCALE",
"NUM_PREC_RADIX",
"SQL_DATATYPE",
"SQL_DATETIME_SUB",
"INTERVAL_PRECISION",
"mysql_native_type",
"mysql_is_num"
};
dbh= dbh;
imp_dbh= imp_dbh;
hv= newHV();
av_push(av, newRV_noinc((SV*) hv));
for (i= 0; i < (int)(sizeof(cols) / sizeof(const char*)); i++)
{
if (!hv_store(hv, (char*) cols[i], strlen(cols[i]), newSViv(i), 0))
{
SvREFCNT_dec((SV*) av);
return Nullav;
}
}
for (i= 0; i < (int)SQL_GET_TYPE_INFO_num; i++)
{
const sql_type_info_t *t= &SQL_GET_TYPE_INFO_values[i];
row= newAV();
av_push(av, newRV_noinc((SV*) row));
PV_PUSH(t->type_name);
IV_PUSH(t->data_type);
IV_PUSH(t->column_size);
PV_PUSH(t->literal_prefix);
PV_PUSH(t->literal_suffix);
PV_PUSH(t->create_params);
IV_PUSH(t->nullable);
IV_PUSH(t->case_sensitive);
IV_PUSH(t->searchable);
IV_PUSH(t->unsigned_attribute);
IV_PUSH(t->fixed_prec_scale);
IV_PUSH(t->auto_unique_value);
PV_PUSH(t->local_type_name);
IV_PUSH(t->minimum_scale);
IV_PUSH(t->maximum_scale);
if (t->num_prec_radix)
{
IV_PUSH(t->num_prec_radix);
}
else
av_push(row, &PL_sv_undef);
IV_PUSH(t->sql_datatype); /* SQL_DATATYPE*/
IV_PUSH(t->sql_datetime_sub); /* SQL_DATETIME_SUB*/
IV_PUSH(t->interval_precision); /* INTERVAL_PERCISION */
IV_PUSH(t->native_type);
IV_PUSH(t->is_num);
}
return av;
}
/*
dbd_db_quote
Properly quotes a value
*/
SV* dbd_db_quote(SV *dbh, SV *str, SV *type)
{
dTHX;
SV *result;
if (SvGMAGICAL(str))
mg_get(str);
if (!SvOK(str))
result= newSVpv("NULL", 4);
else
{
char *ptr, *sptr;
STRLEN len;
D_imp_dbh(dbh);
if (type && SvMAGICAL(type))
mg_get(type);
if (type && SvOK(type))
{
int i;
int tp= SvIV(type);
for (i= 0; i < (int)SQL_GET_TYPE_INFO_num; i++)
{
const sql_type_info_t *t= &SQL_GET_TYPE_INFO_values[i];
if (t->data_type == tp)
{
if (!t->literal_prefix)
return Nullsv;
break;
}
}
}
ptr= SvPV(str, len);
result= newSV(len*2+3);
#ifdef SvUTF8
if (SvUTF8(str)) SvUTF8_on(result);
#endif
sptr= SvPVX(result);
*sptr++ = '\'';
sptr+= mysql_real_escape_string(imp_dbh->pmysql, sptr,
ptr, len);
*sptr++= '\'';
SvPOK_on(result);
SvCUR_set(result, sptr - SvPVX(result));
/* Never hurts NUL terminating a Per string */
*sptr++= '\0';
}
return result;
}
#ifdef DBD_MYSQL_INSERT_ID_IS_GOOD
SV *mysql_db_last_insert_id(SV *dbh, imp_dbh_t *imp_dbh,
SV *catalog, SV *schema, SV *table, SV *field, SV *attr)
{
dTHX;
/* all these non-op settings are to stifle OS X compile warnings */
imp_dbh= imp_dbh;
dbh= dbh;
catalog= catalog;
schema= schema;
table= table;
field= field;
attr= attr;
ASYNC_CHECK_RETURN(dbh, &PL_sv_undef);
return sv_2mortal(my_ulonglong2str(aTHX_ mysql_insert_id(imp_dbh->pmysql)));
}
#endif
#if MYSQL_ASYNC
int mysql_db_async_result(SV* h, MYSQL_RES** resp)
{
dTHX;
D_imp_xxh(h);
imp_dbh_t* dbh;
MYSQL* svsock = NULL;
MYSQL_RES* _res;
int retval = 0;
int htype;
if(! resp) {
resp = &_res;
}
htype = DBIc_TYPE(imp_xxh);
if(htype == DBIt_DB) {
D_imp_dbh(h);
dbh = imp_dbh;
} else {
D_imp_sth(h);
D_imp_dbh_from_sth;
dbh = imp_dbh;
}
if(! dbh->async_query_in_flight) {
do_error(h, 2000, "Gathering asynchronous results for a synchronous handle", "HY000");
return -1;
}
if(dbh->async_query_in_flight != imp_xxh) {
do_error(h, 2000, "Gathering async_query_in_flight results for the wrong handle", "HY000");
return -1;
}
dbh->async_query_in_flight = NULL;
svsock= dbh->pmysql;
retval= mysql_read_query_result(svsock);
if(! retval) {
*resp= mysql_store_result(svsock);
if (mysql_errno(svsock))
do_error(h, mysql_errno(svsock), mysql_error(svsock), mysql_sqlstate(svsock));
if (!*resp)
retval= mysql_affected_rows(svsock);
else {
retval= mysql_num_rows(*resp);
if(resp == &_res) {
mysql_free_result(*resp);
}
}
if(htype == DBIt_ST) {
D_imp_sth(h);
D_imp_dbh_from_sth;
if(retval+1 != (my_ulonglong)-1) {
if(! *resp) {
imp_sth->insertid= mysql_insert_id(svsock);
#if MYSQL_VERSION_ID >= MULTIPLE_RESULT_SET_VERSION
if(! mysql_more_results(svsock))
DBIc_ACTIVE_off(imp_sth);
#endif
} else {
DBIc_NUM_FIELDS(imp_sth)= mysql_num_fields(imp_sth->result);
imp_sth->done_desc= 0;
imp_sth->fetch_done= 0;
}
}
imp_sth->warning_count = mysql_warning_count(imp_dbh->pmysql);
}
} else {
do_error(h, mysql_errno(svsock), mysql_error(svsock),
mysql_sqlstate(svsock));
return -1;
}
return retval;
}
int mysql_db_async_ready(SV* h)
{
dTHX;
D_imp_xxh(h);
imp_dbh_t* dbh;
int htype;
htype = DBIc_TYPE(imp_xxh);
if(htype == DBIt_DB) {
D_imp_dbh(h);
dbh = imp_dbh;
} else {
D_imp_sth(h);
D_imp_dbh_from_sth;
dbh = imp_dbh;
}
if(dbh->async_query_in_flight) {
if(dbh->async_query_in_flight == imp_xxh) {
struct pollfd fds;
int retval;
fds.fd = dbh->pmysql->net.fd;
fds.events = POLLIN;
retval = poll(&fds, 1, 0);
if(retval < 0) {
do_error(h, errno, strerror(errno), "HY000");
}
return retval;
} else {
do_error(h, 2000, "Calling mysql_async_ready on the wrong handle", "HY000");
return -1;
}
} else {
do_error(h, 2000, "Handle is not in asynchronous mode", "HY000");
return -1;
}
}
#endif
static int parse_number(char *string, STRLEN len, char **end)
{
int seen_neg;
int seen_dec;
int seen_e;
int seen_plus;
int seen_digit;
char *cp;
seen_neg= seen_dec= seen_e= seen_plus= seen_digit= 0;
if (len <= 0) {
len= strlen(string);
}
cp= string;
/* Skip leading whitespace */
while (*cp && isspace(*cp))
cp++;
for ( ; *cp; cp++)
{
if ('-' == *cp)
{
if (seen_neg >= 2)
{
/*
third '-'. number can contains two '-'.
because -1e-10 is valid number */
break;
}
seen_neg += 1;
}
else if ('.' == *cp)
{
if (seen_dec)
{
/* second '.' */
break;
}
seen_dec= 1;
}
else if ('e' == *cp)
{
if (seen_e)
{
/* second 'e' */
break;
}
seen_e= 1;
}
else if ('+' == *cp)
{
if (seen_plus)
{
/* second '+' */
break;
}
seen_plus= 1;
}
else if (!isdigit(*cp))
{
/* Not sure why this was changed */
/* seen_digit= 1; */
break;
}
}
*end= cp;
/* length 0 -> not a number */
/* Need to revisit this */
/*if (len == 0 || cp - string < (int) len || seen_digit == 0) {*/
if (len == 0 || cp - string < (int) len) {
return -1;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-416/c/good_1840_0 |
crossvul-cpp_data_good_822_0 | #include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/spinlock.h>
#include <linux/mm.h>
#include <linux/memremap.h>
#include <linux/pagemap.h>
#include <linux/rmap.h>
#include <linux/swap.h>
#include <linux/swapops.h>
#include <linux/sched/signal.h>
#include <linux/rwsem.h>
#include <linux/hugetlb.h>
#include <asm/mmu_context.h>
#include <asm/pgtable.h>
#include <asm/tlbflush.h>
#include "internal.h"
struct follow_page_context {
struct dev_pagemap *pgmap;
unsigned int page_mask;
};
static struct page *no_page_table(struct vm_area_struct *vma,
unsigned int flags)
{
/*
* When core dumping an enormous anonymous area that nobody
* has touched so far, we don't want to allocate unnecessary pages or
* page tables. Return error instead of NULL to skip handle_mm_fault,
* then get_dump_page() will return NULL to leave a hole in the dump.
* But we can only make this optimization where a hole would surely
* be zero-filled if handle_mm_fault() actually did handle it.
*/
if ((flags & FOLL_DUMP) && (!vma->vm_ops || !vma->vm_ops->fault))
return ERR_PTR(-EFAULT);
return NULL;
}
static int follow_pfn_pte(struct vm_area_struct *vma, unsigned long address,
pte_t *pte, unsigned int flags)
{
/* No page to get reference */
if (flags & FOLL_GET)
return -EFAULT;
if (flags & FOLL_TOUCH) {
pte_t entry = *pte;
if (flags & FOLL_WRITE)
entry = pte_mkdirty(entry);
entry = pte_mkyoung(entry);
if (!pte_same(*pte, entry)) {
set_pte_at(vma->vm_mm, address, pte, entry);
update_mmu_cache(vma, address, pte);
}
}
/* Proper page table entry exists, but no corresponding struct page */
return -EEXIST;
}
/*
* FOLL_FORCE can write to even unwritable pte's, but only
* after we've gone through a COW cycle and they are dirty.
*/
static inline bool can_follow_write_pte(pte_t pte, unsigned int flags)
{
return pte_write(pte) ||
((flags & FOLL_FORCE) && (flags & FOLL_COW) && pte_dirty(pte));
}
static struct page *follow_page_pte(struct vm_area_struct *vma,
unsigned long address, pmd_t *pmd, unsigned int flags,
struct dev_pagemap **pgmap)
{
struct mm_struct *mm = vma->vm_mm;
struct page *page;
spinlock_t *ptl;
pte_t *ptep, pte;
retry:
if (unlikely(pmd_bad(*pmd)))
return no_page_table(vma, flags);
ptep = pte_offset_map_lock(mm, pmd, address, &ptl);
pte = *ptep;
if (!pte_present(pte)) {
swp_entry_t entry;
/*
* KSM's break_ksm() relies upon recognizing a ksm page
* even while it is being migrated, so for that case we
* need migration_entry_wait().
*/
if (likely(!(flags & FOLL_MIGRATION)))
goto no_page;
if (pte_none(pte))
goto no_page;
entry = pte_to_swp_entry(pte);
if (!is_migration_entry(entry))
goto no_page;
pte_unmap_unlock(ptep, ptl);
migration_entry_wait(mm, pmd, address);
goto retry;
}
if ((flags & FOLL_NUMA) && pte_protnone(pte))
goto no_page;
if ((flags & FOLL_WRITE) && !can_follow_write_pte(pte, flags)) {
pte_unmap_unlock(ptep, ptl);
return NULL;
}
page = vm_normal_page(vma, address, pte);
if (!page && pte_devmap(pte) && (flags & FOLL_GET)) {
/*
* Only return device mapping pages in the FOLL_GET case since
* they are only valid while holding the pgmap reference.
*/
*pgmap = get_dev_pagemap(pte_pfn(pte), *pgmap);
if (*pgmap)
page = pte_page(pte);
else
goto no_page;
} else if (unlikely(!page)) {
if (flags & FOLL_DUMP) {
/* Avoid special (like zero) pages in core dumps */
page = ERR_PTR(-EFAULT);
goto out;
}
if (is_zero_pfn(pte_pfn(pte))) {
page = pte_page(pte);
} else {
int ret;
ret = follow_pfn_pte(vma, address, ptep, flags);
page = ERR_PTR(ret);
goto out;
}
}
if (flags & FOLL_SPLIT && PageTransCompound(page)) {
int ret;
get_page(page);
pte_unmap_unlock(ptep, ptl);
lock_page(page);
ret = split_huge_page(page);
unlock_page(page);
put_page(page);
if (ret)
return ERR_PTR(ret);
goto retry;
}
if (flags & FOLL_GET) {
if (unlikely(!try_get_page(page))) {
page = ERR_PTR(-ENOMEM);
goto out;
}
}
if (flags & FOLL_TOUCH) {
if ((flags & FOLL_WRITE) &&
!pte_dirty(pte) && !PageDirty(page))
set_page_dirty(page);
/*
* pte_mkyoung() would be more correct here, but atomic care
* is needed to avoid losing the dirty bit: it is easier to use
* mark_page_accessed().
*/
mark_page_accessed(page);
}
if ((flags & FOLL_MLOCK) && (vma->vm_flags & VM_LOCKED)) {
/* Do not mlock pte-mapped THP */
if (PageTransCompound(page))
goto out;
/*
* The preliminary mapping check is mainly to avoid the
* pointless overhead of lock_page on the ZERO_PAGE
* which might bounce very badly if there is contention.
*
* If the page is already locked, we don't need to
* handle it now - vmscan will handle it later if and
* when it attempts to reclaim the page.
*/
if (page->mapping && trylock_page(page)) {
lru_add_drain(); /* push cached pages to LRU */
/*
* Because we lock page here, and migration is
* blocked by the pte's page reference, and we
* know the page is still mapped, we don't even
* need to check for file-cache page truncation.
*/
mlock_vma_page(page);
unlock_page(page);
}
}
out:
pte_unmap_unlock(ptep, ptl);
return page;
no_page:
pte_unmap_unlock(ptep, ptl);
if (!pte_none(pte))
return NULL;
return no_page_table(vma, flags);
}
static struct page *follow_pmd_mask(struct vm_area_struct *vma,
unsigned long address, pud_t *pudp,
unsigned int flags,
struct follow_page_context *ctx)
{
pmd_t *pmd, pmdval;
spinlock_t *ptl;
struct page *page;
struct mm_struct *mm = vma->vm_mm;
pmd = pmd_offset(pudp, address);
/*
* The READ_ONCE() will stabilize the pmdval in a register or
* on the stack so that it will stop changing under the code.
*/
pmdval = READ_ONCE(*pmd);
if (pmd_none(pmdval))
return no_page_table(vma, flags);
if (pmd_huge(pmdval) && vma->vm_flags & VM_HUGETLB) {
page = follow_huge_pmd(mm, address, pmd, flags);
if (page)
return page;
return no_page_table(vma, flags);
}
if (is_hugepd(__hugepd(pmd_val(pmdval)))) {
page = follow_huge_pd(vma, address,
__hugepd(pmd_val(pmdval)), flags,
PMD_SHIFT);
if (page)
return page;
return no_page_table(vma, flags);
}
retry:
if (!pmd_present(pmdval)) {
if (likely(!(flags & FOLL_MIGRATION)))
return no_page_table(vma, flags);
VM_BUG_ON(thp_migration_supported() &&
!is_pmd_migration_entry(pmdval));
if (is_pmd_migration_entry(pmdval))
pmd_migration_entry_wait(mm, pmd);
pmdval = READ_ONCE(*pmd);
/*
* MADV_DONTNEED may convert the pmd to null because
* mmap_sem is held in read mode
*/
if (pmd_none(pmdval))
return no_page_table(vma, flags);
goto retry;
}
if (pmd_devmap(pmdval)) {
ptl = pmd_lock(mm, pmd);
page = follow_devmap_pmd(vma, address, pmd, flags, &ctx->pgmap);
spin_unlock(ptl);
if (page)
return page;
}
if (likely(!pmd_trans_huge(pmdval)))
return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
if ((flags & FOLL_NUMA) && pmd_protnone(pmdval))
return no_page_table(vma, flags);
retry_locked:
ptl = pmd_lock(mm, pmd);
if (unlikely(pmd_none(*pmd))) {
spin_unlock(ptl);
return no_page_table(vma, flags);
}
if (unlikely(!pmd_present(*pmd))) {
spin_unlock(ptl);
if (likely(!(flags & FOLL_MIGRATION)))
return no_page_table(vma, flags);
pmd_migration_entry_wait(mm, pmd);
goto retry_locked;
}
if (unlikely(!pmd_trans_huge(*pmd))) {
spin_unlock(ptl);
return follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
}
if (flags & FOLL_SPLIT) {
int ret;
page = pmd_page(*pmd);
if (is_huge_zero_page(page)) {
spin_unlock(ptl);
ret = 0;
split_huge_pmd(vma, pmd, address);
if (pmd_trans_unstable(pmd))
ret = -EBUSY;
} else {
if (unlikely(!try_get_page(page))) {
spin_unlock(ptl);
return ERR_PTR(-ENOMEM);
}
spin_unlock(ptl);
lock_page(page);
ret = split_huge_page(page);
unlock_page(page);
put_page(page);
if (pmd_none(*pmd))
return no_page_table(vma, flags);
}
return ret ? ERR_PTR(ret) :
follow_page_pte(vma, address, pmd, flags, &ctx->pgmap);
}
page = follow_trans_huge_pmd(vma, address, pmd, flags);
spin_unlock(ptl);
ctx->page_mask = HPAGE_PMD_NR - 1;
return page;
}
static struct page *follow_pud_mask(struct vm_area_struct *vma,
unsigned long address, p4d_t *p4dp,
unsigned int flags,
struct follow_page_context *ctx)
{
pud_t *pud;
spinlock_t *ptl;
struct page *page;
struct mm_struct *mm = vma->vm_mm;
pud = pud_offset(p4dp, address);
if (pud_none(*pud))
return no_page_table(vma, flags);
if (pud_huge(*pud) && vma->vm_flags & VM_HUGETLB) {
page = follow_huge_pud(mm, address, pud, flags);
if (page)
return page;
return no_page_table(vma, flags);
}
if (is_hugepd(__hugepd(pud_val(*pud)))) {
page = follow_huge_pd(vma, address,
__hugepd(pud_val(*pud)), flags,
PUD_SHIFT);
if (page)
return page;
return no_page_table(vma, flags);
}
if (pud_devmap(*pud)) {
ptl = pud_lock(mm, pud);
page = follow_devmap_pud(vma, address, pud, flags, &ctx->pgmap);
spin_unlock(ptl);
if (page)
return page;
}
if (unlikely(pud_bad(*pud)))
return no_page_table(vma, flags);
return follow_pmd_mask(vma, address, pud, flags, ctx);
}
static struct page *follow_p4d_mask(struct vm_area_struct *vma,
unsigned long address, pgd_t *pgdp,
unsigned int flags,
struct follow_page_context *ctx)
{
p4d_t *p4d;
struct page *page;
p4d = p4d_offset(pgdp, address);
if (p4d_none(*p4d))
return no_page_table(vma, flags);
BUILD_BUG_ON(p4d_huge(*p4d));
if (unlikely(p4d_bad(*p4d)))
return no_page_table(vma, flags);
if (is_hugepd(__hugepd(p4d_val(*p4d)))) {
page = follow_huge_pd(vma, address,
__hugepd(p4d_val(*p4d)), flags,
P4D_SHIFT);
if (page)
return page;
return no_page_table(vma, flags);
}
return follow_pud_mask(vma, address, p4d, flags, ctx);
}
/**
* follow_page_mask - look up a page descriptor from a user-virtual address
* @vma: vm_area_struct mapping @address
* @address: virtual address to look up
* @flags: flags modifying lookup behaviour
* @ctx: contains dev_pagemap for %ZONE_DEVICE memory pinning and a
* pointer to output page_mask
*
* @flags can have FOLL_ flags set, defined in <linux/mm.h>
*
* When getting pages from ZONE_DEVICE memory, the @ctx->pgmap caches
* the device's dev_pagemap metadata to avoid repeating expensive lookups.
*
* On output, the @ctx->page_mask is set according to the size of the page.
*
* Return: the mapped (struct page *), %NULL if no mapping exists, or
* an error pointer if there is a mapping to something not represented
* by a page descriptor (see also vm_normal_page()).
*/
struct page *follow_page_mask(struct vm_area_struct *vma,
unsigned long address, unsigned int flags,
struct follow_page_context *ctx)
{
pgd_t *pgd;
struct page *page;
struct mm_struct *mm = vma->vm_mm;
ctx->page_mask = 0;
/* make this handle hugepd */
page = follow_huge_addr(mm, address, flags & FOLL_WRITE);
if (!IS_ERR(page)) {
BUG_ON(flags & FOLL_GET);
return page;
}
pgd = pgd_offset(mm, address);
if (pgd_none(*pgd) || unlikely(pgd_bad(*pgd)))
return no_page_table(vma, flags);
if (pgd_huge(*pgd)) {
page = follow_huge_pgd(mm, address, pgd, flags);
if (page)
return page;
return no_page_table(vma, flags);
}
if (is_hugepd(__hugepd(pgd_val(*pgd)))) {
page = follow_huge_pd(vma, address,
__hugepd(pgd_val(*pgd)), flags,
PGDIR_SHIFT);
if (page)
return page;
return no_page_table(vma, flags);
}
return follow_p4d_mask(vma, address, pgd, flags, ctx);
}
struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
unsigned int foll_flags)
{
struct follow_page_context ctx = { NULL };
struct page *page;
page = follow_page_mask(vma, address, foll_flags, &ctx);
if (ctx.pgmap)
put_dev_pagemap(ctx.pgmap);
return page;
}
static int get_gate_page(struct mm_struct *mm, unsigned long address,
unsigned int gup_flags, struct vm_area_struct **vma,
struct page **page)
{
pgd_t *pgd;
p4d_t *p4d;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
int ret = -EFAULT;
/* user gate pages are read-only */
if (gup_flags & FOLL_WRITE)
return -EFAULT;
if (address > TASK_SIZE)
pgd = pgd_offset_k(address);
else
pgd = pgd_offset_gate(mm, address);
BUG_ON(pgd_none(*pgd));
p4d = p4d_offset(pgd, address);
BUG_ON(p4d_none(*p4d));
pud = pud_offset(p4d, address);
BUG_ON(pud_none(*pud));
pmd = pmd_offset(pud, address);
if (!pmd_present(*pmd))
return -EFAULT;
VM_BUG_ON(pmd_trans_huge(*pmd));
pte = pte_offset_map(pmd, address);
if (pte_none(*pte))
goto unmap;
*vma = get_gate_vma(mm);
if (!page)
goto out;
*page = vm_normal_page(*vma, address, *pte);
if (!*page) {
if ((gup_flags & FOLL_DUMP) || !is_zero_pfn(pte_pfn(*pte)))
goto unmap;
*page = pte_page(*pte);
/*
* This should never happen (a device public page in the gate
* area).
*/
if (is_device_public_page(*page))
goto unmap;
}
if (unlikely(!try_get_page(*page))) {
ret = -ENOMEM;
goto unmap;
}
out:
ret = 0;
unmap:
pte_unmap(pte);
return ret;
}
/*
* mmap_sem must be held on entry. If @nonblocking != NULL and
* *@flags does not include FOLL_NOWAIT, the mmap_sem may be released.
* If it is, *@nonblocking will be set to 0 and -EBUSY returned.
*/
static int faultin_page(struct task_struct *tsk, struct vm_area_struct *vma,
unsigned long address, unsigned int *flags, int *nonblocking)
{
unsigned int fault_flags = 0;
vm_fault_t ret;
/* mlock all present pages, but do not fault in new pages */
if ((*flags & (FOLL_POPULATE | FOLL_MLOCK)) == FOLL_MLOCK)
return -ENOENT;
if (*flags & FOLL_WRITE)
fault_flags |= FAULT_FLAG_WRITE;
if (*flags & FOLL_REMOTE)
fault_flags |= FAULT_FLAG_REMOTE;
if (nonblocking)
fault_flags |= FAULT_FLAG_ALLOW_RETRY;
if (*flags & FOLL_NOWAIT)
fault_flags |= FAULT_FLAG_ALLOW_RETRY | FAULT_FLAG_RETRY_NOWAIT;
if (*flags & FOLL_TRIED) {
VM_WARN_ON_ONCE(fault_flags & FAULT_FLAG_ALLOW_RETRY);
fault_flags |= FAULT_FLAG_TRIED;
}
ret = handle_mm_fault(vma, address, fault_flags);
if (ret & VM_FAULT_ERROR) {
int err = vm_fault_to_errno(ret, *flags);
if (err)
return err;
BUG();
}
if (tsk) {
if (ret & VM_FAULT_MAJOR)
tsk->maj_flt++;
else
tsk->min_flt++;
}
if (ret & VM_FAULT_RETRY) {
if (nonblocking && !(fault_flags & FAULT_FLAG_RETRY_NOWAIT))
*nonblocking = 0;
return -EBUSY;
}
/*
* The VM_FAULT_WRITE bit tells us that do_wp_page has broken COW when
* necessary, even if maybe_mkwrite decided not to set pte_write. We
* can thus safely do subsequent page lookups as if they were reads.
* But only do so when looping for pte_write is futile: in some cases
* userspace may also be wanting to write to the gotten user page,
* which a read fault here might prevent (a readonly page might get
* reCOWed by userspace write).
*/
if ((ret & VM_FAULT_WRITE) && !(vma->vm_flags & VM_WRITE))
*flags |= FOLL_COW;
return 0;
}
static int check_vma_flags(struct vm_area_struct *vma, unsigned long gup_flags)
{
vm_flags_t vm_flags = vma->vm_flags;
int write = (gup_flags & FOLL_WRITE);
int foreign = (gup_flags & FOLL_REMOTE);
if (vm_flags & (VM_IO | VM_PFNMAP))
return -EFAULT;
if (gup_flags & FOLL_ANON && !vma_is_anonymous(vma))
return -EFAULT;
if (write) {
if (!(vm_flags & VM_WRITE)) {
if (!(gup_flags & FOLL_FORCE))
return -EFAULT;
/*
* We used to let the write,force case do COW in a
* VM_MAYWRITE VM_SHARED !VM_WRITE vma, so ptrace could
* set a breakpoint in a read-only mapping of an
* executable, without corrupting the file (yet only
* when that file had been opened for writing!).
* Anon pages in shared mappings are surprising: now
* just reject it.
*/
if (!is_cow_mapping(vm_flags))
return -EFAULT;
}
} else if (!(vm_flags & VM_READ)) {
if (!(gup_flags & FOLL_FORCE))
return -EFAULT;
/*
* Is there actually any vma we can reach here which does not
* have VM_MAYREAD set?
*/
if (!(vm_flags & VM_MAYREAD))
return -EFAULT;
}
/*
* gups are always data accesses, not instruction
* fetches, so execute=false here
*/
if (!arch_vma_access_permitted(vma, write, false, foreign))
return -EFAULT;
return 0;
}
/**
* __get_user_pages() - pin user pages in memory
* @tsk: task_struct of target task
* @mm: mm_struct of target mm
* @start: starting user address
* @nr_pages: number of pages from start to pin
* @gup_flags: flags modifying pin behaviour
* @pages: array that receives pointers to the pages pinned.
* Should be at least nr_pages long. Or NULL, if caller
* only intends to ensure the pages are faulted in.
* @vmas: array of pointers to vmas corresponding to each page.
* Or NULL if the caller does not require them.
* @nonblocking: whether waiting for disk IO or mmap_sem contention
*
* Returns number of pages pinned. This may be fewer than the number
* requested. If nr_pages is 0 or negative, returns 0. If no pages
* were pinned, returns -errno. Each page returned must be released
* with a put_page() call when it is finished with. vmas will only
* remain valid while mmap_sem is held.
*
* Must be called with mmap_sem held. It may be released. See below.
*
* __get_user_pages walks a process's page tables and takes a reference to
* each struct page that each user address corresponds to at a given
* instant. That is, it takes the page that would be accessed if a user
* thread accesses the given user virtual address at that instant.
*
* This does not guarantee that the page exists in the user mappings when
* __get_user_pages returns, and there may even be a completely different
* page there in some cases (eg. if mmapped pagecache has been invalidated
* and subsequently re faulted). However it does guarantee that the page
* won't be freed completely. And mostly callers simply care that the page
* contains data that was valid *at some point in time*. Typically, an IO
* or similar operation cannot guarantee anything stronger anyway because
* locks can't be held over the syscall boundary.
*
* If @gup_flags & FOLL_WRITE == 0, the page must not be written to. If
* the page is written to, set_page_dirty (or set_page_dirty_lock, as
* appropriate) must be called after the page is finished with, and
* before put_page is called.
*
* If @nonblocking != NULL, __get_user_pages will not wait for disk IO
* or mmap_sem contention, and if waiting is needed to pin all pages,
* *@nonblocking will be set to 0. Further, if @gup_flags does not
* include FOLL_NOWAIT, the mmap_sem will be released via up_read() in
* this case.
*
* A caller using such a combination of @nonblocking and @gup_flags
* must therefore hold the mmap_sem for reading only, and recognize
* when it's been released. Otherwise, it must be held for either
* reading or writing and will not be released.
*
* In most cases, get_user_pages or get_user_pages_fast should be used
* instead of __get_user_pages. __get_user_pages should be used only if
* you need some special @gup_flags.
*/
static long __get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
unsigned long start, unsigned long nr_pages,
unsigned int gup_flags, struct page **pages,
struct vm_area_struct **vmas, int *nonblocking)
{
long ret = 0, i = 0;
struct vm_area_struct *vma = NULL;
struct follow_page_context ctx = { NULL };
if (!nr_pages)
return 0;
VM_BUG_ON(!!pages != !!(gup_flags & FOLL_GET));
/*
* If FOLL_FORCE is set then do not force a full fault as the hinting
* fault information is unrelated to the reference behaviour of a task
* using the address space
*/
if (!(gup_flags & FOLL_FORCE))
gup_flags |= FOLL_NUMA;
do {
struct page *page;
unsigned int foll_flags = gup_flags;
unsigned int page_increm;
/* first iteration or cross vma bound */
if (!vma || start >= vma->vm_end) {
vma = find_extend_vma(mm, start);
if (!vma && in_gate_area(mm, start)) {
ret = get_gate_page(mm, start & PAGE_MASK,
gup_flags, &vma,
pages ? &pages[i] : NULL);
if (ret)
goto out;
ctx.page_mask = 0;
goto next_page;
}
if (!vma || check_vma_flags(vma, gup_flags)) {
ret = -EFAULT;
goto out;
}
if (is_vm_hugetlb_page(vma)) {
i = follow_hugetlb_page(mm, vma, pages, vmas,
&start, &nr_pages, i,
gup_flags, nonblocking);
continue;
}
}
retry:
/*
* If we have a pending SIGKILL, don't keep faulting pages and
* potentially allocating memory.
*/
if (fatal_signal_pending(current)) {
ret = -ERESTARTSYS;
goto out;
}
cond_resched();
page = follow_page_mask(vma, start, foll_flags, &ctx);
if (!page) {
ret = faultin_page(tsk, vma, start, &foll_flags,
nonblocking);
switch (ret) {
case 0:
goto retry;
case -EBUSY:
ret = 0;
/* FALLTHRU */
case -EFAULT:
case -ENOMEM:
case -EHWPOISON:
goto out;
case -ENOENT:
goto next_page;
}
BUG();
} else if (PTR_ERR(page) == -EEXIST) {
/*
* Proper page table entry exists, but no corresponding
* struct page.
*/
goto next_page;
} else if (IS_ERR(page)) {
ret = PTR_ERR(page);
goto out;
}
if (pages) {
pages[i] = page;
flush_anon_page(vma, page, start);
flush_dcache_page(page);
ctx.page_mask = 0;
}
next_page:
if (vmas) {
vmas[i] = vma;
ctx.page_mask = 0;
}
page_increm = 1 + (~(start >> PAGE_SHIFT) & ctx.page_mask);
if (page_increm > nr_pages)
page_increm = nr_pages;
i += page_increm;
start += page_increm * PAGE_SIZE;
nr_pages -= page_increm;
} while (nr_pages);
out:
if (ctx.pgmap)
put_dev_pagemap(ctx.pgmap);
return i ? i : ret;
}
static bool vma_permits_fault(struct vm_area_struct *vma,
unsigned int fault_flags)
{
bool write = !!(fault_flags & FAULT_FLAG_WRITE);
bool foreign = !!(fault_flags & FAULT_FLAG_REMOTE);
vm_flags_t vm_flags = write ? VM_WRITE : VM_READ;
if (!(vm_flags & vma->vm_flags))
return false;
/*
* The architecture might have a hardware protection
* mechanism other than read/write that can deny access.
*
* gup always represents data access, not instruction
* fetches, so execute=false here:
*/
if (!arch_vma_access_permitted(vma, write, false, foreign))
return false;
return true;
}
/*
* fixup_user_fault() - manually resolve a user page fault
* @tsk: the task_struct to use for page fault accounting, or
* NULL if faults are not to be recorded.
* @mm: mm_struct of target mm
* @address: user address
* @fault_flags:flags to pass down to handle_mm_fault()
* @unlocked: did we unlock the mmap_sem while retrying, maybe NULL if caller
* does not allow retry
*
* This is meant to be called in the specific scenario where for locking reasons
* we try to access user memory in atomic context (within a pagefault_disable()
* section), this returns -EFAULT, and we want to resolve the user fault before
* trying again.
*
* Typically this is meant to be used by the futex code.
*
* The main difference with get_user_pages() is that this function will
* unconditionally call handle_mm_fault() which will in turn perform all the
* necessary SW fixup of the dirty and young bits in the PTE, while
* get_user_pages() only guarantees to update these in the struct page.
*
* This is important for some architectures where those bits also gate the
* access permission to the page because they are maintained in software. On
* such architectures, gup() will not be enough to make a subsequent access
* succeed.
*
* This function will not return with an unlocked mmap_sem. So it has not the
* same semantics wrt the @mm->mmap_sem as does filemap_fault().
*/
int fixup_user_fault(struct task_struct *tsk, struct mm_struct *mm,
unsigned long address, unsigned int fault_flags,
bool *unlocked)
{
struct vm_area_struct *vma;
vm_fault_t ret, major = 0;
if (unlocked)
fault_flags |= FAULT_FLAG_ALLOW_RETRY;
retry:
vma = find_extend_vma(mm, address);
if (!vma || address < vma->vm_start)
return -EFAULT;
if (!vma_permits_fault(vma, fault_flags))
return -EFAULT;
ret = handle_mm_fault(vma, address, fault_flags);
major |= ret & VM_FAULT_MAJOR;
if (ret & VM_FAULT_ERROR) {
int err = vm_fault_to_errno(ret, 0);
if (err)
return err;
BUG();
}
if (ret & VM_FAULT_RETRY) {
down_read(&mm->mmap_sem);
if (!(fault_flags & FAULT_FLAG_TRIED)) {
*unlocked = true;
fault_flags &= ~FAULT_FLAG_ALLOW_RETRY;
fault_flags |= FAULT_FLAG_TRIED;
goto retry;
}
}
if (tsk) {
if (major)
tsk->maj_flt++;
else
tsk->min_flt++;
}
return 0;
}
EXPORT_SYMBOL_GPL(fixup_user_fault);
static __always_inline long __get_user_pages_locked(struct task_struct *tsk,
struct mm_struct *mm,
unsigned long start,
unsigned long nr_pages,
struct page **pages,
struct vm_area_struct **vmas,
int *locked,
unsigned int flags)
{
long ret, pages_done;
bool lock_dropped;
if (locked) {
/* if VM_FAULT_RETRY can be returned, vmas become invalid */
BUG_ON(vmas);
/* check caller initialized locked */
BUG_ON(*locked != 1);
}
if (pages)
flags |= FOLL_GET;
pages_done = 0;
lock_dropped = false;
for (;;) {
ret = __get_user_pages(tsk, mm, start, nr_pages, flags, pages,
vmas, locked);
if (!locked)
/* VM_FAULT_RETRY couldn't trigger, bypass */
return ret;
/* VM_FAULT_RETRY cannot return errors */
if (!*locked) {
BUG_ON(ret < 0);
BUG_ON(ret >= nr_pages);
}
if (!pages)
/* If it's a prefault don't insist harder */
return ret;
if (ret > 0) {
nr_pages -= ret;
pages_done += ret;
if (!nr_pages)
break;
}
if (*locked) {
/*
* VM_FAULT_RETRY didn't trigger or it was a
* FOLL_NOWAIT.
*/
if (!pages_done)
pages_done = ret;
break;
}
/* VM_FAULT_RETRY triggered, so seek to the faulting offset */
pages += ret;
start += ret << PAGE_SHIFT;
/*
* Repeat on the address that fired VM_FAULT_RETRY
* without FAULT_FLAG_ALLOW_RETRY but with
* FAULT_FLAG_TRIED.
*/
*locked = 1;
lock_dropped = true;
down_read(&mm->mmap_sem);
ret = __get_user_pages(tsk, mm, start, 1, flags | FOLL_TRIED,
pages, NULL, NULL);
if (ret != 1) {
BUG_ON(ret > 1);
if (!pages_done)
pages_done = ret;
break;
}
nr_pages--;
pages_done++;
if (!nr_pages)
break;
pages++;
start += PAGE_SIZE;
}
if (lock_dropped && *locked) {
/*
* We must let the caller know we temporarily dropped the lock
* and so the critical section protected by it was lost.
*/
up_read(&mm->mmap_sem);
*locked = 0;
}
return pages_done;
}
/*
* We can leverage the VM_FAULT_RETRY functionality in the page fault
* paths better by using either get_user_pages_locked() or
* get_user_pages_unlocked().
*
* get_user_pages_locked() is suitable to replace the form:
*
* down_read(&mm->mmap_sem);
* do_something()
* get_user_pages(tsk, mm, ..., pages, NULL);
* up_read(&mm->mmap_sem);
*
* to:
*
* int locked = 1;
* down_read(&mm->mmap_sem);
* do_something()
* get_user_pages_locked(tsk, mm, ..., pages, &locked);
* if (locked)
* up_read(&mm->mmap_sem);
*/
long get_user_pages_locked(unsigned long start, unsigned long nr_pages,
unsigned int gup_flags, struct page **pages,
int *locked)
{
return __get_user_pages_locked(current, current->mm, start, nr_pages,
pages, NULL, locked,
gup_flags | FOLL_TOUCH);
}
EXPORT_SYMBOL(get_user_pages_locked);
/*
* get_user_pages_unlocked() is suitable to replace the form:
*
* down_read(&mm->mmap_sem);
* get_user_pages(tsk, mm, ..., pages, NULL);
* up_read(&mm->mmap_sem);
*
* with:
*
* get_user_pages_unlocked(tsk, mm, ..., pages);
*
* It is functionally equivalent to get_user_pages_fast so
* get_user_pages_fast should be used instead if specific gup_flags
* (e.g. FOLL_FORCE) are not required.
*/
long get_user_pages_unlocked(unsigned long start, unsigned long nr_pages,
struct page **pages, unsigned int gup_flags)
{
struct mm_struct *mm = current->mm;
int locked = 1;
long ret;
down_read(&mm->mmap_sem);
ret = __get_user_pages_locked(current, mm, start, nr_pages, pages, NULL,
&locked, gup_flags | FOLL_TOUCH);
if (locked)
up_read(&mm->mmap_sem);
return ret;
}
EXPORT_SYMBOL(get_user_pages_unlocked);
/*
* get_user_pages_remote() - pin user pages in memory
* @tsk: the task_struct to use for page fault accounting, or
* NULL if faults are not to be recorded.
* @mm: mm_struct of target mm
* @start: starting user address
* @nr_pages: number of pages from start to pin
* @gup_flags: flags modifying lookup behaviour
* @pages: array that receives pointers to the pages pinned.
* Should be at least nr_pages long. Or NULL, if caller
* only intends to ensure the pages are faulted in.
* @vmas: array of pointers to vmas corresponding to each page.
* Or NULL if the caller does not require them.
* @locked: pointer to lock flag indicating whether lock is held and
* subsequently whether VM_FAULT_RETRY functionality can be
* utilised. Lock must initially be held.
*
* Returns number of pages pinned. This may be fewer than the number
* requested. If nr_pages is 0 or negative, returns 0. If no pages
* were pinned, returns -errno. Each page returned must be released
* with a put_page() call when it is finished with. vmas will only
* remain valid while mmap_sem is held.
*
* Must be called with mmap_sem held for read or write.
*
* get_user_pages walks a process's page tables and takes a reference to
* each struct page that each user address corresponds to at a given
* instant. That is, it takes the page that would be accessed if a user
* thread accesses the given user virtual address at that instant.
*
* This does not guarantee that the page exists in the user mappings when
* get_user_pages returns, and there may even be a completely different
* page there in some cases (eg. if mmapped pagecache has been invalidated
* and subsequently re faulted). However it does guarantee that the page
* won't be freed completely. And mostly callers simply care that the page
* contains data that was valid *at some point in time*. Typically, an IO
* or similar operation cannot guarantee anything stronger anyway because
* locks can't be held over the syscall boundary.
*
* If gup_flags & FOLL_WRITE == 0, the page must not be written to. If the page
* is written to, set_page_dirty (or set_page_dirty_lock, as appropriate) must
* be called after the page is finished with, and before put_page is called.
*
* get_user_pages is typically used for fewer-copy IO operations, to get a
* handle on the memory by some means other than accesses via the user virtual
* addresses. The pages may be submitted for DMA to devices or accessed via
* their kernel linear mapping (via the kmap APIs). Care should be taken to
* use the correct cache flushing APIs.
*
* See also get_user_pages_fast, for performance critical applications.
*
* get_user_pages should be phased out in favor of
* get_user_pages_locked|unlocked or get_user_pages_fast. Nothing
* should use get_user_pages because it cannot pass
* FAULT_FLAG_ALLOW_RETRY to handle_mm_fault.
*/
long get_user_pages_remote(struct task_struct *tsk, struct mm_struct *mm,
unsigned long start, unsigned long nr_pages,
unsigned int gup_flags, struct page **pages,
struct vm_area_struct **vmas, int *locked)
{
return __get_user_pages_locked(tsk, mm, start, nr_pages, pages, vmas,
locked,
gup_flags | FOLL_TOUCH | FOLL_REMOTE);
}
EXPORT_SYMBOL(get_user_pages_remote);
/*
* This is the same as get_user_pages_remote(), just with a
* less-flexible calling convention where we assume that the task
* and mm being operated on are the current task's and don't allow
* passing of a locked parameter. We also obviously don't pass
* FOLL_REMOTE in here.
*/
long get_user_pages(unsigned long start, unsigned long nr_pages,
unsigned int gup_flags, struct page **pages,
struct vm_area_struct **vmas)
{
return __get_user_pages_locked(current, current->mm, start, nr_pages,
pages, vmas, NULL,
gup_flags | FOLL_TOUCH);
}
EXPORT_SYMBOL(get_user_pages);
#ifdef CONFIG_FS_DAX
/*
* This is the same as get_user_pages() in that it assumes we are
* operating on the current task's mm, but it goes further to validate
* that the vmas associated with the address range are suitable for
* longterm elevated page reference counts. For example, filesystem-dax
* mappings are subject to the lifetime enforced by the filesystem and
* we need guarantees that longterm users like RDMA and V4L2 only
* establish mappings that have a kernel enforced revocation mechanism.
*
* "longterm" == userspace controlled elevated page count lifetime.
* Contrast this to iov_iter_get_pages() usages which are transient.
*/
long get_user_pages_longterm(unsigned long start, unsigned long nr_pages,
unsigned int gup_flags, struct page **pages,
struct vm_area_struct **vmas_arg)
{
struct vm_area_struct **vmas = vmas_arg;
struct vm_area_struct *vma_prev = NULL;
long rc, i;
if (!pages)
return -EINVAL;
if (!vmas) {
vmas = kcalloc(nr_pages, sizeof(struct vm_area_struct *),
GFP_KERNEL);
if (!vmas)
return -ENOMEM;
}
rc = get_user_pages(start, nr_pages, gup_flags, pages, vmas);
for (i = 0; i < rc; i++) {
struct vm_area_struct *vma = vmas[i];
if (vma == vma_prev)
continue;
vma_prev = vma;
if (vma_is_fsdax(vma))
break;
}
/*
* Either get_user_pages() failed, or the vma validation
* succeeded, in either case we don't need to put_page() before
* returning.
*/
if (i >= rc)
goto out;
for (i = 0; i < rc; i++)
put_page(pages[i]);
rc = -EOPNOTSUPP;
out:
if (vmas != vmas_arg)
kfree(vmas);
return rc;
}
EXPORT_SYMBOL(get_user_pages_longterm);
#endif /* CONFIG_FS_DAX */
/**
* populate_vma_page_range() - populate a range of pages in the vma.
* @vma: target vma
* @start: start address
* @end: end address
* @nonblocking:
*
* This takes care of mlocking the pages too if VM_LOCKED is set.
*
* return 0 on success, negative error code on error.
*
* vma->vm_mm->mmap_sem must be held.
*
* If @nonblocking is NULL, it may be held for read or write and will
* be unperturbed.
*
* If @nonblocking is non-NULL, it must held for read only and may be
* released. If it's released, *@nonblocking will be set to 0.
*/
long populate_vma_page_range(struct vm_area_struct *vma,
unsigned long start, unsigned long end, int *nonblocking)
{
struct mm_struct *mm = vma->vm_mm;
unsigned long nr_pages = (end - start) / PAGE_SIZE;
int gup_flags;
VM_BUG_ON(start & ~PAGE_MASK);
VM_BUG_ON(end & ~PAGE_MASK);
VM_BUG_ON_VMA(start < vma->vm_start, vma);
VM_BUG_ON_VMA(end > vma->vm_end, vma);
VM_BUG_ON_MM(!rwsem_is_locked(&mm->mmap_sem), mm);
gup_flags = FOLL_TOUCH | FOLL_POPULATE | FOLL_MLOCK;
if (vma->vm_flags & VM_LOCKONFAULT)
gup_flags &= ~FOLL_POPULATE;
/*
* We want to touch writable mappings with a write fault in order
* to break COW, except for shared mappings because these don't COW
* and we would not want to dirty them for nothing.
*/
if ((vma->vm_flags & (VM_WRITE | VM_SHARED)) == VM_WRITE)
gup_flags |= FOLL_WRITE;
/*
* We want mlock to succeed for regions that have any permissions
* other than PROT_NONE.
*/
if (vma->vm_flags & (VM_READ | VM_WRITE | VM_EXEC))
gup_flags |= FOLL_FORCE;
/*
* We made sure addr is within a VMA, so the following will
* not result in a stack expansion that recurses back here.
*/
return __get_user_pages(current, mm, start, nr_pages, gup_flags,
NULL, NULL, nonblocking);
}
/*
* __mm_populate - populate and/or mlock pages within a range of address space.
*
* This is used to implement mlock() and the MAP_POPULATE / MAP_LOCKED mmap
* flags. VMAs must be already marked with the desired vm_flags, and
* mmap_sem must not be held.
*/
int __mm_populate(unsigned long start, unsigned long len, int ignore_errors)
{
struct mm_struct *mm = current->mm;
unsigned long end, nstart, nend;
struct vm_area_struct *vma = NULL;
int locked = 0;
long ret = 0;
end = start + len;
for (nstart = start; nstart < end; nstart = nend) {
/*
* We want to fault in pages for [nstart; end) address range.
* Find first corresponding VMA.
*/
if (!locked) {
locked = 1;
down_read(&mm->mmap_sem);
vma = find_vma(mm, nstart);
} else if (nstart >= vma->vm_end)
vma = vma->vm_next;
if (!vma || vma->vm_start >= end)
break;
/*
* Set [nstart; nend) to intersection of desired address
* range with the first VMA. Also, skip undesirable VMA types.
*/
nend = min(end, vma->vm_end);
if (vma->vm_flags & (VM_IO | VM_PFNMAP))
continue;
if (nstart < vma->vm_start)
nstart = vma->vm_start;
/*
* Now fault in a range of pages. populate_vma_page_range()
* double checks the vma flags, so that it won't mlock pages
* if the vma was already munlocked.
*/
ret = populate_vma_page_range(vma, nstart, nend, &locked);
if (ret < 0) {
if (ignore_errors) {
ret = 0;
continue; /* continue at next VMA */
}
break;
}
nend = nstart + ret * PAGE_SIZE;
ret = 0;
}
if (locked)
up_read(&mm->mmap_sem);
return ret; /* 0 or negative error code */
}
/**
* get_dump_page() - pin user page in memory while writing it to core dump
* @addr: user address
*
* Returns struct page pointer of user page pinned for dump,
* to be freed afterwards by put_page().
*
* Returns NULL on any kind of failure - a hole must then be inserted into
* the corefile, to preserve alignment with its headers; and also returns
* NULL wherever the ZERO_PAGE, or an anonymous pte_none, has been found -
* allowing a hole to be left in the corefile to save diskspace.
*
* Called without mmap_sem, but after all other threads have been killed.
*/
#ifdef CONFIG_ELF_CORE
struct page *get_dump_page(unsigned long addr)
{
struct vm_area_struct *vma;
struct page *page;
if (__get_user_pages(current, current->mm, addr, 1,
FOLL_FORCE | FOLL_DUMP | FOLL_GET, &page, &vma,
NULL) < 1)
return NULL;
flush_cache_page(vma, addr, page_to_pfn(page));
return page;
}
#endif /* CONFIG_ELF_CORE */
/*
* Generic Fast GUP
*
* get_user_pages_fast attempts to pin user pages by walking the page
* tables directly and avoids taking locks. Thus the walker needs to be
* protected from page table pages being freed from under it, and should
* block any THP splits.
*
* One way to achieve this is to have the walker disable interrupts, and
* rely on IPIs from the TLB flushing code blocking before the page table
* pages are freed. This is unsuitable for architectures that do not need
* to broadcast an IPI when invalidating TLBs.
*
* Another way to achieve this is to batch up page table containing pages
* belonging to more than one mm_user, then rcu_sched a callback to free those
* pages. Disabling interrupts will allow the fast_gup walker to both block
* the rcu_sched callback, and an IPI that we broadcast for splitting THPs
* (which is a relatively rare event). The code below adopts this strategy.
*
* Before activating this code, please be aware that the following assumptions
* are currently made:
*
* *) Either HAVE_RCU_TABLE_FREE is enabled, and tlb_remove_table() is used to
* free pages containing page tables or TLB flushing requires IPI broadcast.
*
* *) ptes can be read atomically by the architecture.
*
* *) access_ok is sufficient to validate userspace address ranges.
*
* The last two assumptions can be relaxed by the addition of helper functions.
*
* This code is based heavily on the PowerPC implementation by Nick Piggin.
*/
#ifdef CONFIG_HAVE_GENERIC_GUP
#ifndef gup_get_pte
/*
* We assume that the PTE can be read atomically. If this is not the case for
* your architecture, please provide the helper.
*/
static inline pte_t gup_get_pte(pte_t *ptep)
{
return READ_ONCE(*ptep);
}
#endif
static void undo_dev_pagemap(int *nr, int nr_start, struct page **pages)
{
while ((*nr) - nr_start) {
struct page *page = pages[--(*nr)];
ClearPageReferenced(page);
put_page(page);
}
}
/*
* Return the compund head page with ref appropriately incremented,
* or NULL if that failed.
*/
static inline struct page *try_get_compound_head(struct page *page, int refs)
{
struct page *head = compound_head(page);
if (WARN_ON_ONCE(page_ref_count(head) < 0))
return NULL;
if (unlikely(!page_cache_add_speculative(head, refs)))
return NULL;
return head;
}
#ifdef CONFIG_ARCH_HAS_PTE_SPECIAL
static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
int write, struct page **pages, int *nr)
{
struct dev_pagemap *pgmap = NULL;
int nr_start = *nr, ret = 0;
pte_t *ptep, *ptem;
ptem = ptep = pte_offset_map(&pmd, addr);
do {
pte_t pte = gup_get_pte(ptep);
struct page *head, *page;
/*
* Similar to the PMD case below, NUMA hinting must take slow
* path using the pte_protnone check.
*/
if (pte_protnone(pte))
goto pte_unmap;
if (!pte_access_permitted(pte, write))
goto pte_unmap;
if (pte_devmap(pte)) {
pgmap = get_dev_pagemap(pte_pfn(pte), pgmap);
if (unlikely(!pgmap)) {
undo_dev_pagemap(nr, nr_start, pages);
goto pte_unmap;
}
} else if (pte_special(pte))
goto pte_unmap;
VM_BUG_ON(!pfn_valid(pte_pfn(pte)));
page = pte_page(pte);
head = try_get_compound_head(page, 1);
if (!head)
goto pte_unmap;
if (unlikely(pte_val(pte) != pte_val(*ptep))) {
put_page(head);
goto pte_unmap;
}
VM_BUG_ON_PAGE(compound_head(page) != head, page);
SetPageReferenced(page);
pages[*nr] = page;
(*nr)++;
} while (ptep++, addr += PAGE_SIZE, addr != end);
ret = 1;
pte_unmap:
if (pgmap)
put_dev_pagemap(pgmap);
pte_unmap(ptem);
return ret;
}
#else
/*
* If we can't determine whether or not a pte is special, then fail immediately
* for ptes. Note, we can still pin HugeTLB and THP as these are guaranteed not
* to be special.
*
* For a futex to be placed on a THP tail page, get_futex_key requires a
* __get_user_pages_fast implementation that can pin pages. Thus it's still
* useful to have gup_huge_pmd even if we can't operate on ptes.
*/
static int gup_pte_range(pmd_t pmd, unsigned long addr, unsigned long end,
int write, struct page **pages, int *nr)
{
return 0;
}
#endif /* CONFIG_ARCH_HAS_PTE_SPECIAL */
#if defined(__HAVE_ARCH_PTE_DEVMAP) && defined(CONFIG_TRANSPARENT_HUGEPAGE)
static int __gup_device_huge(unsigned long pfn, unsigned long addr,
unsigned long end, struct page **pages, int *nr)
{
int nr_start = *nr;
struct dev_pagemap *pgmap = NULL;
do {
struct page *page = pfn_to_page(pfn);
pgmap = get_dev_pagemap(pfn, pgmap);
if (unlikely(!pgmap)) {
undo_dev_pagemap(nr, nr_start, pages);
return 0;
}
SetPageReferenced(page);
pages[*nr] = page;
get_page(page);
(*nr)++;
pfn++;
} while (addr += PAGE_SIZE, addr != end);
if (pgmap)
put_dev_pagemap(pgmap);
return 1;
}
static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
unsigned long end, struct page **pages, int *nr)
{
unsigned long fault_pfn;
int nr_start = *nr;
fault_pfn = pmd_pfn(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
if (!__gup_device_huge(fault_pfn, addr, end, pages, nr))
return 0;
if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
undo_dev_pagemap(nr, nr_start, pages);
return 0;
}
return 1;
}
static int __gup_device_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
unsigned long end, struct page **pages, int *nr)
{
unsigned long fault_pfn;
int nr_start = *nr;
fault_pfn = pud_pfn(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
if (!__gup_device_huge(fault_pfn, addr, end, pages, nr))
return 0;
if (unlikely(pud_val(orig) != pud_val(*pudp))) {
undo_dev_pagemap(nr, nr_start, pages);
return 0;
}
return 1;
}
#else
static int __gup_device_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
unsigned long end, struct page **pages, int *nr)
{
BUILD_BUG();
return 0;
}
static int __gup_device_huge_pud(pud_t pud, pud_t *pudp, unsigned long addr,
unsigned long end, struct page **pages, int *nr)
{
BUILD_BUG();
return 0;
}
#endif
static int gup_huge_pmd(pmd_t orig, pmd_t *pmdp, unsigned long addr,
unsigned long end, int write, struct page **pages, int *nr)
{
struct page *head, *page;
int refs;
if (!pmd_access_permitted(orig, write))
return 0;
if (pmd_devmap(orig))
return __gup_device_huge_pmd(orig, pmdp, addr, end, pages, nr);
refs = 0;
page = pmd_page(orig) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
do {
pages[*nr] = page;
(*nr)++;
page++;
refs++;
} while (addr += PAGE_SIZE, addr != end);
head = try_get_compound_head(pmd_page(orig), refs);
if (!head) {
*nr -= refs;
return 0;
}
if (unlikely(pmd_val(orig) != pmd_val(*pmdp))) {
*nr -= refs;
while (refs--)
put_page(head);
return 0;
}
SetPageReferenced(head);
return 1;
}
static int gup_huge_pud(pud_t orig, pud_t *pudp, unsigned long addr,
unsigned long end, int write, struct page **pages, int *nr)
{
struct page *head, *page;
int refs;
if (!pud_access_permitted(orig, write))
return 0;
if (pud_devmap(orig))
return __gup_device_huge_pud(orig, pudp, addr, end, pages, nr);
refs = 0;
page = pud_page(orig) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
do {
pages[*nr] = page;
(*nr)++;
page++;
refs++;
} while (addr += PAGE_SIZE, addr != end);
head = try_get_compound_head(pud_page(orig), refs);
if (!head) {
*nr -= refs;
return 0;
}
if (unlikely(pud_val(orig) != pud_val(*pudp))) {
*nr -= refs;
while (refs--)
put_page(head);
return 0;
}
SetPageReferenced(head);
return 1;
}
static int gup_huge_pgd(pgd_t orig, pgd_t *pgdp, unsigned long addr,
unsigned long end, int write,
struct page **pages, int *nr)
{
int refs;
struct page *head, *page;
if (!pgd_access_permitted(orig, write))
return 0;
BUILD_BUG_ON(pgd_devmap(orig));
refs = 0;
page = pgd_page(orig) + ((addr & ~PGDIR_MASK) >> PAGE_SHIFT);
do {
pages[*nr] = page;
(*nr)++;
page++;
refs++;
} while (addr += PAGE_SIZE, addr != end);
head = try_get_compound_head(pgd_page(orig), refs);
if (!head) {
*nr -= refs;
return 0;
}
if (unlikely(pgd_val(orig) != pgd_val(*pgdp))) {
*nr -= refs;
while (refs--)
put_page(head);
return 0;
}
SetPageReferenced(head);
return 1;
}
static int gup_pmd_range(pud_t pud, unsigned long addr, unsigned long end,
int write, struct page **pages, int *nr)
{
unsigned long next;
pmd_t *pmdp;
pmdp = pmd_offset(&pud, addr);
do {
pmd_t pmd = READ_ONCE(*pmdp);
next = pmd_addr_end(addr, end);
if (!pmd_present(pmd))
return 0;
if (unlikely(pmd_trans_huge(pmd) || pmd_huge(pmd) ||
pmd_devmap(pmd))) {
/*
* NUMA hinting faults need to be handled in the GUP
* slowpath for accounting purposes and so that they
* can be serialised against THP migration.
*/
if (pmd_protnone(pmd))
return 0;
if (!gup_huge_pmd(pmd, pmdp, addr, next, write,
pages, nr))
return 0;
} else if (unlikely(is_hugepd(__hugepd(pmd_val(pmd))))) {
/*
* architecture have different format for hugetlbfs
* pmd format and THP pmd format
*/
if (!gup_huge_pd(__hugepd(pmd_val(pmd)), addr,
PMD_SHIFT, next, write, pages, nr))
return 0;
} else if (!gup_pte_range(pmd, addr, next, write, pages, nr))
return 0;
} while (pmdp++, addr = next, addr != end);
return 1;
}
static int gup_pud_range(p4d_t p4d, unsigned long addr, unsigned long end,
int write, struct page **pages, int *nr)
{
unsigned long next;
pud_t *pudp;
pudp = pud_offset(&p4d, addr);
do {
pud_t pud = READ_ONCE(*pudp);
next = pud_addr_end(addr, end);
if (pud_none(pud))
return 0;
if (unlikely(pud_huge(pud))) {
if (!gup_huge_pud(pud, pudp, addr, next, write,
pages, nr))
return 0;
} else if (unlikely(is_hugepd(__hugepd(pud_val(pud))))) {
if (!gup_huge_pd(__hugepd(pud_val(pud)), addr,
PUD_SHIFT, next, write, pages, nr))
return 0;
} else if (!gup_pmd_range(pud, addr, next, write, pages, nr))
return 0;
} while (pudp++, addr = next, addr != end);
return 1;
}
static int gup_p4d_range(pgd_t pgd, unsigned long addr, unsigned long end,
int write, struct page **pages, int *nr)
{
unsigned long next;
p4d_t *p4dp;
p4dp = p4d_offset(&pgd, addr);
do {
p4d_t p4d = READ_ONCE(*p4dp);
next = p4d_addr_end(addr, end);
if (p4d_none(p4d))
return 0;
BUILD_BUG_ON(p4d_huge(p4d));
if (unlikely(is_hugepd(__hugepd(p4d_val(p4d))))) {
if (!gup_huge_pd(__hugepd(p4d_val(p4d)), addr,
P4D_SHIFT, next, write, pages, nr))
return 0;
} else if (!gup_pud_range(p4d, addr, next, write, pages, nr))
return 0;
} while (p4dp++, addr = next, addr != end);
return 1;
}
static void gup_pgd_range(unsigned long addr, unsigned long end,
int write, struct page **pages, int *nr)
{
unsigned long next;
pgd_t *pgdp;
pgdp = pgd_offset(current->mm, addr);
do {
pgd_t pgd = READ_ONCE(*pgdp);
next = pgd_addr_end(addr, end);
if (pgd_none(pgd))
return;
if (unlikely(pgd_huge(pgd))) {
if (!gup_huge_pgd(pgd, pgdp, addr, next, write,
pages, nr))
return;
} else if (unlikely(is_hugepd(__hugepd(pgd_val(pgd))))) {
if (!gup_huge_pd(__hugepd(pgd_val(pgd)), addr,
PGDIR_SHIFT, next, write, pages, nr))
return;
} else if (!gup_p4d_range(pgd, addr, next, write, pages, nr))
return;
} while (pgdp++, addr = next, addr != end);
}
#ifndef gup_fast_permitted
/*
* Check if it's allowed to use __get_user_pages_fast() for the range, or
* we need to fall back to the slow version:
*/
bool gup_fast_permitted(unsigned long start, int nr_pages, int write)
{
unsigned long len, end;
len = (unsigned long) nr_pages << PAGE_SHIFT;
end = start + len;
return end >= start;
}
#endif
/*
* Like get_user_pages_fast() except it's IRQ-safe in that it won't fall back to
* the regular GUP.
* Note a difference with get_user_pages_fast: this always returns the
* number of pages pinned, 0 if no pages were pinned.
*/
int __get_user_pages_fast(unsigned long start, int nr_pages, int write,
struct page **pages)
{
unsigned long len, end;
unsigned long flags;
int nr = 0;
start &= PAGE_MASK;
len = (unsigned long) nr_pages << PAGE_SHIFT;
end = start + len;
if (unlikely(!access_ok((void __user *)start, len)))
return 0;
/*
* Disable interrupts. We use the nested form as we can already have
* interrupts disabled by get_futex_key.
*
* With interrupts disabled, we block page table pages from being
* freed from under us. See struct mmu_table_batch comments in
* include/asm-generic/tlb.h for more details.
*
* We do not adopt an rcu_read_lock(.) here as we also want to
* block IPIs that come from THPs splitting.
*/
if (gup_fast_permitted(start, nr_pages, write)) {
local_irq_save(flags);
gup_pgd_range(start, end, write, pages, &nr);
local_irq_restore(flags);
}
return nr;
}
/**
* get_user_pages_fast() - pin user pages in memory
* @start: starting user address
* @nr_pages: number of pages from start to pin
* @write: whether pages will be written to
* @pages: array that receives pointers to the pages pinned.
* Should be at least nr_pages long.
*
* Attempt to pin user pages in memory without taking mm->mmap_sem.
* If not successful, it will fall back to taking the lock and
* calling get_user_pages().
*
* Returns number of pages pinned. This may be fewer than the number
* requested. If nr_pages is 0 or negative, returns 0. If no pages
* were pinned, returns -errno.
*/
int get_user_pages_fast(unsigned long start, int nr_pages, int write,
struct page **pages)
{
unsigned long addr, len, end;
int nr = 0, ret = 0;
start &= PAGE_MASK;
addr = start;
len = (unsigned long) nr_pages << PAGE_SHIFT;
end = start + len;
if (nr_pages <= 0)
return 0;
if (unlikely(!access_ok((void __user *)start, len)))
return -EFAULT;
if (gup_fast_permitted(start, nr_pages, write)) {
local_irq_disable();
gup_pgd_range(addr, end, write, pages, &nr);
local_irq_enable();
ret = nr;
}
if (nr < nr_pages) {
/* Try to get the remaining pages with get_user_pages */
start += nr << PAGE_SHIFT;
pages += nr;
ret = get_user_pages_unlocked(start, nr_pages - nr, pages,
write ? FOLL_WRITE : 0);
/* Have to be a bit careful with return values */
if (nr > 0) {
if (ret < 0)
ret = nr;
else
ret += nr;
}
}
return ret;
}
#endif /* CONFIG_HAVE_GENERIC_GUP */
| ./CrossVul/dataset_final_sorted/CWE-416/c/good_822_0 |
crossvul-cpp_data_good_375_0 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_NET_IF_H
#include <net/if.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef __VMS
#include <in.h>
#include <inet.h>
#endif
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#ifndef HAVE_SOCKET
#error "We can't compile without socket() support!"
#endif
#include <limits.h>
#ifdef USE_LIBIDN2
#include <idn2.h>
#elif defined(USE_WIN32_IDN)
/* prototype for curl_win32_idn_to_ascii() */
bool curl_win32_idn_to_ascii(const char *in, char **out);
#endif /* USE_LIBIDN2 */
#include "urldata.h"
#include "netrc.h"
#include "formdata.h"
#include "mime.h"
#include "vtls/vtls.h"
#include "hostip.h"
#include "transfer.h"
#include "sendf.h"
#include "progress.h"
#include "cookie.h"
#include "strcase.h"
#include "strerror.h"
#include "escape.h"
#include "strtok.h"
#include "share.h"
#include "content_encoding.h"
#include "http_digest.h"
#include "http_negotiate.h"
#include "select.h"
#include "multiif.h"
#include "easyif.h"
#include "speedcheck.h"
#include "warnless.h"
#include "non-ascii.h"
#include "inet_pton.h"
#include "getinfo.h"
#include "urlapi-int.h"
/* And now for the protocols */
#include "ftp.h"
#include "dict.h"
#include "telnet.h"
#include "tftp.h"
#include "http.h"
#include "http2.h"
#include "file.h"
#include "curl_ldap.h"
#include "ssh.h"
#include "imap.h"
#include "url.h"
#include "connect.h"
#include "inet_ntop.h"
#include "http_ntlm.h"
#include "curl_ntlm_wb.h"
#include "socks.h"
#include "curl_rtmp.h"
#include "gopher.h"
#include "http_proxy.h"
#include "conncache.h"
#include "multihandle.h"
#include "pipeline.h"
#include "dotdot.h"
#include "strdup.h"
#include "setopt.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
static void conn_free(struct connectdata *conn);
static void free_fixed_hostname(struct hostname *host);
static unsigned int get_protocol_family(unsigned int protocol);
/* Some parts of the code (e.g. chunked encoding) assume this buffer has at
* more than just a few bytes to play with. Don't let it become too small or
* bad things will happen.
*/
#if READBUFFER_SIZE < READBUFFER_MIN
# error READBUFFER_SIZE is too small
#endif
/*
* Protocol table.
*/
static const struct Curl_handler * const protocols[] = {
#ifndef CURL_DISABLE_HTTP
&Curl_handler_http,
#endif
#if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
&Curl_handler_https,
#endif
#ifndef CURL_DISABLE_FTP
&Curl_handler_ftp,
#endif
#if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
&Curl_handler_ftps,
#endif
#ifndef CURL_DISABLE_TELNET
&Curl_handler_telnet,
#endif
#ifndef CURL_DISABLE_DICT
&Curl_handler_dict,
#endif
#ifndef CURL_DISABLE_LDAP
&Curl_handler_ldap,
#if !defined(CURL_DISABLE_LDAPS) && \
((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
(!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
&Curl_handler_ldaps,
#endif
#endif
#ifndef CURL_DISABLE_FILE
&Curl_handler_file,
#endif
#ifndef CURL_DISABLE_TFTP
&Curl_handler_tftp,
#endif
#if defined(USE_LIBSSH2) || defined(USE_LIBSSH)
&Curl_handler_scp,
#endif
#if defined(USE_LIBSSH2) || defined(USE_LIBSSH)
&Curl_handler_sftp,
#endif
#ifndef CURL_DISABLE_IMAP
&Curl_handler_imap,
#ifdef USE_SSL
&Curl_handler_imaps,
#endif
#endif
#ifndef CURL_DISABLE_POP3
&Curl_handler_pop3,
#ifdef USE_SSL
&Curl_handler_pop3s,
#endif
#endif
#if !defined(CURL_DISABLE_SMB) && defined(USE_NTLM) && \
(CURL_SIZEOF_CURL_OFF_T > 4) && \
(!defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO))
&Curl_handler_smb,
#ifdef USE_SSL
&Curl_handler_smbs,
#endif
#endif
#ifndef CURL_DISABLE_SMTP
&Curl_handler_smtp,
#ifdef USE_SSL
&Curl_handler_smtps,
#endif
#endif
#ifndef CURL_DISABLE_RTSP
&Curl_handler_rtsp,
#endif
#ifndef CURL_DISABLE_GOPHER
&Curl_handler_gopher,
#endif
#ifdef USE_LIBRTMP
&Curl_handler_rtmp,
&Curl_handler_rtmpt,
&Curl_handler_rtmpe,
&Curl_handler_rtmpte,
&Curl_handler_rtmps,
&Curl_handler_rtmpts,
#endif
(struct Curl_handler *) NULL
};
/*
* Dummy handler for undefined protocol schemes.
*/
static const struct Curl_handler Curl_handler_dummy = {
"<no protocol>", /* scheme */
ZERO_NULL, /* setup_connection */
ZERO_NULL, /* do_it */
ZERO_NULL, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
0, /* defport */
0, /* protocol */
PROTOPT_NONE /* flags */
};
void Curl_freeset(struct Curl_easy *data)
{
/* Free all dynamic strings stored in the data->set substructure. */
enum dupstring i;
for(i = (enum dupstring)0; i < STRING_LAST; i++) {
Curl_safefree(data->set.str[i]);
}
if(data->change.referer_alloc) {
Curl_safefree(data->change.referer);
data->change.referer_alloc = FALSE;
}
data->change.referer = NULL;
if(data->change.url_alloc) {
Curl_safefree(data->change.url);
data->change.url_alloc = FALSE;
}
data->change.url = NULL;
Curl_mime_cleanpart(&data->set.mimepost);
}
/* free the URL pieces */
void Curl_up_free(struct Curl_easy *data)
{
struct urlpieces *up = &data->state.up;
Curl_safefree(up->scheme);
Curl_safefree(up->hostname);
Curl_safefree(up->port);
Curl_safefree(up->user);
Curl_safefree(up->password);
Curl_safefree(up->options);
Curl_safefree(up->path);
Curl_safefree(up->query);
curl_url_cleanup(data->state.uh);
data->state.uh = NULL;
}
/*
* This is the internal function curl_easy_cleanup() calls. This should
* cleanup and free all resources associated with this sessionhandle.
*
* NOTE: if we ever add something that attempts to write to a socket or
* similar here, we must ignore SIGPIPE first. It is currently only done
* when curl_easy_perform() is invoked.
*/
CURLcode Curl_close(struct Curl_easy *data)
{
struct Curl_multi *m;
if(!data)
return CURLE_OK;
Curl_expire_clear(data); /* shut off timers */
m = data->multi;
if(m)
/* This handle is still part of a multi handle, take care of this first
and detach this handle from there. */
curl_multi_remove_handle(data->multi, data);
if(data->multi_easy) {
/* when curl_easy_perform() is used, it creates its own multi handle to
use and this is the one */
curl_multi_cleanup(data->multi_easy);
data->multi_easy = NULL;
}
/* Destroy the timeout list that is held in the easy handle. It is
/normally/ done by curl_multi_remove_handle() but this is "just in
case" */
Curl_llist_destroy(&data->state.timeoutlist, NULL);
data->magic = 0; /* force a clear AFTER the possibly enforced removal from
the multi handle, since that function uses the magic
field! */
if(data->state.rangestringalloc)
free(data->state.range);
/* freed here just in case DONE wasn't called */
Curl_free_request_state(data);
/* Close down all open SSL info and sessions */
Curl_ssl_close_all(data);
Curl_safefree(data->state.first_host);
Curl_safefree(data->state.scratch);
Curl_ssl_free_certinfo(data);
/* Cleanup possible redirect junk */
free(data->req.newurl);
data->req.newurl = NULL;
if(data->change.referer_alloc) {
Curl_safefree(data->change.referer);
data->change.referer_alloc = FALSE;
}
data->change.referer = NULL;
Curl_up_free(data);
Curl_safefree(data->state.buffer);
Curl_safefree(data->state.headerbuff);
Curl_safefree(data->state.ulbuf);
Curl_flush_cookies(data, 1);
Curl_digest_cleanup(data);
Curl_safefree(data->info.contenttype);
Curl_safefree(data->info.wouldredirect);
/* this destroys the channel and we cannot use it anymore after this */
Curl_resolver_cleanup(data->state.resolver);
Curl_http2_cleanup_dependencies(data);
Curl_convert_close(data);
/* No longer a dirty share, if it exists */
if(data->share) {
Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
data->share->dirty--;
Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
}
/* destruct wildcard structures if it is needed */
Curl_wildcard_dtor(&data->wildcard);
Curl_freeset(data);
free(data);
return CURLE_OK;
}
/*
* Initialize the UserDefined fields within a Curl_easy.
* This may be safely called on a new or existing Curl_easy.
*/
CURLcode Curl_init_userdefined(struct Curl_easy *data)
{
struct UserDefined *set = &data->set;
CURLcode result = CURLE_OK;
set->out = stdout; /* default output to stdout */
set->in_set = stdin; /* default input from stdin */
set->err = stderr; /* default stderr to stderr */
/* use fwrite as default function to store output */
set->fwrite_func = (curl_write_callback)fwrite;
/* use fread as default function to read input */
set->fread_func_set = (curl_read_callback)fread;
set->is_fread_set = 0;
set->is_fwrite_set = 0;
set->seek_func = ZERO_NULL;
set->seek_client = ZERO_NULL;
/* conversion callbacks for non-ASCII hosts */
set->convfromnetwork = ZERO_NULL;
set->convtonetwork = ZERO_NULL;
set->convfromutf8 = ZERO_NULL;
set->filesize = -1; /* we don't know the size */
set->postfieldsize = -1; /* unknown size */
set->maxredirs = -1; /* allow any amount by default */
set->httpreq = HTTPREQ_GET; /* Default HTTP request */
set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */
set->ftp_filemethod = FTPFILE_MULTICWD;
set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
/* Set the default size of the SSL session ID cache */
set->general_ssl.max_ssl_sessions = 5;
set->proxyport = 0;
set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
/* SOCKS5 proxy auth defaults to username/password + GSS-API */
set->socks5auth = CURLAUTH_BASIC | CURLAUTH_GSSAPI;
/* make libcurl quiet by default: */
set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
Curl_mime_initpart(&set->mimepost, data);
/*
* libcurl 7.10 introduced SSL verification *by default*! This needs to be
* switched off unless wanted.
*/
set->ssl.primary.verifypeer = TRUE;
set->ssl.primary.verifyhost = TRUE;
#ifdef USE_TLS_SRP
set->ssl.authtype = CURL_TLSAUTH_NONE;
#endif
set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
type */
set->ssl.primary.sessionid = TRUE; /* session ID caching enabled by
default */
set->proxy_ssl = set->ssl;
set->new_file_perms = 0644; /* Default permissions */
set->new_directory_perms = 0755; /* Default permissions */
/* for the *protocols fields we don't use the CURLPROTO_ALL convenience
define since we internally only use the lower 16 bits for the passed
in bitmask to not conflict with the private bits */
set->allowed_protocols = CURLPROTO_ALL;
set->redir_protocols = CURLPROTO_ALL & /* All except FILE, SCP and SMB */
~(CURLPROTO_FILE | CURLPROTO_SCP | CURLPROTO_SMB |
CURLPROTO_SMBS);
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
/*
* disallow unprotected protection negotiation NEC reference implementation
* seem not to follow rfc1961 section 4.3/4.4
*/
set->socks5_gssapi_nec = FALSE;
#endif
/* Set the default CA cert bundle/path detected/specified at build time.
*
* If Schannel (WinSSL) is the selected SSL backend then these locations
* are ignored. We allow setting CA location for schannel only when
* explicitly specified by the user via CURLOPT_CAINFO / --cacert.
*/
if(Curl_ssl_backend() != CURLSSLBACKEND_SCHANNEL) {
#if defined(CURL_CA_BUNDLE)
result = Curl_setstropt(&set->str[STRING_SSL_CAFILE_ORIG], CURL_CA_BUNDLE);
if(result)
return result;
result = Curl_setstropt(&set->str[STRING_SSL_CAFILE_PROXY],
CURL_CA_BUNDLE);
if(result)
return result;
#endif
#if defined(CURL_CA_PATH)
result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_ORIG], CURL_CA_PATH);
if(result)
return result;
result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_PROXY], CURL_CA_PATH);
if(result)
return result;
#endif
}
set->wildcard_enabled = FALSE;
set->chunk_bgn = ZERO_NULL;
set->chunk_end = ZERO_NULL;
set->tcp_keepalive = FALSE;
set->tcp_keepintvl = 60;
set->tcp_keepidle = 60;
set->tcp_fastopen = FALSE;
set->tcp_nodelay = TRUE;
set->ssl_enable_npn = TRUE;
set->ssl_enable_alpn = TRUE;
set->expect_100_timeout = 1000L; /* Wait for a second by default. */
set->sep_headers = TRUE; /* separated header lists by default */
set->buffer_size = READBUFFER_SIZE;
set->upload_buffer_size = UPLOADBUFFER_DEFAULT;
set->happy_eyeballs_timeout = CURL_HET_DEFAULT;
set->fnmatch = ZERO_NULL;
set->upkeep_interval_ms = CURL_UPKEEP_INTERVAL_DEFAULT;
set->maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */
set->httpversion =
#ifdef USE_NGHTTP2
CURL_HTTP_VERSION_2TLS
#else
CURL_HTTP_VERSION_1_1
#endif
;
Curl_http2_init_userset(set);
return result;
}
/**
* Curl_open()
*
* @param curl is a pointer to a sessionhandle pointer that gets set by this
* function.
* @return CURLcode
*/
CURLcode Curl_open(struct Curl_easy **curl)
{
CURLcode result;
struct Curl_easy *data;
/* Very simple start-up: alloc the struct, init it with zeroes and return */
data = calloc(1, sizeof(struct Curl_easy));
if(!data) {
/* this is a very serious error */
DEBUGF(fprintf(stderr, "Error: calloc of Curl_easy failed\n"));
return CURLE_OUT_OF_MEMORY;
}
data->magic = CURLEASY_MAGIC_NUMBER;
result = Curl_resolver_init(&data->state.resolver);
if(result) {
DEBUGF(fprintf(stderr, "Error: resolver_init failed\n"));
free(data);
return result;
}
/* We do some initial setup here, all those fields that can't be just 0 */
data->state.buffer = malloc(READBUFFER_SIZE + 1);
if(!data->state.buffer) {
DEBUGF(fprintf(stderr, "Error: malloc of buffer failed\n"));
result = CURLE_OUT_OF_MEMORY;
}
else {
data->state.headerbuff = malloc(HEADERSIZE);
if(!data->state.headerbuff) {
DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n"));
result = CURLE_OUT_OF_MEMORY;
}
else {
result = Curl_init_userdefined(data);
data->state.headersize = HEADERSIZE;
Curl_convert_init(data);
Curl_initinfo(data);
/* most recent connection is not yet defined */
data->state.lastconnect = NULL;
data->progress.flags |= PGRS_HIDE;
data->state.current_speed = -1; /* init to negative == impossible */
Curl_http2_init_state(&data->state);
}
}
if(result) {
Curl_resolver_cleanup(data->state.resolver);
free(data->state.buffer);
free(data->state.headerbuff);
Curl_freeset(data);
free(data);
data = NULL;
}
else
*curl = data;
return result;
}
#ifdef USE_RECV_BEFORE_SEND_WORKAROUND
static void conn_reset_postponed_data(struct connectdata *conn, int num)
{
struct postponed_data * const psnd = &(conn->postponed[num]);
if(psnd->buffer) {
DEBUGASSERT(psnd->allocated_size > 0);
DEBUGASSERT(psnd->recv_size <= psnd->allocated_size);
DEBUGASSERT(psnd->recv_size ?
(psnd->recv_processed < psnd->recv_size) :
(psnd->recv_processed == 0));
DEBUGASSERT(psnd->bindsock != CURL_SOCKET_BAD);
free(psnd->buffer);
psnd->buffer = NULL;
psnd->allocated_size = 0;
psnd->recv_size = 0;
psnd->recv_processed = 0;
#ifdef DEBUGBUILD
psnd->bindsock = CURL_SOCKET_BAD; /* used only for DEBUGASSERT */
#endif /* DEBUGBUILD */
}
else {
DEBUGASSERT(psnd->allocated_size == 0);
DEBUGASSERT(psnd->recv_size == 0);
DEBUGASSERT(psnd->recv_processed == 0);
DEBUGASSERT(psnd->bindsock == CURL_SOCKET_BAD);
}
}
static void conn_reset_all_postponed_data(struct connectdata *conn)
{
conn_reset_postponed_data(conn, 0);
conn_reset_postponed_data(conn, 1);
}
#else /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
/* Use "do-nothing" macro instead of function when workaround not used */
#define conn_reset_all_postponed_data(c) do {} WHILE_FALSE
#endif /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
static void conn_free(struct connectdata *conn)
{
if(!conn)
return;
/* possible left-overs from the async name resolvers */
Curl_resolver_cancel(conn);
/* close the SSL stuff before we close any sockets since they will/may
write to the sockets */
Curl_ssl_close(conn, FIRSTSOCKET);
Curl_ssl_close(conn, SECONDARYSOCKET);
/* close possibly still open sockets */
if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]);
if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
Curl_closesocket(conn, conn->sock[FIRSTSOCKET]);
if(CURL_SOCKET_BAD != conn->tempsock[0])
Curl_closesocket(conn, conn->tempsock[0]);
if(CURL_SOCKET_BAD != conn->tempsock[1])
Curl_closesocket(conn, conn->tempsock[1]);
#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
defined(NTLM_WB_ENABLED)
Curl_ntlm_wb_cleanup(conn);
#endif
Curl_safefree(conn->user);
Curl_safefree(conn->passwd);
Curl_safefree(conn->oauth_bearer);
Curl_safefree(conn->options);
Curl_safefree(conn->http_proxy.user);
Curl_safefree(conn->socks_proxy.user);
Curl_safefree(conn->http_proxy.passwd);
Curl_safefree(conn->socks_proxy.passwd);
Curl_safefree(conn->allocptr.proxyuserpwd);
Curl_safefree(conn->allocptr.uagent);
Curl_safefree(conn->allocptr.userpwd);
Curl_safefree(conn->allocptr.accept_encoding);
Curl_safefree(conn->allocptr.te);
Curl_safefree(conn->allocptr.rangeline);
Curl_safefree(conn->allocptr.ref);
Curl_safefree(conn->allocptr.host);
Curl_safefree(conn->allocptr.cookiehost);
Curl_safefree(conn->allocptr.rtsp_transport);
Curl_safefree(conn->trailer);
Curl_safefree(conn->host.rawalloc); /* host name buffer */
Curl_safefree(conn->conn_to_host.rawalloc); /* host name buffer */
Curl_safefree(conn->secondaryhostname);
Curl_safefree(conn->http_proxy.host.rawalloc); /* http proxy name buffer */
Curl_safefree(conn->socks_proxy.host.rawalloc); /* socks proxy name buffer */
Curl_safefree(conn->master_buffer);
Curl_safefree(conn->connect_state);
conn_reset_all_postponed_data(conn);
Curl_llist_destroy(&conn->send_pipe, NULL);
Curl_llist_destroy(&conn->recv_pipe, NULL);
Curl_safefree(conn->localdev);
Curl_free_primary_ssl_config(&conn->ssl_config);
Curl_free_primary_ssl_config(&conn->proxy_ssl_config);
#ifdef USE_UNIX_SOCKETS
Curl_safefree(conn->unix_domain_socket);
#endif
#ifdef USE_SSL
Curl_safefree(conn->ssl_extra);
#endif
free(conn); /* free all the connection oriented data */
}
/*
* Disconnects the given connection. Note the connection may not be the
* primary connection, like when freeing room in the connection cache or
* killing of a dead old connection.
*
* A connection needs an easy handle when closing down. We support this passed
* in separately since the connection to get closed here is often already
* disassociated from an easy handle.
*
* This function MUST NOT reset state in the Curl_easy struct if that
* isn't strictly bound to the life-time of *this* particular connection.
*
*/
CURLcode Curl_disconnect(struct Curl_easy *data,
struct connectdata *conn, bool dead_connection)
{
if(!conn)
return CURLE_OK; /* this is closed and fine already */
if(!data) {
DEBUGF(infof(data, "DISCONNECT without easy handle, ignoring\n"));
return CURLE_OK;
}
/*
* If this connection isn't marked to force-close, leave it open if there
* are other users of it
*/
if(CONN_INUSE(conn) && !dead_connection) {
DEBUGF(infof(data, "Curl_disconnect when inuse: %zu\n", CONN_INUSE(conn)));
return CURLE_OK;
}
conn->data = data;
if(conn->dns_entry != NULL) {
Curl_resolv_unlock(data, conn->dns_entry);
conn->dns_entry = NULL;
}
Curl_hostcache_prune(data); /* kill old DNS cache entries */
#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM)
/* Cleanup NTLM connection-related data */
Curl_http_ntlm_cleanup(conn);
#endif
if(conn->handler->disconnect)
/* This is set if protocol-specific cleanups should be made */
conn->handler->disconnect(conn, dead_connection);
/* unlink ourselves! */
infof(data, "Closing connection %ld\n", conn->connection_id);
Curl_conncache_remove_conn(conn, TRUE);
free_fixed_hostname(&conn->host);
free_fixed_hostname(&conn->conn_to_host);
free_fixed_hostname(&conn->http_proxy.host);
free_fixed_hostname(&conn->socks_proxy.host);
DEBUGASSERT(conn->data == data);
/* this assumes that the pointer is still there after the connection was
detected from the cache */
Curl_ssl_close(conn, FIRSTSOCKET);
conn_free(conn);
return CURLE_OK;
}
/*
* This function should return TRUE if the socket is to be assumed to
* be dead. Most commonly this happens when the server has closed the
* connection due to inactivity.
*/
static bool SocketIsDead(curl_socket_t sock)
{
int sval;
bool ret_val = TRUE;
sval = SOCKET_READABLE(sock, 0);
if(sval == 0)
/* timeout */
ret_val = FALSE;
return ret_val;
}
/*
* IsPipeliningPossible()
*
* Return a bitmask with the available pipelining and multiplexing options for
* the given requested connection.
*/
static int IsPipeliningPossible(const struct Curl_easy *handle,
const struct connectdata *conn)
{
int avail = 0;
/* If a HTTP protocol and pipelining is enabled */
if((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
(!conn->bits.protoconnstart || !conn->bits.close)) {
if(Curl_pipeline_wanted(handle->multi, CURLPIPE_HTTP1) &&
(handle->set.httpversion != CURL_HTTP_VERSION_1_0) &&
(handle->set.httpreq == HTTPREQ_GET ||
handle->set.httpreq == HTTPREQ_HEAD))
/* didn't ask for HTTP/1.0 and a GET or HEAD */
avail |= CURLPIPE_HTTP1;
if(Curl_pipeline_wanted(handle->multi, CURLPIPE_MULTIPLEX) &&
(handle->set.httpversion >= CURL_HTTP_VERSION_2))
/* allows HTTP/2 */
avail |= CURLPIPE_MULTIPLEX;
}
return avail;
}
/* Returns non-zero if a handle was removed */
int Curl_removeHandleFromPipeline(struct Curl_easy *handle,
struct curl_llist *pipeline)
{
if(pipeline) {
struct curl_llist_element *curr;
curr = pipeline->head;
while(curr) {
if(curr->ptr == handle) {
Curl_llist_remove(pipeline, curr, NULL);
return 1; /* we removed a handle */
}
curr = curr->next;
}
}
return 0;
}
#if 0 /* this code is saved here as it is useful for debugging purposes */
static void Curl_printPipeline(struct curl_llist *pipeline)
{
struct curl_llist_element *curr;
curr = pipeline->head;
while(curr) {
struct Curl_easy *data = (struct Curl_easy *) curr->ptr;
infof(data, "Handle in pipeline: %s\n", data->state.path);
curr = curr->next;
}
}
#endif
static struct Curl_easy* gethandleathead(struct curl_llist *pipeline)
{
struct curl_llist_element *curr = pipeline->head;
#ifdef DEBUGBUILD
{
struct curl_llist_element *p = pipeline->head;
while(p) {
struct Curl_easy *e = p->ptr;
DEBUGASSERT(GOOD_EASY_HANDLE(e));
p = p->next;
}
}
#endif
if(curr) {
return (struct Curl_easy *) curr->ptr;
}
return NULL;
}
/* remove the specified connection from all (possible) pipelines and related
queues */
void Curl_getoff_all_pipelines(struct Curl_easy *data,
struct connectdata *conn)
{
if(!conn->bundle)
return;
if(conn->bundle->multiuse == BUNDLE_PIPELINING) {
bool recv_head = (conn->readchannel_inuse &&
Curl_recvpipe_head(data, conn));
bool send_head = (conn->writechannel_inuse &&
Curl_sendpipe_head(data, conn));
if(Curl_removeHandleFromPipeline(data, &conn->recv_pipe) && recv_head)
Curl_pipeline_leave_read(conn);
if(Curl_removeHandleFromPipeline(data, &conn->send_pipe) && send_head)
Curl_pipeline_leave_write(conn);
}
else {
(void)Curl_removeHandleFromPipeline(data, &conn->recv_pipe);
(void)Curl_removeHandleFromPipeline(data, &conn->send_pipe);
}
}
static bool
proxy_info_matches(const struct proxy_info* data,
const struct proxy_info* needle)
{
if((data->proxytype == needle->proxytype) &&
(data->port == needle->port) &&
Curl_safe_strcasecompare(data->host.name, needle->host.name))
return TRUE;
return FALSE;
}
/*
* This function checks if the given connection is dead and extracts it from
* the connection cache if so.
*
* When this is called as a Curl_conncache_foreach() callback, the connection
* cache lock is held!
*
* Returns TRUE if the connection was dead and extracted.
*/
static bool extract_if_dead(struct connectdata *conn,
struct Curl_easy *data)
{
size_t pipeLen = conn->send_pipe.size + conn->recv_pipe.size;
if(!pipeLen && !CONN_INUSE(conn)) {
/* The check for a dead socket makes sense only if there are no
handles in pipeline and the connection isn't already marked in
use */
bool dead;
conn->data = data;
if(conn->handler->connection_check) {
/* The protocol has a special method for checking the state of the
connection. Use it to check if the connection is dead. */
unsigned int state;
state = conn->handler->connection_check(conn, CONNCHECK_ISDEAD);
dead = (state & CONNRESULT_DEAD);
}
else {
/* Use the general method for determining the death of a connection */
dead = SocketIsDead(conn->sock[FIRSTSOCKET]);
}
if(dead) {
infof(data, "Connection %ld seems to be dead!\n", conn->connection_id);
Curl_conncache_remove_conn(conn, FALSE);
conn->data = NULL; /* detach */
return TRUE;
}
}
return FALSE;
}
struct prunedead {
struct Curl_easy *data;
struct connectdata *extracted;
};
/*
* Wrapper to use extract_if_dead() function in Curl_conncache_foreach()
*
*/
static int call_extract_if_dead(struct connectdata *conn, void *param)
{
struct prunedead *p = (struct prunedead *)param;
if(extract_if_dead(conn, p->data)) {
/* stop the iteration here, pass back the connection that was extracted */
p->extracted = conn;
return 1;
}
return 0; /* continue iteration */
}
/*
* This function scans the connection cache for half-open/dead connections,
* closes and removes them.
* The cleanup is done at most once per second.
*/
static void prune_dead_connections(struct Curl_easy *data)
{
struct curltime now = Curl_now();
time_t elapsed = Curl_timediff(now, data->state.conn_cache->last_cleanup);
if(elapsed >= 1000L) {
struct prunedead prune;
prune.data = data;
prune.extracted = NULL;
while(Curl_conncache_foreach(data, data->state.conn_cache, &prune,
call_extract_if_dead)) {
/* disconnect it */
(void)Curl_disconnect(data, prune.extracted, /* dead_connection */TRUE);
}
data->state.conn_cache->last_cleanup = now;
}
}
static size_t max_pipeline_length(struct Curl_multi *multi)
{
return multi ? multi->max_pipeline_length : 0;
}
/*
* Given one filled in connection struct (named needle), this function should
* detect if there already is one that has all the significant details
* exactly the same and thus should be used instead.
*
* If there is a match, this function returns TRUE - and has marked the
* connection as 'in-use'. It must later be called with ConnectionDone() to
* return back to 'idle' (unused) state.
*
* The force_reuse flag is set if the connection must be used, even if
* the pipelining strategy wants to open a new connection instead of reusing.
*/
static bool
ConnectionExists(struct Curl_easy *data,
struct connectdata *needle,
struct connectdata **usethis,
bool *force_reuse,
bool *waitpipe)
{
struct connectdata *check;
struct connectdata *chosen = 0;
bool foundPendingCandidate = FALSE;
int canpipe = IsPipeliningPossible(data, needle);
struct connectbundle *bundle;
#ifdef USE_NTLM
bool wantNTLMhttp = ((data->state.authhost.want &
(CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
(needle->handler->protocol & PROTO_FAMILY_HTTP));
bool wantProxyNTLMhttp = (needle->bits.proxy_user_passwd &&
((data->state.authproxy.want &
(CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
(needle->handler->protocol & PROTO_FAMILY_HTTP)));
#endif
*force_reuse = FALSE;
*waitpipe = FALSE;
/* We can't pipeline if the site is blacklisted */
if((canpipe & CURLPIPE_HTTP1) &&
Curl_pipeline_site_blacklisted(data, needle))
canpipe &= ~ CURLPIPE_HTTP1;
/* Look up the bundle with all the connections to this particular host.
Locks the connection cache, beware of early returns! */
bundle = Curl_conncache_find_bundle(needle, data->state.conn_cache);
if(bundle) {
/* Max pipe length is zero (unlimited) for multiplexed connections */
size_t max_pipe_len = (bundle->multiuse != BUNDLE_MULTIPLEX)?
max_pipeline_length(data->multi):0;
size_t best_pipe_len = max_pipe_len;
struct curl_llist_element *curr;
infof(data, "Found bundle for host %s: %p [%s]\n",
(needle->bits.conn_to_host ? needle->conn_to_host.name :
needle->host.name), (void *)bundle,
(bundle->multiuse == BUNDLE_PIPELINING ?
"can pipeline" :
(bundle->multiuse == BUNDLE_MULTIPLEX ?
"can multiplex" : "serially")));
/* We can't pipeline if we don't know anything about the server */
if(canpipe) {
if(bundle->multiuse <= BUNDLE_UNKNOWN) {
if((bundle->multiuse == BUNDLE_UNKNOWN) && data->set.pipewait) {
infof(data, "Server doesn't support multi-use yet, wait\n");
*waitpipe = TRUE;
Curl_conncache_unlock(needle);
return FALSE; /* no re-use */
}
infof(data, "Server doesn't support multi-use (yet)\n");
canpipe = 0;
}
if((bundle->multiuse == BUNDLE_PIPELINING) &&
!Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1)) {
/* not asked for, switch off */
infof(data, "Could pipeline, but not asked to!\n");
canpipe = 0;
}
else if((bundle->multiuse == BUNDLE_MULTIPLEX) &&
!Curl_pipeline_wanted(data->multi, CURLPIPE_MULTIPLEX)) {
infof(data, "Could multiplex, but not asked to!\n");
canpipe = 0;
}
}
curr = bundle->conn_list.head;
while(curr) {
bool match = FALSE;
size_t pipeLen;
/*
* Note that if we use a HTTP proxy in normal mode (no tunneling), we
* check connections to that proxy and not to the actual remote server.
*/
check = curr->ptr;
curr = curr->next;
if(extract_if_dead(check, data)) {
/* disconnect it */
(void)Curl_disconnect(data, check, /* dead_connection */TRUE);
continue;
}
pipeLen = check->send_pipe.size + check->recv_pipe.size;
if(canpipe) {
if(check->bits.protoconnstart && check->bits.close)
continue;
if(!check->bits.multiplex) {
/* If not multiplexing, make sure the connection is fine for HTTP/1
pipelining */
struct Curl_easy* sh = gethandleathead(&check->send_pipe);
struct Curl_easy* rh = gethandleathead(&check->recv_pipe);
if(sh) {
if(!(IsPipeliningPossible(sh, check) & CURLPIPE_HTTP1))
continue;
}
else if(rh) {
if(!(IsPipeliningPossible(rh, check) & CURLPIPE_HTTP1))
continue;
}
}
}
else {
if(pipeLen > 0) {
/* can only happen within multi handles, and means that another easy
handle is using this connection */
continue;
}
if(Curl_resolver_asynch()) {
/* ip_addr_str[0] is NUL only if the resolving of the name hasn't
completed yet and until then we don't re-use this connection */
if(!check->ip_addr_str[0]) {
infof(data,
"Connection #%ld is still name resolving, can't reuse\n",
check->connection_id);
continue;
}
}
if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) ||
check->bits.close) {
if(!check->bits.close)
foundPendingCandidate = TRUE;
/* Don't pick a connection that hasn't connected yet or that is going
to get closed. */
infof(data, "Connection #%ld isn't open enough, can't reuse\n",
check->connection_id);
#ifdef DEBUGBUILD
if(check->recv_pipe.size > 0) {
infof(data,
"BAD! Unconnected #%ld has a non-empty recv pipeline!\n",
check->connection_id);
}
#endif
continue;
}
}
#ifdef USE_UNIX_SOCKETS
if(needle->unix_domain_socket) {
if(!check->unix_domain_socket)
continue;
if(strcmp(needle->unix_domain_socket, check->unix_domain_socket))
continue;
if(needle->abstract_unix_socket != check->abstract_unix_socket)
continue;
}
else if(check->unix_domain_socket)
continue;
#endif
if((needle->handler->flags&PROTOPT_SSL) !=
(check->handler->flags&PROTOPT_SSL))
/* don't do mixed SSL and non-SSL connections */
if(get_protocol_family(check->handler->protocol) !=
needle->handler->protocol || !check->tls_upgraded)
/* except protocols that have been upgraded via TLS */
continue;
if(needle->bits.httpproxy != check->bits.httpproxy ||
needle->bits.socksproxy != check->bits.socksproxy)
continue;
if(needle->bits.socksproxy && !proxy_info_matches(&needle->socks_proxy,
&check->socks_proxy))
continue;
if(needle->bits.conn_to_host != check->bits.conn_to_host)
/* don't mix connections that use the "connect to host" feature and
* connections that don't use this feature */
continue;
if(needle->bits.conn_to_port != check->bits.conn_to_port)
/* don't mix connections that use the "connect to port" feature and
* connections that don't use this feature */
continue;
if(needle->bits.httpproxy) {
if(!proxy_info_matches(&needle->http_proxy, &check->http_proxy))
continue;
if(needle->bits.tunnel_proxy != check->bits.tunnel_proxy)
continue;
if(needle->http_proxy.proxytype == CURLPROXY_HTTPS) {
/* use https proxy */
if(needle->handler->flags&PROTOPT_SSL) {
/* use double layer ssl */
if(!Curl_ssl_config_matches(&needle->proxy_ssl_config,
&check->proxy_ssl_config))
continue;
if(check->proxy_ssl[FIRSTSOCKET].state != ssl_connection_complete)
continue;
}
else {
if(!Curl_ssl_config_matches(&needle->ssl_config,
&check->ssl_config))
continue;
if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete)
continue;
}
}
}
if(!canpipe && CONN_INUSE(check))
/* this request can't be pipelined but the checked connection is
already in use so we skip it */
continue;
if(CONN_INUSE(check) && (check->data->multi != needle->data->multi))
/* this could be subject for pipeline/multiplex use, but only
if they belong to the same multi handle */
continue;
if(needle->localdev || needle->localport) {
/* If we are bound to a specific local end (IP+port), we must not
re-use a random other one, although if we didn't ask for a
particular one we can reuse one that was bound.
This comparison is a bit rough and too strict. Since the input
parameters can be specified in numerous ways and still end up the
same it would take a lot of processing to make it really accurate.
Instead, this matching will assume that re-uses of bound connections
will most likely also re-use the exact same binding parameters and
missing out a few edge cases shouldn't hurt anyone very much.
*/
if((check->localport != needle->localport) ||
(check->localportrange != needle->localportrange) ||
(needle->localdev &&
(!check->localdev || strcmp(check->localdev, needle->localdev))))
continue;
}
if(!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) {
/* This protocol requires credentials per connection,
so verify that we're using the same name and password as well */
if(strcmp(needle->user, check->user) ||
strcmp(needle->passwd, check->passwd)) {
/* one of them was different */
continue;
}
}
if(!needle->bits.httpproxy || (needle->handler->flags&PROTOPT_SSL) ||
needle->bits.tunnel_proxy) {
/* The requested connection does not use a HTTP proxy or it uses SSL or
it is a non-SSL protocol tunneled or it is a non-SSL protocol which
is allowed to be upgraded via TLS */
if((strcasecompare(needle->handler->scheme, check->handler->scheme) ||
(get_protocol_family(check->handler->protocol) ==
needle->handler->protocol && check->tls_upgraded)) &&
(!needle->bits.conn_to_host || strcasecompare(
needle->conn_to_host.name, check->conn_to_host.name)) &&
(!needle->bits.conn_to_port ||
needle->conn_to_port == check->conn_to_port) &&
strcasecompare(needle->host.name, check->host.name) &&
needle->remote_port == check->remote_port) {
/* The schemes match or the the protocol family is the same and the
previous connection was TLS upgraded, and the hostname and host
port match */
if(needle->handler->flags & PROTOPT_SSL) {
/* This is a SSL connection so verify that we're using the same
SSL options as well */
if(!Curl_ssl_config_matches(&needle->ssl_config,
&check->ssl_config)) {
DEBUGF(infof(data,
"Connection #%ld has different SSL parameters, "
"can't reuse\n",
check->connection_id));
continue;
}
if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
foundPendingCandidate = TRUE;
DEBUGF(infof(data,
"Connection #%ld has not started SSL connect, "
"can't reuse\n",
check->connection_id));
continue;
}
}
match = TRUE;
}
}
else {
/* The requested connection is using the same HTTP proxy in normal
mode (no tunneling) */
match = TRUE;
}
if(match) {
#if defined(USE_NTLM)
/* If we are looking for an HTTP+NTLM connection, check if this is
already authenticating with the right credentials. If not, keep
looking so that we can reuse NTLM connections if
possible. (Especially we must not reuse the same connection if
partway through a handshake!) */
if(wantNTLMhttp) {
if(strcmp(needle->user, check->user) ||
strcmp(needle->passwd, check->passwd))
continue;
}
else if(check->ntlm.state != NTLMSTATE_NONE) {
/* Connection is using NTLM auth but we don't want NTLM */
continue;
}
/* Same for Proxy NTLM authentication */
if(wantProxyNTLMhttp) {
/* Both check->http_proxy.user and check->http_proxy.passwd can be
* NULL */
if(!check->http_proxy.user || !check->http_proxy.passwd)
continue;
if(strcmp(needle->http_proxy.user, check->http_proxy.user) ||
strcmp(needle->http_proxy.passwd, check->http_proxy.passwd))
continue;
}
else if(check->proxyntlm.state != NTLMSTATE_NONE) {
/* Proxy connection is using NTLM auth but we don't want NTLM */
continue;
}
if(wantNTLMhttp || wantProxyNTLMhttp) {
/* Credentials are already checked, we can use this connection */
chosen = check;
if((wantNTLMhttp &&
(check->ntlm.state != NTLMSTATE_NONE)) ||
(wantProxyNTLMhttp &&
(check->proxyntlm.state != NTLMSTATE_NONE))) {
/* We must use this connection, no other */
*force_reuse = TRUE;
break;
}
/* Continue look up for a better connection */
continue;
}
#endif
if(canpipe) {
/* We can pipeline if we want to. Let's continue looking for
the optimal connection to use, i.e the shortest pipe that is not
blacklisted. */
if(pipeLen == 0) {
/* We have the optimal connection. Let's stop looking. */
chosen = check;
break;
}
/* We can't use the connection if the pipe is full */
if(max_pipe_len && (pipeLen >= max_pipe_len)) {
infof(data, "Pipe is full, skip (%zu)\n", pipeLen);
continue;
}
#ifdef USE_NGHTTP2
/* If multiplexed, make sure we don't go over concurrency limit */
if(check->bits.multiplex) {
/* Multiplexed connections can only be HTTP/2 for now */
struct http_conn *httpc = &check->proto.httpc;
if(pipeLen >= httpc->settings.max_concurrent_streams) {
infof(data, "MAX_CONCURRENT_STREAMS reached, skip (%zu)\n",
pipeLen);
continue;
}
}
#endif
/* We can't use the connection if the pipe is penalized */
if(Curl_pipeline_penalized(data, check)) {
infof(data, "Penalized, skip\n");
continue;
}
if(max_pipe_len) {
if(pipeLen < best_pipe_len) {
/* This connection has a shorter pipe so far. We'll pick this
and continue searching */
chosen = check;
best_pipe_len = pipeLen;
continue;
}
}
else {
/* When not pipelining (== multiplexed), we have a match here! */
chosen = check;
infof(data, "Multiplexed connection found!\n");
break;
}
}
else {
/* We have found a connection. Let's stop searching. */
chosen = check;
break;
}
}
}
}
if(chosen) {
/* mark it as used before releasing the lock */
chosen->data = data; /* own it! */
Curl_conncache_unlock(needle);
*usethis = chosen;
return TRUE; /* yes, we found one to use! */
}
Curl_conncache_unlock(needle);
if(foundPendingCandidate && data->set.pipewait) {
infof(data,
"Found pending candidate for reuse and CURLOPT_PIPEWAIT is set\n");
*waitpipe = TRUE;
}
return FALSE; /* no matching connecting exists */
}
/* after a TCP connection to the proxy has been verified, this function does
the next magic step.
Note: this function's sub-functions call failf()
*/
CURLcode Curl_connected_proxy(struct connectdata *conn, int sockindex)
{
CURLcode result = CURLE_OK;
if(conn->bits.socksproxy) {
#ifndef CURL_DISABLE_PROXY
/* for the secondary socket (FTP), use the "connect to host"
* but ignore the "connect to port" (use the secondary port)
*/
const char * const host = conn->bits.httpproxy ?
conn->http_proxy.host.name :
conn->bits.conn_to_host ?
conn->conn_to_host.name :
sockindex == SECONDARYSOCKET ?
conn->secondaryhostname : conn->host.name;
const int port = conn->bits.httpproxy ? (int)conn->http_proxy.port :
sockindex == SECONDARYSOCKET ? conn->secondary_port :
conn->bits.conn_to_port ? conn->conn_to_port :
conn->remote_port;
conn->bits.socksproxy_connecting = TRUE;
switch(conn->socks_proxy.proxytype) {
case CURLPROXY_SOCKS5:
case CURLPROXY_SOCKS5_HOSTNAME:
result = Curl_SOCKS5(conn->socks_proxy.user, conn->socks_proxy.passwd,
host, port, sockindex, conn);
break;
case CURLPROXY_SOCKS4:
case CURLPROXY_SOCKS4A:
result = Curl_SOCKS4(conn->socks_proxy.user, host, port, sockindex,
conn);
break;
default:
failf(conn->data, "unknown proxytype option given");
result = CURLE_COULDNT_CONNECT;
} /* switch proxytype */
conn->bits.socksproxy_connecting = FALSE;
#else
(void)sockindex;
#endif /* CURL_DISABLE_PROXY */
}
return result;
}
/*
* verboseconnect() displays verbose information after a connect
*/
#ifndef CURL_DISABLE_VERBOSE_STRINGS
void Curl_verboseconnect(struct connectdata *conn)
{
if(conn->data->set.verbose)
infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
conn->bits.socksproxy ? conn->socks_proxy.host.dispname :
conn->bits.httpproxy ? conn->http_proxy.host.dispname :
conn->bits.conn_to_host ? conn->conn_to_host.dispname :
conn->host.dispname,
conn->ip_addr_str, conn->port, conn->connection_id);
}
#endif
int Curl_protocol_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks)
{
if(conn->handler->proto_getsock)
return conn->handler->proto_getsock(conn, socks, numsocks);
/* Backup getsock logic. Since there is a live socket in use, we must wait
for it or it will be removed from watching when the multi_socket API is
used. */
socks[0] = conn->sock[FIRSTSOCKET];
return GETSOCK_READSOCK(0) | GETSOCK_WRITESOCK(0);
}
int Curl_doing_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks)
{
if(conn && conn->handler->doing_getsock)
return conn->handler->doing_getsock(conn, socks, numsocks);
return GETSOCK_BLANK;
}
/*
* We are doing protocol-specific connecting and this is being called over and
* over from the multi interface until the connection phase is done on
* protocol layer.
*/
CURLcode Curl_protocol_connecting(struct connectdata *conn,
bool *done)
{
CURLcode result = CURLE_OK;
if(conn && conn->handler->connecting) {
*done = FALSE;
result = conn->handler->connecting(conn, done);
}
else
*done = TRUE;
return result;
}
/*
* We are DOING this is being called over and over from the multi interface
* until the DOING phase is done on protocol layer.
*/
CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
{
CURLcode result = CURLE_OK;
if(conn && conn->handler->doing) {
*done = FALSE;
result = conn->handler->doing(conn, done);
}
else
*done = TRUE;
return result;
}
/*
* We have discovered that the TCP connection has been successful, we can now
* proceed with some action.
*
*/
CURLcode Curl_protocol_connect(struct connectdata *conn,
bool *protocol_done)
{
CURLcode result = CURLE_OK;
*protocol_done = FALSE;
if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) {
/* We already are connected, get back. This may happen when the connect
worked fine in the first call, like when we connect to a local server
or proxy. Note that we don't know if the protocol is actually done.
Unless this protocol doesn't have any protocol-connect callback, as
then we know we're done. */
if(!conn->handler->connecting)
*protocol_done = TRUE;
return CURLE_OK;
}
if(!conn->bits.protoconnstart) {
result = Curl_proxy_connect(conn, FIRSTSOCKET);
if(result)
return result;
if(CONNECT_FIRSTSOCKET_PROXY_SSL())
/* wait for HTTPS proxy SSL initialization to complete */
return CURLE_OK;
if(conn->bits.tunnel_proxy && conn->bits.httpproxy &&
Curl_connect_ongoing(conn))
/* when using an HTTP tunnel proxy, await complete tunnel establishment
before proceeding further. Return CURLE_OK so we'll be called again */
return CURLE_OK;
if(conn->handler->connect_it) {
/* is there a protocol-specific connect() procedure? */
/* Call the protocol-specific connect function */
result = conn->handler->connect_it(conn, protocol_done);
}
else
*protocol_done = TRUE;
/* it has started, possibly even completed but that knowledge isn't stored
in this bit! */
if(!result)
conn->bits.protoconnstart = TRUE;
}
return result; /* pass back status */
}
/*
* Helpers for IDNA conversions.
*/
static bool is_ASCII_name(const char *hostname)
{
const unsigned char *ch = (const unsigned char *)hostname;
while(*ch) {
if(*ch++ & 0x80)
return FALSE;
}
return TRUE;
}
/*
* Perform any necessary IDN conversion of hostname
*/
static CURLcode fix_hostname(struct connectdata *conn, struct hostname *host)
{
size_t len;
struct Curl_easy *data = conn->data;
#ifndef USE_LIBIDN2
(void)data;
(void)conn;
#elif defined(CURL_DISABLE_VERBOSE_STRINGS)
(void)conn;
#endif
/* set the name we use to display the host name */
host->dispname = host->name;
len = strlen(host->name);
if(len && (host->name[len-1] == '.'))
/* strip off a single trailing dot if present, primarily for SNI but
there's no use for it */
host->name[len-1] = 0;
/* Check name for non-ASCII and convert hostname to ACE form if we can */
if(!is_ASCII_name(host->name)) {
#ifdef USE_LIBIDN2
if(idn2_check_version(IDN2_VERSION)) {
char *ace_hostname = NULL;
#if IDN2_VERSION_NUMBER >= 0x00140000
/* IDN2_NFC_INPUT: Normalize input string using normalization form C.
IDN2_NONTRANSITIONAL: Perform Unicode TR46 non-transitional
processing. */
int flags = IDN2_NFC_INPUT | IDN2_NONTRANSITIONAL;
#else
int flags = IDN2_NFC_INPUT;
#endif
int rc = idn2_lookup_ul((const char *)host->name, &ace_hostname, flags);
if(rc == IDN2_OK) {
host->encalloc = (char *)ace_hostname;
/* change the name pointer to point to the encoded hostname */
host->name = host->encalloc;
}
else {
failf(data, "Failed to convert %s to ACE; %s\n", host->name,
idn2_strerror(rc));
return CURLE_URL_MALFORMAT;
}
}
#elif defined(USE_WIN32_IDN)
char *ace_hostname = NULL;
if(curl_win32_idn_to_ascii(host->name, &ace_hostname)) {
host->encalloc = ace_hostname;
/* change the name pointer to point to the encoded hostname */
host->name = host->encalloc;
}
else {
failf(data, "Failed to convert %s to ACE;\n", host->name);
return CURLE_URL_MALFORMAT;
}
#else
infof(data, "IDN support not present, can't parse Unicode domains\n");
#endif
}
{
char *hostp;
for(hostp = host->name; *hostp; hostp++) {
if(*hostp <= 32) {
failf(data, "Host name '%s' contains bad letter", host->name);
return CURLE_URL_MALFORMAT;
}
}
}
return CURLE_OK;
}
/*
* Frees data allocated by fix_hostname()
*/
static void free_fixed_hostname(struct hostname *host)
{
#if defined(USE_LIBIDN2)
if(host->encalloc) {
idn2_free(host->encalloc); /* must be freed with idn2_free() since this was
allocated by libidn */
host->encalloc = NULL;
}
#elif defined(USE_WIN32_IDN)
free(host->encalloc); /* must be freed with free() since this was
allocated by curl_win32_idn_to_ascii */
host->encalloc = NULL;
#else
(void)host;
#endif
}
static void llist_dtor(void *user, void *element)
{
(void)user;
(void)element;
/* Do nothing */
}
/*
* Allocate and initialize a new connectdata object.
*/
static struct connectdata *allocate_conn(struct Curl_easy *data)
{
struct connectdata *conn = calloc(1, sizeof(struct connectdata));
if(!conn)
return NULL;
#ifdef USE_SSL
/* The SSL backend-specific data (ssl_backend_data) objects are allocated as
a separate array to ensure suitable alignment.
Note that these backend pointers can be swapped by vtls (eg ssl backend
data becomes proxy backend data). */
{
size_t sslsize = Curl_ssl->sizeof_ssl_backend_data;
char *ssl = calloc(4, sslsize);
if(!ssl) {
free(conn);
return NULL;
}
conn->ssl_extra = ssl;
conn->ssl[0].backend = (void *)ssl;
conn->ssl[1].backend = (void *)(ssl + sslsize);
conn->proxy_ssl[0].backend = (void *)(ssl + 2 * sslsize);
conn->proxy_ssl[1].backend = (void *)(ssl + 3 * sslsize);
}
#endif
conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined
already from start to avoid NULL
situations and checks */
/* and we setup a few fields in case we end up actually using this struct */
conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
conn->tempsock[0] = CURL_SOCKET_BAD; /* no file descriptor */
conn->tempsock[1] = CURL_SOCKET_BAD; /* no file descriptor */
conn->connection_id = -1; /* no ID */
conn->port = -1; /* unknown at this point */
conn->remote_port = -1; /* unknown at this point */
#if defined(USE_RECV_BEFORE_SEND_WORKAROUND) && defined(DEBUGBUILD)
conn->postponed[0].bindsock = CURL_SOCKET_BAD; /* no file descriptor */
conn->postponed[1].bindsock = CURL_SOCKET_BAD; /* no file descriptor */
#endif /* USE_RECV_BEFORE_SEND_WORKAROUND && DEBUGBUILD */
/* Default protocol-independent behavior doesn't support persistent
connections, so we set this to force-close. Protocols that support
this need to set this to FALSE in their "curl_do" functions. */
connclose(conn, "Default to force-close");
/* Store creation time to help future close decision making */
conn->created = Curl_now();
/* Store current time to give a baseline to keepalive connection times. */
conn->keepalive = Curl_now();
/* Store off the configured connection upkeep time. */
conn->upkeep_interval_ms = data->set.upkeep_interval_ms;
conn->data = data; /* Setup the association between this connection
and the Curl_easy */
conn->http_proxy.proxytype = data->set.proxytype;
conn->socks_proxy.proxytype = CURLPROXY_SOCKS4;
#ifdef CURL_DISABLE_PROXY
conn->bits.proxy = FALSE;
conn->bits.httpproxy = FALSE;
conn->bits.socksproxy = FALSE;
conn->bits.proxy_user_passwd = FALSE;
conn->bits.tunnel_proxy = FALSE;
#else /* CURL_DISABLE_PROXY */
/* note that these two proxy bits are now just on what looks to be
requested, they may be altered down the road */
conn->bits.proxy = (data->set.str[STRING_PROXY] &&
*data->set.str[STRING_PROXY]) ? TRUE : FALSE;
conn->bits.httpproxy = (conn->bits.proxy &&
(conn->http_proxy.proxytype == CURLPROXY_HTTP ||
conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0 ||
conn->http_proxy.proxytype == CURLPROXY_HTTPS)) ?
TRUE : FALSE;
conn->bits.socksproxy = (conn->bits.proxy &&
!conn->bits.httpproxy) ? TRUE : FALSE;
if(data->set.str[STRING_PRE_PROXY] && *data->set.str[STRING_PRE_PROXY]) {
conn->bits.proxy = TRUE;
conn->bits.socksproxy = TRUE;
}
conn->bits.proxy_user_passwd =
(data->set.str[STRING_PROXYUSERNAME]) ? TRUE : FALSE;
conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
#endif /* CURL_DISABLE_PROXY */
conn->bits.user_passwd = (data->set.str[STRING_USERNAME]) ? TRUE : FALSE;
conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
conn->ssl_config.verifystatus = data->set.ssl.primary.verifystatus;
conn->ssl_config.verifypeer = data->set.ssl.primary.verifypeer;
conn->ssl_config.verifyhost = data->set.ssl.primary.verifyhost;
conn->proxy_ssl_config.verifystatus =
data->set.proxy_ssl.primary.verifystatus;
conn->proxy_ssl_config.verifypeer = data->set.proxy_ssl.primary.verifypeer;
conn->proxy_ssl_config.verifyhost = data->set.proxy_ssl.primary.verifyhost;
conn->ip_version = data->set.ipver;
#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
defined(NTLM_WB_ENABLED)
conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
conn->ntlm_auth_hlpr_pid = 0;
conn->challenge_header = NULL;
conn->response_header = NULL;
#endif
if(Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1) &&
!conn->master_buffer) {
/* Allocate master_buffer to be used for HTTP/1 pipelining */
conn->master_buffer = calloc(MASTERBUF_SIZE, sizeof(char));
if(!conn->master_buffer)
goto error;
}
/* Initialize the pipeline lists */
Curl_llist_init(&conn->send_pipe, (curl_llist_dtor) llist_dtor);
Curl_llist_init(&conn->recv_pipe, (curl_llist_dtor) llist_dtor);
#ifdef HAVE_GSSAPI
conn->data_prot = PROT_CLEAR;
#endif
/* Store the local bind parameters that will be used for this connection */
if(data->set.str[STRING_DEVICE]) {
conn->localdev = strdup(data->set.str[STRING_DEVICE]);
if(!conn->localdev)
goto error;
}
conn->localportrange = data->set.localportrange;
conn->localport = data->set.localport;
/* the close socket stuff needs to be copied to the connection struct as
it may live on without (this specific) Curl_easy */
conn->fclosesocket = data->set.fclosesocket;
conn->closesocket_client = data->set.closesocket_client;
return conn;
error:
Curl_llist_destroy(&conn->send_pipe, NULL);
Curl_llist_destroy(&conn->recv_pipe, NULL);
free(conn->master_buffer);
free(conn->localdev);
#ifdef USE_SSL
free(conn->ssl_extra);
#endif
free(conn);
return NULL;
}
/* returns the handler if the given scheme is built-in */
const struct Curl_handler *Curl_builtin_scheme(const char *scheme)
{
const struct Curl_handler * const *pp;
const struct Curl_handler *p;
/* Scan protocol handler table and match against 'scheme'. The handler may
be changed later when the protocol specific setup function is called. */
for(pp = protocols; (p = *pp) != NULL; pp++)
if(strcasecompare(p->scheme, scheme))
/* Protocol found in table. Check if allowed */
return p;
return NULL; /* not found */
}
static CURLcode findprotocol(struct Curl_easy *data,
struct connectdata *conn,
const char *protostr)
{
const struct Curl_handler *p = Curl_builtin_scheme(protostr);
if(p && /* Protocol found in table. Check if allowed */
(data->set.allowed_protocols & p->protocol)) {
/* it is allowed for "normal" request, now do an extra check if this is
the result of a redirect */
if(data->state.this_is_a_follow &&
!(data->set.redir_protocols & p->protocol))
/* nope, get out */
;
else {
/* Perform setup complement if some. */
conn->handler = conn->given = p;
/* 'port' and 'remote_port' are set in setup_connection_internals() */
return CURLE_OK;
}
}
/* The protocol was not found in the table, but we don't have to assign it
to anything since it is already assigned to a dummy-struct in the
create_conn() function when the connectdata struct is allocated. */
failf(data, "Protocol \"%s\" not supported or disabled in " LIBCURL_NAME,
protostr);
return CURLE_UNSUPPORTED_PROTOCOL;
}
CURLcode Curl_uc_to_curlcode(CURLUcode uc)
{
switch(uc) {
default:
return CURLE_URL_MALFORMAT;
case CURLUE_UNSUPPORTED_SCHEME:
return CURLE_UNSUPPORTED_PROTOCOL;
case CURLUE_OUT_OF_MEMORY:
return CURLE_OUT_OF_MEMORY;
case CURLUE_USER_NOT_ALLOWED:
return CURLE_LOGIN_DENIED;
}
}
/*
* Parse URL and fill in the relevant members of the connection struct.
*/
static CURLcode parseurlandfillconn(struct Curl_easy *data,
struct connectdata *conn)
{
CURLcode result;
CURLU *uh;
CURLUcode uc;
char *hostname;
Curl_up_free(data); /* cleanup previous leftovers first */
/* parse the URL */
uh = data->state.uh = curl_url();
if(!uh)
return CURLE_OUT_OF_MEMORY;
if(data->set.str[STRING_DEFAULT_PROTOCOL] &&
!Curl_is_absolute_url(data->change.url, NULL, MAX_SCHEME_LEN)) {
char *url;
if(data->change.url_alloc)
free(data->change.url);
url = aprintf("%s://%s", data->set.str[STRING_DEFAULT_PROTOCOL],
data->change.url);
if(!url)
return CURLE_OUT_OF_MEMORY;
data->change.url = url;
data->change.url_alloc = TRUE;
}
uc = curl_url_set(uh, CURLUPART_URL, data->change.url,
CURLU_GUESS_SCHEME |
CURLU_NON_SUPPORT_SCHEME |
(data->set.disallow_username_in_url ?
CURLU_DISALLOW_USER : 0) |
(data->set.path_as_is ? CURLU_PATH_AS_IS : 0));
if(uc)
return Curl_uc_to_curlcode(uc);
uc = curl_url_get(uh, CURLUPART_SCHEME, &data->state.up.scheme, 0);
if(uc)
return Curl_uc_to_curlcode(uc);
result = findprotocol(data, conn, data->state.up.scheme);
if(result)
return result;
uc = curl_url_get(uh, CURLUPART_USER, &data->state.up.user,
CURLU_URLDECODE);
if(!uc) {
conn->user = strdup(data->state.up.user);
if(!conn->user)
return CURLE_OUT_OF_MEMORY;
conn->bits.user_passwd = TRUE;
}
else if(uc != CURLUE_NO_USER)
return Curl_uc_to_curlcode(uc);
uc = curl_url_get(uh, CURLUPART_PASSWORD, &data->state.up.password,
CURLU_URLDECODE);
if(!uc) {
conn->passwd = strdup(data->state.up.password);
if(!conn->passwd)
return CURLE_OUT_OF_MEMORY;
conn->bits.user_passwd = TRUE;
}
else if(uc != CURLUE_NO_PASSWORD)
return Curl_uc_to_curlcode(uc);
uc = curl_url_get(uh, CURLUPART_OPTIONS, &data->state.up.options,
CURLU_URLDECODE);
if(!uc) {
conn->options = strdup(data->state.up.options);
if(!conn->options)
return CURLE_OUT_OF_MEMORY;
}
else if(uc != CURLUE_NO_OPTIONS)
return Curl_uc_to_curlcode(uc);
uc = curl_url_get(uh, CURLUPART_HOST, &data->state.up.hostname, 0);
if(uc) {
if(!strcasecompare("file", data->state.up.scheme))
return CURLE_OUT_OF_MEMORY;
}
uc = curl_url_get(uh, CURLUPART_PATH, &data->state.up.path, 0);
if(uc)
return Curl_uc_to_curlcode(uc);
uc = curl_url_get(uh, CURLUPART_PORT, &data->state.up.port,
CURLU_DEFAULT_PORT);
if(uc) {
if(!strcasecompare("file", data->state.up.scheme))
return CURLE_OUT_OF_MEMORY;
}
else {
unsigned long port = strtoul(data->state.up.port, NULL, 10);
conn->remote_port = curlx_ultous(port);
}
(void)curl_url_get(uh, CURLUPART_QUERY, &data->state.up.query, 0);
hostname = data->state.up.hostname;
if(!hostname)
/* this is for file:// transfers, get a dummy made */
hostname = (char *)"";
if(hostname[0] == '[') {
/* This looks like an IPv6 address literal. See if there is an address
scope. */
char *percent = strchr(++hostname, '%');
conn->bits.ipv6_ip = TRUE;
if(percent) {
unsigned int identifier_offset = 3;
char *endp;
unsigned long scope;
if(strncmp("%25", percent, 3) != 0) {
infof(data,
"Please URL encode %% as %%25, see RFC 6874.\n");
identifier_offset = 1;
}
scope = strtoul(percent + identifier_offset, &endp, 10);
if(*endp == ']') {
/* The address scope was well formed. Knock it out of the
hostname. */
memmove(percent, endp, strlen(endp) + 1);
conn->scope_id = (unsigned int)scope;
}
else {
/* Zone identifier is not numeric */
#if defined(HAVE_NET_IF_H) && defined(IFNAMSIZ) && defined(HAVE_IF_NAMETOINDEX)
char ifname[IFNAMSIZ + 2];
char *square_bracket;
unsigned int scopeidx = 0;
strncpy(ifname, percent + identifier_offset, IFNAMSIZ + 2);
/* Ensure nullbyte termination */
ifname[IFNAMSIZ + 1] = '\0';
square_bracket = strchr(ifname, ']');
if(square_bracket) {
/* Remove ']' */
*square_bracket = '\0';
scopeidx = if_nametoindex(ifname);
if(scopeidx == 0) {
infof(data, "Invalid network interface: %s; %s\n", ifname,
strerror(errno));
}
}
if(scopeidx > 0) {
char *p = percent + identifier_offset + strlen(ifname);
/* Remove zone identifier from hostname */
memmove(percent, p, strlen(p) + 1);
conn->scope_id = scopeidx;
}
else
#endif /* HAVE_NET_IF_H && IFNAMSIZ */
infof(data, "Invalid IPv6 address format\n");
}
}
percent = strchr(hostname, ']');
if(percent)
/* terminate IPv6 numerical at end bracket */
*percent = 0;
}
/* make sure the connect struct gets its own copy of the host name */
conn->host.rawalloc = strdup(hostname);
if(!conn->host.rawalloc)
return CURLE_OUT_OF_MEMORY;
conn->host.name = conn->host.rawalloc;
if(data->set.scope_id)
/* Override any scope that was set above. */
conn->scope_id = data->set.scope_id;
return CURLE_OK;
}
/*
* If we're doing a resumed transfer, we need to setup our stuff
* properly.
*/
static CURLcode setup_range(struct Curl_easy *data)
{
struct UrlState *s = &data->state;
s->resume_from = data->set.set_resume_from;
if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
if(s->rangestringalloc)
free(s->range);
if(s->resume_from)
s->range = aprintf("%" CURL_FORMAT_CURL_OFF_T "-", s->resume_from);
else
s->range = strdup(data->set.str[STRING_SET_RANGE]);
s->rangestringalloc = (s->range) ? TRUE : FALSE;
if(!s->range)
return CURLE_OUT_OF_MEMORY;
/* tell ourselves to fetch this range */
s->use_range = TRUE; /* enable range download */
}
else
s->use_range = FALSE; /* disable range download */
return CURLE_OK;
}
/*
* setup_connection_internals() -
*
* Setup connection internals specific to the requested protocol in the
* Curl_easy. This is inited and setup before the connection is made but
* is about the particular protocol that is to be used.
*
* This MUST get called after proxy magic has been figured out.
*/
static CURLcode setup_connection_internals(struct connectdata *conn)
{
const struct Curl_handler * p;
CURLcode result;
conn->socktype = SOCK_STREAM; /* most of them are TCP streams */
/* Perform setup complement if some. */
p = conn->handler;
if(p->setup_connection) {
result = (*p->setup_connection)(conn);
if(result)
return result;
p = conn->handler; /* May have changed. */
}
if(conn->port < 0)
/* we check for -1 here since if proxy was detected already, this
was very likely already set to the proxy port */
conn->port = p->defport;
return CURLE_OK;
}
/*
* Curl_free_request_state() should free temp data that was allocated in the
* Curl_easy for this single request.
*/
void Curl_free_request_state(struct Curl_easy *data)
{
Curl_safefree(data->req.protop);
Curl_safefree(data->req.newurl);
}
#ifndef CURL_DISABLE_PROXY
/****************************************************************
* Checks if the host is in the noproxy list. returns true if it matches
* and therefore the proxy should NOT be used.
****************************************************************/
static bool check_noproxy(const char *name, const char *no_proxy)
{
/* no_proxy=domain1.dom,host.domain2.dom
* (a comma-separated list of hosts which should
* not be proxied, or an asterisk to override
* all proxy variables)
*/
if(no_proxy && no_proxy[0]) {
size_t tok_start;
size_t tok_end;
const char *separator = ", ";
size_t no_proxy_len;
size_t namelen;
char *endptr;
if(strcasecompare("*", no_proxy)) {
return TRUE;
}
/* NO_PROXY was specified and it wasn't just an asterisk */
no_proxy_len = strlen(no_proxy);
if(name[0] == '[') {
/* IPv6 numerical address */
endptr = strchr(name, ']');
if(!endptr)
return FALSE;
name++;
namelen = endptr - name;
}
else
namelen = strlen(name);
for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
while(tok_start < no_proxy_len &&
strchr(separator, no_proxy[tok_start]) != NULL) {
/* Look for the beginning of the token. */
++tok_start;
}
if(tok_start == no_proxy_len)
break; /* It was all trailing separator chars, no more tokens. */
for(tok_end = tok_start; tok_end < no_proxy_len &&
strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end)
/* Look for the end of the token. */
;
/* To match previous behaviour, where it was necessary to specify
* ".local.com" to prevent matching "notlocal.com", we will leave
* the '.' off.
*/
if(no_proxy[tok_start] == '.')
++tok_start;
if((tok_end - tok_start) <= namelen) {
/* Match the last part of the name to the domain we are checking. */
const char *checkn = name + namelen - (tok_end - tok_start);
if(strncasecompare(no_proxy + tok_start, checkn,
tok_end - tok_start)) {
if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
/* We either have an exact match, or the previous character is a .
* so it is within the same domain, so no proxy for this host.
*/
return TRUE;
}
}
} /* if((tok_end - tok_start) <= namelen) */
} /* for(tok_start = 0; tok_start < no_proxy_len;
tok_start = tok_end + 1) */
} /* NO_PROXY was specified and it wasn't just an asterisk */
return FALSE;
}
#ifndef CURL_DISABLE_HTTP
/****************************************************************
* Detect what (if any) proxy to use. Remember that this selects a host
* name and is not limited to HTTP proxies only.
* The returned pointer must be freed by the caller (unless NULL)
****************************************************************/
static char *detect_proxy(struct connectdata *conn)
{
char *proxy = NULL;
/* If proxy was not specified, we check for default proxy environment
* variables, to enable i.e Lynx compliance:
*
* http_proxy=http://some.server.dom:port/
* https_proxy=http://some.server.dom:port/
* ftp_proxy=http://some.server.dom:port/
* no_proxy=domain1.dom,host.domain2.dom
* (a comma-separated list of hosts which should
* not be proxied, or an asterisk to override
* all proxy variables)
* all_proxy=http://some.server.dom:port/
* (seems to exist for the CERN www lib. Probably
* the first to check for.)
*
* For compatibility, the all-uppercase versions of these variables are
* checked if the lowercase versions don't exist.
*/
char proxy_env[128];
const char *protop = conn->handler->scheme;
char *envp = proxy_env;
char *prox;
/* Now, build <protocol>_proxy and check for such a one to use */
while(*protop)
*envp++ = (char)tolower((int)*protop++);
/* append _proxy */
strcpy(envp, "_proxy");
/* read the protocol proxy: */
prox = curl_getenv(proxy_env);
/*
* We don't try the uppercase version of HTTP_PROXY because of
* security reasons:
*
* When curl is used in a webserver application
* environment (cgi or php), this environment variable can
* be controlled by the web server user by setting the
* http header 'Proxy:' to some value.
*
* This can cause 'internal' http/ftp requests to be
* arbitrarily redirected by any external attacker.
*/
if(!prox && !strcasecompare("http_proxy", proxy_env)) {
/* There was no lowercase variable, try the uppercase version: */
Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
prox = curl_getenv(proxy_env);
}
envp = proxy_env;
if(prox) {
proxy = prox; /* use this */
}
else {
envp = (char *)"all_proxy";
proxy = curl_getenv(envp); /* default proxy to use */
if(!proxy) {
envp = (char *)"ALL_PROXY";
proxy = curl_getenv(envp);
}
}
if(proxy)
infof(conn->data, "Uses proxy env variable %s == '%s'\n", envp, proxy);
return proxy;
}
#endif /* CURL_DISABLE_HTTP */
/*
* If this is supposed to use a proxy, we need to figure out the proxy
* host name, so that we can re-use an existing connection
* that may exist registered to the same proxy host.
*/
static CURLcode parse_proxy(struct Curl_easy *data,
struct connectdata *conn, char *proxy,
curl_proxytype proxytype)
{
char *prox_portno;
char *endofprot;
/* We use 'proxyptr' to point to the proxy name from now on... */
char *proxyptr;
char *portptr;
char *atsign;
long port = -1;
char *proxyuser = NULL;
char *proxypasswd = NULL;
bool sockstype;
/* We do the proxy host string parsing here. We want the host name and the
* port name. Accept a protocol:// prefix
*/
/* Parse the protocol part if present */
endofprot = strstr(proxy, "://");
if(endofprot) {
proxyptr = endofprot + 3;
if(checkprefix("https", proxy))
proxytype = CURLPROXY_HTTPS;
else if(checkprefix("socks5h", proxy))
proxytype = CURLPROXY_SOCKS5_HOSTNAME;
else if(checkprefix("socks5", proxy))
proxytype = CURLPROXY_SOCKS5;
else if(checkprefix("socks4a", proxy))
proxytype = CURLPROXY_SOCKS4A;
else if(checkprefix("socks4", proxy) || checkprefix("socks", proxy))
proxytype = CURLPROXY_SOCKS4;
else if(checkprefix("http:", proxy))
; /* leave it as HTTP or HTTP/1.0 */
else {
/* Any other xxx:// reject! */
failf(data, "Unsupported proxy scheme for \'%s\'", proxy);
return CURLE_COULDNT_CONNECT;
}
}
else
proxyptr = proxy; /* No xxx:// head: It's a HTTP proxy */
#ifdef USE_SSL
if(!(Curl_ssl->supports & SSLSUPP_HTTPS_PROXY))
#endif
if(proxytype == CURLPROXY_HTTPS) {
failf(data, "Unsupported proxy \'%s\', libcurl is built without the "
"HTTPS-proxy support.", proxy);
return CURLE_NOT_BUILT_IN;
}
sockstype = proxytype == CURLPROXY_SOCKS5_HOSTNAME ||
proxytype == CURLPROXY_SOCKS5 ||
proxytype == CURLPROXY_SOCKS4A ||
proxytype == CURLPROXY_SOCKS4;
/* Is there a username and password given in this proxy url? */
atsign = strchr(proxyptr, '@');
if(atsign) {
CURLcode result =
Curl_parse_login_details(proxyptr, atsign - proxyptr,
&proxyuser, &proxypasswd, NULL);
if(result)
return result;
proxyptr = atsign + 1;
}
/* start scanning for port number at this point */
portptr = proxyptr;
/* detect and extract RFC6874-style IPv6-addresses */
if(*proxyptr == '[') {
char *ptr = ++proxyptr; /* advance beyond the initial bracket */
while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
ptr++;
if(*ptr == '%') {
/* There might be a zone identifier */
if(strncmp("%25", ptr, 3))
infof(data, "Please URL encode %% as %%25, see RFC 6874.\n");
ptr++;
/* Allow unreserved characters as defined in RFC 3986 */
while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
(*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
ptr++;
}
if(*ptr == ']')
/* yeps, it ended nicely with a bracket as well */
*ptr++ = 0;
else
infof(data, "Invalid IPv6 address format\n");
portptr = ptr;
/* Note that if this didn't end with a bracket, we still advanced the
* proxyptr first, but I can't see anything wrong with that as no host
* name nor a numeric can legally start with a bracket.
*/
}
/* Get port number off proxy.server.com:1080 */
prox_portno = strchr(portptr, ':');
if(prox_portno) {
char *endp = NULL;
*prox_portno = 0x0; /* cut off number from host name */
prox_portno ++;
/* now set the local port number */
port = strtol(prox_portno, &endp, 10);
if((endp && *endp && (*endp != '/') && (*endp != ' ')) ||
(port < 0) || (port > 65535)) {
/* meant to detect for example invalid IPv6 numerical addresses without
brackets: "2a00:fac0:a000::7:13". Accept a trailing slash only
because we then allow "URL style" with the number followed by a
slash, used in curl test cases already. Space is also an acceptable
terminating symbol. */
infof(data, "No valid port number in proxy string (%s)\n",
prox_portno);
}
else
conn->port = port;
}
else {
if(proxyptr[0]=='/') {
/* If the first character in the proxy string is a slash, fail
immediately. The following code will otherwise clear the string which
will lead to code running as if no proxy was set! */
Curl_safefree(proxyuser);
Curl_safefree(proxypasswd);
return CURLE_COULDNT_RESOLVE_PROXY;
}
/* without a port number after the host name, some people seem to use
a slash so we strip everything from the first slash */
atsign = strchr(proxyptr, '/');
if(atsign)
*atsign = '\0'; /* cut off path part from host name */
if(data->set.proxyport)
/* None given in the proxy string, then get the default one if it is
given */
port = data->set.proxyport;
else {
if(proxytype == CURLPROXY_HTTPS)
port = CURL_DEFAULT_HTTPS_PROXY_PORT;
else
port = CURL_DEFAULT_PROXY_PORT;
}
}
if(*proxyptr) {
struct proxy_info *proxyinfo =
sockstype ? &conn->socks_proxy : &conn->http_proxy;
proxyinfo->proxytype = proxytype;
if(proxyuser) {
/* found user and password, rip them out. note that we are unescaping
them, as there is otherwise no way to have a username or password
with reserved characters like ':' in them. */
Curl_safefree(proxyinfo->user);
proxyinfo->user = curl_easy_unescape(data, proxyuser, 0, NULL);
Curl_safefree(proxyuser);
if(!proxyinfo->user) {
Curl_safefree(proxypasswd);
return CURLE_OUT_OF_MEMORY;
}
Curl_safefree(proxyinfo->passwd);
if(proxypasswd && strlen(proxypasswd) < MAX_CURL_PASSWORD_LENGTH)
proxyinfo->passwd = curl_easy_unescape(data, proxypasswd, 0, NULL);
else
proxyinfo->passwd = strdup("");
Curl_safefree(proxypasswd);
if(!proxyinfo->passwd)
return CURLE_OUT_OF_MEMORY;
conn->bits.proxy_user_passwd = TRUE; /* enable it */
}
if(port >= 0) {
proxyinfo->port = port;
if(conn->port < 0 || sockstype || !conn->socks_proxy.host.rawalloc)
conn->port = port;
}
/* now, clone the cleaned proxy host name */
Curl_safefree(proxyinfo->host.rawalloc);
proxyinfo->host.rawalloc = strdup(proxyptr);
proxyinfo->host.name = proxyinfo->host.rawalloc;
if(!proxyinfo->host.rawalloc)
return CURLE_OUT_OF_MEMORY;
}
Curl_safefree(proxyuser);
Curl_safefree(proxypasswd);
return CURLE_OK;
}
/*
* Extract the user and password from the authentication string
*/
static CURLcode parse_proxy_auth(struct Curl_easy *data,
struct connectdata *conn)
{
char proxyuser[MAX_CURL_USER_LENGTH]="";
char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
CURLcode result;
if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
MAX_CURL_USER_LENGTH);
proxyuser[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/
}
if(data->set.str[STRING_PROXYPASSWORD] != NULL) {
strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD],
MAX_CURL_PASSWORD_LENGTH);
proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
}
result = Curl_urldecode(data, proxyuser, 0, &conn->http_proxy.user, NULL,
FALSE);
if(!result)
result = Curl_urldecode(data, proxypasswd, 0, &conn->http_proxy.passwd,
NULL, FALSE);
return result;
}
/* create_conn helper to parse and init proxy values. to be called after unix
socket init but before any proxy vars are evaluated. */
static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
{
char *proxy = NULL;
char *socksproxy = NULL;
char *no_proxy = NULL;
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
/*************************************************************
* Extract the user and password from the authentication string
*************************************************************/
if(conn->bits.proxy_user_passwd) {
result = parse_proxy_auth(data, conn);
if(result)
goto out;
}
/*************************************************************
* Detect what (if any) proxy to use
*************************************************************/
if(data->set.str[STRING_PROXY]) {
proxy = strdup(data->set.str[STRING_PROXY]);
/* if global proxy is set, this is it */
if(NULL == proxy) {
failf(data, "memory shortage");
result = CURLE_OUT_OF_MEMORY;
goto out;
}
}
if(data->set.str[STRING_PRE_PROXY]) {
socksproxy = strdup(data->set.str[STRING_PRE_PROXY]);
/* if global socks proxy is set, this is it */
if(NULL == socksproxy) {
failf(data, "memory shortage");
result = CURLE_OUT_OF_MEMORY;
goto out;
}
}
if(!data->set.str[STRING_NOPROXY]) {
const char *p = "no_proxy";
no_proxy = curl_getenv(p);
if(!no_proxy) {
p = "NO_PROXY";
no_proxy = curl_getenv(p);
}
if(no_proxy) {
infof(conn->data, "Uses proxy env variable %s == '%s'\n", p, no_proxy);
}
}
if(check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY] ?
data->set.str[STRING_NOPROXY] : no_proxy)) {
Curl_safefree(proxy);
Curl_safefree(socksproxy);
}
#ifndef CURL_DISABLE_HTTP
else if(!proxy && !socksproxy)
/* if the host is not in the noproxy list, detect proxy. */
proxy = detect_proxy(conn);
#endif /* CURL_DISABLE_HTTP */
Curl_safefree(no_proxy);
#ifdef USE_UNIX_SOCKETS
/* For the time being do not mix proxy and unix domain sockets. See #1274 */
if(proxy && conn->unix_domain_socket) {
free(proxy);
proxy = NULL;
}
#endif
if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) {
free(proxy); /* Don't bother with an empty proxy string or if the
protocol doesn't work with network */
proxy = NULL;
}
if(socksproxy && (!*socksproxy ||
(conn->handler->flags & PROTOPT_NONETWORK))) {
free(socksproxy); /* Don't bother with an empty socks proxy string or if
the protocol doesn't work with network */
socksproxy = NULL;
}
/***********************************************************************
* If this is supposed to use a proxy, we need to figure out the proxy host
* name, proxy type and port number, so that we can re-use an existing
* connection that may exist registered to the same proxy host.
***********************************************************************/
if(proxy || socksproxy) {
if(proxy) {
result = parse_proxy(data, conn, proxy, conn->http_proxy.proxytype);
Curl_safefree(proxy); /* parse_proxy copies the proxy string */
if(result)
goto out;
}
if(socksproxy) {
result = parse_proxy(data, conn, socksproxy,
conn->socks_proxy.proxytype);
/* parse_proxy copies the socks proxy string */
Curl_safefree(socksproxy);
if(result)
goto out;
}
if(conn->http_proxy.host.rawalloc) {
#ifdef CURL_DISABLE_HTTP
/* asking for a HTTP proxy is a bit funny when HTTP is disabled... */
result = CURLE_UNSUPPORTED_PROTOCOL;
goto out;
#else
/* force this connection's protocol to become HTTP if compatible */
if(!(conn->handler->protocol & PROTO_FAMILY_HTTP)) {
if((conn->handler->flags & PROTOPT_PROXY_AS_HTTP) &&
!conn->bits.tunnel_proxy)
conn->handler = &Curl_handler_http;
else
/* if not converting to HTTP over the proxy, enforce tunneling */
conn->bits.tunnel_proxy = TRUE;
}
conn->bits.httpproxy = TRUE;
#endif
}
else {
conn->bits.httpproxy = FALSE; /* not a HTTP proxy */
conn->bits.tunnel_proxy = FALSE; /* no tunneling if not HTTP */
}
if(conn->socks_proxy.host.rawalloc) {
if(!conn->http_proxy.host.rawalloc) {
/* once a socks proxy */
if(!conn->socks_proxy.user) {
conn->socks_proxy.user = conn->http_proxy.user;
conn->http_proxy.user = NULL;
Curl_safefree(conn->socks_proxy.passwd);
conn->socks_proxy.passwd = conn->http_proxy.passwd;
conn->http_proxy.passwd = NULL;
}
}
conn->bits.socksproxy = TRUE;
}
else
conn->bits.socksproxy = FALSE; /* not a socks proxy */
}
else {
conn->bits.socksproxy = FALSE;
conn->bits.httpproxy = FALSE;
}
conn->bits.proxy = conn->bits.httpproxy || conn->bits.socksproxy;
if(!conn->bits.proxy) {
/* we aren't using the proxy after all... */
conn->bits.proxy = FALSE;
conn->bits.httpproxy = FALSE;
conn->bits.socksproxy = FALSE;
conn->bits.proxy_user_passwd = FALSE;
conn->bits.tunnel_proxy = FALSE;
}
out:
free(socksproxy);
free(proxy);
return result;
}
#endif /* CURL_DISABLE_PROXY */
/*
* Curl_parse_login_details()
*
* This is used to parse a login string for user name, password and options in
* the following formats:
*
* user
* user:password
* user:password;options
* user;options
* user;options:password
* :password
* :password;options
* ;options
* ;options:password
*
* Parameters:
*
* login [in] - The login string.
* len [in] - The length of the login string.
* userp [in/out] - The address where a pointer to newly allocated memory
* holding the user will be stored upon completion.
* passwdp [in/out] - The address where a pointer to newly allocated memory
* holding the password will be stored upon completion.
* optionsp [in/out] - The address where a pointer to newly allocated memory
* holding the options will be stored upon completion.
*
* Returns CURLE_OK on success.
*/
CURLcode Curl_parse_login_details(const char *login, const size_t len,
char **userp, char **passwdp,
char **optionsp)
{
CURLcode result = CURLE_OK;
char *ubuf = NULL;
char *pbuf = NULL;
char *obuf = NULL;
const char *psep = NULL;
const char *osep = NULL;
size_t ulen;
size_t plen;
size_t olen;
/* Attempt to find the password separator */
if(passwdp) {
psep = strchr(login, ':');
/* Within the constraint of the login string */
if(psep >= login + len)
psep = NULL;
}
/* Attempt to find the options separator */
if(optionsp) {
osep = strchr(login, ';');
/* Within the constraint of the login string */
if(osep >= login + len)
osep = NULL;
}
/* Calculate the portion lengths */
ulen = (psep ?
(size_t)(osep && psep > osep ? osep - login : psep - login) :
(osep ? (size_t)(osep - login) : len));
plen = (psep ?
(osep && osep > psep ? (size_t)(osep - psep) :
(size_t)(login + len - psep)) - 1 : 0);
olen = (osep ?
(psep && psep > osep ? (size_t)(psep - osep) :
(size_t)(login + len - osep)) - 1 : 0);
/* Allocate the user portion buffer */
if(userp && ulen) {
ubuf = malloc(ulen + 1);
if(!ubuf)
result = CURLE_OUT_OF_MEMORY;
}
/* Allocate the password portion buffer */
if(!result && passwdp && plen) {
pbuf = malloc(plen + 1);
if(!pbuf) {
free(ubuf);
result = CURLE_OUT_OF_MEMORY;
}
}
/* Allocate the options portion buffer */
if(!result && optionsp && olen) {
obuf = malloc(olen + 1);
if(!obuf) {
free(pbuf);
free(ubuf);
result = CURLE_OUT_OF_MEMORY;
}
}
if(!result) {
/* Store the user portion if necessary */
if(ubuf) {
memcpy(ubuf, login, ulen);
ubuf[ulen] = '\0';
Curl_safefree(*userp);
*userp = ubuf;
}
/* Store the password portion if necessary */
if(pbuf) {
memcpy(pbuf, psep + 1, plen);
pbuf[plen] = '\0';
Curl_safefree(*passwdp);
*passwdp = pbuf;
}
/* Store the options portion if necessary */
if(obuf) {
memcpy(obuf, osep + 1, olen);
obuf[olen] = '\0';
Curl_safefree(*optionsp);
*optionsp = obuf;
}
}
return result;
}
/*************************************************************
* Figure out the remote port number and fix it in the URL
*
* No matter if we use a proxy or not, we have to figure out the remote
* port number of various reasons.
*
* The port number embedded in the URL is replaced, if necessary.
*************************************************************/
static CURLcode parse_remote_port(struct Curl_easy *data,
struct connectdata *conn)
{
if(data->set.use_port && data->state.allow_port) {
/* if set, we use this instead of the port possibly given in the URL */
char portbuf[16];
CURLUcode uc;
conn->remote_port = (unsigned short)data->set.use_port;
snprintf(portbuf, sizeof(portbuf), "%u", conn->remote_port);
uc = curl_url_set(data->state.uh, CURLUPART_PORT, portbuf, 0);
if(uc)
return CURLE_OUT_OF_MEMORY;
}
return CURLE_OK;
}
/*
* Override the login details from the URL with that in the CURLOPT_USERPWD
* option or a .netrc file, if applicable.
*/
static CURLcode override_login(struct Curl_easy *data,
struct connectdata *conn,
char **userp, char **passwdp, char **optionsp)
{
bool user_changed = FALSE;
bool passwd_changed = FALSE;
CURLUcode uc;
if(data->set.str[STRING_USERNAME]) {
free(*userp);
*userp = strdup(data->set.str[STRING_USERNAME]);
if(!*userp)
return CURLE_OUT_OF_MEMORY;
conn->bits.user_passwd = TRUE; /* enable user+password */
user_changed = TRUE;
}
if(data->set.str[STRING_PASSWORD]) {
free(*passwdp);
*passwdp = strdup(data->set.str[STRING_PASSWORD]);
if(!*passwdp)
return CURLE_OUT_OF_MEMORY;
conn->bits.user_passwd = TRUE; /* enable user+password */
passwd_changed = TRUE;
}
if(data->set.str[STRING_OPTIONS]) {
free(*optionsp);
*optionsp = strdup(data->set.str[STRING_OPTIONS]);
if(!*optionsp)
return CURLE_OUT_OF_MEMORY;
}
conn->bits.netrc = FALSE;
if(data->set.use_netrc != CURL_NETRC_IGNORED) {
char *nuser = NULL;
char *npasswd = NULL;
int ret;
if(data->set.use_netrc == CURL_NETRC_OPTIONAL)
nuser = *userp; /* to separate otherwise identical machines */
ret = Curl_parsenetrc(conn->host.name,
&nuser, &npasswd,
data->set.str[STRING_NETRC_FILE]);
if(ret > 0) {
infof(data, "Couldn't find host %s in the "
DOT_CHAR "netrc file; using defaults\n",
conn->host.name);
}
else if(ret < 0) {
return CURLE_OUT_OF_MEMORY;
}
else {
/* set bits.netrc TRUE to remember that we got the name from a .netrc
file, so that it is safe to use even if we followed a Location: to a
different host or similar. */
conn->bits.netrc = TRUE;
conn->bits.user_passwd = TRUE; /* enable user+password */
if(data->set.use_netrc == CURL_NETRC_OPTIONAL) {
/* prefer credentials outside netrc */
if(nuser && !*userp) {
free(*userp);
*userp = nuser;
user_changed = TRUE;
}
if(npasswd && !*passwdp) {
free(*passwdp);
*passwdp = npasswd;
passwd_changed = TRUE;
}
}
else {
/* prefer netrc credentials */
if(nuser) {
free(*userp);
*userp = nuser;
user_changed = TRUE;
}
if(npasswd) {
free(*passwdp);
*passwdp = npasswd;
passwd_changed = TRUE;
}
}
}
}
/* for updated strings, we update them in the URL */
if(user_changed) {
uc = curl_url_set(data->state.uh, CURLUPART_USER, *userp, 0);
if(uc)
return Curl_uc_to_curlcode(uc);
}
if(passwd_changed) {
uc = curl_url_set(data->state.uh, CURLUPART_PASSWORD, *passwdp, 0);
if(uc)
return Curl_uc_to_curlcode(uc);
}
return CURLE_OK;
}
/*
* Set the login details so they're available in the connection
*/
static CURLcode set_login(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
const char *setuser = CURL_DEFAULT_USER;
const char *setpasswd = CURL_DEFAULT_PASSWORD;
/* If our protocol needs a password and we have none, use the defaults */
if((conn->handler->flags & PROTOPT_NEEDSPWD) && !conn->bits.user_passwd)
;
else {
setuser = "";
setpasswd = "";
}
/* Store the default user */
if(!conn->user) {
conn->user = strdup(setuser);
if(!conn->user)
return CURLE_OUT_OF_MEMORY;
}
/* Store the default password */
if(!conn->passwd) {
conn->passwd = strdup(setpasswd);
if(!conn->passwd)
result = CURLE_OUT_OF_MEMORY;
}
/* if there's a user without password, consider password blank */
if(conn->user && !conn->passwd) {
conn->passwd = strdup("");
if(!conn->passwd)
result = CURLE_OUT_OF_MEMORY;
}
return result;
}
/*
* Parses a "host:port" string to connect to.
* The hostname and the port may be empty; in this case, NULL is returned for
* the hostname and -1 for the port.
*/
static CURLcode parse_connect_to_host_port(struct Curl_easy *data,
const char *host,
char **hostname_result,
int *port_result)
{
char *host_dup;
char *hostptr;
char *host_portno;
char *portptr;
int port = -1;
#if defined(CURL_DISABLE_VERBOSE_STRINGS)
(void) data;
#endif
*hostname_result = NULL;
*port_result = -1;
if(!host || !*host)
return CURLE_OK;
host_dup = strdup(host);
if(!host_dup)
return CURLE_OUT_OF_MEMORY;
hostptr = host_dup;
/* start scanning for port number at this point */
portptr = hostptr;
/* detect and extract RFC6874-style IPv6-addresses */
if(*hostptr == '[') {
#ifdef ENABLE_IPV6
char *ptr = ++hostptr; /* advance beyond the initial bracket */
while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
ptr++;
if(*ptr == '%') {
/* There might be a zone identifier */
if(strncmp("%25", ptr, 3))
infof(data, "Please URL encode %% as %%25, see RFC 6874.\n");
ptr++;
/* Allow unreserved characters as defined in RFC 3986 */
while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
(*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
ptr++;
}
if(*ptr == ']')
/* yeps, it ended nicely with a bracket as well */
*ptr++ = '\0';
else
infof(data, "Invalid IPv6 address format\n");
portptr = ptr;
/* Note that if this didn't end with a bracket, we still advanced the
* hostptr first, but I can't see anything wrong with that as no host
* name nor a numeric can legally start with a bracket.
*/
#else
failf(data, "Use of IPv6 in *_CONNECT_TO without IPv6 support built-in!");
free(host_dup);
return CURLE_NOT_BUILT_IN;
#endif
}
/* Get port number off server.com:1080 */
host_portno = strchr(portptr, ':');
if(host_portno) {
char *endp = NULL;
*host_portno = '\0'; /* cut off number from host name */
host_portno++;
if(*host_portno) {
long portparse = strtol(host_portno, &endp, 10);
if((endp && *endp) || (portparse < 0) || (portparse > 65535)) {
infof(data, "No valid port number in connect to host string (%s)\n",
host_portno);
hostptr = NULL;
port = -1;
}
else
port = (int)portparse; /* we know it will fit */
}
}
/* now, clone the cleaned host name */
if(hostptr) {
*hostname_result = strdup(hostptr);
if(!*hostname_result) {
free(host_dup);
return CURLE_OUT_OF_MEMORY;
}
}
*port_result = port;
free(host_dup);
return CURLE_OK;
}
/*
* Parses one "connect to" string in the form:
* "HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT".
*/
static CURLcode parse_connect_to_string(struct Curl_easy *data,
struct connectdata *conn,
const char *conn_to_host,
char **host_result,
int *port_result)
{
CURLcode result = CURLE_OK;
const char *ptr = conn_to_host;
int host_match = FALSE;
int port_match = FALSE;
*host_result = NULL;
*port_result = -1;
if(*ptr == ':') {
/* an empty hostname always matches */
host_match = TRUE;
ptr++;
}
else {
/* check whether the URL's hostname matches */
size_t hostname_to_match_len;
char *hostname_to_match = aprintf("%s%s%s",
conn->bits.ipv6_ip ? "[" : "",
conn->host.name,
conn->bits.ipv6_ip ? "]" : "");
if(!hostname_to_match)
return CURLE_OUT_OF_MEMORY;
hostname_to_match_len = strlen(hostname_to_match);
host_match = strncasecompare(ptr, hostname_to_match,
hostname_to_match_len);
free(hostname_to_match);
ptr += hostname_to_match_len;
host_match = host_match && *ptr == ':';
ptr++;
}
if(host_match) {
if(*ptr == ':') {
/* an empty port always matches */
port_match = TRUE;
ptr++;
}
else {
/* check whether the URL's port matches */
char *ptr_next = strchr(ptr, ':');
if(ptr_next) {
char *endp = NULL;
long port_to_match = strtol(ptr, &endp, 10);
if((endp == ptr_next) && (port_to_match == conn->remote_port)) {
port_match = TRUE;
ptr = ptr_next + 1;
}
}
}
}
if(host_match && port_match) {
/* parse the hostname and port to connect to */
result = parse_connect_to_host_port(data, ptr, host_result, port_result);
}
return result;
}
/*
* Processes all strings in the "connect to" slist, and uses the "connect
* to host" and "connect to port" of the first string that matches.
*/
static CURLcode parse_connect_to_slist(struct Curl_easy *data,
struct connectdata *conn,
struct curl_slist *conn_to_host)
{
CURLcode result = CURLE_OK;
char *host = NULL;
int port = -1;
while(conn_to_host && !host && port == -1) {
result = parse_connect_to_string(data, conn, conn_to_host->data,
&host, &port);
if(result)
return result;
if(host && *host) {
conn->conn_to_host.rawalloc = host;
conn->conn_to_host.name = host;
conn->bits.conn_to_host = TRUE;
infof(data, "Connecting to hostname: %s\n", host);
}
else {
/* no "connect to host" */
conn->bits.conn_to_host = FALSE;
Curl_safefree(host);
}
if(port >= 0) {
conn->conn_to_port = port;
conn->bits.conn_to_port = TRUE;
infof(data, "Connecting to port: %d\n", port);
}
else {
/* no "connect to port" */
conn->bits.conn_to_port = FALSE;
port = -1;
}
conn_to_host = conn_to_host->next;
}
return result;
}
/*************************************************************
* Resolve the address of the server or proxy
*************************************************************/
static CURLcode resolve_server(struct Curl_easy *data,
struct connectdata *conn,
bool *async)
{
CURLcode result = CURLE_OK;
timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
/*************************************************************
* Resolve the name of the server or proxy
*************************************************************/
if(conn->bits.reuse)
/* We're reusing the connection - no need to resolve anything, and
fix_hostname() was called already in create_conn() for the re-use
case. */
*async = FALSE;
else {
/* this is a fresh connect */
int rc;
struct Curl_dns_entry *hostaddr;
#ifdef USE_UNIX_SOCKETS
if(conn->unix_domain_socket) {
/* Unix domain sockets are local. The host gets ignored, just use the
* specified domain socket address. Do not cache "DNS entries". There is
* no DNS involved and we already have the filesystem path available */
const char *path = conn->unix_domain_socket;
hostaddr = calloc(1, sizeof(struct Curl_dns_entry));
if(!hostaddr)
result = CURLE_OUT_OF_MEMORY;
else {
bool longpath = FALSE;
hostaddr->addr = Curl_unix2addr(path, &longpath,
conn->abstract_unix_socket);
if(hostaddr->addr)
hostaddr->inuse++;
else {
/* Long paths are not supported for now */
if(longpath) {
failf(data, "Unix socket path too long: '%s'", path);
result = CURLE_COULDNT_RESOLVE_HOST;
}
else
result = CURLE_OUT_OF_MEMORY;
free(hostaddr);
hostaddr = NULL;
}
}
}
else
#endif
if(!conn->bits.proxy) {
struct hostname *connhost;
if(conn->bits.conn_to_host)
connhost = &conn->conn_to_host;
else
connhost = &conn->host;
/* If not connecting via a proxy, extract the port from the URL, if it is
* there, thus overriding any defaults that might have been set above. */
if(conn->bits.conn_to_port)
conn->port = conn->conn_to_port;
else
conn->port = conn->remote_port;
/* Resolve target host right on */
rc = Curl_resolv_timeout(conn, connhost->name, (int)conn->port,
&hostaddr, timeout_ms);
if(rc == CURLRESOLV_PENDING)
*async = TRUE;
else if(rc == CURLRESOLV_TIMEDOUT)
result = CURLE_OPERATION_TIMEDOUT;
else if(!hostaddr) {
failf(data, "Couldn't resolve host '%s'", connhost->dispname);
result = CURLE_COULDNT_RESOLVE_HOST;
/* don't return yet, we need to clean up the timeout first */
}
}
else {
/* This is a proxy that hasn't been resolved yet. */
struct hostname * const host = conn->bits.socksproxy ?
&conn->socks_proxy.host : &conn->http_proxy.host;
/* resolve proxy */
rc = Curl_resolv_timeout(conn, host->name, (int)conn->port,
&hostaddr, timeout_ms);
if(rc == CURLRESOLV_PENDING)
*async = TRUE;
else if(rc == CURLRESOLV_TIMEDOUT)
result = CURLE_OPERATION_TIMEDOUT;
else if(!hostaddr) {
failf(data, "Couldn't resolve proxy '%s'", host->dispname);
result = CURLE_COULDNT_RESOLVE_PROXY;
/* don't return yet, we need to clean up the timeout first */
}
}
DEBUGASSERT(conn->dns_entry == NULL);
conn->dns_entry = hostaddr;
}
return result;
}
/*
* Cleanup the connection just allocated before we can move along and use the
* previously existing one. All relevant data is copied over and old_conn is
* ready for freeing once this function returns.
*/
static void reuse_conn(struct connectdata *old_conn,
struct connectdata *conn)
{
free_fixed_hostname(&old_conn->http_proxy.host);
free_fixed_hostname(&old_conn->socks_proxy.host);
free(old_conn->http_proxy.host.rawalloc);
free(old_conn->socks_proxy.host.rawalloc);
/* free the SSL config struct from this connection struct as this was
allocated in vain and is targeted for destruction */
Curl_free_primary_ssl_config(&old_conn->ssl_config);
Curl_free_primary_ssl_config(&old_conn->proxy_ssl_config);
conn->data = old_conn->data;
/* get the user+password information from the old_conn struct since it may
* be new for this request even when we re-use an existing connection */
conn->bits.user_passwd = old_conn->bits.user_passwd;
if(conn->bits.user_passwd) {
/* use the new user name and password though */
Curl_safefree(conn->user);
Curl_safefree(conn->passwd);
conn->user = old_conn->user;
conn->passwd = old_conn->passwd;
old_conn->user = NULL;
old_conn->passwd = NULL;
}
conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
if(conn->bits.proxy_user_passwd) {
/* use the new proxy user name and proxy password though */
Curl_safefree(conn->http_proxy.user);
Curl_safefree(conn->socks_proxy.user);
Curl_safefree(conn->http_proxy.passwd);
Curl_safefree(conn->socks_proxy.passwd);
conn->http_proxy.user = old_conn->http_proxy.user;
conn->socks_proxy.user = old_conn->socks_proxy.user;
conn->http_proxy.passwd = old_conn->http_proxy.passwd;
conn->socks_proxy.passwd = old_conn->socks_proxy.passwd;
old_conn->http_proxy.user = NULL;
old_conn->socks_proxy.user = NULL;
old_conn->http_proxy.passwd = NULL;
old_conn->socks_proxy.passwd = NULL;
}
/* host can change, when doing keepalive with a proxy or if the case is
different this time etc */
free_fixed_hostname(&conn->host);
free_fixed_hostname(&conn->conn_to_host);
Curl_safefree(conn->host.rawalloc);
Curl_safefree(conn->conn_to_host.rawalloc);
conn->host = old_conn->host;
conn->conn_to_host = old_conn->conn_to_host;
conn->conn_to_port = old_conn->conn_to_port;
conn->remote_port = old_conn->remote_port;
/* persist connection info in session handle */
Curl_persistconninfo(conn);
conn_reset_all_postponed_data(old_conn); /* free buffers */
/* re-use init */
conn->bits.reuse = TRUE; /* yes, we're re-using here */
Curl_safefree(old_conn->user);
Curl_safefree(old_conn->passwd);
Curl_safefree(old_conn->options);
Curl_safefree(old_conn->http_proxy.user);
Curl_safefree(old_conn->socks_proxy.user);
Curl_safefree(old_conn->http_proxy.passwd);
Curl_safefree(old_conn->socks_proxy.passwd);
Curl_safefree(old_conn->localdev);
Curl_llist_destroy(&old_conn->send_pipe, NULL);
Curl_llist_destroy(&old_conn->recv_pipe, NULL);
Curl_safefree(old_conn->master_buffer);
#ifdef USE_UNIX_SOCKETS
Curl_safefree(old_conn->unix_domain_socket);
#endif
}
/**
* create_conn() sets up a new connectdata struct, or re-uses an already
* existing one, and resolves host name.
*
* if this function returns CURLE_OK and *async is set to TRUE, the resolve
* response will be coming asynchronously. If *async is FALSE, the name is
* already resolved.
*
* @param data The sessionhandle pointer
* @param in_connect is set to the next connection data pointer
* @param async is set TRUE when an async DNS resolution is pending
* @see Curl_setup_conn()
*
* *NOTE* this function assigns the conn->data pointer!
*/
static CURLcode create_conn(struct Curl_easy *data,
struct connectdata **in_connect,
bool *async)
{
CURLcode result = CURLE_OK;
struct connectdata *conn;
struct connectdata *conn_temp = NULL;
bool reuse;
bool connections_available = TRUE;
bool force_reuse = FALSE;
bool waitpipe = FALSE;
size_t max_host_connections = Curl_multi_max_host_connections(data->multi);
size_t max_total_connections = Curl_multi_max_total_connections(data->multi);
*async = FALSE;
/*************************************************************
* Check input data
*************************************************************/
if(!data->change.url) {
result = CURLE_URL_MALFORMAT;
goto out;
}
/* First, split up the current URL in parts so that we can use the
parts for checking against the already present connections. In order
to not have to modify everything at once, we allocate a temporary
connection data struct and fill in for comparison purposes. */
conn = allocate_conn(data);
if(!conn) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
/* We must set the return variable as soon as possible, so that our
parent can cleanup any possible allocs we may have done before
any failure */
*in_connect = conn;
result = parseurlandfillconn(data, conn);
if(result)
goto out;
if(data->set.str[STRING_BEARER]) {
conn->oauth_bearer = strdup(data->set.str[STRING_BEARER]);
if(!conn->oauth_bearer) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
}
#ifdef USE_UNIX_SOCKETS
if(data->set.str[STRING_UNIX_SOCKET_PATH]) {
conn->unix_domain_socket = strdup(data->set.str[STRING_UNIX_SOCKET_PATH]);
if(conn->unix_domain_socket == NULL) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
conn->abstract_unix_socket = data->set.abstract_unix_socket;
}
#endif
/* After the unix socket init but before the proxy vars are used, parse and
initialize the proxy vars */
#ifndef CURL_DISABLE_PROXY
result = create_conn_helper_init_proxy(conn);
if(result)
goto out;
#endif
/*************************************************************
* If the protocol is using SSL and HTTP proxy is used, we set
* the tunnel_proxy bit.
*************************************************************/
if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy)
conn->bits.tunnel_proxy = TRUE;
/*************************************************************
* Figure out the remote port number and fix it in the URL
*************************************************************/
result = parse_remote_port(data, conn);
if(result)
goto out;
/* Check for overridden login details and set them accordingly so they
they are known when protocol->setup_connection is called! */
result = override_login(data, conn, &conn->user, &conn->passwd,
&conn->options);
if(result)
goto out;
result = set_login(conn); /* default credentials */
if(result)
goto out;
/*************************************************************
* Process the "connect to" linked list of hostname/port mappings.
* Do this after the remote port number has been fixed in the URL.
*************************************************************/
result = parse_connect_to_slist(data, conn, data->set.connect_to);
if(result)
goto out;
/*************************************************************
* IDN-fix the hostnames
*************************************************************/
result = fix_hostname(conn, &conn->host);
if(result)
goto out;
if(conn->bits.conn_to_host) {
result = fix_hostname(conn, &conn->conn_to_host);
if(result)
goto out;
}
if(conn->bits.httpproxy) {
result = fix_hostname(conn, &conn->http_proxy.host);
if(result)
goto out;
}
if(conn->bits.socksproxy) {
result = fix_hostname(conn, &conn->socks_proxy.host);
if(result)
goto out;
}
/*************************************************************
* Check whether the host and the "connect to host" are equal.
* Do this after the hostnames have been IDN-fixed.
*************************************************************/
if(conn->bits.conn_to_host &&
strcasecompare(conn->conn_to_host.name, conn->host.name)) {
conn->bits.conn_to_host = FALSE;
}
/*************************************************************
* Check whether the port and the "connect to port" are equal.
* Do this after the remote port number has been fixed in the URL.
*************************************************************/
if(conn->bits.conn_to_port && conn->conn_to_port == conn->remote_port) {
conn->bits.conn_to_port = FALSE;
}
/*************************************************************
* If the "connect to" feature is used with an HTTP proxy,
* we set the tunnel_proxy bit.
*************************************************************/
if((conn->bits.conn_to_host || conn->bits.conn_to_port) &&
conn->bits.httpproxy)
conn->bits.tunnel_proxy = TRUE;
/*************************************************************
* Setup internals depending on protocol. Needs to be done after
* we figured out what/if proxy to use.
*************************************************************/
result = setup_connection_internals(conn);
if(result)
goto out;
conn->recv[FIRSTSOCKET] = Curl_recv_plain;
conn->send[FIRSTSOCKET] = Curl_send_plain;
conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
conn->send[SECONDARYSOCKET] = Curl_send_plain;
conn->bits.tcp_fastopen = data->set.tcp_fastopen;
/***********************************************************************
* file: is a special case in that it doesn't need a network connection
***********************************************************************/
#ifndef CURL_DISABLE_FILE
if(conn->handler->flags & PROTOPT_NONETWORK) {
bool done;
/* this is supposed to be the connect function so we better at least check
that the file is present here! */
DEBUGASSERT(conn->handler->connect_it);
Curl_persistconninfo(conn);
result = conn->handler->connect_it(conn, &done);
/* Setup a "faked" transfer that'll do nothing */
if(!result) {
conn->data = data;
conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */
result = Curl_conncache_add_conn(data->state.conn_cache, conn);
if(result)
goto out;
/*
* Setup whatever necessary for a resumed transfer
*/
result = setup_range(data);
if(result) {
DEBUGASSERT(conn->handler->done);
/* we ignore the return code for the protocol-specific DONE */
(void)conn->handler->done(conn, result, FALSE);
goto out;
}
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
-1, NULL); /* no upload */
}
/* since we skip do_init() */
Curl_init_do(data, conn);
goto out;
}
#endif
/* Get a cloned copy of the SSL config situation stored in the
connection struct. But to get this going nicely, we must first make
sure that the strings in the master copy are pointing to the correct
strings in the session handle strings array!
Keep in mind that the pointers in the master copy are pointing to strings
that will be freed as part of the Curl_easy struct, but all cloned
copies will be separately allocated.
*/
data->set.ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_ORIG];
data->set.proxy_ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_PROXY];
data->set.ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_ORIG];
data->set.proxy_ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_PROXY];
data->set.ssl.primary.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
data->set.proxy_ssl.primary.random_file =
data->set.str[STRING_SSL_RANDOM_FILE];
data->set.ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
data->set.proxy_ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
data->set.ssl.primary.cipher_list =
data->set.str[STRING_SSL_CIPHER_LIST_ORIG];
data->set.proxy_ssl.primary.cipher_list =
data->set.str[STRING_SSL_CIPHER_LIST_PROXY];
data->set.ssl.primary.cipher_list13 =
data->set.str[STRING_SSL_CIPHER13_LIST_ORIG];
data->set.proxy_ssl.primary.cipher_list13 =
data->set.str[STRING_SSL_CIPHER13_LIST_PROXY];
data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_ORIG];
data->set.proxy_ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_PROXY];
data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_ORIG];
data->set.proxy_ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_PROXY];
data->set.ssl.cert = data->set.str[STRING_CERT_ORIG];
data->set.proxy_ssl.cert = data->set.str[STRING_CERT_PROXY];
data->set.ssl.cert_type = data->set.str[STRING_CERT_TYPE_ORIG];
data->set.proxy_ssl.cert_type = data->set.str[STRING_CERT_TYPE_PROXY];
data->set.ssl.key = data->set.str[STRING_KEY_ORIG];
data->set.proxy_ssl.key = data->set.str[STRING_KEY_PROXY];
data->set.ssl.key_type = data->set.str[STRING_KEY_TYPE_ORIG];
data->set.proxy_ssl.key_type = data->set.str[STRING_KEY_TYPE_PROXY];
data->set.ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_ORIG];
data->set.proxy_ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_PROXY];
data->set.ssl.primary.clientcert = data->set.str[STRING_CERT_ORIG];
data->set.proxy_ssl.primary.clientcert = data->set.str[STRING_CERT_PROXY];
#ifdef USE_TLS_SRP
data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_ORIG];
data->set.proxy_ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_PROXY];
data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_ORIG];
data->set.proxy_ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_PROXY];
#endif
if(!Curl_clone_primary_ssl_config(&data->set.ssl.primary,
&conn->ssl_config)) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
if(!Curl_clone_primary_ssl_config(&data->set.proxy_ssl.primary,
&conn->proxy_ssl_config)) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
prune_dead_connections(data);
/*************************************************************
* Check the current list of connections to see if we can
* re-use an already existing one or if we have to create a
* new one.
*************************************************************/
DEBUGASSERT(conn->user);
DEBUGASSERT(conn->passwd);
/* reuse_fresh is TRUE if we are told to use a new connection by force, but
we only acknowledge this option if this is not a re-used connection
already (which happens due to follow-location or during a HTTP
authentication phase). */
if(data->set.reuse_fresh && !data->state.this_is_a_follow)
reuse = FALSE;
else
reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse, &waitpipe);
/* If we found a reusable connection that is now marked as in use, we may
still want to open a new connection if we are pipelining. */
if(reuse && !force_reuse && IsPipeliningPossible(data, conn_temp)) {
size_t pipelen = conn_temp->send_pipe.size + conn_temp->recv_pipe.size;
if(pipelen > 0) {
infof(data, "Found connection %ld, with requests in the pipe (%zu)\n",
conn_temp->connection_id, pipelen);
if(Curl_conncache_bundle_size(conn_temp) < max_host_connections &&
Curl_conncache_size(data) < max_total_connections) {
/* We want a new connection anyway */
reuse = FALSE;
infof(data, "We can reuse, but we want a new connection anyway\n");
Curl_conncache_return_conn(conn_temp);
}
}
}
if(reuse) {
/*
* We already have a connection for this, we got the former connection
* in the conn_temp variable and thus we need to cleanup the one we
* just allocated before we can move along and use the previously
* existing one.
*/
reuse_conn(conn, conn_temp);
#ifdef USE_SSL
free(conn->ssl_extra);
#endif
free(conn); /* we don't need this anymore */
conn = conn_temp;
*in_connect = conn;
infof(data, "Re-using existing connection! (#%ld) with %s %s\n",
conn->connection_id,
conn->bits.proxy?"proxy":"host",
conn->socks_proxy.host.name ? conn->socks_proxy.host.dispname :
conn->http_proxy.host.name ? conn->http_proxy.host.dispname :
conn->host.dispname);
}
else {
/* We have decided that we want a new connection. However, we may not
be able to do that if we have reached the limit of how many
connections we are allowed to open. */
if(conn->handler->flags & PROTOPT_ALPN_NPN) {
/* The protocol wants it, so set the bits if enabled in the easy handle
(default) */
if(data->set.ssl_enable_alpn)
conn->bits.tls_enable_alpn = TRUE;
if(data->set.ssl_enable_npn)
conn->bits.tls_enable_npn = TRUE;
}
if(waitpipe)
/* There is a connection that *might* become usable for pipelining
"soon", and we wait for that */
connections_available = FALSE;
else {
/* this gets a lock on the conncache */
struct connectbundle *bundle =
Curl_conncache_find_bundle(conn, data->state.conn_cache);
if(max_host_connections > 0 && bundle &&
(bundle->num_connections >= max_host_connections)) {
struct connectdata *conn_candidate;
/* The bundle is full. Extract the oldest connection. */
conn_candidate = Curl_conncache_extract_bundle(data, bundle);
Curl_conncache_unlock(conn);
if(conn_candidate)
(void)Curl_disconnect(data, conn_candidate,
/* dead_connection */ FALSE);
else {
infof(data, "No more connections allowed to host: %zu\n",
max_host_connections);
connections_available = FALSE;
}
}
else
Curl_conncache_unlock(conn);
}
if(connections_available &&
(max_total_connections > 0) &&
(Curl_conncache_size(data) >= max_total_connections)) {
struct connectdata *conn_candidate;
/* The cache is full. Let's see if we can kill a connection. */
conn_candidate = Curl_conncache_extract_oldest(data);
if(conn_candidate)
(void)Curl_disconnect(data, conn_candidate,
/* dead_connection */ FALSE);
else {
infof(data, "No connections available in cache\n");
connections_available = FALSE;
}
}
if(!connections_available) {
infof(data, "No connections available.\n");
conn_free(conn);
*in_connect = NULL;
result = CURLE_NO_CONNECTION_AVAILABLE;
goto out;
}
else {
/*
* This is a brand new connection, so let's store it in the connection
* cache of ours!
*/
result = Curl_conncache_add_conn(data->state.conn_cache, conn);
if(result)
goto out;
}
#if defined(USE_NTLM)
/* If NTLM is requested in a part of this connection, make sure we don't
assume the state is fine as this is a fresh connection and NTLM is
connection based. */
if((data->state.authhost.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
data->state.authhost.done) {
infof(data, "NTLM picked AND auth done set, clear picked!\n");
data->state.authhost.picked = CURLAUTH_NONE;
data->state.authhost.done = FALSE;
}
if((data->state.authproxy.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
data->state.authproxy.done) {
infof(data, "NTLM-proxy picked AND auth done set, clear picked!\n");
data->state.authproxy.picked = CURLAUTH_NONE;
data->state.authproxy.done = FALSE;
}
#endif
}
/* Setup and init stuff before DO starts, in preparing for the transfer. */
Curl_init_do(data, conn);
/*
* Setup whatever necessary for a resumed transfer
*/
result = setup_range(data);
if(result)
goto out;
/* Continue connectdata initialization here. */
/*
* Inherit the proper values from the urldata struct AFTER we have arranged
* the persistent connection stuff
*/
conn->seek_func = data->set.seek_func;
conn->seek_client = data->set.seek_client;
/*************************************************************
* Resolve the address of the server or proxy
*************************************************************/
result = resolve_server(data, conn, async);
out:
return result;
}
/* Curl_setup_conn() is called after the name resolve initiated in
* create_conn() is all done.
*
* Curl_setup_conn() also handles reused connections
*
* conn->data MUST already have been setup fine (in create_conn)
*/
CURLcode Curl_setup_conn(struct connectdata *conn,
bool *protocol_done)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
Curl_pgrsTime(data, TIMER_NAMELOOKUP);
if(conn->handler->flags & PROTOPT_NONETWORK) {
/* nothing to setup when not using a network */
*protocol_done = TRUE;
return result;
}
*protocol_done = FALSE; /* default to not done */
/* set proxy_connect_closed to false unconditionally already here since it
is used strictly to provide extra information to a parent function in the
case of proxy CONNECT failures and we must make sure we don't have it
lingering set from a previous invoke */
conn->bits.proxy_connect_closed = FALSE;
/*
* Set user-agent. Used for HTTP, but since we can attempt to tunnel
* basically anything through a http proxy we can't limit this based on
* protocol.
*/
if(data->set.str[STRING_USERAGENT]) {
Curl_safefree(conn->allocptr.uagent);
conn->allocptr.uagent =
aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
if(!conn->allocptr.uagent)
return CURLE_OUT_OF_MEMORY;
}
data->req.headerbytecount = 0;
#ifdef CURL_DO_LINEEND_CONV
data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
#endif /* CURL_DO_LINEEND_CONV */
/* set start time here for timeout purposes in the connect procedure, it
is later set again for the progress meter purpose */
conn->now = Curl_now();
if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
conn->bits.tcpconnect[FIRSTSOCKET] = FALSE;
result = Curl_connecthost(conn, conn->dns_entry);
if(result)
return result;
}
else {
Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */
Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */
conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
*protocol_done = TRUE;
Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]);
Curl_verboseconnect(conn);
}
conn->now = Curl_now(); /* time this *after* the connect is done, we set
this here perhaps a second time */
return result;
}
CURLcode Curl_connect(struct Curl_easy *data,
struct connectdata **in_connect,
bool *asyncp,
bool *protocol_done)
{
CURLcode result;
*asyncp = FALSE; /* assume synchronous resolves by default */
/* init the single-transfer specific data */
Curl_free_request_state(data);
memset(&data->req, 0, sizeof(struct SingleRequest));
data->req.maxdownload = -1;
/* call the stuff that needs to be called */
result = create_conn(data, in_connect, asyncp);
if(!result) {
if(CONN_INUSE(*in_connect))
/* pipelining */
*protocol_done = TRUE;
else if(!*asyncp) {
/* DNS resolution is done: that's either because this is a reused
connection, in which case DNS was unnecessary, or because DNS
really did finish already (synch resolver/fast async resolve) */
result = Curl_setup_conn(*in_connect, protocol_done);
}
}
if(result == CURLE_NO_CONNECTION_AVAILABLE) {
*in_connect = NULL;
return result;
}
else if(result && *in_connect) {
/* We're not allowed to return failure with memory left allocated in the
connectdata struct, free those here */
Curl_disconnect(data, *in_connect, TRUE);
*in_connect = NULL; /* return a NULL */
}
return result;
}
/*
* Curl_init_do() inits the readwrite session. This is inited each time (in
* the DO function before the protocol-specific DO functions are invoked) for
* a transfer, sometimes multiple times on the same Curl_easy. Make sure
* nothing in here depends on stuff that are setup dynamically for the
* transfer.
*
* Allow this function to get called with 'conn' set to NULL.
*/
CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn)
{
struct SingleRequest *k = &data->req;
if(conn) {
conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to
use */
/* if the protocol used doesn't support wildcards, switch it off */
if(data->state.wildcardmatch &&
!(conn->handler->flags & PROTOPT_WILDCARD))
data->state.wildcardmatch = FALSE;
}
data->state.done = FALSE; /* *_done() is not called yet */
data->state.expect100header = FALSE;
if(data->set.opt_no_body)
/* in HTTP lingo, no body means using the HEAD request... */
data->set.httpreq = HTTPREQ_HEAD;
else if(HTTPREQ_HEAD == data->set.httpreq)
/* ... but if unset there really is no perfect method that is the
"opposite" of HEAD but in reality most people probably think GET
then. The important thing is that we can't let it remain HEAD if the
opt_no_body is set FALSE since then we'll behave wrong when getting
HTTP. */
data->set.httpreq = HTTPREQ_GET;
k->start = Curl_now(); /* start time */
k->now = k->start; /* current time is now */
k->header = TRUE; /* assume header */
k->bytecount = 0;
k->buf = data->state.buffer;
k->hbufp = data->state.headerbuff;
k->ignorebody = FALSE;
Curl_speedinit(data);
Curl_pgrsSetUploadCounter(data, 0);
Curl_pgrsSetDownloadCounter(data, 0);
return CURLE_OK;
}
/*
* get_protocol_family()
*
* This is used to return the protocol family for a given protocol.
*
* Parameters:
*
* protocol [in] - A single bit protocol identifier such as HTTP or HTTPS.
*
* Returns the family as a single bit protocol identifier.
*/
static unsigned int get_protocol_family(unsigned int protocol)
{
unsigned int family;
switch(protocol) {
case CURLPROTO_HTTP:
case CURLPROTO_HTTPS:
family = CURLPROTO_HTTP;
break;
case CURLPROTO_FTP:
case CURLPROTO_FTPS:
family = CURLPROTO_FTP;
break;
case CURLPROTO_SCP:
family = CURLPROTO_SCP;
break;
case CURLPROTO_SFTP:
family = CURLPROTO_SFTP;
break;
case CURLPROTO_TELNET:
family = CURLPROTO_TELNET;
break;
case CURLPROTO_LDAP:
case CURLPROTO_LDAPS:
family = CURLPROTO_LDAP;
break;
case CURLPROTO_DICT:
family = CURLPROTO_DICT;
break;
case CURLPROTO_FILE:
family = CURLPROTO_FILE;
break;
case CURLPROTO_TFTP:
family = CURLPROTO_TFTP;
break;
case CURLPROTO_IMAP:
case CURLPROTO_IMAPS:
family = CURLPROTO_IMAP;
break;
case CURLPROTO_POP3:
case CURLPROTO_POP3S:
family = CURLPROTO_POP3;
break;
case CURLPROTO_SMTP:
case CURLPROTO_SMTPS:
family = CURLPROTO_SMTP;
break;
case CURLPROTO_RTSP:
family = CURLPROTO_RTSP;
break;
case CURLPROTO_RTMP:
case CURLPROTO_RTMPS:
family = CURLPROTO_RTMP;
break;
case CURLPROTO_RTMPT:
case CURLPROTO_RTMPTS:
family = CURLPROTO_RTMPT;
break;
case CURLPROTO_RTMPE:
family = CURLPROTO_RTMPE;
break;
case CURLPROTO_RTMPTE:
family = CURLPROTO_RTMPTE;
break;
case CURLPROTO_GOPHER:
family = CURLPROTO_GOPHER;
break;
case CURLPROTO_SMB:
case CURLPROTO_SMBS:
family = CURLPROTO_SMB;
break;
default:
family = 0;
break;
}
return family;
}
/*
* Wrapper to call functions in Curl_conncache_foreach()
*
* Returns always 0.
*/
static int conn_upkeep(struct connectdata *conn,
void *param)
{
/* Param is unused. */
(void)param;
if(conn->handler->connection_check) {
/* Do a protocol-specific keepalive check on the connection. */
conn->handler->connection_check(conn, CONNCHECK_KEEPALIVE);
}
return 0; /* continue iteration */
}
CURLcode Curl_upkeep(struct conncache *conn_cache,
void *data)
{
/* Loop over every connection and make connection alive. */
Curl_conncache_foreach(data,
conn_cache,
data,
conn_upkeep);
return CURLE_OK;
}
| ./CrossVul/dataset_final_sorted/CWE-416/c/good_375_0 |
crossvul-cpp_data_bad_388_4 | // SPDX-License-Identifier: GPL-2.0
/*
* mm/debug.c
*
* mm/ specific debug routines.
*
*/
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/trace_events.h>
#include <linux/memcontrol.h>
#include <trace/events/mmflags.h>
#include <linux/migrate.h>
#include <linux/page_owner.h>
#include "internal.h"
char *migrate_reason_names[MR_TYPES] = {
"compaction",
"memory_failure",
"memory_hotplug",
"syscall_or_cpuset",
"mempolicy_mbind",
"numa_misplaced",
"cma",
};
const struct trace_print_flags pageflag_names[] = {
__def_pageflag_names,
{0, NULL}
};
const struct trace_print_flags gfpflag_names[] = {
__def_gfpflag_names,
{0, NULL}
};
const struct trace_print_flags vmaflag_names[] = {
__def_vmaflag_names,
{0, NULL}
};
void __dump_page(struct page *page, const char *reason)
{
bool page_poisoned = PagePoisoned(page);
int mapcount;
/*
* If struct page is poisoned don't access Page*() functions as that
* leads to recursive loop. Page*() check for poisoned pages, and calls
* dump_page() when detected.
*/
if (page_poisoned) {
pr_emerg("page:%px is uninitialized and poisoned", page);
goto hex_only;
}
/*
* Avoid VM_BUG_ON() in page_mapcount().
* page->_mapcount space in struct page is used by sl[aou]b pages to
* encode own info.
*/
mapcount = PageSlab(page) ? 0 : page_mapcount(page);
pr_emerg("page:%px count:%d mapcount:%d mapping:%px index:%#lx",
page, page_ref_count(page), mapcount,
page->mapping, page_to_pgoff(page));
if (PageCompound(page))
pr_cont(" compound_mapcount: %d", compound_mapcount(page));
pr_cont("\n");
BUILD_BUG_ON(ARRAY_SIZE(pageflag_names) != __NR_PAGEFLAGS + 1);
pr_emerg("flags: %#lx(%pGp)\n", page->flags, &page->flags);
hex_only:
print_hex_dump(KERN_ALERT, "raw: ", DUMP_PREFIX_NONE, 32,
sizeof(unsigned long), page,
sizeof(struct page), false);
if (reason)
pr_alert("page dumped because: %s\n", reason);
#ifdef CONFIG_MEMCG
if (!page_poisoned && page->mem_cgroup)
pr_alert("page->mem_cgroup:%px\n", page->mem_cgroup);
#endif
}
void dump_page(struct page *page, const char *reason)
{
__dump_page(page, reason);
dump_page_owner(page);
}
EXPORT_SYMBOL(dump_page);
#ifdef CONFIG_DEBUG_VM
void dump_vma(const struct vm_area_struct *vma)
{
pr_emerg("vma %px start %px end %px\n"
"next %px prev %px mm %px\n"
"prot %lx anon_vma %px vm_ops %px\n"
"pgoff %lx file %px private_data %px\n"
"flags: %#lx(%pGv)\n",
vma, (void *)vma->vm_start, (void *)vma->vm_end, vma->vm_next,
vma->vm_prev, vma->vm_mm,
(unsigned long)pgprot_val(vma->vm_page_prot),
vma->anon_vma, vma->vm_ops, vma->vm_pgoff,
vma->vm_file, vma->vm_private_data,
vma->vm_flags, &vma->vm_flags);
}
EXPORT_SYMBOL(dump_vma);
void dump_mm(const struct mm_struct *mm)
{
pr_emerg("mm %px mmap %px seqnum %d task_size %lu\n"
#ifdef CONFIG_MMU
"get_unmapped_area %px\n"
#endif
"mmap_base %lu mmap_legacy_base %lu highest_vm_end %lu\n"
"pgd %px mm_users %d mm_count %d pgtables_bytes %lu map_count %d\n"
"hiwater_rss %lx hiwater_vm %lx total_vm %lx locked_vm %lx\n"
"pinned_vm %lx data_vm %lx exec_vm %lx stack_vm %lx\n"
"start_code %lx end_code %lx start_data %lx end_data %lx\n"
"start_brk %lx brk %lx start_stack %lx\n"
"arg_start %lx arg_end %lx env_start %lx env_end %lx\n"
"binfmt %px flags %lx core_state %px\n"
#ifdef CONFIG_AIO
"ioctx_table %px\n"
#endif
#ifdef CONFIG_MEMCG
"owner %px "
#endif
"exe_file %px\n"
#ifdef CONFIG_MMU_NOTIFIER
"mmu_notifier_mm %px\n"
#endif
#ifdef CONFIG_NUMA_BALANCING
"numa_next_scan %lu numa_scan_offset %lu numa_scan_seq %d\n"
#endif
"tlb_flush_pending %d\n"
"def_flags: %#lx(%pGv)\n",
mm, mm->mmap, mm->vmacache_seqnum, mm->task_size,
#ifdef CONFIG_MMU
mm->get_unmapped_area,
#endif
mm->mmap_base, mm->mmap_legacy_base, mm->highest_vm_end,
mm->pgd, atomic_read(&mm->mm_users),
atomic_read(&mm->mm_count),
mm_pgtables_bytes(mm),
mm->map_count,
mm->hiwater_rss, mm->hiwater_vm, mm->total_vm, mm->locked_vm,
mm->pinned_vm, mm->data_vm, mm->exec_vm, mm->stack_vm,
mm->start_code, mm->end_code, mm->start_data, mm->end_data,
mm->start_brk, mm->brk, mm->start_stack,
mm->arg_start, mm->arg_end, mm->env_start, mm->env_end,
mm->binfmt, mm->flags, mm->core_state,
#ifdef CONFIG_AIO
mm->ioctx_table,
#endif
#ifdef CONFIG_MEMCG
mm->owner,
#endif
mm->exe_file,
#ifdef CONFIG_MMU_NOTIFIER
mm->mmu_notifier_mm,
#endif
#ifdef CONFIG_NUMA_BALANCING
mm->numa_next_scan, mm->numa_scan_offset, mm->numa_scan_seq,
#endif
atomic_read(&mm->tlb_flush_pending),
mm->def_flags, &mm->def_flags
);
}
#endif /* CONFIG_DEBUG_VM */
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_388_4 |
crossvul-cpp_data_bad_574_0 | /*
* linux/drivers/block/loop.c
*
* Written by Theodore Ts'o, 3/29/93
*
* Copyright 1993 by Theodore Ts'o. Redistribution of this file is
* permitted under the GNU General Public License.
*
* DES encryption plus some minor changes by Werner Almesberger, 30-MAY-1993
* more DES encryption plus IDEA encryption by Nicholas J. Leon, June 20, 1996
*
* Modularized and updated for 1.1.16 kernel - Mitch Dsouza 28th May 1994
* Adapted for 1.3.59 kernel - Andries Brouwer, 1 Feb 1996
*
* Fixed do_loop_request() re-entrancy - Vincent.Renardias@waw.com Mar 20, 1997
*
* Added devfs support - Richard Gooch <rgooch@atnf.csiro.au> 16-Jan-1998
*
* Handle sparse backing files correctly - Kenn Humborg, Jun 28, 1998
*
* Loadable modules and other fixes by AK, 1998
*
* Make real block number available to downstream transfer functions, enables
* CBC (and relatives) mode encryption requiring unique IVs per data block.
* Reed H. Petty, rhp@draper.net
*
* Maximum number of loop devices now dynamic via max_loop module parameter.
* Russell Kroll <rkroll@exploits.org> 19990701
*
* Maximum number of loop devices when compiled-in now selectable by passing
* max_loop=<1-255> to the kernel on boot.
* Erik I. Bolsø, <eriki@himolde.no>, Oct 31, 1999
*
* Completely rewrite request handling to be make_request_fn style and
* non blocking, pushing work to a helper thread. Lots of fixes from
* Al Viro too.
* Jens Axboe <axboe@suse.de>, Nov 2000
*
* Support up to 256 loop devices
* Heinz Mauelshagen <mge@sistina.com>, Feb 2002
*
* Support for falling back on the write file operation when the address space
* operations write_begin is not available on the backing filesystem.
* Anton Altaparmakov, 16 Feb 2005
*
* Still To Fix:
* - Advisory locking is ignored here.
* - Should use an own CAP_* category instead of CAP_SYS_ADMIN
*
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/stat.h>
#include <linux/errno.h>
#include <linux/major.h>
#include <linux/wait.h>
#include <linux/blkdev.h>
#include <linux/blkpg.h>
#include <linux/init.h>
#include <linux/swap.h>
#include <linux/slab.h>
#include <linux/compat.h>
#include <linux/suspend.h>
#include <linux/freezer.h>
#include <linux/mutex.h>
#include <linux/writeback.h>
#include <linux/completion.h>
#include <linux/highmem.h>
#include <linux/kthread.h>
#include <linux/splice.h>
#include <linux/sysfs.h>
#include <linux/miscdevice.h>
#include <linux/falloc.h>
#include <linux/uio.h>
#include "loop.h"
#include <linux/uaccess.h>
static DEFINE_IDR(loop_index_idr);
static DEFINE_MUTEX(loop_index_mutex);
static int max_part;
static int part_shift;
static int transfer_xor(struct loop_device *lo, int cmd,
struct page *raw_page, unsigned raw_off,
struct page *loop_page, unsigned loop_off,
int size, sector_t real_block)
{
char *raw_buf = kmap_atomic(raw_page) + raw_off;
char *loop_buf = kmap_atomic(loop_page) + loop_off;
char *in, *out, *key;
int i, keysize;
if (cmd == READ) {
in = raw_buf;
out = loop_buf;
} else {
in = loop_buf;
out = raw_buf;
}
key = lo->lo_encrypt_key;
keysize = lo->lo_encrypt_key_size;
for (i = 0; i < size; i++)
*out++ = *in++ ^ key[(i & 511) % keysize];
kunmap_atomic(loop_buf);
kunmap_atomic(raw_buf);
cond_resched();
return 0;
}
static int xor_init(struct loop_device *lo, const struct loop_info64 *info)
{
if (unlikely(info->lo_encrypt_key_size <= 0))
return -EINVAL;
return 0;
}
static struct loop_func_table none_funcs = {
.number = LO_CRYPT_NONE,
};
static struct loop_func_table xor_funcs = {
.number = LO_CRYPT_XOR,
.transfer = transfer_xor,
.init = xor_init
};
/* xfer_funcs[0] is special - its release function is never called */
static struct loop_func_table *xfer_funcs[MAX_LO_CRYPT] = {
&none_funcs,
&xor_funcs
};
static loff_t get_size(loff_t offset, loff_t sizelimit, struct file *file)
{
loff_t loopsize;
/* Compute loopsize in bytes */
loopsize = i_size_read(file->f_mapping->host);
if (offset > 0)
loopsize -= offset;
/* offset is beyond i_size, weird but possible */
if (loopsize < 0)
return 0;
if (sizelimit > 0 && sizelimit < loopsize)
loopsize = sizelimit;
/*
* Unfortunately, if we want to do I/O on the device,
* the number of 512-byte sectors has to fit into a sector_t.
*/
return loopsize >> 9;
}
static loff_t get_loop_size(struct loop_device *lo, struct file *file)
{
return get_size(lo->lo_offset, lo->lo_sizelimit, file);
}
static void __loop_update_dio(struct loop_device *lo, bool dio)
{
struct file *file = lo->lo_backing_file;
struct address_space *mapping = file->f_mapping;
struct inode *inode = mapping->host;
unsigned short sb_bsize = 0;
unsigned dio_align = 0;
bool use_dio;
if (inode->i_sb->s_bdev) {
sb_bsize = bdev_logical_block_size(inode->i_sb->s_bdev);
dio_align = sb_bsize - 1;
}
/*
* We support direct I/O only if lo_offset is aligned with the
* logical I/O size of backing device, and the logical block
* size of loop is bigger than the backing device's and the loop
* needn't transform transfer.
*
* TODO: the above condition may be loosed in the future, and
* direct I/O may be switched runtime at that time because most
* of requests in sane applications should be PAGE_SIZE aligned
*/
if (dio) {
if (queue_logical_block_size(lo->lo_queue) >= sb_bsize &&
!(lo->lo_offset & dio_align) &&
mapping->a_ops->direct_IO &&
!lo->transfer)
use_dio = true;
else
use_dio = false;
} else {
use_dio = false;
}
if (lo->use_dio == use_dio)
return;
/* flush dirty pages before changing direct IO */
vfs_fsync(file, 0);
/*
* The flag of LO_FLAGS_DIRECT_IO is handled similarly with
* LO_FLAGS_READ_ONLY, both are set from kernel, and losetup
* will get updated by ioctl(LOOP_GET_STATUS)
*/
blk_mq_freeze_queue(lo->lo_queue);
lo->use_dio = use_dio;
if (use_dio) {
queue_flag_clear_unlocked(QUEUE_FLAG_NOMERGES, lo->lo_queue);
lo->lo_flags |= LO_FLAGS_DIRECT_IO;
} else {
queue_flag_set_unlocked(QUEUE_FLAG_NOMERGES, lo->lo_queue);
lo->lo_flags &= ~LO_FLAGS_DIRECT_IO;
}
blk_mq_unfreeze_queue(lo->lo_queue);
}
static int
figure_loop_size(struct loop_device *lo, loff_t offset, loff_t sizelimit)
{
loff_t size = get_size(offset, sizelimit, lo->lo_backing_file);
sector_t x = (sector_t)size;
struct block_device *bdev = lo->lo_device;
if (unlikely((loff_t)x != size))
return -EFBIG;
if (lo->lo_offset != offset)
lo->lo_offset = offset;
if (lo->lo_sizelimit != sizelimit)
lo->lo_sizelimit = sizelimit;
set_capacity(lo->lo_disk, x);
bd_set_size(bdev, (loff_t)get_capacity(bdev->bd_disk) << 9);
/* let user-space know about the new size */
kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
return 0;
}
static inline int
lo_do_transfer(struct loop_device *lo, int cmd,
struct page *rpage, unsigned roffs,
struct page *lpage, unsigned loffs,
int size, sector_t rblock)
{
int ret;
ret = lo->transfer(lo, cmd, rpage, roffs, lpage, loffs, size, rblock);
if (likely(!ret))
return 0;
printk_ratelimited(KERN_ERR
"loop: Transfer error at byte offset %llu, length %i.\n",
(unsigned long long)rblock << 9, size);
return ret;
}
static int lo_write_bvec(struct file *file, struct bio_vec *bvec, loff_t *ppos)
{
struct iov_iter i;
ssize_t bw;
iov_iter_bvec(&i, ITER_BVEC, bvec, 1, bvec->bv_len);
file_start_write(file);
bw = vfs_iter_write(file, &i, ppos, 0);
file_end_write(file);
if (likely(bw == bvec->bv_len))
return 0;
printk_ratelimited(KERN_ERR
"loop: Write error at byte offset %llu, length %i.\n",
(unsigned long long)*ppos, bvec->bv_len);
if (bw >= 0)
bw = -EIO;
return bw;
}
static int lo_write_simple(struct loop_device *lo, struct request *rq,
loff_t pos)
{
struct bio_vec bvec;
struct req_iterator iter;
int ret = 0;
rq_for_each_segment(bvec, rq, iter) {
ret = lo_write_bvec(lo->lo_backing_file, &bvec, &pos);
if (ret < 0)
break;
cond_resched();
}
return ret;
}
/*
* This is the slow, transforming version that needs to double buffer the
* data as it cannot do the transformations in place without having direct
* access to the destination pages of the backing file.
*/
static int lo_write_transfer(struct loop_device *lo, struct request *rq,
loff_t pos)
{
struct bio_vec bvec, b;
struct req_iterator iter;
struct page *page;
int ret = 0;
page = alloc_page(GFP_NOIO);
if (unlikely(!page))
return -ENOMEM;
rq_for_each_segment(bvec, rq, iter) {
ret = lo_do_transfer(lo, WRITE, page, 0, bvec.bv_page,
bvec.bv_offset, bvec.bv_len, pos >> 9);
if (unlikely(ret))
break;
b.bv_page = page;
b.bv_offset = 0;
b.bv_len = bvec.bv_len;
ret = lo_write_bvec(lo->lo_backing_file, &b, &pos);
if (ret < 0)
break;
}
__free_page(page);
return ret;
}
static int lo_read_simple(struct loop_device *lo, struct request *rq,
loff_t pos)
{
struct bio_vec bvec;
struct req_iterator iter;
struct iov_iter i;
ssize_t len;
rq_for_each_segment(bvec, rq, iter) {
iov_iter_bvec(&i, ITER_BVEC, &bvec, 1, bvec.bv_len);
len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
if (len < 0)
return len;
flush_dcache_page(bvec.bv_page);
if (len != bvec.bv_len) {
struct bio *bio;
__rq_for_each_bio(bio, rq)
zero_fill_bio(bio);
break;
}
cond_resched();
}
return 0;
}
static int lo_read_transfer(struct loop_device *lo, struct request *rq,
loff_t pos)
{
struct bio_vec bvec, b;
struct req_iterator iter;
struct iov_iter i;
struct page *page;
ssize_t len;
int ret = 0;
page = alloc_page(GFP_NOIO);
if (unlikely(!page))
return -ENOMEM;
rq_for_each_segment(bvec, rq, iter) {
loff_t offset = pos;
b.bv_page = page;
b.bv_offset = 0;
b.bv_len = bvec.bv_len;
iov_iter_bvec(&i, ITER_BVEC, &b, 1, b.bv_len);
len = vfs_iter_read(lo->lo_backing_file, &i, &pos, 0);
if (len < 0) {
ret = len;
goto out_free_page;
}
ret = lo_do_transfer(lo, READ, page, 0, bvec.bv_page,
bvec.bv_offset, len, offset >> 9);
if (ret)
goto out_free_page;
flush_dcache_page(bvec.bv_page);
if (len != bvec.bv_len) {
struct bio *bio;
__rq_for_each_bio(bio, rq)
zero_fill_bio(bio);
break;
}
}
ret = 0;
out_free_page:
__free_page(page);
return ret;
}
static int lo_discard(struct loop_device *lo, struct request *rq, loff_t pos)
{
/*
* We use punch hole to reclaim the free space used by the
* image a.k.a. discard. However we do not support discard if
* encryption is enabled, because it may give an attacker
* useful information.
*/
struct file *file = lo->lo_backing_file;
int mode = FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE;
int ret;
if ((!file->f_op->fallocate) || lo->lo_encrypt_key_size) {
ret = -EOPNOTSUPP;
goto out;
}
ret = file->f_op->fallocate(file, mode, pos, blk_rq_bytes(rq));
if (unlikely(ret && ret != -EINVAL && ret != -EOPNOTSUPP))
ret = -EIO;
out:
return ret;
}
static int lo_req_flush(struct loop_device *lo, struct request *rq)
{
struct file *file = lo->lo_backing_file;
int ret = vfs_fsync(file, 0);
if (unlikely(ret && ret != -EINVAL))
ret = -EIO;
return ret;
}
static void lo_complete_rq(struct request *rq)
{
struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
if (unlikely(req_op(cmd->rq) == REQ_OP_READ && cmd->use_aio &&
cmd->ret >= 0 && cmd->ret < blk_rq_bytes(cmd->rq))) {
struct bio *bio = cmd->rq->bio;
bio_advance(bio, cmd->ret);
zero_fill_bio(bio);
}
blk_mq_end_request(rq, cmd->ret < 0 ? BLK_STS_IOERR : BLK_STS_OK);
}
static void lo_rw_aio_do_completion(struct loop_cmd *cmd)
{
if (!atomic_dec_and_test(&cmd->ref))
return;
kfree(cmd->bvec);
cmd->bvec = NULL;
blk_mq_complete_request(cmd->rq);
}
static void lo_rw_aio_complete(struct kiocb *iocb, long ret, long ret2)
{
struct loop_cmd *cmd = container_of(iocb, struct loop_cmd, iocb);
if (cmd->css)
css_put(cmd->css);
cmd->ret = ret;
lo_rw_aio_do_completion(cmd);
}
static int lo_rw_aio(struct loop_device *lo, struct loop_cmd *cmd,
loff_t pos, bool rw)
{
struct iov_iter iter;
struct bio_vec *bvec;
struct request *rq = cmd->rq;
struct bio *bio = rq->bio;
struct file *file = lo->lo_backing_file;
unsigned int offset;
int segments = 0;
int ret;
if (rq->bio != rq->biotail) {
struct req_iterator iter;
struct bio_vec tmp;
__rq_for_each_bio(bio, rq)
segments += bio_segments(bio);
bvec = kmalloc(sizeof(struct bio_vec) * segments, GFP_NOIO);
if (!bvec)
return -EIO;
cmd->bvec = bvec;
/*
* The bios of the request may be started from the middle of
* the 'bvec' because of bio splitting, so we can't directly
* copy bio->bi_iov_vec to new bvec. The rq_for_each_segment
* API will take care of all details for us.
*/
rq_for_each_segment(tmp, rq, iter) {
*bvec = tmp;
bvec++;
}
bvec = cmd->bvec;
offset = 0;
} else {
/*
* Same here, this bio may be started from the middle of the
* 'bvec' because of bio splitting, so offset from the bvec
* must be passed to iov iterator
*/
offset = bio->bi_iter.bi_bvec_done;
bvec = __bvec_iter_bvec(bio->bi_io_vec, bio->bi_iter);
segments = bio_segments(bio);
}
atomic_set(&cmd->ref, 2);
iov_iter_bvec(&iter, ITER_BVEC | rw, bvec,
segments, blk_rq_bytes(rq));
iter.iov_offset = offset;
cmd->iocb.ki_pos = pos;
cmd->iocb.ki_filp = file;
cmd->iocb.ki_complete = lo_rw_aio_complete;
cmd->iocb.ki_flags = IOCB_DIRECT;
if (cmd->css)
kthread_associate_blkcg(cmd->css);
if (rw == WRITE)
ret = call_write_iter(file, &cmd->iocb, &iter);
else
ret = call_read_iter(file, &cmd->iocb, &iter);
lo_rw_aio_do_completion(cmd);
kthread_associate_blkcg(NULL);
if (ret != -EIOCBQUEUED)
cmd->iocb.ki_complete(&cmd->iocb, ret, 0);
return 0;
}
static int do_req_filebacked(struct loop_device *lo, struct request *rq)
{
struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
loff_t pos = ((loff_t) blk_rq_pos(rq) << 9) + lo->lo_offset;
/*
* lo_write_simple and lo_read_simple should have been covered
* by io submit style function like lo_rw_aio(), one blocker
* is that lo_read_simple() need to call flush_dcache_page after
* the page is written from kernel, and it isn't easy to handle
* this in io submit style function which submits all segments
* of the req at one time. And direct read IO doesn't need to
* run flush_dcache_page().
*/
switch (req_op(rq)) {
case REQ_OP_FLUSH:
return lo_req_flush(lo, rq);
case REQ_OP_DISCARD:
case REQ_OP_WRITE_ZEROES:
return lo_discard(lo, rq, pos);
case REQ_OP_WRITE:
if (lo->transfer)
return lo_write_transfer(lo, rq, pos);
else if (cmd->use_aio)
return lo_rw_aio(lo, cmd, pos, WRITE);
else
return lo_write_simple(lo, rq, pos);
case REQ_OP_READ:
if (lo->transfer)
return lo_read_transfer(lo, rq, pos);
else if (cmd->use_aio)
return lo_rw_aio(lo, cmd, pos, READ);
else
return lo_read_simple(lo, rq, pos);
default:
WARN_ON_ONCE(1);
return -EIO;
break;
}
}
static inline void loop_update_dio(struct loop_device *lo)
{
__loop_update_dio(lo, io_is_direct(lo->lo_backing_file) |
lo->use_dio);
}
static void loop_reread_partitions(struct loop_device *lo,
struct block_device *bdev)
{
int rc;
/*
* bd_mutex has been held already in release path, so don't
* acquire it if this function is called in such case.
*
* If the reread partition isn't from release path, lo_refcnt
* must be at least one and it can only become zero when the
* current holder is released.
*/
if (!atomic_read(&lo->lo_refcnt))
rc = __blkdev_reread_part(bdev);
else
rc = blkdev_reread_part(bdev);
if (rc)
pr_warn("%s: partition scan of loop%d (%s) failed (rc=%d)\n",
__func__, lo->lo_number, lo->lo_file_name, rc);
}
/*
* loop_change_fd switched the backing store of a loopback device to
* a new file. This is useful for operating system installers to free up
* the original file and in High Availability environments to switch to
* an alternative location for the content in case of server meltdown.
* This can only work if the loop device is used read-only, and if the
* new backing store is the same size and type as the old backing store.
*/
static int loop_change_fd(struct loop_device *lo, struct block_device *bdev,
unsigned int arg)
{
struct file *file, *old_file;
struct inode *inode;
int error;
error = -ENXIO;
if (lo->lo_state != Lo_bound)
goto out;
/* the loop device has to be read-only */
error = -EINVAL;
if (!(lo->lo_flags & LO_FLAGS_READ_ONLY))
goto out;
error = -EBADF;
file = fget(arg);
if (!file)
goto out;
inode = file->f_mapping->host;
old_file = lo->lo_backing_file;
error = -EINVAL;
if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
goto out_putf;
/* size of the new backing store needs to be the same */
if (get_loop_size(lo, file) != get_loop_size(lo, old_file))
goto out_putf;
/* and ... switch */
blk_mq_freeze_queue(lo->lo_queue);
mapping_set_gfp_mask(old_file->f_mapping, lo->old_gfp_mask);
lo->lo_backing_file = file;
lo->old_gfp_mask = mapping_gfp_mask(file->f_mapping);
mapping_set_gfp_mask(file->f_mapping,
lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
loop_update_dio(lo);
blk_mq_unfreeze_queue(lo->lo_queue);
fput(old_file);
if (lo->lo_flags & LO_FLAGS_PARTSCAN)
loop_reread_partitions(lo, bdev);
return 0;
out_putf:
fput(file);
out:
return error;
}
static inline int is_loop_device(struct file *file)
{
struct inode *i = file->f_mapping->host;
return i && S_ISBLK(i->i_mode) && MAJOR(i->i_rdev) == LOOP_MAJOR;
}
/* loop sysfs attributes */
static ssize_t loop_attr_show(struct device *dev, char *page,
ssize_t (*callback)(struct loop_device *, char *))
{
struct gendisk *disk = dev_to_disk(dev);
struct loop_device *lo = disk->private_data;
return callback(lo, page);
}
#define LOOP_ATTR_RO(_name) \
static ssize_t loop_attr_##_name##_show(struct loop_device *, char *); \
static ssize_t loop_attr_do_show_##_name(struct device *d, \
struct device_attribute *attr, char *b) \
{ \
return loop_attr_show(d, b, loop_attr_##_name##_show); \
} \
static struct device_attribute loop_attr_##_name = \
__ATTR(_name, S_IRUGO, loop_attr_do_show_##_name, NULL);
static ssize_t loop_attr_backing_file_show(struct loop_device *lo, char *buf)
{
ssize_t ret;
char *p = NULL;
spin_lock_irq(&lo->lo_lock);
if (lo->lo_backing_file)
p = file_path(lo->lo_backing_file, buf, PAGE_SIZE - 1);
spin_unlock_irq(&lo->lo_lock);
if (IS_ERR_OR_NULL(p))
ret = PTR_ERR(p);
else {
ret = strlen(p);
memmove(buf, p, ret);
buf[ret++] = '\n';
buf[ret] = 0;
}
return ret;
}
static ssize_t loop_attr_offset_show(struct loop_device *lo, char *buf)
{
return sprintf(buf, "%llu\n", (unsigned long long)lo->lo_offset);
}
static ssize_t loop_attr_sizelimit_show(struct loop_device *lo, char *buf)
{
return sprintf(buf, "%llu\n", (unsigned long long)lo->lo_sizelimit);
}
static ssize_t loop_attr_autoclear_show(struct loop_device *lo, char *buf)
{
int autoclear = (lo->lo_flags & LO_FLAGS_AUTOCLEAR);
return sprintf(buf, "%s\n", autoclear ? "1" : "0");
}
static ssize_t loop_attr_partscan_show(struct loop_device *lo, char *buf)
{
int partscan = (lo->lo_flags & LO_FLAGS_PARTSCAN);
return sprintf(buf, "%s\n", partscan ? "1" : "0");
}
static ssize_t loop_attr_dio_show(struct loop_device *lo, char *buf)
{
int dio = (lo->lo_flags & LO_FLAGS_DIRECT_IO);
return sprintf(buf, "%s\n", dio ? "1" : "0");
}
LOOP_ATTR_RO(backing_file);
LOOP_ATTR_RO(offset);
LOOP_ATTR_RO(sizelimit);
LOOP_ATTR_RO(autoclear);
LOOP_ATTR_RO(partscan);
LOOP_ATTR_RO(dio);
static struct attribute *loop_attrs[] = {
&loop_attr_backing_file.attr,
&loop_attr_offset.attr,
&loop_attr_sizelimit.attr,
&loop_attr_autoclear.attr,
&loop_attr_partscan.attr,
&loop_attr_dio.attr,
NULL,
};
static struct attribute_group loop_attribute_group = {
.name = "loop",
.attrs= loop_attrs,
};
static int loop_sysfs_init(struct loop_device *lo)
{
return sysfs_create_group(&disk_to_dev(lo->lo_disk)->kobj,
&loop_attribute_group);
}
static void loop_sysfs_exit(struct loop_device *lo)
{
sysfs_remove_group(&disk_to_dev(lo->lo_disk)->kobj,
&loop_attribute_group);
}
static void loop_config_discard(struct loop_device *lo)
{
struct file *file = lo->lo_backing_file;
struct inode *inode = file->f_mapping->host;
struct request_queue *q = lo->lo_queue;
/*
* We use punch hole to reclaim the free space used by the
* image a.k.a. discard. However we do not support discard if
* encryption is enabled, because it may give an attacker
* useful information.
*/
if ((!file->f_op->fallocate) ||
lo->lo_encrypt_key_size) {
q->limits.discard_granularity = 0;
q->limits.discard_alignment = 0;
blk_queue_max_discard_sectors(q, 0);
blk_queue_max_write_zeroes_sectors(q, 0);
queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD, q);
return;
}
q->limits.discard_granularity = inode->i_sb->s_blocksize;
q->limits.discard_alignment = 0;
blk_queue_max_discard_sectors(q, UINT_MAX >> 9);
blk_queue_max_write_zeroes_sectors(q, UINT_MAX >> 9);
queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, q);
}
static void loop_unprepare_queue(struct loop_device *lo)
{
kthread_flush_worker(&lo->worker);
kthread_stop(lo->worker_task);
}
static int loop_kthread_worker_fn(void *worker_ptr)
{
current->flags |= PF_LESS_THROTTLE;
return kthread_worker_fn(worker_ptr);
}
static int loop_prepare_queue(struct loop_device *lo)
{
kthread_init_worker(&lo->worker);
lo->worker_task = kthread_run(loop_kthread_worker_fn,
&lo->worker, "loop%d", lo->lo_number);
if (IS_ERR(lo->worker_task))
return -ENOMEM;
set_user_nice(lo->worker_task, MIN_NICE);
return 0;
}
static int loop_set_fd(struct loop_device *lo, fmode_t mode,
struct block_device *bdev, unsigned int arg)
{
struct file *file, *f;
struct inode *inode;
struct address_space *mapping;
int lo_flags = 0;
int error;
loff_t size;
/* This is safe, since we have a reference from open(). */
__module_get(THIS_MODULE);
error = -EBADF;
file = fget(arg);
if (!file)
goto out;
error = -EBUSY;
if (lo->lo_state != Lo_unbound)
goto out_putf;
/* Avoid recursion */
f = file;
while (is_loop_device(f)) {
struct loop_device *l;
if (f->f_mapping->host->i_bdev == bdev)
goto out_putf;
l = f->f_mapping->host->i_bdev->bd_disk->private_data;
if (l->lo_state == Lo_unbound) {
error = -EINVAL;
goto out_putf;
}
f = l->lo_backing_file;
}
mapping = file->f_mapping;
inode = mapping->host;
error = -EINVAL;
if (!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))
goto out_putf;
if (!(file->f_mode & FMODE_WRITE) || !(mode & FMODE_WRITE) ||
!file->f_op->write_iter)
lo_flags |= LO_FLAGS_READ_ONLY;
error = -EFBIG;
size = get_loop_size(lo, file);
if ((loff_t)(sector_t)size != size)
goto out_putf;
error = loop_prepare_queue(lo);
if (error)
goto out_putf;
error = 0;
set_device_ro(bdev, (lo_flags & LO_FLAGS_READ_ONLY) != 0);
lo->use_dio = false;
lo->lo_device = bdev;
lo->lo_flags = lo_flags;
lo->lo_backing_file = file;
lo->transfer = NULL;
lo->ioctl = NULL;
lo->lo_sizelimit = 0;
lo->old_gfp_mask = mapping_gfp_mask(mapping);
mapping_set_gfp_mask(mapping, lo->old_gfp_mask & ~(__GFP_IO|__GFP_FS));
if (!(lo_flags & LO_FLAGS_READ_ONLY) && file->f_op->fsync)
blk_queue_write_cache(lo->lo_queue, true, false);
loop_update_dio(lo);
set_capacity(lo->lo_disk, size);
bd_set_size(bdev, size << 9);
loop_sysfs_init(lo);
/* let user-space know about the new size */
kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
set_blocksize(bdev, S_ISBLK(inode->i_mode) ?
block_size(inode->i_bdev) : PAGE_SIZE);
lo->lo_state = Lo_bound;
if (part_shift)
lo->lo_flags |= LO_FLAGS_PARTSCAN;
if (lo->lo_flags & LO_FLAGS_PARTSCAN)
loop_reread_partitions(lo, bdev);
/* Grab the block_device to prevent its destruction after we
* put /dev/loopXX inode. Later in loop_clr_fd() we bdput(bdev).
*/
bdgrab(bdev);
return 0;
out_putf:
fput(file);
out:
/* This is safe: open() is still holding a reference. */
module_put(THIS_MODULE);
return error;
}
static int
loop_release_xfer(struct loop_device *lo)
{
int err = 0;
struct loop_func_table *xfer = lo->lo_encryption;
if (xfer) {
if (xfer->release)
err = xfer->release(lo);
lo->transfer = NULL;
lo->lo_encryption = NULL;
module_put(xfer->owner);
}
return err;
}
static int
loop_init_xfer(struct loop_device *lo, struct loop_func_table *xfer,
const struct loop_info64 *i)
{
int err = 0;
if (xfer) {
struct module *owner = xfer->owner;
if (!try_module_get(owner))
return -EINVAL;
if (xfer->init)
err = xfer->init(lo, i);
if (err)
module_put(owner);
else
lo->lo_encryption = xfer;
}
return err;
}
static int loop_clr_fd(struct loop_device *lo)
{
struct file *filp = lo->lo_backing_file;
gfp_t gfp = lo->old_gfp_mask;
struct block_device *bdev = lo->lo_device;
if (lo->lo_state != Lo_bound)
return -ENXIO;
/*
* If we've explicitly asked to tear down the loop device,
* and it has an elevated reference count, set it for auto-teardown when
* the last reference goes away. This stops $!~#$@ udev from
* preventing teardown because it decided that it needs to run blkid on
* the loopback device whenever they appear. xfstests is notorious for
* failing tests because blkid via udev races with a losetup
* <dev>/do something like mkfs/losetup -d <dev> causing the losetup -d
* command to fail with EBUSY.
*/
if (atomic_read(&lo->lo_refcnt) > 1) {
lo->lo_flags |= LO_FLAGS_AUTOCLEAR;
mutex_unlock(&lo->lo_ctl_mutex);
return 0;
}
if (filp == NULL)
return -EINVAL;
/* freeze request queue during the transition */
blk_mq_freeze_queue(lo->lo_queue);
spin_lock_irq(&lo->lo_lock);
lo->lo_state = Lo_rundown;
lo->lo_backing_file = NULL;
spin_unlock_irq(&lo->lo_lock);
loop_release_xfer(lo);
lo->transfer = NULL;
lo->ioctl = NULL;
lo->lo_device = NULL;
lo->lo_encryption = NULL;
lo->lo_offset = 0;
lo->lo_sizelimit = 0;
lo->lo_encrypt_key_size = 0;
memset(lo->lo_encrypt_key, 0, LO_KEY_SIZE);
memset(lo->lo_crypt_name, 0, LO_NAME_SIZE);
memset(lo->lo_file_name, 0, LO_NAME_SIZE);
blk_queue_logical_block_size(lo->lo_queue, 512);
blk_queue_physical_block_size(lo->lo_queue, 512);
blk_queue_io_min(lo->lo_queue, 512);
if (bdev) {
bdput(bdev);
invalidate_bdev(bdev);
}
set_capacity(lo->lo_disk, 0);
loop_sysfs_exit(lo);
if (bdev) {
bd_set_size(bdev, 0);
/* let user-space know about this change */
kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, KOBJ_CHANGE);
}
mapping_set_gfp_mask(filp->f_mapping, gfp);
lo->lo_state = Lo_unbound;
/* This is safe: open() is still holding a reference. */
module_put(THIS_MODULE);
blk_mq_unfreeze_queue(lo->lo_queue);
if (lo->lo_flags & LO_FLAGS_PARTSCAN && bdev)
loop_reread_partitions(lo, bdev);
lo->lo_flags = 0;
if (!part_shift)
lo->lo_disk->flags |= GENHD_FL_NO_PART_SCAN;
loop_unprepare_queue(lo);
mutex_unlock(&lo->lo_ctl_mutex);
/*
* Need not hold lo_ctl_mutex to fput backing file.
* Calling fput holding lo_ctl_mutex triggers a circular
* lock dependency possibility warning as fput can take
* bd_mutex which is usually taken before lo_ctl_mutex.
*/
fput(filp);
return 0;
}
static int
loop_set_status(struct loop_device *lo, const struct loop_info64 *info)
{
int err;
struct loop_func_table *xfer;
kuid_t uid = current_uid();
if (lo->lo_encrypt_key_size &&
!uid_eq(lo->lo_key_owner, uid) &&
!capable(CAP_SYS_ADMIN))
return -EPERM;
if (lo->lo_state != Lo_bound)
return -ENXIO;
if ((unsigned int) info->lo_encrypt_key_size > LO_KEY_SIZE)
return -EINVAL;
/* I/O need to be drained during transfer transition */
blk_mq_freeze_queue(lo->lo_queue);
err = loop_release_xfer(lo);
if (err)
goto exit;
if (info->lo_encrypt_type) {
unsigned int type = info->lo_encrypt_type;
if (type >= MAX_LO_CRYPT)
return -EINVAL;
xfer = xfer_funcs[type];
if (xfer == NULL)
return -EINVAL;
} else
xfer = NULL;
err = loop_init_xfer(lo, xfer, info);
if (err)
goto exit;
if (lo->lo_offset != info->lo_offset ||
lo->lo_sizelimit != info->lo_sizelimit) {
if (figure_loop_size(lo, info->lo_offset, info->lo_sizelimit)) {
err = -EFBIG;
goto exit;
}
}
loop_config_discard(lo);
memcpy(lo->lo_file_name, info->lo_file_name, LO_NAME_SIZE);
memcpy(lo->lo_crypt_name, info->lo_crypt_name, LO_NAME_SIZE);
lo->lo_file_name[LO_NAME_SIZE-1] = 0;
lo->lo_crypt_name[LO_NAME_SIZE-1] = 0;
if (!xfer)
xfer = &none_funcs;
lo->transfer = xfer->transfer;
lo->ioctl = xfer->ioctl;
if ((lo->lo_flags & LO_FLAGS_AUTOCLEAR) !=
(info->lo_flags & LO_FLAGS_AUTOCLEAR))
lo->lo_flags ^= LO_FLAGS_AUTOCLEAR;
lo->lo_encrypt_key_size = info->lo_encrypt_key_size;
lo->lo_init[0] = info->lo_init[0];
lo->lo_init[1] = info->lo_init[1];
if (info->lo_encrypt_key_size) {
memcpy(lo->lo_encrypt_key, info->lo_encrypt_key,
info->lo_encrypt_key_size);
lo->lo_key_owner = uid;
}
/* update dio if lo_offset or transfer is changed */
__loop_update_dio(lo, lo->use_dio);
exit:
blk_mq_unfreeze_queue(lo->lo_queue);
if (!err && (info->lo_flags & LO_FLAGS_PARTSCAN) &&
!(lo->lo_flags & LO_FLAGS_PARTSCAN)) {
lo->lo_flags |= LO_FLAGS_PARTSCAN;
lo->lo_disk->flags &= ~GENHD_FL_NO_PART_SCAN;
loop_reread_partitions(lo, lo->lo_device);
}
return err;
}
static int
loop_get_status(struct loop_device *lo, struct loop_info64 *info)
{
struct file *file = lo->lo_backing_file;
struct kstat stat;
int error;
if (lo->lo_state != Lo_bound)
return -ENXIO;
error = vfs_getattr(&file->f_path, &stat,
STATX_INO, AT_STATX_SYNC_AS_STAT);
if (error)
return error;
memset(info, 0, sizeof(*info));
info->lo_number = lo->lo_number;
info->lo_device = huge_encode_dev(stat.dev);
info->lo_inode = stat.ino;
info->lo_rdevice = huge_encode_dev(lo->lo_device ? stat.rdev : stat.dev);
info->lo_offset = lo->lo_offset;
info->lo_sizelimit = lo->lo_sizelimit;
info->lo_flags = lo->lo_flags;
memcpy(info->lo_file_name, lo->lo_file_name, LO_NAME_SIZE);
memcpy(info->lo_crypt_name, lo->lo_crypt_name, LO_NAME_SIZE);
info->lo_encrypt_type =
lo->lo_encryption ? lo->lo_encryption->number : 0;
if (lo->lo_encrypt_key_size && capable(CAP_SYS_ADMIN)) {
info->lo_encrypt_key_size = lo->lo_encrypt_key_size;
memcpy(info->lo_encrypt_key, lo->lo_encrypt_key,
lo->lo_encrypt_key_size);
}
return 0;
}
static void
loop_info64_from_old(const struct loop_info *info, struct loop_info64 *info64)
{
memset(info64, 0, sizeof(*info64));
info64->lo_number = info->lo_number;
info64->lo_device = info->lo_device;
info64->lo_inode = info->lo_inode;
info64->lo_rdevice = info->lo_rdevice;
info64->lo_offset = info->lo_offset;
info64->lo_sizelimit = 0;
info64->lo_encrypt_type = info->lo_encrypt_type;
info64->lo_encrypt_key_size = info->lo_encrypt_key_size;
info64->lo_flags = info->lo_flags;
info64->lo_init[0] = info->lo_init[0];
info64->lo_init[1] = info->lo_init[1];
if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
memcpy(info64->lo_crypt_name, info->lo_name, LO_NAME_SIZE);
else
memcpy(info64->lo_file_name, info->lo_name, LO_NAME_SIZE);
memcpy(info64->lo_encrypt_key, info->lo_encrypt_key, LO_KEY_SIZE);
}
static int
loop_info64_to_old(const struct loop_info64 *info64, struct loop_info *info)
{
memset(info, 0, sizeof(*info));
info->lo_number = info64->lo_number;
info->lo_device = info64->lo_device;
info->lo_inode = info64->lo_inode;
info->lo_rdevice = info64->lo_rdevice;
info->lo_offset = info64->lo_offset;
info->lo_encrypt_type = info64->lo_encrypt_type;
info->lo_encrypt_key_size = info64->lo_encrypt_key_size;
info->lo_flags = info64->lo_flags;
info->lo_init[0] = info64->lo_init[0];
info->lo_init[1] = info64->lo_init[1];
if (info->lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
memcpy(info->lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
else
memcpy(info->lo_name, info64->lo_file_name, LO_NAME_SIZE);
memcpy(info->lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
/* error in case values were truncated */
if (info->lo_device != info64->lo_device ||
info->lo_rdevice != info64->lo_rdevice ||
info->lo_inode != info64->lo_inode ||
info->lo_offset != info64->lo_offset)
return -EOVERFLOW;
return 0;
}
static int
loop_set_status_old(struct loop_device *lo, const struct loop_info __user *arg)
{
struct loop_info info;
struct loop_info64 info64;
if (copy_from_user(&info, arg, sizeof (struct loop_info)))
return -EFAULT;
loop_info64_from_old(&info, &info64);
return loop_set_status(lo, &info64);
}
static int
loop_set_status64(struct loop_device *lo, const struct loop_info64 __user *arg)
{
struct loop_info64 info64;
if (copy_from_user(&info64, arg, sizeof (struct loop_info64)))
return -EFAULT;
return loop_set_status(lo, &info64);
}
static int
loop_get_status_old(struct loop_device *lo, struct loop_info __user *arg) {
struct loop_info info;
struct loop_info64 info64;
int err = 0;
if (!arg)
err = -EINVAL;
if (!err)
err = loop_get_status(lo, &info64);
if (!err)
err = loop_info64_to_old(&info64, &info);
if (!err && copy_to_user(arg, &info, sizeof(info)))
err = -EFAULT;
return err;
}
static int
loop_get_status64(struct loop_device *lo, struct loop_info64 __user *arg) {
struct loop_info64 info64;
int err = 0;
if (!arg)
err = -EINVAL;
if (!err)
err = loop_get_status(lo, &info64);
if (!err && copy_to_user(arg, &info64, sizeof(info64)))
err = -EFAULT;
return err;
}
static int loop_set_capacity(struct loop_device *lo)
{
if (unlikely(lo->lo_state != Lo_bound))
return -ENXIO;
return figure_loop_size(lo, lo->lo_offset, lo->lo_sizelimit);
}
static int loop_set_dio(struct loop_device *lo, unsigned long arg)
{
int error = -ENXIO;
if (lo->lo_state != Lo_bound)
goto out;
__loop_update_dio(lo, !!arg);
if (lo->use_dio == !!arg)
return 0;
error = -EINVAL;
out:
return error;
}
static int loop_set_block_size(struct loop_device *lo, unsigned long arg)
{
if (lo->lo_state != Lo_bound)
return -ENXIO;
if (arg < 512 || arg > PAGE_SIZE || !is_power_of_2(arg))
return -EINVAL;
blk_mq_freeze_queue(lo->lo_queue);
blk_queue_logical_block_size(lo->lo_queue, arg);
blk_queue_physical_block_size(lo->lo_queue, arg);
blk_queue_io_min(lo->lo_queue, arg);
loop_update_dio(lo);
blk_mq_unfreeze_queue(lo->lo_queue);
return 0;
}
static int lo_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
struct loop_device *lo = bdev->bd_disk->private_data;
int err;
mutex_lock_nested(&lo->lo_ctl_mutex, 1);
switch (cmd) {
case LOOP_SET_FD:
err = loop_set_fd(lo, mode, bdev, arg);
break;
case LOOP_CHANGE_FD:
err = loop_change_fd(lo, bdev, arg);
break;
case LOOP_CLR_FD:
/* loop_clr_fd would have unlocked lo_ctl_mutex on success */
err = loop_clr_fd(lo);
if (!err)
goto out_unlocked;
break;
case LOOP_SET_STATUS:
err = -EPERM;
if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN))
err = loop_set_status_old(lo,
(struct loop_info __user *)arg);
break;
case LOOP_GET_STATUS:
err = loop_get_status_old(lo, (struct loop_info __user *) arg);
break;
case LOOP_SET_STATUS64:
err = -EPERM;
if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN))
err = loop_set_status64(lo,
(struct loop_info64 __user *) arg);
break;
case LOOP_GET_STATUS64:
err = loop_get_status64(lo, (struct loop_info64 __user *) arg);
break;
case LOOP_SET_CAPACITY:
err = -EPERM;
if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN))
err = loop_set_capacity(lo);
break;
case LOOP_SET_DIRECT_IO:
err = -EPERM;
if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN))
err = loop_set_dio(lo, arg);
break;
case LOOP_SET_BLOCK_SIZE:
err = -EPERM;
if ((mode & FMODE_WRITE) || capable(CAP_SYS_ADMIN))
err = loop_set_block_size(lo, arg);
break;
default:
err = lo->ioctl ? lo->ioctl(lo, cmd, arg) : -EINVAL;
}
mutex_unlock(&lo->lo_ctl_mutex);
out_unlocked:
return err;
}
#ifdef CONFIG_COMPAT
struct compat_loop_info {
compat_int_t lo_number; /* ioctl r/o */
compat_dev_t lo_device; /* ioctl r/o */
compat_ulong_t lo_inode; /* ioctl r/o */
compat_dev_t lo_rdevice; /* ioctl r/o */
compat_int_t lo_offset;
compat_int_t lo_encrypt_type;
compat_int_t lo_encrypt_key_size; /* ioctl w/o */
compat_int_t lo_flags; /* ioctl r/o */
char lo_name[LO_NAME_SIZE];
unsigned char lo_encrypt_key[LO_KEY_SIZE]; /* ioctl w/o */
compat_ulong_t lo_init[2];
char reserved[4];
};
/*
* Transfer 32-bit compatibility structure in userspace to 64-bit loop info
* - noinlined to reduce stack space usage in main part of driver
*/
static noinline int
loop_info64_from_compat(const struct compat_loop_info __user *arg,
struct loop_info64 *info64)
{
struct compat_loop_info info;
if (copy_from_user(&info, arg, sizeof(info)))
return -EFAULT;
memset(info64, 0, sizeof(*info64));
info64->lo_number = info.lo_number;
info64->lo_device = info.lo_device;
info64->lo_inode = info.lo_inode;
info64->lo_rdevice = info.lo_rdevice;
info64->lo_offset = info.lo_offset;
info64->lo_sizelimit = 0;
info64->lo_encrypt_type = info.lo_encrypt_type;
info64->lo_encrypt_key_size = info.lo_encrypt_key_size;
info64->lo_flags = info.lo_flags;
info64->lo_init[0] = info.lo_init[0];
info64->lo_init[1] = info.lo_init[1];
if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
memcpy(info64->lo_crypt_name, info.lo_name, LO_NAME_SIZE);
else
memcpy(info64->lo_file_name, info.lo_name, LO_NAME_SIZE);
memcpy(info64->lo_encrypt_key, info.lo_encrypt_key, LO_KEY_SIZE);
return 0;
}
/*
* Transfer 64-bit loop info to 32-bit compatibility structure in userspace
* - noinlined to reduce stack space usage in main part of driver
*/
static noinline int
loop_info64_to_compat(const struct loop_info64 *info64,
struct compat_loop_info __user *arg)
{
struct compat_loop_info info;
memset(&info, 0, sizeof(info));
info.lo_number = info64->lo_number;
info.lo_device = info64->lo_device;
info.lo_inode = info64->lo_inode;
info.lo_rdevice = info64->lo_rdevice;
info.lo_offset = info64->lo_offset;
info.lo_encrypt_type = info64->lo_encrypt_type;
info.lo_encrypt_key_size = info64->lo_encrypt_key_size;
info.lo_flags = info64->lo_flags;
info.lo_init[0] = info64->lo_init[0];
info.lo_init[1] = info64->lo_init[1];
if (info.lo_encrypt_type == LO_CRYPT_CRYPTOAPI)
memcpy(info.lo_name, info64->lo_crypt_name, LO_NAME_SIZE);
else
memcpy(info.lo_name, info64->lo_file_name, LO_NAME_SIZE);
memcpy(info.lo_encrypt_key, info64->lo_encrypt_key, LO_KEY_SIZE);
/* error in case values were truncated */
if (info.lo_device != info64->lo_device ||
info.lo_rdevice != info64->lo_rdevice ||
info.lo_inode != info64->lo_inode ||
info.lo_offset != info64->lo_offset ||
info.lo_init[0] != info64->lo_init[0] ||
info.lo_init[1] != info64->lo_init[1])
return -EOVERFLOW;
if (copy_to_user(arg, &info, sizeof(info)))
return -EFAULT;
return 0;
}
static int
loop_set_status_compat(struct loop_device *lo,
const struct compat_loop_info __user *arg)
{
struct loop_info64 info64;
int ret;
ret = loop_info64_from_compat(arg, &info64);
if (ret < 0)
return ret;
return loop_set_status(lo, &info64);
}
static int
loop_get_status_compat(struct loop_device *lo,
struct compat_loop_info __user *arg)
{
struct loop_info64 info64;
int err = 0;
if (!arg)
err = -EINVAL;
if (!err)
err = loop_get_status(lo, &info64);
if (!err)
err = loop_info64_to_compat(&info64, arg);
return err;
}
static int lo_compat_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
struct loop_device *lo = bdev->bd_disk->private_data;
int err;
switch(cmd) {
case LOOP_SET_STATUS:
mutex_lock(&lo->lo_ctl_mutex);
err = loop_set_status_compat(
lo, (const struct compat_loop_info __user *) arg);
mutex_unlock(&lo->lo_ctl_mutex);
break;
case LOOP_GET_STATUS:
mutex_lock(&lo->lo_ctl_mutex);
err = loop_get_status_compat(
lo, (struct compat_loop_info __user *) arg);
mutex_unlock(&lo->lo_ctl_mutex);
break;
case LOOP_SET_CAPACITY:
case LOOP_CLR_FD:
case LOOP_GET_STATUS64:
case LOOP_SET_STATUS64:
arg = (unsigned long) compat_ptr(arg);
case LOOP_SET_FD:
case LOOP_CHANGE_FD:
err = lo_ioctl(bdev, mode, cmd, arg);
break;
default:
err = -ENOIOCTLCMD;
break;
}
return err;
}
#endif
static int lo_open(struct block_device *bdev, fmode_t mode)
{
struct loop_device *lo;
int err = 0;
mutex_lock(&loop_index_mutex);
lo = bdev->bd_disk->private_data;
if (!lo) {
err = -ENXIO;
goto out;
}
atomic_inc(&lo->lo_refcnt);
out:
mutex_unlock(&loop_index_mutex);
return err;
}
static void lo_release(struct gendisk *disk, fmode_t mode)
{
struct loop_device *lo = disk->private_data;
int err;
if (atomic_dec_return(&lo->lo_refcnt))
return;
mutex_lock(&lo->lo_ctl_mutex);
if (lo->lo_flags & LO_FLAGS_AUTOCLEAR) {
/*
* In autoclear mode, stop the loop thread
* and remove configuration after last close.
*/
err = loop_clr_fd(lo);
if (!err)
return;
} else if (lo->lo_state == Lo_bound) {
/*
* Otherwise keep thread (if running) and config,
* but flush possible ongoing bios in thread.
*/
blk_mq_freeze_queue(lo->lo_queue);
blk_mq_unfreeze_queue(lo->lo_queue);
}
mutex_unlock(&lo->lo_ctl_mutex);
}
static const struct block_device_operations lo_fops = {
.owner = THIS_MODULE,
.open = lo_open,
.release = lo_release,
.ioctl = lo_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = lo_compat_ioctl,
#endif
};
/*
* And now the modules code and kernel interface.
*/
static int max_loop;
module_param(max_loop, int, S_IRUGO);
MODULE_PARM_DESC(max_loop, "Maximum number of loop devices");
module_param(max_part, int, S_IRUGO);
MODULE_PARM_DESC(max_part, "Maximum number of partitions per loop device");
MODULE_LICENSE("GPL");
MODULE_ALIAS_BLOCKDEV_MAJOR(LOOP_MAJOR);
int loop_register_transfer(struct loop_func_table *funcs)
{
unsigned int n = funcs->number;
if (n >= MAX_LO_CRYPT || xfer_funcs[n])
return -EINVAL;
xfer_funcs[n] = funcs;
return 0;
}
static int unregister_transfer_cb(int id, void *ptr, void *data)
{
struct loop_device *lo = ptr;
struct loop_func_table *xfer = data;
mutex_lock(&lo->lo_ctl_mutex);
if (lo->lo_encryption == xfer)
loop_release_xfer(lo);
mutex_unlock(&lo->lo_ctl_mutex);
return 0;
}
int loop_unregister_transfer(int number)
{
unsigned int n = number;
struct loop_func_table *xfer;
if (n == 0 || n >= MAX_LO_CRYPT || (xfer = xfer_funcs[n]) == NULL)
return -EINVAL;
xfer_funcs[n] = NULL;
idr_for_each(&loop_index_idr, &unregister_transfer_cb, xfer);
return 0;
}
EXPORT_SYMBOL(loop_register_transfer);
EXPORT_SYMBOL(loop_unregister_transfer);
static blk_status_t loop_queue_rq(struct blk_mq_hw_ctx *hctx,
const struct blk_mq_queue_data *bd)
{
struct loop_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
struct loop_device *lo = cmd->rq->q->queuedata;
blk_mq_start_request(bd->rq);
if (lo->lo_state != Lo_bound)
return BLK_STS_IOERR;
switch (req_op(cmd->rq)) {
case REQ_OP_FLUSH:
case REQ_OP_DISCARD:
case REQ_OP_WRITE_ZEROES:
cmd->use_aio = false;
break;
default:
cmd->use_aio = lo->use_dio;
break;
}
/* always use the first bio's css */
#ifdef CONFIG_BLK_CGROUP
if (cmd->use_aio && cmd->rq->bio && cmd->rq->bio->bi_css) {
cmd->css = cmd->rq->bio->bi_css;
css_get(cmd->css);
} else
#endif
cmd->css = NULL;
kthread_queue_work(&lo->worker, &cmd->work);
return BLK_STS_OK;
}
static void loop_handle_cmd(struct loop_cmd *cmd)
{
const bool write = op_is_write(req_op(cmd->rq));
struct loop_device *lo = cmd->rq->q->queuedata;
int ret = 0;
if (write && (lo->lo_flags & LO_FLAGS_READ_ONLY)) {
ret = -EIO;
goto failed;
}
ret = do_req_filebacked(lo, cmd->rq);
failed:
/* complete non-aio request */
if (!cmd->use_aio || ret) {
cmd->ret = ret ? -EIO : 0;
blk_mq_complete_request(cmd->rq);
}
}
static void loop_queue_work(struct kthread_work *work)
{
struct loop_cmd *cmd =
container_of(work, struct loop_cmd, work);
loop_handle_cmd(cmd);
}
static int loop_init_request(struct blk_mq_tag_set *set, struct request *rq,
unsigned int hctx_idx, unsigned int numa_node)
{
struct loop_cmd *cmd = blk_mq_rq_to_pdu(rq);
cmd->rq = rq;
kthread_init_work(&cmd->work, loop_queue_work);
return 0;
}
static const struct blk_mq_ops loop_mq_ops = {
.queue_rq = loop_queue_rq,
.init_request = loop_init_request,
.complete = lo_complete_rq,
};
static int loop_add(struct loop_device **l, int i)
{
struct loop_device *lo;
struct gendisk *disk;
int err;
err = -ENOMEM;
lo = kzalloc(sizeof(*lo), GFP_KERNEL);
if (!lo)
goto out;
lo->lo_state = Lo_unbound;
/* allocate id, if @id >= 0, we're requesting that specific id */
if (i >= 0) {
err = idr_alloc(&loop_index_idr, lo, i, i + 1, GFP_KERNEL);
if (err == -ENOSPC)
err = -EEXIST;
} else {
err = idr_alloc(&loop_index_idr, lo, 0, 0, GFP_KERNEL);
}
if (err < 0)
goto out_free_dev;
i = err;
err = -ENOMEM;
lo->tag_set.ops = &loop_mq_ops;
lo->tag_set.nr_hw_queues = 1;
lo->tag_set.queue_depth = 128;
lo->tag_set.numa_node = NUMA_NO_NODE;
lo->tag_set.cmd_size = sizeof(struct loop_cmd);
lo->tag_set.flags = BLK_MQ_F_SHOULD_MERGE | BLK_MQ_F_SG_MERGE;
lo->tag_set.driver_data = lo;
err = blk_mq_alloc_tag_set(&lo->tag_set);
if (err)
goto out_free_idr;
lo->lo_queue = blk_mq_init_queue(&lo->tag_set);
if (IS_ERR_OR_NULL(lo->lo_queue)) {
err = PTR_ERR(lo->lo_queue);
goto out_cleanup_tags;
}
lo->lo_queue->queuedata = lo;
blk_queue_max_hw_sectors(lo->lo_queue, BLK_DEF_MAX_SECTORS);
/*
* By default, we do buffer IO, so it doesn't make sense to enable
* merge because the I/O submitted to backing file is handled page by
* page. For directio mode, merge does help to dispatch bigger request
* to underlayer disk. We will enable merge once directio is enabled.
*/
queue_flag_set_unlocked(QUEUE_FLAG_NOMERGES, lo->lo_queue);
err = -ENOMEM;
disk = lo->lo_disk = alloc_disk(1 << part_shift);
if (!disk)
goto out_free_queue;
/*
* Disable partition scanning by default. The in-kernel partition
* scanning can be requested individually per-device during its
* setup. Userspace can always add and remove partitions from all
* devices. The needed partition minors are allocated from the
* extended minor space, the main loop device numbers will continue
* to match the loop minors, regardless of the number of partitions
* used.
*
* If max_part is given, partition scanning is globally enabled for
* all loop devices. The minors for the main loop devices will be
* multiples of max_part.
*
* Note: Global-for-all-devices, set-only-at-init, read-only module
* parameteters like 'max_loop' and 'max_part' make things needlessly
* complicated, are too static, inflexible and may surprise
* userspace tools. Parameters like this in general should be avoided.
*/
if (!part_shift)
disk->flags |= GENHD_FL_NO_PART_SCAN;
disk->flags |= GENHD_FL_EXT_DEVT;
mutex_init(&lo->lo_ctl_mutex);
atomic_set(&lo->lo_refcnt, 0);
lo->lo_number = i;
spin_lock_init(&lo->lo_lock);
disk->major = LOOP_MAJOR;
disk->first_minor = i << part_shift;
disk->fops = &lo_fops;
disk->private_data = lo;
disk->queue = lo->lo_queue;
sprintf(disk->disk_name, "loop%d", i);
add_disk(disk);
*l = lo;
return lo->lo_number;
out_free_queue:
blk_cleanup_queue(lo->lo_queue);
out_cleanup_tags:
blk_mq_free_tag_set(&lo->tag_set);
out_free_idr:
idr_remove(&loop_index_idr, i);
out_free_dev:
kfree(lo);
out:
return err;
}
static void loop_remove(struct loop_device *lo)
{
blk_cleanup_queue(lo->lo_queue);
del_gendisk(lo->lo_disk);
blk_mq_free_tag_set(&lo->tag_set);
put_disk(lo->lo_disk);
kfree(lo);
}
static int find_free_cb(int id, void *ptr, void *data)
{
struct loop_device *lo = ptr;
struct loop_device **l = data;
if (lo->lo_state == Lo_unbound) {
*l = lo;
return 1;
}
return 0;
}
static int loop_lookup(struct loop_device **l, int i)
{
struct loop_device *lo;
int ret = -ENODEV;
if (i < 0) {
int err;
err = idr_for_each(&loop_index_idr, &find_free_cb, &lo);
if (err == 1) {
*l = lo;
ret = lo->lo_number;
}
goto out;
}
/* lookup and return a specific i */
lo = idr_find(&loop_index_idr, i);
if (lo) {
*l = lo;
ret = lo->lo_number;
}
out:
return ret;
}
static struct kobject *loop_probe(dev_t dev, int *part, void *data)
{
struct loop_device *lo;
struct kobject *kobj;
int err;
mutex_lock(&loop_index_mutex);
err = loop_lookup(&lo, MINOR(dev) >> part_shift);
if (err < 0)
err = loop_add(&lo, MINOR(dev) >> part_shift);
if (err < 0)
kobj = NULL;
else
kobj = get_disk(lo->lo_disk);
mutex_unlock(&loop_index_mutex);
*part = 0;
return kobj;
}
static long loop_control_ioctl(struct file *file, unsigned int cmd,
unsigned long parm)
{
struct loop_device *lo;
int ret = -ENOSYS;
mutex_lock(&loop_index_mutex);
switch (cmd) {
case LOOP_CTL_ADD:
ret = loop_lookup(&lo, parm);
if (ret >= 0) {
ret = -EEXIST;
break;
}
ret = loop_add(&lo, parm);
break;
case LOOP_CTL_REMOVE:
ret = loop_lookup(&lo, parm);
if (ret < 0)
break;
mutex_lock(&lo->lo_ctl_mutex);
if (lo->lo_state != Lo_unbound) {
ret = -EBUSY;
mutex_unlock(&lo->lo_ctl_mutex);
break;
}
if (atomic_read(&lo->lo_refcnt) > 0) {
ret = -EBUSY;
mutex_unlock(&lo->lo_ctl_mutex);
break;
}
lo->lo_disk->private_data = NULL;
mutex_unlock(&lo->lo_ctl_mutex);
idr_remove(&loop_index_idr, lo->lo_number);
loop_remove(lo);
break;
case LOOP_CTL_GET_FREE:
ret = loop_lookup(&lo, -1);
if (ret >= 0)
break;
ret = loop_add(&lo, -1);
}
mutex_unlock(&loop_index_mutex);
return ret;
}
static const struct file_operations loop_ctl_fops = {
.open = nonseekable_open,
.unlocked_ioctl = loop_control_ioctl,
.compat_ioctl = loop_control_ioctl,
.owner = THIS_MODULE,
.llseek = noop_llseek,
};
static struct miscdevice loop_misc = {
.minor = LOOP_CTRL_MINOR,
.name = "loop-control",
.fops = &loop_ctl_fops,
};
MODULE_ALIAS_MISCDEV(LOOP_CTRL_MINOR);
MODULE_ALIAS("devname:loop-control");
static int __init loop_init(void)
{
int i, nr;
unsigned long range;
struct loop_device *lo;
int err;
part_shift = 0;
if (max_part > 0) {
part_shift = fls(max_part);
/*
* Adjust max_part according to part_shift as it is exported
* to user space so that user can decide correct minor number
* if [s]he want to create more devices.
*
* Note that -1 is required because partition 0 is reserved
* for the whole disk.
*/
max_part = (1UL << part_shift) - 1;
}
if ((1UL << part_shift) > DISK_MAX_PARTS) {
err = -EINVAL;
goto err_out;
}
if (max_loop > 1UL << (MINORBITS - part_shift)) {
err = -EINVAL;
goto err_out;
}
/*
* If max_loop is specified, create that many devices upfront.
* This also becomes a hard limit. If max_loop is not specified,
* create CONFIG_BLK_DEV_LOOP_MIN_COUNT loop devices at module
* init time. Loop devices can be requested on-demand with the
* /dev/loop-control interface, or be instantiated by accessing
* a 'dead' device node.
*/
if (max_loop) {
nr = max_loop;
range = max_loop << part_shift;
} else {
nr = CONFIG_BLK_DEV_LOOP_MIN_COUNT;
range = 1UL << MINORBITS;
}
err = misc_register(&loop_misc);
if (err < 0)
goto err_out;
if (register_blkdev(LOOP_MAJOR, "loop")) {
err = -EIO;
goto misc_out;
}
blk_register_region(MKDEV(LOOP_MAJOR, 0), range,
THIS_MODULE, loop_probe, NULL, NULL);
/* pre-create number of devices given by config or max_loop */
mutex_lock(&loop_index_mutex);
for (i = 0; i < nr; i++)
loop_add(&lo, i);
mutex_unlock(&loop_index_mutex);
printk(KERN_INFO "loop: module loaded\n");
return 0;
misc_out:
misc_deregister(&loop_misc);
err_out:
return err;
}
static int loop_exit_cb(int id, void *ptr, void *data)
{
struct loop_device *lo = ptr;
loop_remove(lo);
return 0;
}
static void __exit loop_exit(void)
{
unsigned long range;
range = max_loop ? max_loop << part_shift : 1UL << MINORBITS;
idr_for_each(&loop_index_idr, &loop_exit_cb, NULL);
idr_destroy(&loop_index_idr);
blk_unregister_region(MKDEV(LOOP_MAJOR, 0), range);
unregister_blkdev(LOOP_MAJOR, "loop");
misc_deregister(&loop_misc);
}
module_init(loop_init);
module_exit(loop_exit);
#ifndef MODULE
static int __init max_loop_setup(char *str)
{
max_loop = simple_strtol(str, NULL, 0);
return 1;
}
__setup("max_loop=", max_loop_setup);
#endif
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_574_0 |
crossvul-cpp_data_bad_3399_1 | /* radare - LGPL - Copyright 2011-2017 - earada, pancake */
#include <r_core.h>
#include "r_util.h"
#define is_in_range(at, from, sz) ((at) >= (from) && (at) < ((from) + (sz)))
#define VA_FALSE 0
#define VA_TRUE 1
#define VA_NOREBASE 2
#define IS_MODE_SET(mode) (mode & R_CORE_BIN_SET)
#define IS_MODE_SIMPLE(mode) (mode & R_CORE_BIN_SIMPLE)
#define IS_MODE_SIMPLEST(mode) (mode & R_CORE_BIN_SIMPLEST)
#define IS_MODE_JSON(mode) (mode & R_CORE_BIN_JSON)
#define IS_MODE_RAD(mode) (mode & R_CORE_BIN_RADARE)
#define IS_MODE_NORMAL(mode) (!mode)
// dup from cmd_info
#define PAIR_WIDTH 9
static void pair(const char *a, const char *b, int mode, bool last) {
if (!b || !(*b)) {
return;
}
if (IS_MODE_JSON (mode)) {
const char *lst = last ? "" : ",";
r_cons_printf ("\"%s\":%s%s", a, b, lst);
} else {
char ws[16];
int al = strlen (a);
al = PAIR_WIDTH - al;
if (al < 0) {
al = 0;
}
memset (ws, ' ', al);
ws[al] = 0;
r_cons_printf ("%s%s%s\n", a, ws, b);
}
}
static void pair_bool(const char *a, bool t, int mode, bool last) {
pair (a, r_str_bool (t), mode, last);
}
static void pair_int(const char *a, int n, int mode, bool last) {
pair (a, sdb_fmt (0, "%d", n), mode, last);
}
static void pair_str(const char *a, const char *b, int mode, int last) {
if (IS_MODE_JSON (mode)) {
if (!b) {
b = "";
}
char *eb = r_str_utf16_encode (b, -1);
if (eb) {
pair (a, sdb_fmt (0, "\"%s\"", eb), mode, last);
free (eb);
}
} else {
pair (a, b, mode, last);
}
}
#define STR(x) (x)?(x):""
R_API int r_core_bin_set_cur (RCore *core, RBinFile *binfile);
static ut64 rva(RBin *bin, ut64 paddr, ut64 vaddr, int va) {
if (va == VA_TRUE) {
return r_bin_get_vaddr (bin, paddr, vaddr);
}
if (va == VA_NOREBASE) {
return vaddr;
}
return paddr;
}
R_API int r_core_bin_set_by_fd(RCore *core, ut64 bin_fd) {
if (r_bin_file_set_cur_by_fd (core->bin, bin_fd)) {
r_core_bin_set_cur (core, r_core_bin_cur (core));
return true;
}
return false;
}
R_API int r_core_bin_set_by_name(RCore *core, const char * name) {
if (r_bin_file_set_cur_by_name (core->bin, name)) {
r_core_bin_set_cur (core, r_core_bin_cur (core));
return true;
}
return false;
}
R_API int r_core_bin_set_env(RCore *r, RBinFile *binfile) {
RBinObject *binobj = binfile ? binfile->o: NULL;
RBinInfo *info = binobj ? binobj->info: NULL;
if (info) {
int va = info->has_va;
const char * arch = info->arch;
ut16 bits = info->bits;
ut64 baseaddr = r_bin_get_baddr (r->bin);
/* Hack to make baddr work on some corner */
r_config_set_i (r->config, "io.va",
(binobj->info)? binobj->info->has_va: 0);
r_config_set_i (r->config, "bin.baddr", baseaddr);
r_config_set (r->config, "asm.arch", arch);
r_config_set_i (r->config, "asm.bits", bits);
r_config_set (r->config, "anal.arch", arch);
if (info->cpu && *info->cpu) {
r_config_set (r->config, "anal.cpu", info->cpu);
} else {
r_config_set (r->config, "anal.cpu", arch);
}
r_asm_use (r->assembler, arch);
r_core_bin_info (r, R_CORE_BIN_ACC_ALL, R_CORE_BIN_SET, va, NULL, NULL);
r_core_bin_set_cur (r, binfile);
return true;
}
return false;
}
R_API int r_core_bin_set_cur(RCore *core, RBinFile *binfile) {
if (!core->bin) {
return false;
}
if (!binfile) {
// Find first available binfile
ut32 fd = r_core_file_cur_fd (core);
binfile = fd != (ut32)-1
? r_bin_file_find_by_fd (core->bin, fd)
: NULL;
if (!binfile) {
return false;
}
}
r_bin_file_set_cur_binfile (core->bin, binfile);
return true;
}
R_API int r_core_bin_refresh_strings(RCore *r) {
return r_bin_reset_strings (r->bin) ? true: false;
}
R_API RBinFile * r_core_bin_cur(RCore *core) {
RBinFile *binfile = r_bin_cur (core->bin);
return binfile;
}
static bool string_filter(RCore *core, const char *str) {
int i;
/* pointer/rawdata detection */
if (core->bin->strpurge) {
ut8 bo[0x100];
int up = 0;
int lo = 0;
int ot = 0;
int di = 0;
int ln = 0;
int sp = 0;
int nm = 0;
for (i = 0; i < 0x100; i++) {
bo[i] = 0;
}
for (i = 0; str[i]; i++) {
if (IS_DIGIT(str[i])) {
nm++;
} else if (str[i]>='a' && str[i]<='z') {
lo++;
} else if (str[i]>='A' && str[i]<='Z') {
up++;
} else {
ot++;
}
if (str[i]=='\\') {
ot++;
}
if (str[i]==' ') {
sp++;
}
bo[(ut8)str[i]] = 1;
ln++;
}
for (i = 0; i<0x100; i++) {
if (bo[i]) {
di++;
}
}
if (ln > 2 && str[0] != '_') {
if (ln < 10) {
return false;
}
if (ot >= (nm + up + lo)) {
return false;
}
if (lo < 3) {
return false;
}
}
}
switch (core->bin->strfilter) {
case 'U': // only uppercase strings
for (i = 0; str[i]; i++) {
char ch = str[i];
if (ch == ' ') {
continue;
}
if (ch < '@'|| ch > 'Z') {
return false;
}
if (ch < 0 || !IS_PRINTABLE (ch)) {
return false;
}
}
if (str[0] && str[1]) {
for (i = 2; i<6 && str[i]; i++) {
if (str[i] == str[0]) {
return false;
}
if (str[i] == str[1]) {
return false;
}
}
}
if (str[0] == str[2]) {
return false; // rm false positives
}
break;
case 'a': // only alphanumeric - plain ascii
for (i = 0; str[i]; i++) {
char ch = str[i];
if (ch < 1 || !IS_PRINTABLE (ch)) {
return false;
}
}
break;
case 'e': // emails
if (str && *str) {
if (!strstr (str + 1, "@")) {
return false;
}
if (!strstr (str + 1, ".")) {
return false;
}
} else {
return false;
}
break;
case 'f': // format-string
if (str && *str) {
if (!strstr (str+1, "%"))
return false;
} else return false;
break;
case 'u': // URLs
if (!strstr (str, "://")) {
return false;
}
break;
case 'i': //IPV4
{
int segment = 0;
int segmentsum = 0;
bool prevd = false;
for (i = 0; str[i]; i++) {
char ch = str[i];
if (IS_DIGIT(ch)) {
segmentsum = segmentsum*10 + (ch - '0');
if (segment == 3) {
return true;
}
prevd = true;
} else if (ch == '.') {
if (prevd == true && segmentsum < 256){
segment++;
segmentsum = 0;
} else {
segmentsum = 0;
segment = 0;
}
prevd = false;
} else {
segmentsum = 0;
prevd = false;
segment = 0;
}
}
return false;
}
case 'p': // path
if (str[0] != '/') {
return false;
}
break;
case '8': // utf8
for (i = 0; str[i]; i++) {
char ch = str[i];
if (ch < 0) {
return true;
}
}
return false;
}
return true;
}
static void _print_strings(RCore *r, RList *list, int mode, int va) {
int minstr = r_config_get_i (r->config, "bin.minstr");
int maxstr = r_config_get_i (r->config, "bin.maxstr");
RBin *bin = r->bin;
RListIter *iter;
RBinString *string;
RBinSection *section;
char *q;
bin->minstrlen = minstr;
bin->maxstrlen = maxstr;
if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
}
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs strings");
}
if (IS_MODE_SET (mode) && r_config_get_i (r->config, "bin.strings")) {
r_flag_space_set (r->flags, "strings");
r_cons_break_push (NULL, NULL);
}
r_list_foreach (list, iter, string) {
const char *section_name, *type_string;
ut64 paddr, vaddr, addr;
if (!string_filter (r, string->string)) {
continue;
}
paddr = string->paddr;
vaddr = r_bin_get_vaddr (bin, paddr, string->vaddr);
addr = va ? vaddr : paddr;
if (string->length < minstr) {
continue;
}
if (maxstr && string->length > maxstr) {
continue;
}
section = r_bin_get_section_at (r_bin_cur_object (bin), paddr, 0);
section_name = section ? section->name : "unknown";
type_string = r_bin_string_type (string->type);
if (IS_MODE_SET (mode)) {
char *f_name, *str;
if (r_cons_is_breaked ()) {
break;
}
r_meta_add (r->anal, R_META_TYPE_STRING, addr, addr + string->size, string->string);
f_name = strdup (string->string);
r_name_filter (f_name, -1);
if (r->bin->prefix) {
str = r_str_newf ("%s.str.%s", r->bin->prefix, f_name);
} else {
str = r_str_newf ("str.%s", f_name);
}
r_flag_set (r->flags, str, addr, string->size);
free (str);
free (f_name);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%"PFMT64x" %d %d %s\n", addr, string->size, string->length, string->string);
} else if (IS_MODE_SIMPLEST (mode)) {
r_cons_println (string->string);
} else if (IS_MODE_JSON (mode)) {
q = r_base64_encode_dyn (string->string, -1);
r_cons_printf ("%s{\"vaddr\":%"PFMT64d
",\"paddr\":%"PFMT64d",\"ordinal\":%d"
",\"size\":%d,\"length\":%d,\"section\":\"%s\","
"\"type\":\"%s\",\"string\":\"%s\"}",
iter->p ? ",": "",
vaddr, paddr, string->ordinal, string->size,
string->length, section_name, type_string, q);
free (q);
} else if (IS_MODE_RAD (mode)) {
char *f_name, *str;
f_name = strdup (string->string);
r_name_filter (f_name, R_FLAG_NAME_SIZE);
if (r->bin->prefix) {
str = r_str_newf ("%s.str.%s", r->bin->prefix, f_name);
r_cons_printf ("f %s.str.%s %"PFMT64d" @ 0x%08"PFMT64x"\n"
"Cs %"PFMT64d" @ 0x%08"PFMT64x"\n",
r->bin->prefix, f_name, string->size, addr,
string->size, addr);
} else {
str = r_str_newf ("str.%s", f_name);
r_cons_printf ("f str.%s %"PFMT64d" @ 0x%08"PFMT64x"\n"
"Cs %"PFMT64d" @ 0x%08"PFMT64x"\n",
f_name, string->size, addr,
string->size, addr);
}
free (str);
free (f_name);
} else {
r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"
PFMT64x" ordinal=%03u sz=%u len=%u "
"section=%s type=%s string=%s\n",
vaddr, paddr, string->ordinal, string->size,
string->length, section_name, type_string,
string->string);
}
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
}
if (IS_MODE_SET (mode)) {
r_cons_break_pop ();
}
}
static bool bin_raw_strings(RCore *r, int mode, int va) {
RBinFile *bf = r_bin_cur (r->bin);
if (!bf && r->io && r->io->desc && r->io->desc->uri) {
const char *file = r->io->desc->uri;
r_sys_cmdf ("rabin2 -qzzz '%s'", file);
// eprintf ("Likely you used -nn \n");
// eprintf ("try: .!rabin2 -B <baddr> -zzr filename\n");
return false;
}
if (bf && strstr (bf->file, "malloc://")) {
//sync bf->buf to search string on it
r_io_read_at (r->io, 0, bf->buf->buf, bf->size);
}
if (!r->file) {
eprintf ("Core file not open\n");
return false;
}
RList *l = r_bin_raw_strings (bf, 0);
_print_strings (r, l, mode, va);
return true;
}
static bool bin_strings(RCore *r, int mode, int va) {
RList *list;
RBinFile *binfile = r_core_bin_cur (r);
RBinPlugin *plugin = r_bin_file_cur_plugin (binfile);
int rawstr = r_config_get_i (r->config, "bin.rawstr");
if (!binfile) {
return false;
}
if (!r_config_get_i (r->config, "bin.strings")) {
return 0;
}
if (!plugin) {
return 0;
}
if (plugin->info && plugin->name) {
if (strcmp (plugin->name, "any") == 0 && !rawstr) {
if (IS_MODE_JSON (mode)) {
r_cons_print("[]");
}
return false;
}
}
if (!(list = r_bin_get_strings (r->bin))) {
return false;
}
_print_strings (r, list, mode, va);
return true;
}
static const char* get_compile_time(Sdb *binFileSdb) {
Sdb *info_ns = sdb_ns (binFileSdb, "info", false);
const char *timeDateStamp_string = sdb_const_get (info_ns,
"image_file_header.TimeDateStamp_string", 0);
return timeDateStamp_string;
}
static int is_executable(RBinObject *obj) {
RListIter *it;
RBinSection* sec;
if (obj) {
if (obj->info && obj->info->arch) {
return true;
}
r_list_foreach (obj->sections, it, sec) {
if (R_BIN_SCN_EXECUTABLE & sec->srwx) {
return true;
}
}
}
return false;
}
#define DBSPATH R2_PREFIX "/share/radare2/" R2_VERSION "/fcnsign"
static void sdb_concat_by_path(Sdb *s, const char *path) {
Sdb *db = sdb_new (0, path, 0);
sdb_merge (s, db);
sdb_close (db);
sdb_free (db);
}
R_API void r_core_anal_type_init(RCore *core) {
Sdb *types = NULL;
const char *anal_arch = NULL, *os = NULL;
int bits = 0;
char *dbpath;
if (!core || !core->anal) {
return;
}
bits = core->assembler->bits;
types = core->anal->sdb_types;
// make sure they are empty this is initializing
sdb_reset (types);
anal_arch = r_config_get (core->config, "anal.arch");
os = r_config_get (core->config, "asm.os");
if (r_file_exists (DBSPATH"/types.sdb")) {
sdb_concat_by_path (types, DBSPATH"/types.sdb");
}
dbpath = sdb_fmt (-1, DBSPATH"/types-%s.sdb", anal_arch);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (-1, DBSPATH"/types-%s.sdb", os);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (-1, DBSPATH"/types-%d.sdb", bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (-1, DBSPATH"/types-%s-%d.sdb", os, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (-1, DBSPATH"/types-%s-%d.sdb", anal_arch, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (-1, DBSPATH"/types-%s-%s.sdb", anal_arch, os);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
dbpath = sdb_fmt (-1, DBSPATH"/types-%s-%s-%d.sdb", anal_arch, os, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (types, dbpath);
}
}
static int save_ptr(void *p, const char *k, const char *v) {
Sdb *sdbs[2];
sdbs[0] = ((Sdb**) p)[0];
sdbs[1] = ((Sdb**) p)[1];
if (!strncmp (v, "cc", strlen ("cc") + 1)) {
const char *x = sdb_const_get (sdbs[1], sdb_fmt (-1, "cc.%s.name", k), 0);
char *tmp = sdb_fmt (-1, "%p", x);
sdb_set (sdbs[0], tmp, x, 0);
}
return 1;
}
R_API void r_core_anal_cc_init(RCore *core) {
Sdb *sdbs[2] = {
sdb_new0 (),
core->anal->sdb_cc
};
//save pointers and values stored inside them
//to recover from freeing heeps
const char *defaultcc = sdb_const_get (sdbs[1], "default.cc", 0);
sdb_set (sdbs[0], sdb_fmt (-1, "0x%08"PFMT64x, r_num_get (NULL, defaultcc)), defaultcc, 0);
sdb_foreach (core->anal->sdb_cc, save_ptr, sdbs);
sdb_reset ( core->anal->sdb_cc);
const char *anal_arch = r_config_get (core->config, "anal.arch");
int bits = core->anal->bits;
if (bits == 16 && !strcmp (anal_arch, "arm")) {
bits = 32;
}
char *dbpath = sdb_fmt (-1, DBSPATH"/cc-%s-%d.sdb", anal_arch, bits);
if (r_file_exists (dbpath)) {
sdb_concat_by_path (core->anal->sdb_cc, dbpath);
}
//restore all freed CC or replace with new default cc
RListIter *it;
RAnalFunction *fcn;
r_list_foreach (core->anal->fcns, it, fcn) {
char *ptr = sdb_fmt (-1, "%p", fcn->cc);
const char *cc = sdb_const_get (sdbs[0], ptr, 0);
if (cc) {
fcn->cc = r_anal_cc_to_constant (core->anal, (char *)cc);
}
if (!fcn->cc) {
fcn->cc = r_anal_cc_default (core->anal);
}
fcn->cc = r_str_const (fcn->cc);
}
sdb_close (sdbs[0]);
sdb_free (sdbs[0]);
}
#undef DBSPATH
static int bin_info(RCore *r, int mode) {
int i, j, v;
char str[R_FLAG_NAME_SIZE];
RBinInfo *info = r_bin_get_info (r->bin);
RBinFile *binfile = r_core_bin_cur (r);
RBinObject *obj = r_bin_cur_object (r->bin);
const char *compiled = NULL;
bool havecode;
if (!binfile || !info || !obj) {
if (mode & R_CORE_BIN_JSON) {
r_cons_printf ("{}");
}
return false;
}
havecode = is_executable (obj) | (obj->entries != NULL);
compiled = get_compile_time (binfile->sdb);
if (IS_MODE_SET (mode)) {
r_config_set (r->config, "file.type", info->rclass);
r_config_set (r->config, "cfg.bigendian",
info->big_endian ? "true" : "false");
if (info->rclass && !strcmp (info->rclass, "fs")) {
r_config_set (r->config, "asm.arch", info->arch);
r_core_cmdf (r, "m /root %s 0", info->arch);
} else {
if (info->lang) {
r_config_set (r->config, "bin.lang", info->lang);
}
r_config_set (r->config, "asm.os", info->os);
r_config_set (r->config, "asm.arch", info->arch);
r_config_set (r->config, "anal.arch", info->arch);
snprintf (str, R_FLAG_NAME_SIZE, "%i", info->bits);
r_config_set (r->config, "asm.bits", str);
r_config_set (r->config, "asm.dwarf",
(R_BIN_DBG_STRIPPED & info->dbg_info) ? "false" : "true");
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) r_config_set_i (r->config, "asm.pcalign", v);
}
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("arch %s\n", info->arch);
r_cons_printf ("bits %d\n", info->bits);
r_cons_printf ("os %s\n", info->os);
r_cons_printf ("endian %s\n", info->big_endian? "big": "little");
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MIN_OP_SIZE);
if (v != -1) {
r_cons_printf ("minopsz %d\n", v);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MAX_OP_SIZE);
if (v != -1) {
r_cons_printf ("maxopsz %d\n", v);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) {
r_cons_printf ("pcalign %d\n", v);
}
} else if (IS_MODE_RAD (mode)) {
if (info->type && !strcmp (info->type, "fs")) {
r_cons_printf ("e file.type=fs\n");
r_cons_printf ("m /root %s 0\n", info->arch);
} else {
r_cons_printf ("e cfg.bigendian=%s\n"
"e asm.bits=%i\n"
"e asm.dwarf=%s\n",
r_str_bool (info->big_endian),
info->bits,
r_str_bool (R_BIN_DBG_STRIPPED &info->dbg_info));
if (info->lang && *info->lang) {
r_cons_printf ("e bin.lang=%s\n", info->lang);
}
if (info->rclass && *info->rclass) {
r_cons_printf ("e file.type=%s\n",
info->rclass);
}
if (info->os) {
r_cons_printf ("e asm.os=%s\n", info->os);
}
if (info->arch) {
r_cons_printf ("e asm.arch=%s\n", info->arch);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) r_cons_printf ("e asm.pcalign=%d\n", v);
}
} else {
// XXX: if type is 'fs' show something different?
char *tmp_buf;
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{");
}
pair_str ("arch", info->arch, mode, false);
pair_int ("binsz", r_bin_get_size (r->bin), mode, false);
pair_str ("bintype", info->rclass, mode, false);
pair_int ("bits", info->bits, mode, false);
pair_bool ("canary", info->has_canary, mode, false);
pair_str ("class", info->bclass, mode, false);
if (info->actual_checksum) {
/* computed checksum */
pair_str ("cmp.csum", info->actual_checksum, mode, false);
}
pair_str ("compiled", compiled, mode, false);
pair_bool ("crypto", info->has_crypto, mode, false);
tmp_buf = r_str_escape (info->debug_file_name);
pair_str ("dbg_file", tmp_buf, mode, false);
free (tmp_buf);
pair_str ("endian", info->big_endian ? "big" : "little", mode, false);
pair_bool ("havecode", havecode, mode, false);
if (info->claimed_checksum) {
/* checksum specified in header */
pair_str ("hdr.csum", info->claimed_checksum, mode, false);
}
pair_str ("guid", info->guid, mode, false);
pair_str ("intrp", info->intrp, mode, false);
pair_str ("lang", info->lang, mode, false);
pair_bool ("linenum", R_BIN_DBG_LINENUMS & info->dbg_info, mode, false);
pair_bool ("lsyms", R_BIN_DBG_SYMS & info->dbg_info, mode, false);
pair_str ("machine", info->machine, mode, false);
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MAX_OP_SIZE);
if (v != -1) {
pair_int ("maxopsz", v, mode, false);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_MIN_OP_SIZE);
if (v != -1) {
pair_int ("minopsz", v, mode, false);
}
pair_bool ("nx", info->has_nx, mode, false);
pair_str ("os", info->os, mode, false);
if (info->rclass && !strcmp (info->rclass, "pe")) {
pair_bool ("overlay", info->pe_overlay, mode, false);
}
v = r_anal_archinfo (r->anal, R_ANAL_ARCHINFO_ALIGN);
if (v != -1) {
pair_int ("pcalign", v, mode, false);
}
pair_bool ("pic", info->has_pi, mode, false);
pair_bool ("relocs", R_BIN_DBG_RELOCS & info->dbg_info, mode, false);
tmp_buf = sdb_get (obj->kv, "elf.relro", 0);
if (tmp_buf) {
pair_str ("relro", tmp_buf, mode, false);
free (tmp_buf);
}
pair_str ("rpath", info->rpath, mode, false);
if (info->rclass && !strcmp (info->rclass, "pe")) {
//this should be moved if added to mach0 (or others)
pair_bool ("signed", info->signature, mode, false);
}
pair_bool ("static", r_bin_is_static (r->bin), mode, false);
pair_bool ("stripped", R_BIN_DBG_STRIPPED & info->dbg_info, mode, false);
pair_str ("subsys", info->subsystem, mode, false);
pair_bool ("va", info->has_va, mode, true);
if (IS_MODE_JSON (mode)) {
r_cons_printf (",\"checksums\":{");
for (i = 0; info->sum[i].type; i++) {
RBinHash *h = &info->sum[i];
ut64 hash = r_hash_name_to_bits (h->type);
RHash *rh = r_hash_new (true, hash);
int len = r_hash_calculate (rh, hash, (const ut8*)
binfile->buf->buf+h->from, h->to);
if (len < 1) {
eprintf ("Invaild checksum length\n");
}
r_hash_free (rh);
r_cons_printf ("%s\"%s\":{\"hex\":\"", i?",": "", h->type);
// r_cons_printf ("%s\t%d-%dc\t", h->type, h->from, h->to+h->from);
for (j = 0; j < h->len; j++) {
r_cons_printf ("%02x", h->buf[j]);
}
r_cons_printf ("\"}");
}
r_cons_printf ("}");
} else {
for (i = 0; info->sum[i].type; i++) {
RBinHash *h = &info->sum[i];
ut64 hash = r_hash_name_to_bits (h->type);
RHash *rh = r_hash_new (true, hash);
int len = r_hash_calculate (rh, hash, (const ut8*)
binfile->buf->buf+h->from, h->to);
if (len < 1) {
eprintf ("Invaild wtf\n");
}
r_hash_free (rh);
r_cons_printf ("%s\t%d-%dc\t", h->type, h->from, h->to+h->from);
for (j = 0; j < h->len; j++) {
r_cons_printf ("%02x", h->buf[j]);
}
r_cons_newline ();
}
}
if (IS_MODE_JSON (mode)) r_cons_printf ("}");
}
r_core_anal_type_init (r);
r_core_anal_cc_init (r);
return true;
}
static int bin_dwarf(RCore *core, int mode) {
RBinDwarfRow *row;
RListIter *iter;
RList *list = NULL;
RBinFile *binfile = r_core_bin_cur (core);
RBinPlugin * plugin = r_bin_file_cur_plugin (binfile);
if (!binfile) {
return false;
}
if (plugin && plugin->lines) {
list = plugin->lines (binfile);
} else if (core->bin) {
// TODO: complete and speed-up support for dwarf
if (r_config_get_i (core->config, "bin.dbginfo")) {
RBinDwarfDebugAbbrev *da = NULL;
da = r_bin_dwarf_parse_abbrev (core->bin, mode);
r_bin_dwarf_parse_info (da, core->bin, mode);
r_bin_dwarf_parse_aranges (core->bin, mode);
list = r_bin_dwarf_parse_line (core->bin, mode);
r_bin_dwarf_free_debug_abbrev (da);
free (da);
}
}
if (!list) {
return false;
}
r_cons_break_push (NULL, NULL);
/* cache file:line contents */
const char *lastFile = NULL;
int *lastFileLines = NULL;
char *lastFileContents = NULL;
int lastFileLinesCount = 0;
/* ugly dupe for speedup */
const char *lastFile2 = NULL;
int *lastFileLines2 = NULL;
char *lastFileContents2 = NULL;
int lastFileLinesCount2 = 0;
const char *lf = NULL;
int *lfl = NULL;
char *lfc = NULL;
int lflc = 0;
//TODO we should need to store all this in sdb, or do a filecontentscache in libr/util
//XXX this whole thing has leaks
r_list_foreach (list, iter, row) {
if (r_cons_is_breaked ()) {
break;
}
if (mode) {
// TODO: use 'Cl' instead of CC
const char *path = row->file;
if (!lastFile || strcmp (path, lastFile)) {
if (lastFile && lastFile2 && !strcmp (path, lastFile2)) {
lf = lastFile;
lfl = lastFileLines;
lfc = lastFileContents;
lflc = lastFileLinesCount;
lastFile = lastFile2;
lastFileLines = lastFileLines2;
lastFileContents = lastFileContents2;
lastFileLinesCount = lastFileLinesCount2;
lastFile2 = lf;
lastFileLines2 = lfl;
lastFileContents2 = lfc;
lastFileLinesCount2 = lflc;
} else {
lastFile2 = lastFile;
lastFileLines2 = lastFileLines;
lastFileContents2 = lastFileContents;
lastFileLinesCount2 = lastFileLinesCount;
lastFile = path;
lastFileContents = r_file_slurp (path, NULL);
if (lastFileContents) {
lastFileLines = r_str_split_lines (lastFileContents, &lastFileLinesCount);
}
}
}
char *line = NULL;
//r_file_slurp_line (path, row->line - 1, 0);
if (lastFileLines && lastFileContents) {
int nl = row->line - 1;
if (nl >= 0 && nl < lastFileLinesCount) {
line = strdup (lastFileContents + lastFileLines[nl]);
}
} else {
line = NULL;
}
if (line) {
r_str_filter (line, strlen (line));
line = r_str_replace (line, "\"", "\\\"", 1);
line = r_str_replace (line, "\\\\", "\\", 1);
}
bool chopPath = !r_config_get_i (core->config, "dir.dwarf.abspath");
char *file = strdup (row->file);
if (chopPath) {
const char *slash = r_str_lchr (file, '/');
if (slash) {
memmove (file, slash + 1, strlen (slash));
}
}
// TODO: implement internal : if ((mode & R_CORE_BIN_SET))
if ((mode & R_CORE_BIN_SET)) {
// TODO: use CL here.. but its not necessary.. so better not do anything imho
// r_core_cmdf (core, "CL %s:%d 0x%08"PFMT64x, file, (int)row->line, row->address);
#if 0
char *cmt = r_str_newf ("%s:%d %s", file, (int)row->line, line? line: "");
r_meta_set_string (core->anal, R_META_TYPE_COMMENT, row->address, cmt);
free (cmt);
#endif
} else {
r_cons_printf ("CL %s:%d 0x%08" PFMT64x "\n",
file, (int)row->line,
row->address);
r_cons_printf ("\"CC %s:%d %s\"@0x%" PFMT64x
"\n",
file, row->line,
line ? line : "", row->address);
}
free (file);
free (line);
} else {
r_cons_printf ("0x%08" PFMT64x "\t%s\t%d\n",
row->address, row->file, row->line);
}
}
r_cons_break_pop ();
R_FREE (lastFileContents);
R_FREE (lastFileContents2);
r_list_free (list);
free (lastFileLines);
return true;
}
static int bin_pdb(RCore *core, int mode) {
R_PDB pdb = R_EMPTY;
ut64 baddr = r_bin_get_baddr (core->bin);
pdb.cb_printf = r_cons_printf;
if (!init_pdb_parser (&pdb, core->bin->file)) {
return false;
}
if (!pdb.pdb_parse (&pdb)) {
eprintf ("pdb was not parsed\n");
pdb.finish_pdb_parse (&pdb);
return false;
}
if (mode == R_CORE_BIN_JSON) {
r_cons_printf("[");
}
switch (mode) {
case R_CORE_BIN_SET:
mode = 's';
r_core_cmd0 (core, ".iP*");
return true;
case R_CORE_BIN_JSON:
mode = 'j';
break;
case '*':
case 1:
mode = 'r';
break;
default:
mode = 'd'; // default
break;
}
pdb.print_types (&pdb, mode);
if (mode == 'j') {
r_cons_printf (",");
}
pdb.print_gvars (&pdb, baddr, mode);
if (mode == 'j') {
r_cons_printf ("]");
}
pdb.finish_pdb_parse (&pdb);
return true;
}
static int bin_main(RCore *r, int mode, int va) {
RBinAddr *binmain = r_bin_get_sym (r->bin, R_BIN_SYM_MAIN);
ut64 addr;
if (!binmain) {
return false;
}
addr = va ? r_bin_a2b (r->bin, binmain->vaddr) : binmain->paddr;
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "symbols");
r_flag_set (r->flags, "main", addr, r->blocksize);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("%"PFMT64d, addr);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
r_cons_printf ("f main @ 0x%08"PFMT64x"\n", addr);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"vaddr\":%" PFMT64d
",\"paddr\":%" PFMT64d "}", addr, binmain->paddr);
} else {
r_cons_printf ("[Main]\n");
r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x"\n",
addr, binmain->paddr);
}
return true;
}
static int bin_entry(RCore *r, int mode, ut64 laddr, int va) {
char str[R_FLAG_NAME_SIZE];
RList *entries = r_bin_get_entries (r->bin);
RListIter *iter;
RBinAddr *entry = NULL;
int i = 0;
ut64 baddr = r_bin_get_baddr (r->bin);
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("[Entrypoints]\n");
}
r_list_foreach (entries, iter, entry) {
ut64 paddr = entry->paddr;
ut64 haddr = UT64_MAX;
if (entry->haddr) {
haddr = entry->haddr;
}
ut64 at = rva (r->bin, paddr, entry->vaddr, va);
const char *type = r_bin_entry_type_string (entry->type);
if (!type) {
type = "unknown";
}
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "symbols");
snprintf (str, R_FLAG_NAME_SIZE, "entry%i", i);
r_flag_set (r->flags, str, at, 1);
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x"\n", at);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s{\"vaddr\":%" PFMT64d ","
"\"paddr\":%" PFMT64d ","
"\"baddr\":%" PFMT64d ","
"\"laddr\":%" PFMT64d ","
"\"haddr\":%" PFMT64d ","
"\"type\":\"%s\"}",
iter->p ? "," : "", at, paddr, baddr, laddr, haddr, type);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("f entry%i 1 @ 0x%08"PFMT64x"\n", i, at);
r_cons_printf ("f entry%i_haddr 1 @ 0x%08"PFMT64x"\n", i, haddr);
r_cons_printf ("s entry%i\n", i);
} else {
r_cons_printf (
"vaddr=0x%08"PFMT64x
" paddr=0x%08"PFMT64x
" baddr=0x%08"PFMT64x
" laddr=0x%08"PFMT64x,
at, paddr, baddr, laddr);
if (haddr == UT64_MAX) {
r_cons_printf (
" haddr=%"PFMT64d
" type=%s\n",
haddr, type);
} else {
r_cons_printf (
" haddr=0x%08"PFMT64x
" type=%s\n",
haddr, type);
}
}
i++;
}
if (IS_MODE_SET (mode)) {
if (entry) {
ut64 at = rva (r->bin, entry->paddr, entry->vaddr, va);
r_core_seek (r, at, 0);
}
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
r_cons_newline ();
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i entrypoints\n", i);
}
return true;
}
static const char *bin_reloc_type_name(RBinReloc *reloc) {
#define CASE(T) case R_BIN_RELOC_ ## T: return reloc->additive ? "ADD_" #T : "SET_" #T
switch (reloc->type) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
}
return "UNKNOWN";
#undef CASE
}
static ut8 bin_reloc_size(RBinReloc *reloc) {
#define CASE(T) case R_BIN_RELOC_ ## T: return T / 8
switch (reloc->type) {
CASE(8);
CASE(16);
CASE(32);
CASE(64);
}
return 0;
#undef CASE
}
static char *resolveModuleOrdinal(Sdb *sdb, const char *module, int ordinal) {
Sdb *db = sdb;
char *foo = sdb_get (db, sdb_fmt (0, "%d", ordinal), 0);
return (foo && *foo) ? foo : NULL;
}
static char *get_reloc_name(RBinReloc *reloc, ut64 addr) {
char *reloc_name = NULL;
if (reloc->import && reloc->import->name) {
reloc_name = sdb_fmt (-1, "reloc.%s_%d", reloc->import->name,
(int)(addr & 0xff));
if (!reloc_name) {
return NULL;
}
r_str_replace_char (reloc_name, '$', '_');
} else if (reloc->symbol && reloc->symbol->name) {
reloc_name = sdb_fmt (-1, "reloc.%s_%d", reloc->symbol->name, (int)(addr & 0xff));
if (!reloc_name) {
return NULL;
}
r_str_replace_char (reloc_name, '$', '_');
} else if (reloc->is_ifunc) {
// addend is the function pointer for the resolving ifunc
reloc_name = sdb_fmt (-1, "reloc.ifunc_%"PFMT64x, reloc->addend);
} else {
// TODO(eddyb) implement constant relocs.
}
return reloc_name;
}
static void set_bin_relocs(RCore *r, RBinReloc *reloc, ut64 addr, Sdb **db, char **sdb_module) {
int bin_demangle = r_config_get_i (r->config, "bin.demangle");
const char *lang = r_config_get (r->config, "bin.lang");
char *reloc_name, *demname = NULL;
bool is_pe = true;
int is_sandbox = r_sandbox_enable (0);
if (reloc->import && reloc->import->name[0]) {
char str[R_FLAG_NAME_SIZE];
RFlagItem *fi;
if (is_pe && !is_sandbox && strstr (reloc->import->name, "Ordinal")) {
const char *TOKEN = ".dll_Ordinal_";
char *module = strdup (reloc->import->name);
char *import = strstr (module, TOKEN);
r_str_case (module, false);
if (import) {
char *filename = NULL;
int ordinal;
*import = 0;
import += strlen (TOKEN);
ordinal = atoi (import);
if (!*sdb_module || strcmp (module, *sdb_module)) {
sdb_free (*db);
*db = NULL;
free (*sdb_module);
*sdb_module = strdup (module);
/* always lowercase */
filename = sdb_fmt (1, "%s.sdb", module);
r_str_case (filename, false);
if (r_file_exists (filename)) {
*db = sdb_new (NULL, filename, 0);
} else {
#if __WINDOWS__
char invoke_dir[MAX_PATH];
if (r_sys_get_src_dir_w32(invoke_dir)) {
filename = sdb_fmt (1, "%s/share/radare2/"R2_VERSION "/format/dll/%s.sdb", invoke_dir, module);
} else {
filename = sdb_fmt (1, "share/radare2/"R2_VERSION"/format/dll/%s.sdb", module);
}
#else
filename = sdb_fmt (1, R2_PREFIX"/share/radare2/" R2_VERSION"/format/dll/%s.sdb", module);
#endif
if (r_file_exists (filename)) {
*db = sdb_new (NULL, filename, 0);
}
}
}
if (*db) {
// ordinal-1 because we enumerate starting at 0
char *symname = resolveModuleOrdinal (*db, module, ordinal - 1);
if (symname) {
if (r->bin->prefix) {
reloc->import->name = r_str_newf
("%s.%s.%s", r->bin->prefix, module, symname);
} else {
reloc->import->name = r_str_newf
("%s.%s", module, symname);
}
}
}
}
free (module);
r_anal_hint_set_size (r->anal, reloc->vaddr, 4);
r_meta_add (r->anal, R_META_TYPE_DATA, reloc->vaddr, reloc->vaddr+4, NULL);
}
reloc_name = reloc->import->name;
if (r->bin->prefix) {
snprintf (str, R_FLAG_NAME_SIZE, "%s.reloc.%s_%d", r->bin->prefix, reloc_name, (int)(addr&0xff));
} else {
snprintf (str, R_FLAG_NAME_SIZE, "reloc.%s_%d", reloc_name, (int)(addr&0xff));
}
if (bin_demangle) {
demname = r_bin_demangle (r->bin->cur, lang, str, addr);
}
r_name_filter (str, 0);
fi = r_flag_set (r->flags, str, addr, bin_reloc_size (reloc));
if (demname) {
char *realname;
if (r->bin->prefix) {
realname = sdb_fmt (0, "%s.reloc.%s", r->bin->prefix, demname);
} else {
realname = sdb_fmt (0, "reloc.%s", demname);
}
r_flag_item_set_realname (fi, realname);
}
} else {
char *reloc_name = get_reloc_name (reloc, addr);
r_flag_set (r->flags, reloc_name, addr, bin_reloc_size (reloc));
}
}
static int bin_relocs(RCore *r, int mode, int va) {
int bin_demangle = r_config_get_i (r->config, "bin.demangle");
RList *relocs;
RListIter *iter;
RBinReloc *reloc = NULL;
Sdb *db = NULL;
char *sdb_module = NULL;
int i = 0;
va = VA_TRUE; // XXX relocs always vaddr?
//this has been created for reloc object files
relocs = r_bin_patch_relocs (r->bin);
if (!relocs) {
relocs = r_bin_get_relocs (r->bin);
}
if (IS_MODE_RAD (mode)) {
r_cons_println ("fs relocs");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Relocations]");
} else if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "relocs");
}
RBinFile * binfile = r->bin->cur;
RBinObject *binobj = binfile ? binfile->o: NULL;
RBinInfo *info = binobj ? binobj->info: NULL;
int cdsz = info? (info->bits == 64? 8: info->bits == 32? 4: info->bits == 16 ? 4: 0): 0;
r_list_foreach (relocs, iter, reloc) {
ut64 addr = rva (r->bin, reloc->paddr, reloc->vaddr, va);
if (IS_MODE_SET (mode)) {
set_bin_relocs (r, reloc, addr, &db, &sdb_module);
if (cdsz) {
r_meta_add (r->anal, R_META_TYPE_DATA, reloc->vaddr, reloc->vaddr + cdsz, NULL);
}
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x" %s\n", addr, reloc->import ? reloc->import->name : "");
} else if (IS_MODE_RAD (mode)) {
char *name = reloc->import
? strdup (reloc->import->name)
: (reloc->symbol ? strdup (reloc->symbol->name) : NULL);
if (name && bin_demangle) {
char *mn = r_bin_demangle (r->bin->cur, NULL, name, addr);
if (mn) {
free (name);
name = mn;
}
}
if (name) {
r_cons_printf ("f %s%s%s @ 0x%08"PFMT64x"\n",
r->bin->prefix ? r->bin->prefix : "reloc.",
r->bin->prefix ? "." : "", name, addr);
if (cdsz) {
r_cons_printf ("f Cd %d @ 0x%08"PFMT64x"\n", cdsz, addr);
}
free (name);
}
} else if (IS_MODE_JSON (mode)) {
if (iter->p) {
r_cons_printf (",{\"name\":");
} else {
r_cons_printf ("{\"name\":");
}
// take care with very long symbol names! do not use sdb_fmt or similar
if (reloc->import) {
r_cons_printf ("\"%s\"", reloc->import->name);
} else if (reloc->symbol) {
r_cons_printf ("\"%s\"", reloc->symbol->name);
} else {
r_cons_printf ("null");
}
r_cons_printf (","
"\"type\":\"%s\","
"\"vaddr\":%"PFMT64d","
"\"paddr\":%"PFMT64d","
"\"is_ifunc\":%s}",
bin_reloc_type_name (reloc),
reloc->vaddr, reloc->paddr,
r_str_bool (reloc->is_ifunc));
} else if (IS_MODE_NORMAL (mode)) {
char *name = reloc->import
? strdup (reloc->import->name)
: reloc->symbol
? strdup (reloc->symbol->name)
: strdup ("null");
if (bin_demangle) {
char *mn = r_bin_demangle (r->bin->cur, NULL, name, addr);
if (mn && *mn) {
free (name);
name = mn;
}
}
r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x" type=%s",
addr, reloc->paddr, bin_reloc_type_name (reloc));
if (reloc->import && reloc->import->name[0]) {
r_cons_printf (" %s", name);
} else if (reloc->symbol && name && name[0]) {
r_cons_printf (" %s", name);
}
free (name);
if (reloc->addend) {
if (reloc->import && reloc->addend > 0) {
r_cons_printf (" +");
}
if (reloc->addend < 0) {
r_cons_printf (" - 0x%08"PFMT64x, -reloc->addend);
} else {
r_cons_printf (" 0x%08"PFMT64x, reloc->addend);
}
}
if (reloc->is_ifunc) {
r_cons_print (" (ifunc)");
}
r_cons_newline ();
}
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
}
if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i relocations\n", i);
}
return relocs != NULL;
}
#define MYDB 1
/* this is a hacky workaround that needs proper refactoring in Rbin to use Sdb */
#if MYDB
static Sdb *mydb = NULL;
static RList *osymbols = NULL;
static RBinSymbol *get_symbol(RBin *bin, RList *symbols, const char *name, ut64 addr) {
RBinSymbol *symbol, *res = NULL;
RListIter *iter;
if (mydb && symbols != osymbols) {
sdb_free (mydb);
mydb = NULL;
osymbols = symbols;
}
if (mydb) {
if (name) {
res = (RBinSymbol*)(void*)(size_t)
sdb_num_get (mydb, sdb_fmt (0, "%x", sdb_hash (name)), NULL);
} else {
res = (RBinSymbol*)(void*)(size_t)
sdb_num_get (mydb, sdb_fmt (0, "0x"PFMT64x, addr), NULL);
}
} else {
mydb = sdb_new0 ();
r_list_foreach (symbols, iter, symbol) {
/* ${name}=${ptrToSymbol} */
if (!sdb_num_add (mydb, sdb_fmt (0, "%x", sdb_hash (symbol->name)), (ut64)(size_t)symbol, 0)) {
// eprintf ("DUP (%s)\n", symbol->name);
}
/* 0x${vaddr}=${ptrToSymbol} */
if (!sdb_num_add (mydb, sdb_fmt (0, "0x"PFMT64x, symbol->vaddr), (ut64)(size_t)symbol, 0)) {
// eprintf ("DUP (%s)\n", symbol->name);
}
if (name) {
if (!res && !strcmp (symbol->name, name)) {
res = symbol;
}
} else {
if (symbol->vaddr == addr) {
res = symbol;
}
}
}
}
return res;
}
#else
static RList *osymbols = NULL;
static RBinSymbol *get_symbol(RBin *bin, RList *symbols, const char *name, ut64 addr) {
RBinSymbol *symbol;
RListIter *iter;
r_list_foreach (symbols, iter, symbol) {
if (name) {
if (!strcmp (symbol->name, name))
return symbol;
} else {
if (symbol->vaddr == addr) {
return symbol;
}
}
}
return NULL;
}
#endif
/* XXX: This is a hack to get PLT references in rabin2 -i */
/* imp. is a prefix that can be rewritten by the symbol table */
static ut64 impaddr(RBin *bin, int va, const char *name) {
char *impname;
RList *symbols;
RBinSymbol *s;
if (!name || !*name) {
return false;
}
if (!(symbols = r_bin_get_symbols (bin))) {
return false;
}
impname = sdb_fmt (2, "imp.%s", name);
s = get_symbol (bin, symbols, impname, 0LL);
if (s) {
if (va) {
return r_bin_get_vaddr (bin, s->paddr, s->vaddr);
}
return s->paddr;
}
return 0LL;
}
static int bin_imports(RCore *r, int mode, int va, const char *name) {
int bin_demangle = r_config_get_i (r->config, "bin.demangle");
RBinImport *import;
RListIter *iter;
RList *imports;
char *str;
int i = 0;
imports = r_bin_get_imports (r->bin);
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_RAD (mode)) {
r_cons_println ("fs imports");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Imports]");
}
r_list_foreach (imports, iter, import) {
char *symname;
ut64 addr;
if (name && strcmp (import->name, name)) {
continue;
}
symname = strdup (import->name);
addr = impaddr (r->bin, va, symname);
if (bin_demangle) {
char *dname = r_bin_demangle (r->bin->cur, NULL, symname, addr);
if (dname) {
free (symname);
symname = r_str_newf ("sym.imp.%s", dname);
free (dname);
}
}
if (r->bin->prefix) {
char *prname;
prname = r_str_newf ("%s.%s", r->bin->prefix, symname);
free (symname);
symname = prname;
}
if (IS_MODE_SET (mode)) {
// TODO(eddyb) symbols that are imports.
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_println (symname);
} else if (IS_MODE_JSON (mode)) {
str = r_str_utf16_encode (symname, -1);
str = r_str_replace (str, "\"", "\\\"", 1);
r_cons_printf ("%s{\"ordinal\":%d,"
"\"bind\":\"%s\","
"\"type\":\"%s\",",
iter->p ? "," : "",
import->ordinal,
import->bind,
import->type);
if (import->classname && import->classname[0]) {
r_cons_printf ("\"classname\":\"%s\","
"\"descriptor\":\"%s\",",
import->classname,
import->descriptor);
}
r_cons_printf ("\"name\":\"%s\",\"plt\":%"PFMT64d"}",
str, addr);
free (str);
} else if (IS_MODE_RAD (mode)) {
// TODO(eddyb) symbols that are imports.
} else {
const char *bind = r_str_get (import->bind);
const char *type = r_str_get (import->type);
r_cons_printf ("ordinal=%03d plt=0x%08"PFMT64x" bind=%s type=%s",
import->ordinal, addr, bind, type);
if (import->classname && import->classname[0]) {
r_cons_printf (" classname=%s", import->classname);
}
r_cons_printf (" name=%s", symname);
if (import->descriptor && import->descriptor[0]) {
r_cons_printf (" descriptor=%s", import->descriptor);
}
r_cons_newline ();
}
free (symname);
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i imports\n", i);
}
#if MYDB
osymbols = NULL;
sdb_free (mydb);
mydb = NULL;
#endif
return true;
}
static const char *getPrefixFor(const char *s) {
if (s) {
if (!strcmp (s, "NOTYPE")) {
return "loc";
}
if (!strcmp (s, "OBJECT")) {
return "obj";
}
}
return "sym";
}
typedef struct {
const char *pfx; // prefix for flags
char *name; // raw symbol name
char *nameflag; // flag name for symbol
char *demname; // demangled raw symbol name
char *demflag; // flag name for demangled symbol
char *classname; // classname
char *classflag; // flag for classname
char *methname; // methods [class]::[method]
char *methflag; // methods flag sym.[class].[method]
} SymName;
static void snInit(RCore *r, SymName *sn, RBinSymbol *sym, const char *lang) {
#define MAXFLAG_LEN 128
int bin_demangle = lang != NULL;
const char *pfx;
if (!r || !sym || !sym->name) return;
pfx = getPrefixFor (sym->type);
sn->name = strdup (sym->name);
if (sym->dup_count) {
sn->nameflag = r_str_newf ("%s.%s_%d", pfx, sym->name, sym->dup_count);
} else {
sn->nameflag = r_str_newf ("%s.%s", pfx, sym->name);
}
r_name_filter (sn->nameflag, MAXFLAG_LEN);
if (sym->classname && sym->classname[0]) {
sn->classname = strdup (sym->classname);
sn->classflag = r_str_newf ("sym.%s.%s", sn->classname, sn->name);
r_name_filter (sn->classflag, MAXFLAG_LEN);
const char *name = sym->dname? sym->dname: sym->name;
sn->methname = r_str_newf ("%s::%s", sn->classname, name);
sn->methflag = r_str_newf ("sym.%s.%s", sn->classname, name);
r_name_filter (sn->methflag, strlen (sn->methflag));
} else {
sn->classname = NULL;
sn->classflag = NULL;
sn->methname = NULL;
sn->methflag = NULL;
}
sn->demname = NULL;
sn->demflag = NULL;
if (bin_demangle && sym->paddr) {
sn->demname = r_bin_demangle (r->bin->cur, lang, sn->name, sym->vaddr);
if (sn->demname) {
sn->demflag = r_str_newf ("%s.%s", pfx, sn->demname);
r_name_filter (sn->demflag, -1);
}
}
}
static void snFini(SymName *sn) {
R_FREE (sn->name);
R_FREE (sn->nameflag);
R_FREE (sn->demname);
R_FREE (sn->demflag);
R_FREE (sn->classname);
R_FREE (sn->classflag);
R_FREE (sn->methname);
R_FREE (sn->methflag);
}
static bool isAnExport(RBinSymbol *s) {
/* workaround for some bin plugs */
if (!strncmp (s->name, "imp.", 4)) {
return false;
}
return (s->bind && !strcmp (s->bind, "GLOBAL"));
}
static int bin_symbols_internal(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, bool exponly) {
RBinInfo *info = r_bin_get_info (r->bin);
RList *entries = r_bin_get_entries (r->bin);
RBinSymbol *symbol;
RBinAddr *entry;
RListIter *iter;
RList *symbols;
const char *lang;
bool firstexp = true;
int i = 0, is_arm, lastfs = 's',
bin_demangle = r_config_get_i (r->config, "bin.demangle");
if (!info) {
return 0;
}
is_arm = info && info->arch && !strncmp (info->arch, "arm", 3);
lang = bin_demangle ? r_config_get (r->config, "bin.lang") : NULL;
symbols = r_bin_get_symbols (r->bin);
r_space_set (&r->anal->meta_spaces, "bin");
if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
} else if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "symbols");
} else if (!at && exponly) {
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs exports\n");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("[Exports]\n");
}
} else if (!at && !exponly) {
if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs symbols\n");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("[Symbols]\n");
}
}
r_list_foreach (symbols, iter, symbol) {
ut64 addr = rva (r->bin, symbol->paddr, symbol->vaddr, va);
SymName sn;
if (exponly && !isAnExport (symbol)) {
continue;
}
if (name && strcmp (symbol->name, name)) {
continue;
}
if (at && (!symbol->size || !is_in_range (at, addr, symbol->size))) {
continue;
}
snInit (r, &sn, symbol, lang);
if (IS_MODE_SET (mode)) {
if (is_arm && info->bits < 33) { // 16 or 32
int force_bits = 0;
if (symbol->paddr & 1 || symbol->bits == 16) {
force_bits = 16;
} else if (info->bits == 16 && symbol->bits == 32) {
force_bits = 32;
} else if (!(symbol->paddr & 1) && symbol->bits == 32) {
force_bits = 32;
}
if (force_bits) {
r_anal_hint_set_bits (r->anal, addr, force_bits);
}
}
if (!strncmp (symbol->name, "imp.", 4)) {
if (lastfs != 'i') {
r_flag_space_set (r->flags, "imports");
}
lastfs = 'i';
} else {
if (lastfs != 's') {
r_flag_space_set (r->flags, "symbols");
}
lastfs = 's';
}
/* If that's a Classed symbol (method or so) */
if (sn.classname) {
RFlagItem *fi = NULL;
char *comment = NULL;
fi = r_flag_get (r->flags, sn.methflag);
if (r->bin->prefix) {
char *prname;
prname = r_str_newf ("%s.%s", r->bin->prefix, sn.methflag);
r_name_filter (sn.methflag, -1);
free (sn.methflag);
sn.methflag = prname;
}
if (fi) {
r_flag_item_set_realname (fi, sn.methname);
if ((fi->offset - r->flags->base) == addr) {
comment = fi->comment ? strdup (fi->comment) : NULL;
r_flag_unset (r->flags, fi);
fi = NULL;
}
} else {
fi = r_flag_set (r->flags, sn.methflag, addr, symbol->size);
comment = fi->comment ? strdup (fi->comment) : NULL;
if (comment) {
r_flag_item_set_comment (fi, comment);
R_FREE (comment);
}
}
} else {
const char *fn, *n;
RFlagItem *fi;
n = sn.demname ? sn.demname : sn.name;
fn = sn.demflag ? sn.demflag : sn.nameflag;
char *fnp = (r->bin->prefix) ?
r_str_newf ("%s.%s", r->bin->prefix, fn):
strdup (fn);
fi = r_flag_set (r->flags, fnp, addr, symbol->size);
if (fi) {
r_flag_item_set_realname (fi, n);
} else {
if (fn) {
eprintf ("[Warning] Can't find flag (%s)\n", fn);
}
}
free (fnp);
}
if (sn.demname) {
r_meta_add (r->anal, R_META_TYPE_COMMENT,
addr, symbol->size, sn.demname);
}
} else if (IS_MODE_JSON (mode)) {
char *str = r_str_utf16_encode (symbol->name, -1);
str = r_str_replace (str, "\"", "\\\"", 1);
r_cons_printf ("%s{\"name\":\"%s\","
"\"demname\":\"%s\","
"\"flagname\":\"%s\","
"\"size\":%d,"
"\"type\":\"%s\","
"\"vaddr\":%"PFMT64d","
"\"paddr\":%"PFMT64d"}",
(exponly && firstexp) ? "" : (iter->p ? "," : ""), str,
sn.demname? sn.demname: "",
sn.nameflag,
(int)symbol->size,
symbol->type,
(ut64)addr, (ut64)symbol->paddr);
free (str);
} else if (IS_MODE_SIMPLE (mode)) {
const char *name = sn.demname? sn.demname: symbol->name;
r_cons_printf ("0x%08"PFMT64x" %d %s\n",
addr, (int)symbol->size, name);
} else if (IS_MODE_SIMPLEST (mode)) {
const char *name = sn.demname? sn.demname: symbol->name;
r_cons_printf ("%s\n", name);
} else if (IS_MODE_RAD (mode)) {
RBinFile *binfile;
RBinPlugin *plugin;
char *name = strdup (sn.demname? sn.demname: symbol->name);
r_name_filter (name, -1);
if (!strncmp (name, "imp.", 4)) {
if (lastfs != 'i')
r_cons_printf ("fs imports\n");
lastfs = 'i';
} else {
if (lastfs != 's') {
r_cons_printf ("fs %s\n",
exponly? "exports": "symbols");
}
lastfs = 's';
}
if (r->bin->prefix) {
if (symbol->dup_count) {
r_cons_printf ("f %s.sym.%s_%d %u 0x%08"PFMT64x"\n",
r->bin->prefix, name, symbol->dup_count, symbol->size, addr);
} else {
r_cons_printf ("f %s.sym.%s %u 0x%08"PFMT64x"\n",
r->bin->prefix, name, symbol->size, addr);
}
} else {
if (symbol->dup_count) {
r_cons_printf ("f sym.%s_%d %u 0x%08"PFMT64x"\n",
name, symbol->dup_count, symbol->size, addr);
} else {
r_cons_printf ("f sym.%s %u 0x%08"PFMT64x"\n",
name, symbol->size, addr);
}
}
binfile = r_core_bin_cur (r);
plugin = r_bin_file_cur_plugin (binfile);
if (plugin && plugin->name) {
if (!strncmp (plugin->name, "pe", 2)) {
char *p, *module = strdup (symbol->name);
p = strstr (module, ".dll_");
if (p) {
const char *symname = p + 5;
*p = 0;
if (r->bin->prefix) {
r_cons_printf ("k bin/pe/%s/%d=%s.%s\n",
module, symbol->ordinal, r->bin->prefix, symname);
} else {
r_cons_printf ("k bin/pe/%s/%d=%s\n",
module, symbol->ordinal, symname);
}
}
free (module);
}
}
} else {
const char *bind = symbol->bind;
const char *type = symbol->type;
const char *name = sn.demname? sn.demname: symbol->name;
const char *fwd = symbol->forwarder;
if (!bind) bind = "";
if (!type) type = "";
if (!fwd) fwd = "";
r_cons_printf ("vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x" ord=%03u "
"fwd=%s sz=%u bind=%s type=%s name=%s\n",
addr, symbol->paddr, symbol->ordinal, fwd,
symbol->size, bind, type, name);
}
snFini (&sn);
i++;
if (exponly && firstexp) {
firstexp = false;
}
}
//handle thumb and arm for entry point since they are not present in symbols
if (is_arm) {
r_list_foreach (entries, iter, entry) {
if (IS_MODE_SET (mode)) {
if (info->bits < 33) { // 16 or 32
int force_bits = 0;
ut64 addr = rva (r->bin, entry->paddr, entry->vaddr, va);
if (entry->paddr & 1 || entry->bits == 16) {
force_bits = 16;
} else if (info->bits == 16 && entry->bits == 32) {
force_bits = 32;
} else if (!(entry->paddr & 1)) {
force_bits = 32;
}
if (force_bits) {
r_anal_hint_set_bits (r->anal, addr, force_bits);
}
}
}
}
}
if (IS_MODE_JSON (mode)) r_cons_printf ("]");
if (IS_MODE_NORMAL (mode) && !at) {
r_cons_printf ("\n%i %s\n", i, exponly ? "exports" : "symbols");
}
r_space_set (&r->anal->meta_spaces, NULL);
return true;
}
static int bin_exports(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name) {
return bin_symbols_internal (r, mode, laddr, va, at, name, true);
}
static int bin_symbols(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name) {
return bin_symbols_internal (r, mode, laddr, va, at, name, false);
}
static char *build_hash_string(int mode, const char *chksum, ut8 *data, ut32 datalen) {
char *chkstr = NULL, *aux, *ret = NULL;
const char *ptr = chksum;
char tmp[128];
int i;
do {
for (i = 0; *ptr && *ptr != ',' && i < sizeof (tmp) -1; i++) {
tmp[i] = *ptr++;
}
tmp[i] = '\0';
chkstr = r_hash_to_string (NULL, tmp, data, datalen);
if (!chkstr) {
if (*ptr && *ptr == ',') {
ptr++;
}
continue;
}
if (IS_MODE_SIMPLE (mode)) {
aux = r_str_newf ("%s ", chkstr);
} else if (IS_MODE_JSON (mode)) {
aux = r_str_newf ("\"%s\":\"%s\",", tmp, chkstr);
} else {
aux = r_str_newf ("%s=%s ", tmp, chkstr);
}
ret = r_str_append (ret, aux);
free (chkstr);
free (aux);
if (*ptr && *ptr == ',') ptr++;
} while (*ptr);
return ret;
}
static int bin_sections(RCore *r, int mode, ut64 laddr, int va, ut64 at, const char *name, const char *chksum) {
char str[R_FLAG_NAME_SIZE];
RBinSection *section;
RBinInfo *info = NULL;
RList *sections;
RListIter *iter;
int i = 0;
int fd = -1;
sections = r_bin_get_sections (r->bin);
bool inDebugger = r_config_get_i (r->config, "cfg.debug");
if (IS_MODE_JSON (mode)) r_cons_printf ("[");
else if (IS_MODE_RAD (mode) && !at) r_cons_printf ("fs sections\n");
else if (IS_MODE_NORMAL (mode) && !at) r_cons_printf ("[Sections]\n");
else if (IS_MODE_SET (mode)) {
fd = r_core_file_cur_fd (r);
r_flag_space_set (r->flags, "sections");
}
r_list_foreach (sections, iter, section) {
char perms[] = "-----";
int va_sect = va;
ut64 addr;
if (va && !(section->srwx & R_BIN_SCN_READABLE)) {
va_sect = VA_NOREBASE;
}
addr = rva (r->bin, section->paddr, section->vaddr, va_sect);
if (name && strcmp (section->name, name)) {
continue;
}
r_name_filter (section->name, sizeof (section->name));
if (at && (!section->size || !is_in_range (at, addr, section->size))) {
continue;
}
if (section->srwx & R_BIN_SCN_MAP) perms[0] = 'm';
if (section->srwx & R_BIN_SCN_SHAREABLE) perms[1] = 's';
if (section->srwx & R_BIN_SCN_READABLE) perms[2] = 'r';
if (section->srwx & R_BIN_SCN_WRITABLE) perms[3] = 'w';
if (section->srwx & R_BIN_SCN_EXECUTABLE) perms[4] = 'x';
if (IS_MODE_SET (mode)) {
#if LOAD_BSS_MALLOC
if (!strcmp (section->name, ".bss")) {
// check if there's already a file opened there
int loaded = 0;
RListIter *iter;
RIOMap *m;
r_list_foreach (r->io->maps, iter, m) {
if (m->from == addr) {
loaded = 1;
}
}
if (!loaded && !inDebugger) {
r_core_cmdf (r, "on malloc://%d 0x%"PFMT64x" # bss\n",
section->vsize, addr);
}
}
#endif
r_name_filter (section->name, 128);
if (section->format) {
// This is damn slow if section vsize is HUGE
if (section->vsize < 1024 * 1024 * 2) {
r_core_cmdf (r, "%s @ 0x%"PFMT64x, section->format, section->vaddr);
}
}
if (r->bin->prefix) {
snprintf (str, sizeof(str)-1, "%s.section.%s",
r->bin->prefix, section->name);
} else {
snprintf (str, sizeof(str)-1, "section.%s", section->name);
}
r_flag_set (r->flags, str, addr, section->size);
if (r->bin->prefix) {
snprintf (str, sizeof(str) - 1, "%s.section_end.%s",
r->bin->prefix, section->name);
} else {
snprintf (str, sizeof(str) - 1, "section_end.%s", section->name);
}
r_flag_set (r->flags, str, addr + section->size, 0);
if (section->arch || section->bits) {
const char *arch = section->arch;
int bits = section->bits;
if (info) {
if (!arch) {
arch = info->arch;
}
if (!bits) {
bits = info->bits;
}
}
//r_io_section_set_archbits (r->io, addr, arch, bits);
}
if (r->bin->prefix) {
snprintf (str, sizeof (str)-1, "section %i va=0x%08"PFMT64x" pa=0x%08"
PFMT64x" sz=%" PFMT64d" vsz=%"PFMT64d" rwx=%s %s.%s",
i, addr, section->paddr, section->size, section->vsize,
perms, r->bin->prefix, section->name);
} else {
snprintf (str, sizeof (str)-1, "section %i va=0x%08"PFMT64x" pa=0x%08"
PFMT64x" sz=%" PFMT64d" vsz=%"PFMT64d" rwx=%s %s",
i, addr, section->paddr, section->size, section->vsize,
perms, section->name);
}
r_meta_add (r->anal, R_META_TYPE_COMMENT, addr, addr, str);
if (section->add) {
r_io_section_add (r->io, section->paddr, addr,
section->size, section->vsize,
section->srwx, section->name,
0, fd);
}
} else if (IS_MODE_SIMPLE (mode)) {
char *hashstr = NULL;
if (chksum) {
ut8 *data = malloc (section->size);
if (!data) {
return false;
}
ut32 datalen = section->size;
r_io_pread (r->io, section->paddr, data, datalen);
hashstr = build_hash_string (mode, chksum,
data, datalen);
free (data);
}
r_cons_printf ("0x%"PFMT64x" 0x%"PFMT64x" %s %s%s%s\n",
addr, addr + section->size,
perms,
hashstr ? hashstr : "", hashstr ? " " : "",
section->name
);
free (hashstr);
} else if (IS_MODE_JSON (mode)) {
char *hashstr = NULL;
if (chksum) {
ut8 *data = malloc (section->size);
if (!data) {
return false;
}
ut32 datalen = section->size;
r_io_pread (r->io, section->paddr, data, datalen);
hashstr = build_hash_string (mode, chksum,
data, datalen);
free (data);
}
r_cons_printf ("%s{\"name\":\"%s\","
"\"size\":%"PFMT64d","
"\"vsize\":%"PFMT64d","
"\"flags\":\"%s\","
"%s"
"\"paddr\":%"PFMT64d","
"\"vaddr\":%"PFMT64d"}",
iter->p?",":"",
section->name,
section->size,
section->vsize,
perms,
hashstr ? hashstr : "",
section->paddr,
addr);
free (hashstr);
} else if (IS_MODE_RAD (mode)) {
if (!strcmp (section->name, ".bss") && !inDebugger) {
#if LOAD_BSS_MALLOC
r_cons_printf ("on malloc://%d 0x%"PFMT64x" # bss\n",
section->vsize, addr);
#endif
}
if (r->bin->prefix) {
r_cons_printf ("S 0x%08"PFMT64x" 0x%08"PFMT64x" 0x%08"PFMT64x" 0x%08"PFMT64x" %s.%s %d\n",
section->paddr, addr, section->size, section->vsize,
r->bin->prefix, section->name, (int)section->srwx);
} else {
r_cons_printf ("S 0x%08"PFMT64x" 0x%08"PFMT64x" 0x%08"PFMT64x" 0x%08"PFMT64x" %s %d\n",
section->paddr, addr, section->size, section->vsize,
section->name, (int)section->srwx);
}
if (section->arch || section->bits) {
const char *arch = section->arch;
int bits = section->bits;
if (info) {
if (!arch) arch = info->arch;
if (!bits) bits = info->bits;
}
if (!arch) {
arch = r_config_get (r->config, "asm.arch");
}
r_cons_printf ("Sa %s %d @ 0x%08"
PFMT64x"\n", arch, bits, addr);
}
if (r->bin->prefix) {
r_cons_printf ("f %s.section.%s %"PFMT64d" 0x%08"PFMT64x"\n",
r->bin->prefix, section->name, section->size, addr);
r_cons_printf ("f %s.section_end.%s 1 0x%08"PFMT64x"\n",
r->bin->prefix, section->name, addr + section->size);
r_cons_printf ("CC section %i va=0x%08"PFMT64x" pa=0x%08"PFMT64x" sz=%"PFMT64d" vsz=%"PFMT64d" "
"rwx=%s %s.%s @ 0x%08"PFMT64x"\n",
i, addr, section->paddr, section->size, section->vsize,
perms, r->bin->prefix, section->name, addr);
} else {
r_cons_printf ("f section.%s %"PFMT64d" 0x%08"PFMT64x"\n",
section->name, section->size, addr);
r_cons_printf ("f section_end.%s 1 0x%08"PFMT64x"\n",
section->name, addr + section->size);
r_cons_printf ("CC section %i va=0x%08"PFMT64x" pa=0x%08"PFMT64x" sz=%"PFMT64d" vsz=%"PFMT64d" "
"rwx=%s %s @ 0x%08"PFMT64x"\n",
i, addr, section->paddr, section->size, section->vsize,
perms, section->name, addr);
}
} else {
char *hashstr = NULL, str[128];
if (chksum) {
ut8 *data = malloc (section->size);
if (!data) return false;
ut32 datalen = section->size;
// VA READ IS BROKEN?
r_io_pread (r->io, section->paddr, data, datalen);
hashstr = build_hash_string (mode, chksum,
data, datalen);
free (data);
}
if (section->arch || section->bits) {
const char *arch = section->arch;
int bits = section->bits;
if (!arch && info) {
arch = info->arch;
if (!arch) {
arch = r_config_get (r->config, "asm.arch");
}
}
if (!bits) {
bits = info? info->bits: R_SYS_BITS;
}
snprintf (str, sizeof (str), "arch=%s bits=%d ",
r_str_get2 (arch), bits);
} else {
str[0] = 0;
}
if (r->bin->prefix) {
r_cons_printf ("idx=%02i vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x" sz=%"PFMT64d" vsz=%"PFMT64d" "
"perm=%s %s%sname=%s.%s\n",
i, addr, section->paddr, section->size, section->vsize,
perms, str, hashstr ?hashstr : "", r->bin->prefix, section->name);
} else {
r_cons_printf ("idx=%02i vaddr=0x%08"PFMT64x" paddr=0x%08"PFMT64x" sz=%"PFMT64d" vsz=%"PFMT64d" "
"perm=%s %s%sname=%s\n",
i, addr, section->paddr, section->size, section->vsize,
perms, str, hashstr ?hashstr : "", section->name);
}
free (hashstr);
}
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_println ("]");
} else if (IS_MODE_NORMAL (mode) && !at) {
r_cons_printf ("\n%i sections\n", i);
}
return true;
}
static int bin_fields(RCore *r, int mode, int va) {
RList *fields;
RListIter *iter;
RBinField *field;
int i = 0;
RBin *bin = r->bin;
RBinFile *binfile = r_core_bin_cur (r);
ut64 size = binfile ? binfile->size : UT64_MAX;
ut64 baddr = r_bin_get_baddr (r->bin);
if (!(fields = r_bin_get_fields (bin))) {
return false;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_RAD (mode)) {
r_cons_println ("fs header");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Header fields]");
}
//why this? there is an overlap in bin_sections with ehdr
//because there can't be two sections with the same name
#if 0
else if (IS_MODE_SET (mode)) {
// XXX: Need more flags??
// this will be set even if the binary does not have an ehdr
int fd = r_core_file_cur_fd(r);
r_io_section_add (r->io, 0, baddr, size, size, 7, "ehdr", 0, fd);
}
#endif
r_list_foreach (fields, iter, field) {
ut64 addr = rva (bin, field->paddr, field->vaddr, va);
if (IS_MODE_RAD (mode)) {
r_name_filter (field->name, -1);
r_cons_printf ("f header.%s @ 0x%08"PFMT64x"\n", field->name, addr);
if (field->comment && *field->comment) {
r_cons_printf ("CC %s @ 0x%"PFMT64x"\n", field->comment, addr);
}
if (field->format && *field->format) {
r_cons_printf ("pf.%s %s\n", field->name, field->format);
}
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s{\"name\":\"%s\","
"\"vaddr\":%"PFMT64d","
"\"paddr\":%"PFMT64d,
iter->p? ",": "",
field->name,
field->vaddr,
field->paddr
);
if (field->comment && *field->comment) {
// TODO: filter comment before json
r_cons_printf (",\"comment\":\"%s\"", field->comment);
}
if (field->format && *field->format) {
// TODO: filter comment before json
r_cons_printf (",\"format\":\"%s\"", field->format);
}
r_cons_printf ("}");
} else if (IS_MODE_NORMAL (mode)) {
const bool haveComment = (field->comment && *field->comment);
r_cons_printf ("0x%08"PFMT64x" 0x%08"PFMT64x" %s%s%s\n",
field->vaddr, field->paddr, field->name,
haveComment? "; ": "",
haveComment? field->comment: "");
}
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
} else if (IS_MODE_RAD (mode)) {
/* add program header section */
r_cons_printf ("S 0 0x%"PFMT64x" 0x%"PFMT64x" 0x%"PFMT64x" ehdr rwx\n",
baddr, size, size);
} else if (IS_MODE_NORMAL (mode)) {
r_cons_printf ("\n%i fields\n", i);
}
return true;
}
static int bin_classes(RCore *r, int mode) {
RListIter *iter, *iter2;
RBinSymbol *sym;
RBinClass *c;
char *name;
RList *cs = r_bin_get_classes (r->bin);
if (!cs) {
if (IS_MODE_JSON (mode)) {
r_cons_print("[]");
}
return false;
}
// XXX: support for classes is broken and needs more love
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_SET (mode)) {
if (!r_config_get_i (r->config, "bin.classes")) {
return false;
}
r_flag_space_set (r->flags, "classes");
} else if (IS_MODE_RAD (mode)) {
r_cons_println ("fs classes");
}
r_list_foreach (cs, iter, c) {
if (!c || !c->name || !c->name[0]) {
continue;
}
name = strdup (c->name);
r_name_filter (name, 0);
ut64 at_min = UT64_MAX;
ut64 at_max = 0LL;
r_list_foreach (c->methods, iter2, sym) {
if (sym->vaddr) {
if (sym->vaddr < at_min) {
at_min = sym->vaddr;
}
if (sym->vaddr + sym->size > at_max) {
at_max = sym->vaddr + sym->size;
}
}
}
if (at_min == UT64_MAX) {
at_min = c->addr;
at_max = c->addr; // XXX + size?
}
if (IS_MODE_SET (mode)) {
const char *classname = sdb_fmt (0, "class.%s", name);
r_flag_set (r->flags, classname, c->addr, 1);
r_list_foreach (c->methods, iter2, sym) {
char *mflags = r_core_bin_method_flags_str (sym, mode);
char *method = sdb_fmt (1, "method%s.%s.%s",
mflags, c->name, sym->name);
R_FREE (mflags);
r_name_filter (method, -1);
r_flag_set (r->flags, method, sym->vaddr, 1);
}
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x" [0x%08"PFMT64x" - 0x%08"PFMT64x"] %s%s%s\n",
c->addr, at_min, at_max, c->name, c->super ? " " : "",
c->super ? c->super : "");
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("\"f class.%s = 0x%"PFMT64x"\"\n",
name, at_min);
if (c->super) {
r_cons_printf ("\"f super.%s.%s = %d\"\n",
c->name, c->super, c->index);
}
r_list_foreach (c->methods, iter2, sym) {
char *mflags = r_core_bin_method_flags_str (sym, mode);
r_cons_printf ("\"f method%s.%s.%s = 0x%"PFMT64x"\"\n", mflags, c->name, sym->name, sym->vaddr);
R_FREE (mflags);
}
} else if (IS_MODE_JSON (mode)) {
if (c->super) {
r_cons_printf ("%s{\"classname\":\"%s\",\"addr\":%"PFMT64d",\"index\":%"PFMT64d",\"super\":\"%s\",\"methods\":[",
iter->p ? "," : "", c->name, c->addr,
c->index, c->super);
} else {
r_cons_printf ("%s{\"classname\":\"%s\",\"addr\":%"PFMT64d",\"index\":%"PFMT64d",\"methods\":[",
iter->p ? "," : "", c->name, c->addr,
c->index);
}
r_list_foreach (c->methods, iter2, sym) {
if (sym->method_flags) {
char *mflags = r_core_bin_method_flags_str (sym, mode);
r_cons_printf ("%s{\"name\":\"%s\",\"flags\":%s,\"addr\":%"PFMT64d"}",
iter2->p? ",": "", sym->name, mflags, sym->vaddr);
R_FREE (mflags);
} else {
r_cons_printf ("%s{\"name\":\"%s\",\"addr\":%"PFMT64d"}",
iter2->p? ",": "", sym->name, sym->vaddr);
}
}
r_cons_printf ("]}");
} else {
int m = 0;
r_cons_printf ("0x%08"PFMT64x" [0x%08"PFMT64x" - 0x%08"PFMT64x"] (sz %d) class %d %s",
c->addr, at_min, at_max, (at_max - at_min), c->index, c->name);
if (c->super) {
r_cons_printf (" super: %s\n", c->super);
} else {
r_cons_newline ();
}
r_list_foreach (c->methods, iter2, sym) {
char *mflags = r_core_bin_method_flags_str (sym, mode);
r_cons_printf ("0x%08"PFMT64x" method %d %s %s\n",
sym->vaddr, m, mflags, sym->dname? sym->dname: sym->name);
R_FREE (mflags);
m++;
}
}
free (name);
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
}
return true;
}
static int bin_size(RCore *r, int mode) {
ut64 size = r_bin_get_size (r->bin);
if (IS_MODE_SIMPLE (mode) || IS_MODE_JSON (mode)) {
r_cons_printf ("%"PFMT64u"\n", size);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("f bin_size @ %"PFMT64u"\n", size);
} else if (IS_MODE_SET (mode)) {
r_core_cmdf (r, "f bin_size @ %"PFMT64u"\n", size);
} else {
r_cons_printf ("%"PFMT64u"\n", size);
}
return true;
}
static int bin_libs(RCore *r, int mode) {
RList *libs;
RListIter *iter;
char* lib;
int i = 0;
if (!(libs = r_bin_get_libs (r->bin))) {
return false;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
} else if (IS_MODE_NORMAL (mode)) {
r_cons_println ("[Linked libraries]");
}
r_list_foreach (libs, iter, lib) {
if (IS_MODE_SET (mode)) {
// Nothing to set.
// TODO: load libraries with iomaps?
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("CCa entry0 %s\n", lib);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("%s\"%s\"", iter->p ? "," : "", lib);
} else {
// simple and normal print mode
r_cons_println (lib);
}
i++;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("]");
} else if (IS_MODE_NORMAL (mode)) {
if (i == 1) {
r_cons_printf ("\n%i library\n", i);
} else {
r_cons_printf ("\n%i libraries\n", i);
}
}
return true;
}
static void bin_mem_print(RList *mems, int perms, int depth, int mode) {
RBinMem *mem;
RListIter *iter;
if (!mems) {
return;
}
r_list_foreach (mems, iter, mem) {
if (IS_MODE_JSON (mode)) {
r_cons_printf ("{\"name\":\"%s\",\"size\":%d,\"address\":%d,"
"\"flags\":\"%s\"}", mem->name, mem->size,
mem->addr, r_str_rwx_i (mem->perms & perms));
} else if (IS_MODE_SIMPLE (mode)) {
r_cons_printf ("0x%08"PFMT64x"\n", mem->addr);
} else {
r_cons_printf ("0x%08"PFMT64x" +0x%04x %s %*s%-*s\n",
mem->addr, mem->size, r_str_rwx_i (mem->perms & perms),
depth, "", 20-depth, mem->name);
}
if (mem->mirrors) {
if (IS_MODE_JSON (mode)) {
r_cons_printf (",");
}
bin_mem_print (mem->mirrors, mem->perms & perms, depth + 1, mode);
}
if (IS_MODE_JSON(mode)) {
if (iter->n) {
r_cons_printf (",");
}
}
}
}
static int bin_mem(RCore *r, int mode) {
RList *mem = NULL;
if (!r) return false;
if (!IS_MODE_JSON(mode)) {
if (!(IS_MODE_RAD (mode) || IS_MODE_SET (mode))) {
r_cons_println ("[Memory]\n");
}
}
if (!(mem = r_bin_get_mem (r->bin))) {
if (IS_MODE_JSON (mode)) {
r_cons_print("[]");
}
return false;
}
if (IS_MODE_JSON (mode)) {
r_cons_print ("[");
bin_mem_print (mem, 7, 0, R_CORE_BIN_JSON);
r_cons_println ("]");
return true;
} else if (!(IS_MODE_RAD (mode) || IS_MODE_SET (mode))) {
bin_mem_print (mem, 7, 0, mode);
}
return true;
}
static void bin_pe_versioninfo(RCore *r) {
Sdb *sdb = NULL;
int num_version = 0;
int num_stringtable = 0;
int num_string = 0;
const char *format_version = "bin/cur/info/vs_version_info/VS_VERSIONINFO%d";
const char *format_stringtable = "%s/string_file_info/stringtable%d";
const char *format_string = "%s/string%d";
r_cons_printf ("=== VS_VERSIONINFO ===\n\n");
do {
char path_version[256] = R_EMPTY;
snprintf (path_version, sizeof (path_version), format_version, num_version);
if (!(sdb = sdb_ns_path (r->sdb, path_version, 0)))
break;
r_cons_printf ("# VS_FIXEDFILEINFO\n\n");
char path_fixedfileinfo[256] = R_EMPTY;
snprintf (path_fixedfileinfo, sizeof (path_fixedfileinfo), "%s/fixed_file_info", path_version);
if (!(sdb = sdb_ns_path (r->sdb, path_fixedfileinfo, 0)))
break;
r_cons_printf (" Signature: 0x%"PFMT64x"\n", sdb_num_get (sdb, "Signature", 0));
r_cons_printf (" StrucVersion: 0x%"PFMT64x"\n", sdb_num_get (sdb, "StrucVersion", 0));
r_cons_printf (" FileVersion: %"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\n",
sdb_num_get (sdb, "FileVersionMS", 0) >> 16,
sdb_num_get (sdb, "FileVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "FileVersionLS", 0) >> 16,
sdb_num_get (sdb, "FileVersionLS", 0) & 0xFFFF);
r_cons_printf (" ProductVersion: %"PFMT64d".%"PFMT64d".%"PFMT64d".%"PFMT64d"\n",
sdb_num_get (sdb, "ProductVersionMS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionMS", 0) & 0xFFFF,
sdb_num_get (sdb, "ProductVersionLS", 0) >> 16,
sdb_num_get (sdb, "ProductVersionLS", 0) & 0xFFFF);
r_cons_printf (" FileFlagsMask: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileFlagsMask", 0));
r_cons_printf (" FileFlags: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileFlags", 0));
r_cons_printf (" FileOS: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileOS", 0));
r_cons_printf (" FileType: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileType", 0));
r_cons_printf (" FileSubType: 0x%"PFMT64x"\n", sdb_num_get (sdb, "FileSubType", 0));
#if 0
r_cons_printf (" FileDate: %d.%d.%d.%d\n",
sdb_num_get (sdb, "FileDateMS", 0) >> 16,
sdb_num_get (sdb, "FileDateMS", 0) & 0xFFFF,
sdb_num_get (sdb, "FileDateLS", 0) >> 16,
sdb_num_get (sdb, "FileDateLS", 0) & 0xFFFF);
#endif
r_cons_newline ();
r_cons_println ("# StringTable\n");
for (num_stringtable = 0; sdb; ++num_stringtable) {
char path_stringtable[256] = R_EMPTY;
snprintf (path_stringtable, sizeof (path_stringtable), format_stringtable, path_version, num_stringtable);
sdb = sdb_ns_path (r->sdb, path_stringtable, 0);
for (num_string = 0; sdb; ++num_string) {
char path_string[256] = R_EMPTY;
snprintf (path_string, sizeof (path_string), format_string, path_stringtable, num_string);
sdb = sdb_ns_path (r->sdb, path_string, 0);
if (sdb) {
int lenkey = 0;
int lenval = 0;
ut8 *key_utf16 = sdb_decode (sdb_const_get (sdb, "key", 0), &lenkey);
ut8 *val_utf16 = sdb_decode (sdb_const_get (sdb, "value", 0), &lenval);
ut8 *key_utf8 = calloc (lenkey * 2, 1);
ut8 *val_utf8 = calloc (lenval * 2, 1);
if (r_str_utf16_to_utf8 (key_utf8, lenkey * 2, key_utf16, lenkey, true) < 0
|| r_str_utf16_to_utf8 (val_utf8, lenval * 2, val_utf16, lenval, true) < 0) {
eprintf ("Warning: Cannot decode utf16 to utf8\n");
} else {
r_cons_printf (" %s: %s\n", (char*)key_utf8, (char*)val_utf8);
}
free (key_utf8);
free (val_utf8);
free (key_utf16);
free (val_utf16);
}
}
}
++num_version;
} while (sdb);
}
static void bin_elf_versioninfo(RCore *r) {
const char *format = "bin/cur/info/versioninfo/%s%d";
char path[256] = R_EMPTY;
int num_versym = 0;
int num_verneed = 0;
int num_entry = 0;
Sdb *sdb = NULL;
do {
snprintf (path, sizeof (path), format, "versym", num_versym++);
if (!(sdb = sdb_ns_path (r->sdb, path, 0))) {
break;
}
ut64 addr = sdb_num_get (sdb, "addr", 0);
ut64 offset = sdb_num_get (sdb, "offset", 0);
ut64 link = sdb_num_get (sdb, "link", 0);
ut64 num_entries = sdb_num_get (sdb, "num_entries", 0);
const char *section_name = sdb_const_get (sdb, "section_name", 0);
const char *link_section_name = sdb_const_get (sdb, "link_section_name", 0);
r_cons_printf ("Version symbols section '%s' contains %"PFMT64u" entries:\n", section_name, num_entries);
r_cons_printf (" Addr: 0x%08"PFMT64x" Offset: 0x%08"PFMT64x" Link: %x (%s)\n",
(ut64)addr, (ut64)offset, (ut32)link, link_section_name);
do {
int num_val = 0;
char path_entry[256] = R_EMPTY;
snprintf (path_entry, sizeof (path_entry), "%s/entry%d", path, num_entry++);
if (!(sdb = sdb_ns_path (r->sdb, path_entry, 0)))
break;
r_cons_printf (" 0x%08"PFMT64x": ", sdb_num_get (sdb, "idx", 0));
const char *value = NULL;
do {
char key[32] = R_EMPTY;
snprintf (key, sizeof (key), "value%d", num_val++);
if ((value = sdb_const_get (sdb, key, 0)))
r_cons_printf ("%s ", value);
} while (value);
r_cons_newline ();
} while (sdb);
r_cons_println ("\n");
} while (sdb);
do {
int num_version = 0;
char path_version[256] = R_EMPTY;
snprintf (path, sizeof (path), format, "verneed", num_verneed++);
if (!(sdb = sdb_ns_path (r->sdb, path, 0)))
break;
r_cons_printf ("Version need section '%s' contains %d entries:\n",
sdb_const_get (sdb, "section_name", 0), (int)sdb_num_get (sdb, "num_entries", 0));
r_cons_printf (" Addr: 0x%08"PFMT64x, sdb_num_get (sdb, "addr", 0));
r_cons_printf (" Offset: 0x%08"PFMT64x" Link to section: %"PFMT64d" (%s)\n",
sdb_num_get (sdb, "offset", 0), sdb_num_get (sdb, "link", 0),
sdb_const_get (sdb, "link_section_name", 0));
do {
snprintf (path_version, sizeof (path_version), "%s/version%d", path, num_version++);
const char *filename = NULL;
char path_vernaux[256] = R_EMPTY;
int num_vernaux = 0;
if (!(sdb = sdb_ns_path (r->sdb, path_version, 0)))
break;
r_cons_printf (" 0x%08"PFMT64x": Version: %d",
sdb_num_get (sdb, "idx", 0), (int)sdb_num_get (sdb, "vn_version", 0));
if ((filename = sdb_const_get (sdb, "file_name", 0)))
r_cons_printf (" File: %s", filename);
r_cons_printf (" Cnt: %d\n", (int)sdb_num_get (sdb, "cnt", 0));
do {
snprintf (path_vernaux, sizeof (path_vernaux), "%s/vernaux%d",
path_version, num_vernaux++);
if (!(sdb = sdb_ns_path (r->sdb, path_vernaux, 0)))
break;
r_cons_printf (" 0x%08"PFMT64x": Name: %s",
sdb_num_get (sdb, "idx", 0), sdb_const_get (sdb, "name", 0));
r_cons_printf (" Flags: %s Version: %d\n",
sdb_const_get (sdb, "flags", 0), (int)sdb_num_get (sdb, "version", 0));
} while (sdb);
} while (sdb);
} while (sdb);
}
static void bin_mach0_versioninfo(RCore *r) {
/* TODO */
}
static void bin_pe_resources(RCore *r, int mode) {
Sdb *sdb = NULL;
int index = 0;
const char *pe_path = "bin/cur/info/pe_resource";
if (!(sdb = sdb_ns_path (r->sdb, pe_path, 0))) {
return;
}
if (IS_MODE_SET (mode)) {
r_flag_space_set (r->flags, "resources");
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs resources\n");
} else if (IS_MODE_JSON (mode)) {
r_cons_printf ("[");
}
while (true) {
const char *timestrKey = sdb_fmt (0, "resource.%d.timestr", index);
const char *paddrKey = sdb_fmt (1, "resource.%d.paddr", index);
const char *sizeKey = sdb_fmt (2, "resource.%d.size", index);
const char *typeKey = sdb_fmt (3, "resource.%d.type", index);
const char *languageKey = sdb_fmt (4, "resource.%d.language", index);
const char *nameKey = sdb_fmt (5, "resource.%d.name", index);
char *timestr = sdb_get (sdb, timestrKey, 0);
if (!timestr) {
break;
}
ut64 paddr = sdb_num_get (sdb, paddrKey, 0);
int size = (int)sdb_num_get (sdb, sizeKey, 0);
int name = (int)sdb_num_get (sdb, nameKey, 0);
char *type = sdb_get (sdb, typeKey, 0);
char *lang = sdb_get (sdb, languageKey, 0);
if (IS_MODE_SET (mode)) {
const char *name = sdb_fmt (4, "resource.%d", index);
r_flag_set (r->flags, name, paddr, size);
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("f resource.%d %d 0x%08"PFMT32x"\n", index, size, paddr);
} else if (IS_MODE_JSON (mode)) {
r_cons_printf("%s{\"name\":%d,\"index\":%d, \"type\":\"%s\","
"\"paddr\":%"PFMT32d", \"size\":%d, \"lang\":\"%s\"}",
index? ",": "", name, index, type, paddr, size, lang);
} else {
char *humanSize = r_num_units (NULL, size);
r_cons_printf ("Resource %d\n", index);
r_cons_printf ("\tname: %d\n", name);
r_cons_printf ("\ttimestamp: %s\n", timestr);
r_cons_printf ("\tpaddr: 0x%08"PFMT32x"\n", paddr);
r_cons_printf ("\tsize: %s\n", humanSize);
r_cons_printf ("\ttype: %s\n", type);
r_cons_printf ("\tlanguage: %s\n", lang);
free (humanSize);
}
index++;
}
if (IS_MODE_JSON (mode)) {
r_cons_printf ("]");
} else if (IS_MODE_RAD (mode)) {
r_cons_printf ("fs *");
}
}
static int bin_resources(RCore *r, int mode) {
const RBinInfo *info = r_bin_get_info (r->bin);
if (!info || !info->rclass) {
return false;
}
if (!strncmp ("pe", info->rclass, 2)) {
bin_pe_resources (r, mode);
}
return true;
}
static int bin_versioninfo(RCore *r, int mode) {
const RBinInfo *info = r_bin_get_info (r->bin);
if (!info || !info->rclass) {
return false;
}
if (!strncmp ("pe", info->rclass, 2)) {
bin_pe_versioninfo (r);
} else if (!strncmp ("elf", info->rclass, 3)) {
bin_elf_versioninfo (r);
} else if (!strncmp ("mach0", info->rclass, 5)) {
bin_mach0_versioninfo (r);
} else {
r_cons_println ("Unknown format");
return false;
}
return true;
}
static int bin_signature(RCore *r, int mode) {
RBinFile *cur = r_bin_cur (r->bin);
RBinPlugin *plg = r_bin_file_cur_plugin (cur);
if (plg && plg->signature) {
const char *signature = plg->signature (cur, IS_MODE_JSON (mode));
r_cons_println (signature);
free ((char*) signature);
return true;
}
return false;
}
R_API void r_core_bin_export_info_rad(RCore *core) {
Sdb *db = NULL;
char *flagname, *offset = NULL;
RBinFile *bf = r_core_bin_cur (core);
if (!bf) {
return;
}
db = sdb_ns (bf->sdb, "info", 0);;
if (!db) {
return;
}
if (db) {
SdbListIter *iter;
SdbKv *kv;
r_cons_printf ("fs format\n");
// iterate over all keys
SdbList *ls = sdb_foreach_list (db, false);
ls_foreach (ls, iter, kv) {
char *k = kv->key;
char *v = kv->value;
char *dup = strdup (k);
//printf ("?e (%s) (%s)\n", k, v);
if ((flagname = strstr (dup, ".offset"))) {
*flagname = 0;
flagname = dup;
r_cons_printf ("f %s @ %s\n", flagname, v);
free (offset);
offset = strdup (v);
}
if ((flagname = strstr (dup, ".cparse"))) {
r_cons_printf ("\"td %s\"\n", v);
}
free (dup);
}
R_FREE (offset);
ls_foreach (ls, iter, kv) {
char *dup = kv->key;
char *v = kv->value;
if ((flagname = strstr (dup, ".format"))) {
*flagname = 0;
if (!offset) {
offset = strdup ("0");
}
flagname = dup;
r_cons_printf ("pf.%s %s\n", flagname, v);
int fmtsize = r_print_format_struct_size (v, core->print, 0);
char *offset_key = r_str_newf ("%s.offset", flagname);
const char *off = sdb_const_get (db, offset_key, 0);
free (offset_key);
if (off) {
r_cons_printf ("Cf %d %s @ %s\n", fmtsize, v, off);
}
}
if ((flagname = strstr (dup, ".size"))) {
*flagname = 0;
flagname = dup;
r_cons_printf ("fl %s %s\n", flagname, v);
}
}
free (offset);
}
}
static int bin_header(RCore *r, int mode) {
RBinFile *cur = r_bin_cur (r->bin);
RBinPlugin *plg = r_bin_file_cur_plugin (cur);
if (plg && plg->header) {
plg->header (cur);
return true;
}
return false;
}
R_API int r_core_bin_info(RCore *core, int action, int mode, int va, RCoreBinFilter *filter, const char *chksum) {
int ret = true;
const char *name = NULL;
ut64 at = 0, loadaddr = r_bin_get_laddr (core->bin);
if (filter && filter->offset) {
at = filter->offset;
}
if (filter && filter->name) {
name = filter->name;
}
// use our internal values for va
va = va ? VA_TRUE : VA_FALSE;
if (r_config_get_i (core->config, "anal.strings")) {
r_core_cmd0 (core, "aar");
}
if ((action & R_CORE_BIN_ACC_STRINGS)) ret &= bin_strings (core, mode, va);
if ((action & R_CORE_BIN_ACC_RAW_STRINGS)) ret &= bin_raw_strings (core, mode, va);
if ((action & R_CORE_BIN_ACC_INFO)) ret &= bin_info (core, mode);
if ((action & R_CORE_BIN_ACC_MAIN)) ret &= bin_main (core, mode, va);
if ((action & R_CORE_BIN_ACC_DWARF)) ret &= bin_dwarf (core, mode);
if ((action & R_CORE_BIN_ACC_PDB)) ret &= bin_pdb (core, mode);
if ((action & R_CORE_BIN_ACC_ENTRIES)) ret &= bin_entry (core, mode, loadaddr, va);
if ((action & R_CORE_BIN_ACC_SECTIONS)) ret &= bin_sections (core, mode, loadaddr, va, at, name, chksum);
if (r_config_get_i (core->config, "bin.relocs")) {
if ((action & R_CORE_BIN_ACC_RELOCS)) ret &= bin_relocs (core, mode, va);
}
if ((action & R_CORE_BIN_ACC_IMPORTS)) ret &= bin_imports (core, mode, va, name);
if ((action & R_CORE_BIN_ACC_EXPORTS)) ret &= bin_exports (core, mode, loadaddr, va, at, name);
if ((action & R_CORE_BIN_ACC_SYMBOLS)) ret &= bin_symbols (core, mode, loadaddr, va, at, name);
if ((action & R_CORE_BIN_ACC_LIBS)) ret &= bin_libs (core, mode);
if ((action & R_CORE_BIN_ACC_CLASSES)) ret &= bin_classes (core, mode);
if ((action & R_CORE_BIN_ACC_SIZE)) ret &= bin_size (core, mode);
if ((action & R_CORE_BIN_ACC_MEM)) ret &= bin_mem (core, mode);
if ((action & R_CORE_BIN_ACC_VERSIONINFO)) ret &= bin_versioninfo (core, mode);
if ((action & R_CORE_BIN_ACC_RESOURCES)) ret &= bin_resources (core, mode);
if ((action & R_CORE_BIN_ACC_SIGNATURE)) ret &= bin_signature (core, mode);
if ((action & R_CORE_BIN_ACC_FIELDS)) {
if (IS_MODE_SIMPLE (mode)) {
if ((action & R_CORE_BIN_ACC_HEADER) || action & R_CORE_BIN_ACC_FIELDS) {
/* ignore mode, just for quiet/simple here */
ret &= bin_fields (core, 0, va);
}
} else {
if (IS_MODE_NORMAL(mode)) {
ret &= bin_header (core, mode);
} else {
if ((action & R_CORE_BIN_ACC_HEADER) || action & R_CORE_BIN_ACC_FIELDS) {
ret &= bin_fields (core, mode, va);
}
}
}
}
return ret;
}
R_API int r_core_bin_set_arch_bits(RCore *r, const char *name, const char * arch, ut16 bits) {
RCoreFile *cf = r_core_file_cur (r);
RBinFile *binfile;
if (!name) {
name = (cf && cf->desc) ? cf->desc->name : NULL;
}
if (!name) {
return false;
}
/* Check if the arch name is a valid name */
if (!r_asm_is_valid (r->assembler, arch)) {
return false;
}
/* Find a file with the requested name/arch/bits */
binfile = r_bin_file_find_by_arch_bits (r->bin, arch, bits, name);
if (!binfile) {
return false;
}
if (!r_bin_use_arch (r->bin, arch, bits, name)) {
return false;
}
r_core_bin_set_cur (r, binfile);
return r_core_bin_set_env (r, binfile);
}
R_API int r_core_bin_update_arch_bits(RCore *r) {
RBinFile *binfile = NULL;
const char *name = NULL, *arch = NULL;
ut16 bits = 0;
if (!r) {
return 0;
}
if (r->assembler) {
bits = r->assembler->bits;
if (r->assembler->cur) {
arch = r->assembler->cur->arch;
}
}
binfile = r_core_bin_cur (r);
name = binfile ? binfile->file : NULL;
if (r && r->bin && r->bin->binxtrs) {
r_anal_hint_clear (r->anal);
}
return r_core_bin_set_arch_bits (r, name, arch, bits);
}
R_API int r_core_bin_raise(RCore *core, ut32 binfile_idx, ut32 binobj_idx) {
RBin *bin = core->bin;
RBinFile *binfile = NULL;
if (binfile_idx == UT32_MAX && binobj_idx == UT32_MAX) {
return false;
}
if (!r_bin_select_by_ids (bin, binfile_idx, binobj_idx)) {
return false;
}
binfile = r_core_bin_cur (core);
if (binfile) {
r_io_raise (core->io, binfile->fd);
}
// it should be 0 to use r_io_use_fd in r_core_block_read
core->switch_file_view = 0;
return binfile && r_core_bin_set_env (core, binfile) && r_core_block_read (core);
}
R_API bool r_core_bin_delete(RCore *core, ut32 binfile_idx, ut32 binobj_idx) {
if (binfile_idx == UT32_MAX && binobj_idx == UT32_MAX) {
return false;
}
if (!r_bin_object_delete (core->bin, binfile_idx, binobj_idx)) {
return false;
}
RBinFile *binfile = r_core_bin_cur (core);
if (binfile) {
r_io_raise (core->io, binfile->fd);
}
core->switch_file_view = 0;
return binfile && r_core_bin_set_env (core, binfile) && r_core_block_read (core);
}
static int r_core_bin_file_print(RCore *core, RBinFile *binfile, int mode) {
RListIter *iter;
RBinObject *obj;
const char *name = binfile ? binfile->file : NULL;
(void)r_bin_get_info (core->bin); // XXX is this necssary for proper iniitialization
ut32 id = binfile ? binfile->id : 0;
ut32 fd = binfile ? binfile->fd : 0;
ut32 bin_sz = binfile ? binfile->size : 0;
// TODO: handle mode to print in json and r2 commands
if (!binfile) {
return false;
}
switch (mode) {
case 'j':
r_cons_printf ("{\"name\":\"%s\",\"fd\":%d,\"id\":%d,\"size\":%d,\"objs\":[",
name, fd, id, bin_sz);
r_list_foreach (binfile->objs, iter, obj) {
RBinInfo *info = obj->info;
ut8 bits = info ? info->bits : 0;
const char *arch = info ? info->arch : "unknown";
r_cons_printf ("{\"objid\":%d,\"arch\":\"%s\",\"bits\":%d,\"binoffset\":%"
PFMT64d",\"objsize\":%"PFMT64d"}",
obj->id, arch, bits, obj->boffset, obj->obj_size);
if (iter->n) {
r_cons_print (",");
}
}
r_cons_print ("]}");
break;
default:
r_cons_printf ("binfile fd=%d name=%s id=%d\n", fd, name, id);
r_list_foreach (binfile->objs, iter, obj) {
RBinInfo *info = obj->info;
ut8 bits = info ? info->bits : 0;
const char *arch = info ? info->arch : "unknown";
if (!arch) {
arch = r_config_get (core->config, "asm.arch");
}
r_cons_printf ("objid=%d arch=%s bits=%d boffset=0x%04"PFMT64x" size=0x%04"PFMT64x"\n",
obj->id, arch, bits, obj->boffset, obj->obj_size );
}
break;
}
return true;
}
R_API int r_core_bin_list(RCore *core, int mode) {
// list all binfiles and there objects and there archs
int count = 0;
RListIter *iter;
RBinFile *binfile = NULL; //, *cur_bf = r_core_bin_cur (core) ;
RBin *bin = core->bin;
const RList *binfiles = bin ? bin->binfiles: NULL;
if (!binfiles) {
return false;
}
if (mode == 'j') {
r_cons_print ("[");
}
r_list_foreach (binfiles, iter, binfile) {
r_core_bin_file_print (core, binfile, mode);
if (iter->n && mode == 'j') {
r_cons_print (",");
}
}
if (mode == 'j') {
r_cons_println ("]");
}
//r_core_file_set_by_file (core, cur_cf);
//r_core_bin_bind (core, cur_bf);
return count;
}
R_API char *r_core_bin_method_flags_str(RBinSymbol *sym, int mode) {
char *str;
RStrBuf *buf;
int i, len = 0;
buf = r_strbuf_new ("");
if (IS_MODE_SET (mode) || IS_MODE_RAD (mode)) {
if (!sym->method_flags) {
goto out;
}
for (i = 0; i != 64; i++) {
ut64 flag = sym->method_flags & (1L << i);
if (flag) {
const char *flag_string = r_bin_get_meth_flag_string (flag, false);
if (flag_string) {
r_strbuf_appendf (buf, ".%s", flag_string);
}
}
}
} else if (IS_MODE_JSON (mode)) {
if (!sym->method_flags) {
r_strbuf_append (buf, "[]");
goto out;
}
r_strbuf_append (buf, "[");
for (i = 0; i != 64; i++) {
ut64 flag = sym->method_flags & (1L << i);
if (flag) {
const char *flag_string = r_bin_get_meth_flag_string (flag, false);
if (len != 0) {
r_strbuf_append (buf, ",");
}
if (flag_string) {
r_strbuf_appendf (buf, "\"%s\"", flag_string);
} else {
r_strbuf_appendf (buf, "\"0x%08"PFMT64x"\"", flag);
}
len++;
}
}
r_strbuf_append (buf, "]");
} else {
int pad_len = 4; //TODO: move to a config variable
if (!sym->method_flags) {
goto padding;
}
for (i = 0; i != 64; i++) {
ut64 flag = sym->method_flags & (1L << i);
if (flag) {
const char *flag_string = r_bin_get_meth_flag_string (flag, true);
if (flag_string) {
r_strbuf_append (buf, flag_string);
} else {
r_strbuf_append (buf, "?");
}
len++;
}
}
padding:
for ( ; len < pad_len; len++) {
r_strbuf_append (buf, " ");
}
}
out:
str = strdup (r_strbuf_get (buf));
r_strbuf_free (buf);
return str;
}
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_3399_1 |
crossvul-cpp_data_good_4020_1 | /* exif-mnote-data-fuji.c
*
* Copyright (c) 2002 Lutz Mueller <lutz@users.sourceforge.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*/
#include <stdlib.h>
#include <string.h>
#include <config.h>
#include <libexif/exif-byte-order.h>
#include <libexif/exif-utils.h>
#include "exif-mnote-data-fuji.h"
#define CHECKOVERFLOW(offset,datasize,structsize) (( offset >= datasize) || (structsize > datasize) || (offset > datasize - structsize ))
struct _MNoteFujiDataPrivate {
ExifByteOrder order;
};
static void
exif_mnote_data_fuji_clear (ExifMnoteDataFuji *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_fuji_free (ExifMnoteData *n)
{
if (!n) return;
exif_mnote_data_fuji_clear ((ExifMnoteDataFuji *) n);
}
static char *
exif_mnote_data_fuji_get_value (ExifMnoteData *d, unsigned int i, char *val, unsigned int maxlen)
{
ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) d;
if (!d || !val) return NULL;
if (i > n->count -1) return NULL;
/*
exif_log (d->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataFuji",
"Querying value for tag '%s'...",
mnote_fuji_tag_get_name (n->entries[i].tag));
*/
return mnote_fuji_entry_get_value (&n->entries[i], val, maxlen);
}
static void
exif_mnote_data_fuji_save (ExifMnoteData *ne, unsigned char **buf,
unsigned int *buf_size)
{
ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) 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 = 8 + 4 + 2 + n->count * 12 + 4;
*buf = exif_mem_alloc (ne->mem, *buf_size);
if (!*buf) {
*buf_size = 0;
return;
}
/*
* Header: "FUJIFILM" and 4 bytes offset to the first entry.
* As the first entry will start right thereafter, the offset is 12.
*/
memcpy (*buf, "FUJIFILM", 8);
exif_set_long (*buf + 8, n->order, 12);
/* Save the number of entries */
exif_set_short (*buf + 8 + 4, n->order, (ExifShort) n->count);
/* Save each entry */
for (i = 0; i < n->count; i++) {
o = 8 + 4 + 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, ts);
if (!t) {
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, 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);
}
}
static void
exif_mnote_data_fuji_load (ExifMnoteData *en,
const unsigned char *buf, unsigned int buf_size)
{
ExifMnoteDataFuji *n = (ExifMnoteDataFuji*) en;
ExifLong c;
size_t i, tcount, o, datao;
if (!n || !buf || !buf_size) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataFuji", "Short MakerNote");
return;
}
datao = 6 + n->offset;
if (CHECKOVERFLOW(datao, buf_size, 12)) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataFuji", "Short MakerNote");
return;
}
n->order = EXIF_BYTE_ORDER_INTEL;
datao += exif_get_long (buf + datao + 8, EXIF_BYTE_ORDER_INTEL);
if (CHECKOVERFLOW(datao, buf_size, 2)) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataFuji", "Short MakerNote");
return;
}
/* Read the number of tags */
c = exif_get_short (buf + datao, EXIF_BYTE_ORDER_INTEL);
datao += 2;
/* Remove any old entries */
exif_mnote_data_fuji_clear (n);
/* Reserve enough space for all the possible MakerNote tags */
n->entries = exif_mem_alloc (en->mem, sizeof (MnoteFujiEntry) * c);
if (!n->entries) {
EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteDataFuji", sizeof (MnoteFujiEntry) * c);
return;
}
/* Parse all c entries, storing ones that are successfully parsed */
tcount = 0;
for (i = c, o = datao; i; --i, o += 12) {
size_t s;
memset(&n->entries[tcount], 0, sizeof(MnoteFujiEntry));
if (CHECKOVERFLOW(o, buf_size, 12)) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataFuji", "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 (en->log, EXIF_LOG_CODE_DEBUG, "ExifMnoteDataFuji",
"Loading entry 0x%x ('%s')...", n->entries[tcount].tag,
mnote_fuji_tag_get_name (n->entries[tcount].tag));
/* Check if we overflow the multiplication. Use buf_size as the max size for integer overflow detection,
* we will check the buffer sizes closer later. */
if ( exif_format_get_size (n->entries[tcount].format) &&
buf_size / exif_format_get_size (n->entries[tcount].format) < n->entries[tcount].components
) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataFuji", "Tag size overflow detected (%u * %lu)", exif_format_get_size (n->entries[tcount].format), n->entries[tcount].components);
continue;
}
/*
* Size? If bigger than 4 bytes, the actual data is not
* in the entry but somewhere else (offset).
*/
s = exif_format_get_size (n->entries[tcount].format) * n->entries[tcount].components;
n->entries[tcount].size = s;
if (s) {
size_t dataofs = o + 8;
if (s > 4)
/* The data in this case is merely a pointer */
dataofs = exif_get_long (buf + dataofs, n->order) + 6 + n->offset;
if (CHECKOVERFLOW(dataofs, buf_size, s)) {
exif_log (en->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteDataFuji", "Tag data past end of "
"buffer (%u >= %u)", (unsigned)(dataofs + s), buf_size);
continue;
}
n->entries[tcount].data = exif_mem_alloc (en->mem, s);
if (!n->entries[tcount].data) {
EXIF_LOG_NO_MEMORY(en->log, "ExifMnoteDataFuji", 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_fuji_count (ExifMnoteData *n)
{
return n ? ((ExifMnoteDataFuji *) n)->count : 0;
}
static unsigned int
exif_mnote_data_fuji_get_id (ExifMnoteData *d, unsigned int n)
{
ExifMnoteDataFuji *note = (ExifMnoteDataFuji *) d;
if (!note) return 0;
if (note->count <= n) return 0;
return note->entries[n].tag;
}
static const char *
exif_mnote_data_fuji_get_name (ExifMnoteData *d, unsigned int i)
{
ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) d;
if (!n) return NULL;
if (i >= n->count) return NULL;
return mnote_fuji_tag_get_name (n->entries[i].tag);
}
static const char *
exif_mnote_data_fuji_get_title (ExifMnoteData *d, unsigned int i)
{
ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) d;
if (!n) return NULL;
if (i >= n->count) return NULL;
return mnote_fuji_tag_get_title (n->entries[i].tag);
}
static const char *
exif_mnote_data_fuji_get_description (ExifMnoteData *d, unsigned int i)
{
ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) d;
if (!n) return NULL;
if (i >= n->count) return NULL;
return mnote_fuji_tag_get_description (n->entries[i].tag);
}
static void
exif_mnote_data_fuji_set_byte_order (ExifMnoteData *d, ExifByteOrder o)
{
ExifByteOrder o_orig;
ExifMnoteDataFuji *n = (ExifMnoteDataFuji *) 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_fuji_set_offset (ExifMnoteData *n, unsigned int o)
{
if (n) ((ExifMnoteDataFuji *) n)->offset = o;
}
int
exif_mnote_data_fuji_identify (const ExifData *ed, const ExifEntry *e)
{
(void) ed; /* unused */
return ((e->size >= 12) && !memcmp (e->data, "FUJIFILM", 8));
}
ExifMnoteData *
exif_mnote_data_fuji_new (ExifMem *mem)
{
ExifMnoteData *d;
if (!mem) return NULL;
d = exif_mem_alloc (mem, sizeof (ExifMnoteDataFuji));
if (!d) return NULL;
exif_mnote_data_construct (d, mem);
/* Set up function pointers */
d->methods.free = exif_mnote_data_fuji_free;
d->methods.set_byte_order = exif_mnote_data_fuji_set_byte_order;
d->methods.set_offset = exif_mnote_data_fuji_set_offset;
d->methods.load = exif_mnote_data_fuji_load;
d->methods.save = exif_mnote_data_fuji_save;
d->methods.count = exif_mnote_data_fuji_count;
d->methods.get_id = exif_mnote_data_fuji_get_id;
d->methods.get_name = exif_mnote_data_fuji_get_name;
d->methods.get_title = exif_mnote_data_fuji_get_title;
d->methods.get_description = exif_mnote_data_fuji_get_description;
d->methods.get_value = exif_mnote_data_fuji_get_value;
return d;
}
| ./CrossVul/dataset_final_sorted/CWE-416/c/good_4020_1 |
crossvul-cpp_data_bad_1186_0 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% DDDD RRRR AAA W W %
% D D R R A A W W %
% D D RRRR AAAAA W W W %
% D D R RN A A WW WW %
% DDDD R R A A W W %
% %
% %
% MagickCore Image Drawing Methods %
% %
% %
% Software Design %
% Cristy %
% July 1998 %
% %
% %
% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Bill Radcliffe of Corbis (www.corbis.com) contributed the polygon
% rendering code based on Paul Heckbert's "Concave Polygon Scan Conversion",
% Graphics Gems, 1990. Leonard Rosenthal and David Harr of Appligent
% (www.appligent.com) contributed the dash pattern, linecap stroking
% algorithm, and minor rendering improvements.
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/annotate.h"
#include "MagickCore/artifact.h"
#include "MagickCore/blob.h"
#include "MagickCore/cache.h"
#include "MagickCore/cache-private.h"
#include "MagickCore/cache-view.h"
#include "MagickCore/channel.h"
#include "MagickCore/color.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/composite.h"
#include "MagickCore/composite-private.h"
#include "MagickCore/constitute.h"
#include "MagickCore/draw.h"
#include "MagickCore/draw-private.h"
#include "MagickCore/enhance.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/gem.h"
#include "MagickCore/geometry.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/log.h"
#include "MagickCore/memory-private.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/option.h"
#include "MagickCore/paint.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/pixel-private.h"
#include "MagickCore/property.h"
#include "MagickCore/resample.h"
#include "MagickCore/resample-private.h"
#include "MagickCore/resource_.h"
#include "MagickCore/splay-tree.h"
#include "MagickCore/string_.h"
#include "MagickCore/string-private.h"
#include "MagickCore/thread-private.h"
#include "MagickCore/token.h"
#include "MagickCore/transform-private.h"
#include "MagickCore/utility.h"
/*
Define declarations.
*/
#define BezierQuantum 200
#define PrimitiveExtentPad 2048
#define MaxBezierCoordinates 4194304
#define ThrowPointExpectedException(token,exception) \
{ \
(void) ThrowMagickException(exception,GetMagickModule(),DrawError, \
"NonconformingDrawingPrimitiveDefinition","`%s'",token); \
status=MagickFalse; \
break; \
}
/*
Typedef declarations.
*/
typedef struct _EdgeInfo
{
SegmentInfo
bounds;
double
scanline;
PointInfo
*points;
size_t
number_points;
ssize_t
direction;
MagickBooleanType
ghostline;
size_t
highwater;
} EdgeInfo;
typedef struct _ElementInfo
{
double
cx,
cy,
major,
minor,
angle;
} ElementInfo;
typedef struct _MVGInfo
{
PrimitiveInfo
**primitive_info;
size_t
*extent;
ssize_t
offset;
PointInfo
point;
ExceptionInfo
*exception;
} MVGInfo;
typedef struct _PolygonInfo
{
EdgeInfo
*edges;
size_t
number_edges;
} PolygonInfo;
typedef enum
{
MoveToCode,
OpenCode,
GhostlineCode,
LineToCode,
EndCode
} PathInfoCode;
typedef struct _PathInfo
{
PointInfo
point;
PathInfoCode
code;
} PathInfo;
/*
Forward declarations.
*/
static Image
*DrawClippingMask(Image *,const DrawInfo *,const char *,const char *,
ExceptionInfo *);
static MagickBooleanType
DrawStrokePolygon(Image *,const DrawInfo *,const PrimitiveInfo *,
ExceptionInfo *),
RenderMVGContent(Image *,const DrawInfo *,const size_t,ExceptionInfo *),
TraceArc(MVGInfo *,const PointInfo,const PointInfo,const PointInfo),
TraceArcPath(MVGInfo *,const PointInfo,const PointInfo,const PointInfo,
const double,const MagickBooleanType,const MagickBooleanType),
TraceBezier(MVGInfo *,const size_t),
TraceCircle(MVGInfo *,const PointInfo,const PointInfo),
TraceEllipse(MVGInfo *,const PointInfo,const PointInfo,const PointInfo),
TraceLine(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceRectangle(PrimitiveInfo *,const PointInfo,const PointInfo),
TraceRoundRectangle(MVGInfo *,const PointInfo,const PointInfo,PointInfo),
TraceSquareLinecap(PrimitiveInfo *,const size_t,const double);
static PrimitiveInfo
*TraceStrokePolygon(const Image *,const DrawInfo *,const PrimitiveInfo *);
static size_t
TracePath(MVGInfo *,const char *,ExceptionInfo *);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% A c q u i r e D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% AcquireDrawInfo() returns a DrawInfo structure properly initialized.
%
% The format of the AcquireDrawInfo method is:
%
% DrawInfo *AcquireDrawInfo(void)
%
*/
MagickExport DrawInfo *AcquireDrawInfo(void)
{
DrawInfo
*draw_info;
draw_info=(DrawInfo *) AcquireCriticalMemory(sizeof(*draw_info));
GetDrawInfo((ImageInfo *) NULL,draw_info);
return(draw_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% C l o n e D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% CloneDrawInfo() makes a copy of the given draw_info structure. If NULL
% is specified, a new DrawInfo structure is created initialized to default
% values.
%
% The format of the CloneDrawInfo method is:
%
% DrawInfo *CloneDrawInfo(const ImageInfo *image_info,
% const DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image_info: the image info.
%
% o draw_info: the draw info.
%
*/
MagickExport DrawInfo *CloneDrawInfo(const ImageInfo *image_info,
const DrawInfo *draw_info)
{
DrawInfo
*clone_info;
ExceptionInfo
*exception;
clone_info=(DrawInfo *) AcquireCriticalMemory(sizeof(*clone_info));
GetDrawInfo(image_info,clone_info);
if (draw_info == (DrawInfo *) NULL)
return(clone_info);
exception=AcquireExceptionInfo();
if (draw_info->primitive != (char *) NULL)
(void) CloneString(&clone_info->primitive,draw_info->primitive);
if (draw_info->geometry != (char *) NULL)
(void) CloneString(&clone_info->geometry,draw_info->geometry);
clone_info->compliance=draw_info->compliance;
clone_info->viewbox=draw_info->viewbox;
clone_info->affine=draw_info->affine;
clone_info->gravity=draw_info->gravity;
clone_info->fill=draw_info->fill;
clone_info->stroke=draw_info->stroke;
clone_info->stroke_width=draw_info->stroke_width;
if (draw_info->fill_pattern != (Image *) NULL)
clone_info->fill_pattern=CloneImage(draw_info->fill_pattern,0,0,MagickTrue,
exception);
if (draw_info->stroke_pattern != (Image *) NULL)
clone_info->stroke_pattern=CloneImage(draw_info->stroke_pattern,0,0,
MagickTrue,exception);
clone_info->stroke_antialias=draw_info->stroke_antialias;
clone_info->text_antialias=draw_info->text_antialias;
clone_info->fill_rule=draw_info->fill_rule;
clone_info->linecap=draw_info->linecap;
clone_info->linejoin=draw_info->linejoin;
clone_info->miterlimit=draw_info->miterlimit;
clone_info->dash_offset=draw_info->dash_offset;
clone_info->decorate=draw_info->decorate;
clone_info->compose=draw_info->compose;
if (draw_info->text != (char *) NULL)
(void) CloneString(&clone_info->text,draw_info->text);
if (draw_info->font != (char *) NULL)
(void) CloneString(&clone_info->font,draw_info->font);
if (draw_info->metrics != (char *) NULL)
(void) CloneString(&clone_info->metrics,draw_info->metrics);
if (draw_info->family != (char *) NULL)
(void) CloneString(&clone_info->family,draw_info->family);
clone_info->style=draw_info->style;
clone_info->stretch=draw_info->stretch;
clone_info->weight=draw_info->weight;
if (draw_info->encoding != (char *) NULL)
(void) CloneString(&clone_info->encoding,draw_info->encoding);
clone_info->pointsize=draw_info->pointsize;
clone_info->kerning=draw_info->kerning;
clone_info->interline_spacing=draw_info->interline_spacing;
clone_info->interword_spacing=draw_info->interword_spacing;
clone_info->direction=draw_info->direction;
if (draw_info->density != (char *) NULL)
(void) CloneString(&clone_info->density,draw_info->density);
clone_info->align=draw_info->align;
clone_info->undercolor=draw_info->undercolor;
clone_info->border_color=draw_info->border_color;
if (draw_info->server_name != (char *) NULL)
(void) CloneString(&clone_info->server_name,draw_info->server_name);
if (draw_info->dash_pattern != (double *) NULL)
{
register ssize_t
x;
for (x=0; fabs(draw_info->dash_pattern[x]) >= MagickEpsilon; x++) ;
clone_info->dash_pattern=(double *) AcquireQuantumMemory((size_t) (2*x+2),
sizeof(*clone_info->dash_pattern));
if (clone_info->dash_pattern == (double *) NULL)
ThrowFatalException(ResourceLimitFatalError,
"UnableToAllocateDashPattern");
(void) memset(clone_info->dash_pattern,0,(size_t) (2*x+2)*
sizeof(*clone_info->dash_pattern));
(void) memcpy(clone_info->dash_pattern,draw_info->dash_pattern,(size_t)
(x+1)*sizeof(*clone_info->dash_pattern));
}
clone_info->gradient=draw_info->gradient;
if (draw_info->gradient.stops != (StopInfo *) NULL)
{
size_t
number_stops;
number_stops=clone_info->gradient.number_stops;
clone_info->gradient.stops=(StopInfo *) AcquireQuantumMemory((size_t)
number_stops,sizeof(*clone_info->gradient.stops));
if (clone_info->gradient.stops == (StopInfo *) NULL)
ThrowFatalException(ResourceLimitFatalError,
"UnableToAllocateDashPattern");
(void) memcpy(clone_info->gradient.stops,draw_info->gradient.stops,
(size_t) number_stops*sizeof(*clone_info->gradient.stops));
}
clone_info->bounds=draw_info->bounds;
clone_info->fill_alpha=draw_info->fill_alpha;
clone_info->stroke_alpha=draw_info->stroke_alpha;
clone_info->element_reference=draw_info->element_reference;
clone_info->clip_path=draw_info->clip_path;
clone_info->clip_units=draw_info->clip_units;
if (draw_info->clip_mask != (char *) NULL)
(void) CloneString(&clone_info->clip_mask,draw_info->clip_mask);
if (draw_info->clipping_mask != (Image *) NULL)
clone_info->clipping_mask=CloneImage(draw_info->clipping_mask,0,0,
MagickTrue,exception);
if (draw_info->composite_mask != (Image *) NULL)
clone_info->composite_mask=CloneImage(draw_info->composite_mask,0,0,
MagickTrue,exception);
clone_info->render=draw_info->render;
clone_info->debug=IsEventLogging();
exception=DestroyExceptionInfo(exception);
return(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n v e r t P a t h T o P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConvertPathToPolygon() converts a path to the more efficient sorted
% rendering form.
%
% The format of the ConvertPathToPolygon method is:
%
% PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info)
%
% A description of each parameter follows:
%
% o Method ConvertPathToPolygon returns the path in a more efficient sorted
% rendering form of type PolygonInfo.
%
% o draw_info: Specifies a pointer to an DrawInfo structure.
%
% o path_info: Specifies a pointer to an PathInfo structure.
%
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int DrawCompareEdges(const void *p_edge,const void *q_edge)
{
#define DrawCompareEdge(p,q) \
{ \
if (((p)-(q)) < 0.0) \
return(-1); \
if (((p)-(q)) > 0.0) \
return(1); \
}
register const PointInfo
*p,
*q;
/*
Edge sorting for right-handed coordinate system.
*/
p=((const EdgeInfo *) p_edge)->points;
q=((const EdgeInfo *) q_edge)->points;
DrawCompareEdge(p[0].y,q[0].y);
DrawCompareEdge(p[0].x,q[0].x);
DrawCompareEdge((p[1].x-p[0].x)*(q[1].y-q[0].y),(p[1].y-p[0].y)*
(q[1].x-q[0].x));
DrawCompareEdge(p[1].y,q[1].y);
DrawCompareEdge(p[1].x,q[1].x);
return(0);
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
static void LogPolygonInfo(const PolygonInfo *polygon_info)
{
register EdgeInfo
*p;
register ssize_t
i,
j;
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin active-edge");
p=polygon_info->edges;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
{
(void) LogMagickEvent(DrawEvent,GetMagickModule()," edge %.20g:",
(double) i);
(void) LogMagickEvent(DrawEvent,GetMagickModule()," direction: %s",
p->direction != MagickFalse ? "down" : "up");
(void) LogMagickEvent(DrawEvent,GetMagickModule()," ghostline: %s",
p->ghostline != MagickFalse ? "transparent" : "opaque");
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" bounds: %g,%g - %g,%g",p->bounds.x1,p->bounds.y1,
p->bounds.x2,p->bounds.y2);
for (j=0; j < (ssize_t) p->number_points; j++)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %g,%g",
p->points[j].x,p->points[j].y);
p++;
}
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end active-edge");
}
static void ReversePoints(PointInfo *points,const size_t number_points)
{
PointInfo
point;
register ssize_t
i;
for (i=0; i < (ssize_t) (number_points >> 1); i++)
{
point=points[i];
points[i]=points[number_points-(i+1)];
points[number_points-(i+1)]=point;
}
}
static PolygonInfo *ConvertPathToPolygon(const PathInfo *path_info)
{
long
direction,
next_direction;
PointInfo
point,
*points;
PolygonInfo
*polygon_info;
SegmentInfo
bounds;
register ssize_t
i,
n;
MagickBooleanType
ghostline;
size_t
edge,
number_edges,
number_points;
/*
Convert a path to the more efficient sorted rendering form.
*/
polygon_info=(PolygonInfo *) AcquireMagickMemory(sizeof(*polygon_info));
if (polygon_info == (PolygonInfo *) NULL)
return((PolygonInfo *) NULL);
number_edges=16;
polygon_info->edges=(EdgeInfo *) AcquireQuantumMemory(number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
(void) memset(polygon_info->edges,0,number_edges*
sizeof(*polygon_info->edges));
direction=0;
edge=0;
ghostline=MagickFalse;
n=0;
number_points=0;
points=(PointInfo *) NULL;
(void) memset(&point,0,sizeof(point));
(void) memset(&bounds,0,sizeof(bounds));
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=0.0;
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) direction;
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->number_edges=0;
for (i=0; path_info[i].code != EndCode; i++)
{
if ((path_info[i].code == MoveToCode) || (path_info[i].code == OpenCode) ||
(path_info[i].code == GhostlineCode))
{
/*
Move to.
*/
if ((points != (PointInfo *) NULL) && (n >= 2))
{
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
points=(PointInfo *) NULL;
ghostline=MagickFalse;
edge++;
}
if (points == (PointInfo *) NULL)
{
number_points=16;
points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
}
ghostline=path_info[i].code == GhostlineCode ? MagickTrue : MagickFalse;
point=path_info[i].point;
points[0]=point;
bounds.x1=point.x;
bounds.x2=point.x;
direction=0;
n=1;
continue;
}
/*
Line to.
*/
next_direction=((path_info[i].point.y > point.y) ||
((fabs(path_info[i].point.y-point.y) < MagickEpsilon) &&
(path_info[i].point.x > point.x))) ? 1 : -1;
if ((points != (PointInfo *) NULL) && (direction != 0) &&
(direction != next_direction))
{
/*
New edge.
*/
point=points[n-1];
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
number_points=16;
points=(PointInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
n=1;
ghostline=MagickFalse;
points[0]=point;
bounds.x1=point.x;
bounds.x2=point.x;
edge++;
}
direction=next_direction;
if (points == (PointInfo *) NULL)
continue;
if (n == (ssize_t) number_points)
{
number_points<<=1;
points=(PointInfo *) ResizeQuantumMemory(points,(size_t) number_points,
sizeof(*points));
if (points == (PointInfo *) NULL)
return((PolygonInfo *) NULL);
}
point=path_info[i].point;
points[n]=point;
if (point.x < bounds.x1)
bounds.x1=point.x;
if (point.x > bounds.x2)
bounds.x2=point.x;
n++;
}
if (points != (PointInfo *) NULL)
{
if (n < 2)
points=(PointInfo *) RelinquishMagickMemory(points);
else
{
if (edge == number_edges)
{
number_edges<<=1;
polygon_info->edges=(EdgeInfo *) ResizeQuantumMemory(
polygon_info->edges,(size_t) number_edges,
sizeof(*polygon_info->edges));
if (polygon_info->edges == (EdgeInfo *) NULL)
return((PolygonInfo *) NULL);
}
polygon_info->edges[edge].number_points=(size_t) n;
polygon_info->edges[edge].scanline=(-1.0);
polygon_info->edges[edge].highwater=0;
polygon_info->edges[edge].ghostline=ghostline;
polygon_info->edges[edge].direction=(ssize_t) (direction > 0);
if (direction < 0)
ReversePoints(points,(size_t) n);
polygon_info->edges[edge].points=points;
polygon_info->edges[edge].bounds=bounds;
polygon_info->edges[edge].bounds.y1=points[0].y;
polygon_info->edges[edge].bounds.y2=points[n-1].y;
ghostline=MagickFalse;
edge++;
}
}
polygon_info->number_edges=edge;
qsort(polygon_info->edges,(size_t) polygon_info->number_edges,
sizeof(*polygon_info->edges),DrawCompareEdges);
if (IsEventLogging() != MagickFalse)
LogPolygonInfo(polygon_info);
return(polygon_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ C o n v e r t P r i m i t i v e T o P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% ConvertPrimitiveToPath() converts a PrimitiveInfo structure into a vector
% path structure.
%
% The format of the ConvertPrimitiveToPath method is:
%
% PathInfo *ConvertPrimitiveToPath(const DrawInfo *draw_info,
% const PrimitiveInfo *primitive_info)
%
% A description of each parameter follows:
%
% o Method ConvertPrimitiveToPath returns a vector path structure of type
% PathInfo.
%
% o draw_info: a structure of type DrawInfo.
%
% o primitive_info: Specifies a pointer to an PrimitiveInfo structure.
%
%
*/
static void LogPathInfo(const PathInfo *path_info)
{
register const PathInfo
*p;
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin vector-path");
for (p=path_info; p->code != EndCode; p++)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %g,%g %s",p->point.x,p->point.y,p->code == GhostlineCode ?
"moveto ghostline" : p->code == OpenCode ? "moveto open" :
p->code == MoveToCode ? "moveto" : p->code == LineToCode ? "lineto" :
"?");
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end vector-path");
}
static PathInfo *ConvertPrimitiveToPath(const PrimitiveInfo *primitive_info)
{
MagickBooleanType
closed_subpath;
PathInfo
*path_info;
PathInfoCode
code;
PointInfo
p,
q;
register ssize_t
i,
n;
ssize_t
coordinates,
start;
/*
Converts a PrimitiveInfo structure into a vector path structure.
*/
switch (primitive_info->primitive)
{
case AlphaPrimitive:
case ColorPrimitive:
case ImagePrimitive:
case PointPrimitive:
case TextPrimitive:
return((PathInfo *) NULL);
default:
break;
}
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
path_info=(PathInfo *) AcquireQuantumMemory((size_t) (3UL*i+1UL),
sizeof(*path_info));
if (path_info == (PathInfo *) NULL)
return((PathInfo *) NULL);
coordinates=0;
closed_subpath=MagickFalse;
n=0;
p.x=(-1.0);
p.y=(-1.0);
q.x=(-1.0);
q.y=(-1.0);
start=0;
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
code=LineToCode;
if (coordinates <= 0)
{
/*
New subpath.
*/
coordinates=(ssize_t) primitive_info[i].coordinates;
p=primitive_info[i].point;
start=n;
code=MoveToCode;
closed_subpath=primitive_info[i].closed_subpath;
}
coordinates--;
if ((code == MoveToCode) || (coordinates <= 0) ||
(fabs(q.x-primitive_info[i].point.x) >= MagickEpsilon) ||
(fabs(q.y-primitive_info[i].point.y) >= MagickEpsilon))
{
/*
Eliminate duplicate points.
*/
path_info[n].code=code;
path_info[n].point=primitive_info[i].point;
q=primitive_info[i].point;
n++;
}
if (coordinates > 0)
continue; /* next point in current subpath */
if (closed_subpath != MagickFalse)
{
closed_subpath=MagickFalse;
continue;
}
/*
Mark the p point as open if the subpath is not closed.
*/
path_info[start].code=OpenCode;
path_info[n].code=GhostlineCode;
path_info[n].point=primitive_info[i].point;
n++;
path_info[n].code=LineToCode;
path_info[n].point=p;
n++;
}
path_info[n].code=EndCode;
path_info[n].point.x=0.0;
path_info[n].point.y=0.0;
if (IsEventLogging() != MagickFalse)
LogPathInfo(path_info);
path_info=(PathInfo *) ResizeQuantumMemory(path_info,(size_t) (n+1),
sizeof(*path_info));
return(path_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyDrawInfo() deallocates memory associated with an DrawInfo structure.
%
% The format of the DestroyDrawInfo method is:
%
% DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o draw_info: the draw info.
%
*/
MagickExport DrawInfo *DestroyDrawInfo(DrawInfo *draw_info)
{
assert(draw_info != (DrawInfo *) NULL);
if (draw_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(draw_info->signature == MagickCoreSignature);
if (draw_info->primitive != (char *) NULL)
draw_info->primitive=DestroyString(draw_info->primitive);
if (draw_info->text != (char *) NULL)
draw_info->text=DestroyString(draw_info->text);
if (draw_info->geometry != (char *) NULL)
draw_info->geometry=DestroyString(draw_info->geometry);
if (draw_info->fill_pattern != (Image *) NULL)
draw_info->fill_pattern=DestroyImage(draw_info->fill_pattern);
if (draw_info->stroke_pattern != (Image *) NULL)
draw_info->stroke_pattern=DestroyImage(draw_info->stroke_pattern);
if (draw_info->font != (char *) NULL)
draw_info->font=DestroyString(draw_info->font);
if (draw_info->metrics != (char *) NULL)
draw_info->metrics=DestroyString(draw_info->metrics);
if (draw_info->family != (char *) NULL)
draw_info->family=DestroyString(draw_info->family);
if (draw_info->encoding != (char *) NULL)
draw_info->encoding=DestroyString(draw_info->encoding);
if (draw_info->density != (char *) NULL)
draw_info->density=DestroyString(draw_info->density);
if (draw_info->server_name != (char *) NULL)
draw_info->server_name=(char *)
RelinquishMagickMemory(draw_info->server_name);
if (draw_info->dash_pattern != (double *) NULL)
draw_info->dash_pattern=(double *) RelinquishMagickMemory(
draw_info->dash_pattern);
if (draw_info->gradient.stops != (StopInfo *) NULL)
draw_info->gradient.stops=(StopInfo *) RelinquishMagickMemory(
draw_info->gradient.stops);
if (draw_info->clip_mask != (char *) NULL)
draw_info->clip_mask=DestroyString(draw_info->clip_mask);
if (draw_info->clipping_mask != (Image *) NULL)
draw_info->clipping_mask=DestroyImage(draw_info->clipping_mask);
if (draw_info->composite_mask != (Image *) NULL)
draw_info->composite_mask=DestroyImage(draw_info->composite_mask);
draw_info->signature=(~MagickCoreSignature);
draw_info=(DrawInfo *) RelinquishMagickMemory(draw_info);
return(draw_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y E d g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyEdge() destroys the specified polygon edge.
%
% The format of the DestroyEdge method is:
%
% ssize_t DestroyEdge(PolygonInfo *polygon_info,const int edge)
%
% A description of each parameter follows:
%
% o polygon_info: Specifies a pointer to an PolygonInfo structure.
%
% o edge: the polygon edge number to destroy.
%
*/
static size_t DestroyEdge(PolygonInfo *polygon_info,
const size_t edge)
{
assert(edge < polygon_info->number_edges);
polygon_info->edges[edge].points=(PointInfo *) RelinquishMagickMemory(
polygon_info->edges[edge].points);
polygon_info->number_edges--;
if (edge < polygon_info->number_edges)
(void) memmove(polygon_info->edges+edge,polygon_info->edges+edge+1,
(size_t) (polygon_info->number_edges-edge)*sizeof(*polygon_info->edges));
return(polygon_info->number_edges);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D e s t r o y P o l y g o n I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyPolygonInfo() destroys the PolygonInfo data structure.
%
% The format of the DestroyPolygonInfo method is:
%
% PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)
%
% A description of each parameter follows:
%
% o polygon_info: Specifies a pointer to an PolygonInfo structure.
%
*/
static PolygonInfo *DestroyPolygonInfo(PolygonInfo *polygon_info)
{
register ssize_t
i;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
polygon_info->edges[i].points=(PointInfo *)
RelinquishMagickMemory(polygon_info->edges[i].points);
polygon_info->edges=(EdgeInfo *) RelinquishMagickMemory(polygon_info->edges);
return((PolygonInfo *) RelinquishMagickMemory(polygon_info));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w A f f i n e I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawAffineImage() composites the source over the destination image as
% dictated by the affine transform.
%
% The format of the DrawAffineImage method is:
%
% MagickBooleanType DrawAffineImage(Image *image,const Image *source,
% const AffineMatrix *affine,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o source: the source image.
%
% o affine: the affine transform.
%
% o exception: return any errors or warnings in this structure.
%
*/
static SegmentInfo AffineEdge(const Image *image,const AffineMatrix *affine,
const double y,const SegmentInfo *edge)
{
double
intercept,
z;
register double
x;
SegmentInfo
inverse_edge;
/*
Determine left and right edges.
*/
inverse_edge.x1=edge->x1;
inverse_edge.y1=edge->y1;
inverse_edge.x2=edge->x2;
inverse_edge.y2=edge->y2;
z=affine->ry*y+affine->tx;
if (affine->sx >= MagickEpsilon)
{
intercept=(-z/affine->sx);
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z+(double) image->columns)/affine->sx;
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if (affine->sx < -MagickEpsilon)
{
intercept=(-z+(double) image->columns)/affine->sx;
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z/affine->sx);
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->columns))
{
inverse_edge.x2=edge->x1;
return(inverse_edge);
}
/*
Determine top and bottom edges.
*/
z=affine->sy*y+affine->ty;
if (affine->rx >= MagickEpsilon)
{
intercept=(-z/affine->rx);
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z+(double) image->rows)/affine->rx;
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if (affine->rx < -MagickEpsilon)
{
intercept=(-z+(double) image->rows)/affine->rx;
x=intercept;
if (x > inverse_edge.x1)
inverse_edge.x1=x;
intercept=(-z/affine->rx);
x=intercept;
if (x < inverse_edge.x2)
inverse_edge.x2=x;
}
else
if ((z < 0.0) || ((size_t) floor(z+0.5) >= image->rows))
{
inverse_edge.x2=edge->x2;
return(inverse_edge);
}
return(inverse_edge);
}
static AffineMatrix InverseAffineMatrix(const AffineMatrix *affine)
{
AffineMatrix
inverse_affine;
double
determinant;
determinant=PerceptibleReciprocal(affine->sx*affine->sy-affine->rx*
affine->ry);
inverse_affine.sx=determinant*affine->sy;
inverse_affine.rx=determinant*(-affine->rx);
inverse_affine.ry=determinant*(-affine->ry);
inverse_affine.sy=determinant*affine->sx;
inverse_affine.tx=(-affine->tx)*inverse_affine.sx-affine->ty*
inverse_affine.ry;
inverse_affine.ty=(-affine->tx)*inverse_affine.rx-affine->ty*
inverse_affine.sy;
return(inverse_affine);
}
MagickExport MagickBooleanType DrawAffineImage(Image *image,
const Image *source,const AffineMatrix *affine,ExceptionInfo *exception)
{
AffineMatrix
inverse_affine;
CacheView
*image_view,
*source_view;
MagickBooleanType
status;
PixelInfo
zero;
PointInfo
extent[4],
min,
max;
register ssize_t
i;
SegmentInfo
edge;
ssize_t
start,
stop,
y;
/*
Determine bounding box.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(source != (const Image *) NULL);
assert(source->signature == MagickCoreSignature);
assert(affine != (AffineMatrix *) NULL);
extent[0].x=0.0;
extent[0].y=0.0;
extent[1].x=(double) source->columns-1.0;
extent[1].y=0.0;
extent[2].x=(double) source->columns-1.0;
extent[2].y=(double) source->rows-1.0;
extent[3].x=0.0;
extent[3].y=(double) source->rows-1.0;
for (i=0; i < 4; i++)
{
PointInfo
point;
point=extent[i];
extent[i].x=point.x*affine->sx+point.y*affine->ry+affine->tx;
extent[i].y=point.x*affine->rx+point.y*affine->sy+affine->ty;
}
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;
}
/*
Affine transform image.
*/
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
status=MagickTrue;
edge.x1=MagickMax(min.x,0.0);
edge.y1=MagickMax(min.y,0.0);
edge.x2=MagickMin(max.x,(double) image->columns-1.0);
edge.y2=MagickMin(max.y,(double) image->rows-1.0);
inverse_affine=InverseAffineMatrix(affine);
GetPixelInfo(image,&zero);
start=(ssize_t) ceil(edge.y1-0.5);
stop=(ssize_t) floor(edge.y2+0.5);
source_view=AcquireVirtualCacheView(source,exception);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(source,image,stop-start,1)
#endif
for (y=start; y <= stop; y++)
{
PixelInfo
composite,
pixel;
PointInfo
point;
register ssize_t
x;
register Quantum
*magick_restrict q;
SegmentInfo
inverse_edge;
ssize_t
x_offset;
inverse_edge=AffineEdge(source,&inverse_affine,(double) y,&edge);
if (inverse_edge.x2 < inverse_edge.x1)
continue;
q=GetCacheViewAuthenticPixels(image_view,(ssize_t) ceil(inverse_edge.x1-
0.5),y,(size_t) (floor(inverse_edge.x2+0.5)-ceil(inverse_edge.x1-0.5)+1),
1,exception);
if (q == (Quantum *) NULL)
continue;
pixel=zero;
composite=zero;
x_offset=0;
for (x=(ssize_t) ceil(inverse_edge.x1-0.5); x <= (ssize_t) floor(inverse_edge.x2+0.5); x++)
{
point.x=(double) x*inverse_affine.sx+y*inverse_affine.ry+
inverse_affine.tx;
point.y=(double) x*inverse_affine.rx+y*inverse_affine.sy+
inverse_affine.ty;
status=InterpolatePixelInfo(source,source_view,UndefinedInterpolatePixel,
point.x,point.y,&pixel,exception);
if (status == MagickFalse)
break;
GetPixelInfoPixel(image,q,&composite);
CompositePixelInfoOver(&pixel,pixel.alpha,&composite,composite.alpha,
&composite);
SetPixelViaPixelInfo(image,&composite,q);
x_offset++;
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
source_view=DestroyCacheView(source_view);
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w B o u n d i n g R e c t a n g l e s %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawBoundingRectangles() draws the bounding rectangles on the image. This
% is only useful for developers debugging the rendering algorithm.
%
% The format of the DrawBoundingRectangles method is:
%
% MagickBooleanType DrawBoundingRectangles(Image *image,
% const DrawInfo *draw_info,PolygonInfo *polygon_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o polygon_info: Specifies a pointer to a PolygonInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double SaneStrokeWidth(const Image *image,
const DrawInfo *draw_info)
{
return(MagickMin((double) draw_info->stroke_width,
(2.0*sqrt(2.0)+MagickEpsilon)*MagickMax(image->columns,image->rows)));
}
static MagickBooleanType DrawBoundingRectangles(Image *image,
const DrawInfo *draw_info,const PolygonInfo *polygon_info,
ExceptionInfo *exception)
{
double
mid;
DrawInfo
*clone_info;
MagickStatusType
status;
PointInfo
end,
resolution,
start;
PrimitiveInfo
primitive_info[6];
register ssize_t
i;
SegmentInfo
bounds;
ssize_t
coordinates;
(void) memset(primitive_info,0,sizeof(primitive_info));
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
status=QueryColorCompliance("#000F",AllCompliance,&clone_info->fill,
exception);
if (status == MagickFalse)
{
clone_info=DestroyDrawInfo(clone_info);
return(MagickFalse);
}
resolution.x=96.0;
resolution.y=96.0;
if (clone_info->density != (char *) NULL)
{
GeometryInfo
geometry_info;
MagickStatusType
flags;
flags=ParseGeometry(clone_info->density,&geometry_info);
resolution.x=geometry_info.rho;
resolution.y=geometry_info.sigma;
if ((flags & SigmaValue) == MagickFalse)
resolution.y=resolution.x;
}
mid=(resolution.x/96.0)*ExpandAffine(&clone_info->affine)*
SaneStrokeWidth(image,clone_info)/2.0;
bounds.x1=0.0;
bounds.y1=0.0;
bounds.x2=0.0;
bounds.y2=0.0;
if (polygon_info != (PolygonInfo *) NULL)
{
bounds=polygon_info->edges[0].bounds;
for (i=1; i < (ssize_t) polygon_info->number_edges; i++)
{
if (polygon_info->edges[i].bounds.x1 < (double) bounds.x1)
bounds.x1=polygon_info->edges[i].bounds.x1;
if (polygon_info->edges[i].bounds.y1 < (double) bounds.y1)
bounds.y1=polygon_info->edges[i].bounds.y1;
if (polygon_info->edges[i].bounds.x2 > (double) bounds.x2)
bounds.x2=polygon_info->edges[i].bounds.x2;
if (polygon_info->edges[i].bounds.y2 > (double) bounds.y2)
bounds.y2=polygon_info->edges[i].bounds.y2;
}
bounds.x1-=mid;
bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double)
image->columns ? (double) image->columns-1 : bounds.x1;
bounds.y1-=mid;
bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double)
image->rows ? (double) image->rows-1 : bounds.y1;
bounds.x2+=mid;
bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double)
image->columns ? (double) image->columns-1 : bounds.x2;
bounds.y2+=mid;
bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double)
image->rows ? (double) image->rows-1 : bounds.y2;
for (i=0; i < (ssize_t) polygon_info->number_edges; i++)
{
if (polygon_info->edges[i].direction != 0)
status=QueryColorCompliance("#f00",AllCompliance,&clone_info->stroke,
exception);
else
status=QueryColorCompliance("#0f0",AllCompliance,&clone_info->stroke,
exception);
if (status == MagickFalse)
break;
start.x=(double) (polygon_info->edges[i].bounds.x1-mid);
start.y=(double) (polygon_info->edges[i].bounds.y1-mid);
end.x=(double) (polygon_info->edges[i].bounds.x2+mid);
end.y=(double) (polygon_info->edges[i].bounds.y2+mid);
primitive_info[0].primitive=RectanglePrimitive;
status&=TraceRectangle(primitive_info,start,end);
primitive_info[0].method=ReplaceMethod;
coordinates=(ssize_t) primitive_info[0].coordinates;
primitive_info[coordinates].primitive=UndefinedPrimitive;
status=DrawPrimitive(image,clone_info,primitive_info,exception);
if (status == MagickFalse)
break;
}
if (i < (ssize_t) polygon_info->number_edges)
{
clone_info=DestroyDrawInfo(clone_info);
return(status == 0 ? MagickFalse : MagickTrue);
}
}
status=QueryColorCompliance("#00f",AllCompliance,&clone_info->stroke,
exception);
if (status == MagickFalse)
{
clone_info=DestroyDrawInfo(clone_info);
return(MagickFalse);
}
start.x=(double) (bounds.x1-mid);
start.y=(double) (bounds.y1-mid);
end.x=(double) (bounds.x2+mid);
end.y=(double) (bounds.y2+mid);
primitive_info[0].primitive=RectanglePrimitive;
status&=TraceRectangle(primitive_info,start,end);
primitive_info[0].method=ReplaceMethod;
coordinates=(ssize_t) primitive_info[0].coordinates;
primitive_info[coordinates].primitive=UndefinedPrimitive;
status=DrawPrimitive(image,clone_info,primitive_info,exception);
clone_info=DestroyDrawInfo(clone_info);
return(status == 0 ? MagickFalse : MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w C l i p P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawClipPath() draws the clip path on the image mask.
%
% The format of the DrawClipPath method is:
%
% MagickBooleanType DrawClipPath(Image *image,const DrawInfo *draw_info,
% const char *id,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o id: the clip path id.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType DrawClipPath(Image *image,
const DrawInfo *draw_info,const char *id,ExceptionInfo *exception)
{
const char
*clip_path;
Image
*clipping_mask;
MagickBooleanType
status;
clip_path=GetImageArtifact(image,id);
if (clip_path == (const char *) NULL)
return(MagickFalse);
clipping_mask=DrawClippingMask(image,draw_info,draw_info->clip_mask,clip_path,
exception);
if (clipping_mask == (Image *) NULL)
return(MagickFalse);
status=SetImageMask(image,WritePixelMask,clipping_mask,exception);
clipping_mask=DestroyImage(clipping_mask);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w C l i p p i n g M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawClippingMask() draws the clip path and returns it as an image clipping
% mask.
%
% The format of the DrawClippingMask method is:
%
% Image *DrawClippingMask(Image *image,const DrawInfo *draw_info,
% const char *id,const char *clip_path,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o id: the clip path id.
%
% o clip_path: the clip path.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *DrawClippingMask(Image *image,const DrawInfo *draw_info,
const char *id,const char *clip_path,ExceptionInfo *exception)
{
DrawInfo
*clone_info;
Image
*clip_mask,
*separate_mask;
MagickStatusType
status;
/*
Draw a clip path.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
clip_mask=AcquireImage((const ImageInfo *) NULL,exception);
status=SetImageExtent(clip_mask,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImage(clip_mask));
status=SetImageMask(clip_mask,WritePixelMask,(Image *) NULL,exception);
status=QueryColorCompliance("#0000",AllCompliance,
&clip_mask->background_color,exception);
clip_mask->background_color.alpha=(MagickRealType) TransparentAlpha;
clip_mask->background_color.alpha_trait=BlendPixelTrait;
status=SetImageBackgroundColor(clip_mask,exception);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin clip-path %s",
id);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) CloneString(&clone_info->primitive,clip_path);
status=QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill,
exception);
if (clone_info->clip_mask != (char *) NULL)
clone_info->clip_mask=DestroyString(clone_info->clip_mask);
status=QueryColorCompliance("#00000000",AllCompliance,&clone_info->stroke,
exception);
clone_info->stroke_width=0.0;
clone_info->alpha=OpaqueAlpha;
clone_info->clip_path=MagickTrue;
status=RenderMVGContent(clip_mask,clone_info,0,exception);
clone_info=DestroyDrawInfo(clone_info);
separate_mask=SeparateImage(clip_mask,AlphaChannel,exception);
if (separate_mask != (Image *) NULL)
{
clip_mask=DestroyImage(clip_mask);
clip_mask=separate_mask;
status=NegateImage(clip_mask,MagickFalse,exception);
if (status == MagickFalse)
clip_mask=DestroyImage(clip_mask);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end clip-path");
return(clip_mask);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w C o m p o s i t e M a s k %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawCompositeMask() draws the mask path and returns it as an image mask.
%
% The format of the DrawCompositeMask method is:
%
% Image *DrawCompositeMask(Image *image,const DrawInfo *draw_info,
% const char *id,const char *mask_path,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o id: the mask path id.
%
% o mask_path: the mask path.
%
% o exception: return any errors or warnings in this structure.
%
*/
static Image *DrawCompositeMask(Image *image,const DrawInfo *draw_info,
const char *id,const char *mask_path,ExceptionInfo *exception)
{
Image
*composite_mask,
*separate_mask;
DrawInfo
*clone_info;
MagickStatusType
status;
/*
Draw a mask path.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
composite_mask=AcquireImage((const ImageInfo *) NULL,exception);
status=SetImageExtent(composite_mask,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImage(composite_mask));
status=SetImageMask(composite_mask,CompositePixelMask,(Image *) NULL,
exception);
status=QueryColorCompliance("#0000",AllCompliance,
&composite_mask->background_color,exception);
composite_mask->background_color.alpha=(MagickRealType) TransparentAlpha;
composite_mask->background_color.alpha_trait=BlendPixelTrait;
(void) SetImageBackgroundColor(composite_mask,exception);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"\nbegin mask-path %s",
id);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) CloneString(&clone_info->primitive,mask_path);
status=QueryColorCompliance("#ffffff",AllCompliance,&clone_info->fill,
exception);
status=QueryColorCompliance("#00000000",AllCompliance,&clone_info->stroke,
exception);
clone_info->stroke_width=0.0;
clone_info->alpha=OpaqueAlpha;
status=RenderMVGContent(composite_mask,clone_info,0,exception);
clone_info=DestroyDrawInfo(clone_info);
separate_mask=SeparateImage(composite_mask,AlphaChannel,exception);
if (separate_mask != (Image *) NULL)
{
composite_mask=DestroyImage(composite_mask);
composite_mask=separate_mask;
status=NegateImage(composite_mask,MagickFalse,exception);
if (status == MagickFalse)
composite_mask=DestroyImage(composite_mask);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end mask-path");
return(composite_mask);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w D a s h P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawDashPolygon() draws a dashed polygon (line, rectangle, ellipse) on the
% image while respecting the dash offset and dash pattern attributes.
%
% The format of the DrawDashPolygon method is:
%
% MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
% const PrimitiveInfo *primitive_info,Image *image,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType DrawDashPolygon(const DrawInfo *draw_info,
const PrimitiveInfo *primitive_info,Image *image,ExceptionInfo *exception)
{
double
length,
maximum_length,
offset,
scale,
total_length;
DrawInfo
*clone_info;
MagickStatusType
status;
PrimitiveInfo
*dash_polygon;
register double
dx,
dy;
register ssize_t
i;
size_t
number_vertices;
ssize_t
j,
n;
assert(draw_info != (const DrawInfo *) NULL);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-dash");
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++) ;
number_vertices=(size_t) i;
dash_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
(2UL*number_vertices+32UL),sizeof(*dash_polygon));
if (dash_polygon == (PrimitiveInfo *) NULL)
return(MagickFalse);
(void) memset(dash_polygon,0,(2UL*number_vertices+32UL)*
sizeof(*dash_polygon));
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->miterlimit=0;
dash_polygon[0]=primitive_info[0];
scale=ExpandAffine(&draw_info->affine);
length=scale*draw_info->dash_pattern[0];
offset=fabs(draw_info->dash_offset) >= MagickEpsilon ?
scale*draw_info->dash_offset : 0.0;
j=1;
for (n=0; offset > 0.0; j=0)
{
if (draw_info->dash_pattern[n] <= 0.0)
break;
length=scale*(draw_info->dash_pattern[n]+(n == 0 ? -0.5 : 0.5));
if (offset > length)
{
offset-=length;
n++;
length=scale*draw_info->dash_pattern[n];
continue;
}
if (offset < length)
{
length-=offset;
offset=0.0;
break;
}
offset=0.0;
n++;
}
status=MagickTrue;
maximum_length=0.0;
total_length=0.0;
for (i=1; (i < (ssize_t) number_vertices) && (length >= 0.0); i++)
{
dx=primitive_info[i].point.x-primitive_info[i-1].point.x;
dy=primitive_info[i].point.y-primitive_info[i-1].point.y;
maximum_length=hypot(dx,dy);
if (maximum_length > MaxBezierCoordinates)
break;
if (fabs(length) < MagickEpsilon)
{
if (fabs(draw_info->dash_pattern[n]) >= MagickEpsilon)
n++;
if (fabs(draw_info->dash_pattern[n]) < MagickEpsilon)
n=0;
length=scale*draw_info->dash_pattern[n];
}
for (total_length=0.0; (length >= 0.0) && (maximum_length >= (total_length+length)); )
{
total_length+=length;
if ((n & 0x01) != 0)
{
dash_polygon[0]=primitive_info[0];
dash_polygon[0].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length*PerceptibleReciprocal(maximum_length));
dash_polygon[0].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length*PerceptibleReciprocal(maximum_length));
j=1;
}
else
{
if ((j+1) > (ssize_t) number_vertices)
break;
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x=(double) (primitive_info[i-1].point.x+dx*
total_length*PerceptibleReciprocal(maximum_length));
dash_polygon[j].point.y=(double) (primitive_info[i-1].point.y+dy*
total_length*PerceptibleReciprocal(maximum_length));
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);
if (status == MagickFalse)
break;
}
if (fabs(draw_info->dash_pattern[n]) >= MagickEpsilon)
n++;
if (fabs(draw_info->dash_pattern[n]) < MagickEpsilon)
n=0;
length=scale*draw_info->dash_pattern[n];
}
length-=(maximum_length-total_length);
if ((n & 0x01) != 0)
continue;
dash_polygon[j]=primitive_info[i];
dash_polygon[j].coordinates=1;
j++;
}
if ((status != MagickFalse) && (total_length < maximum_length) &&
((n & 0x01) == 0) && (j > 1))
{
dash_polygon[j]=primitive_info[i-1];
dash_polygon[j].point.x+=MagickEpsilon;
dash_polygon[j].point.y+=MagickEpsilon;
dash_polygon[j].coordinates=1;
j++;
dash_polygon[0].coordinates=(size_t) j;
dash_polygon[j].primitive=UndefinedPrimitive;
status&=DrawStrokePolygon(image,clone_info,dash_polygon,exception);
}
dash_polygon=(PrimitiveInfo *) RelinquishMagickMemory(dash_polygon);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-dash");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w G r a d i e n t I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawGradientImage() draws a linear gradient on the image.
%
% The format of the DrawGradientImage method is:
%
% MagickBooleanType DrawGradientImage(Image *image,
% const DrawInfo *draw_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double GetStopColorOffset(const GradientInfo *gradient,
const ssize_t x,const ssize_t y)
{
switch (gradient->type)
{
case UndefinedGradient:
case LinearGradient:
{
double
gamma,
length,
offset,
scale;
PointInfo
p,
q;
const SegmentInfo
*gradient_vector;
gradient_vector=(&gradient->gradient_vector);
p.x=gradient_vector->x2-gradient_vector->x1;
p.y=gradient_vector->y2-gradient_vector->y1;
q.x=(double) x-gradient_vector->x1;
q.y=(double) y-gradient_vector->y1;
length=sqrt(q.x*q.x+q.y*q.y);
gamma=sqrt(p.x*p.x+p.y*p.y)*length;
gamma=PerceptibleReciprocal(gamma);
scale=p.x*q.x+p.y*q.y;
offset=gamma*scale*length;
return(offset);
}
case RadialGradient:
{
PointInfo
v;
if (gradient->spread == RepeatSpread)
{
v.x=(double) x-gradient->center.x;
v.y=(double) y-gradient->center.y;
return(sqrt(v.x*v.x+v.y*v.y));
}
v.x=(double) (((x-gradient->center.x)*cos(DegreesToRadians(
gradient->angle)))+((y-gradient->center.y)*sin(DegreesToRadians(
gradient->angle))))*PerceptibleReciprocal(gradient->radii.x);
v.y=(double) (((x-gradient->center.x)*sin(DegreesToRadians(
gradient->angle)))-((y-gradient->center.y)*cos(DegreesToRadians(
gradient->angle))))*PerceptibleReciprocal(gradient->radii.y);
return(sqrt(v.x*v.x+v.y*v.y));
}
}
return(0.0);
}
static int StopInfoCompare(const void *x,const void *y)
{
StopInfo
*stop_1,
*stop_2;
stop_1=(StopInfo *) x;
stop_2=(StopInfo *) y;
if (stop_1->offset > stop_2->offset)
return(1);
if (fabs(stop_1->offset-stop_2->offset) <= MagickEpsilon)
return(0);
return(-1);
}
MagickExport MagickBooleanType DrawGradientImage(Image *image,
const DrawInfo *draw_info,ExceptionInfo *exception)
{
CacheView
*image_view;
const GradientInfo
*gradient;
const SegmentInfo
*gradient_vector;
double
length;
MagickBooleanType
status;
PixelInfo
zero;
PointInfo
point;
RectangleInfo
bounding_box;
ssize_t
y;
/*
Draw linear or radial gradient on image.
*/
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
gradient=(&draw_info->gradient);
qsort(gradient->stops,gradient->number_stops,sizeof(StopInfo),
StopInfoCompare);
gradient_vector=(&gradient->gradient_vector);
point.x=gradient_vector->x2-gradient_vector->x1;
point.y=gradient_vector->y2-gradient_vector->y1;
length=sqrt(point.x*point.x+point.y*point.y);
bounding_box=gradient->bounding_box;
status=MagickTrue;
GetPixelInfo(image,&zero);
image_view=AcquireAuthenticCacheView(image,exception);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,bounding_box.height-bounding_box.y,1)
#endif
for (y=bounding_box.y; y < (ssize_t) bounding_box.height; y++)
{
PixelInfo
composite,
pixel;
double
alpha,
offset;
register Quantum
*magick_restrict q;
register ssize_t
i,
x;
ssize_t
j;
if (status == MagickFalse)
continue;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
pixel=zero;
composite=zero;
offset=GetStopColorOffset(gradient,0,y);
if (gradient->type != RadialGradient)
offset*=PerceptibleReciprocal(length);
for (x=bounding_box.x; x < (ssize_t) bounding_box.width; x++)
{
GetPixelInfoPixel(image,q,&pixel);
switch (gradient->spread)
{
case UndefinedSpread:
case PadSpread:
{
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type != RadialGradient)
offset*=PerceptibleReciprocal(length);
}
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if ((offset < 0.0) || (i == 0))
composite=gradient->stops[0].color;
else
if ((offset > 1.0) || (i == (ssize_t) gradient->number_stops))
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
case ReflectSpread:
{
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type != RadialGradient)
offset*=PerceptibleReciprocal(length);
}
if (offset < 0.0)
offset=(-offset);
if ((ssize_t) fmod(offset,2.0) == 0)
offset=fmod(offset,1.0);
else
offset=1.0-fmod(offset,1.0);
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if (i == 0)
composite=gradient->stops[0].color;
else
if (i == (ssize_t) gradient->number_stops)
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
case RepeatSpread:
{
MagickBooleanType
antialias;
double
repeat;
antialias=MagickFalse;
repeat=0.0;
if ((x != (ssize_t) ceil(gradient_vector->x1-0.5)) ||
(y != (ssize_t) ceil(gradient_vector->y1-0.5)))
{
offset=GetStopColorOffset(gradient,x,y);
if (gradient->type == LinearGradient)
{
repeat=fmod(offset,length);
if (repeat < 0.0)
repeat=length-fmod(-repeat,length);
else
repeat=fmod(offset,length);
antialias=(repeat < length) && ((repeat+1.0) > length) ?
MagickTrue : MagickFalse;
offset=PerceptibleReciprocal(length)*repeat;
}
else
{
repeat=fmod(offset,gradient->radius);
if (repeat < 0.0)
repeat=gradient->radius-fmod(-repeat,gradient->radius);
else
repeat=fmod(offset,gradient->radius);
antialias=repeat+1.0 > gradient->radius ? MagickTrue :
MagickFalse;
offset=repeat/gradient->radius;
}
}
for (i=0; i < (ssize_t) gradient->number_stops; i++)
if (offset < gradient->stops[i].offset)
break;
if (i == 0)
composite=gradient->stops[0].color;
else
if (i == (ssize_t) gradient->number_stops)
composite=gradient->stops[gradient->number_stops-1].color;
else
{
j=i;
i--;
alpha=(offset-gradient->stops[i].offset)/
(gradient->stops[j].offset-gradient->stops[i].offset);
if (antialias != MagickFalse)
{
if (gradient->type == LinearGradient)
alpha=length-repeat;
else
alpha=gradient->radius-repeat;
i=0;
j=(ssize_t) gradient->number_stops-1L;
}
CompositePixelInfoBlend(&gradient->stops[i].color,1.0-alpha,
&gradient->stops[j].color,alpha,&composite);
}
break;
}
}
CompositePixelInfoOver(&composite,composite.alpha,&pixel,pixel.alpha,
&pixel);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w I m a g e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawImage() draws a graphic primitive on your image. The primitive
% may be represented as a string or filename. Precede the filename with an
% "at" sign (@) and the contents of the file are drawn on the image. You
% can affect how text is drawn by setting one or more members of the draw
% info structure.
%
% The format of the DrawImage method is:
%
% MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType CheckPrimitiveExtent(MVGInfo *mvg_info,
const size_t pad)
{
double
extent;
size_t
quantum;
/*
Check if there is enough storage for drawing pimitives.
*/
extent=(double) mvg_info->offset+pad+PrimitiveExtentPad;
quantum=sizeof(**mvg_info->primitive_info);
if (((extent*quantum) < (double) SSIZE_MAX) &&
((extent*quantum) < (double) GetMaxMemoryRequest()))
{
if (extent <= (double) *mvg_info->extent)
return(MagickTrue);
*mvg_info->primitive_info=(PrimitiveInfo *) ResizeQuantumMemory(
*mvg_info->primitive_info,(size_t) extent,quantum);
if (*mvg_info->primitive_info != (PrimitiveInfo *) NULL)
{
register ssize_t
i;
*mvg_info->extent=(size_t) extent;
for (i=mvg_info->offset+1; i < (ssize_t) extent; i++)
(*mvg_info->primitive_info)[i].primitive=UndefinedPrimitive;
return(MagickTrue);
}
}
/*
Reallocation failed, allocate a primitive to facilitate unwinding.
*/
(void) ThrowMagickException(mvg_info->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'","");
if (*mvg_info->primitive_info != (PrimitiveInfo *) NULL)
*mvg_info->primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(
*mvg_info->primitive_info);
*mvg_info->primitive_info=(PrimitiveInfo *) AcquireCriticalMemory(
PrimitiveExtentPad*quantum);
(void) memset(*mvg_info->primitive_info,0,PrimitiveExtentPad*quantum);
*mvg_info->extent=1;
return(MagickFalse);
}
MagickExport int MVGMacroCompare(const void *target,const void *source)
{
const char
*p,
*q;
p=(const char *) target;
q=(const char *) source;
return(strcmp(p,q));
}
static SplayTreeInfo *GetMVGMacros(const char *primitive)
{
char
*macro,
*token;
const char
*q;
size_t
extent;
SplayTreeInfo
*macros;
/*
Scan graphic primitives for definitions and classes.
*/
if (primitive == (const char *) NULL)
return((SplayTreeInfo *) NULL);
macros=NewSplayTree(MVGMacroCompare,RelinquishMagickMemory,
RelinquishMagickMemory);
macro=AcquireString(primitive);
token=AcquireString(primitive);
extent=strlen(token)+MagickPathExtent;
for (q=primitive; *q != '\0'; )
{
if (GetNextToken(q,&q,extent,token) < 1)
break;
if (*token == '\0')
break;
if (LocaleCompare("push",token) == 0)
{
register const char
*end,
*start;
(void) GetNextToken(q,&q,extent,token);
if (*q == '"')
{
char
name[MagickPathExtent];
const char
*p;
ssize_t
n;
/*
Named macro (e.g. push graphic-context "wheel").
*/
(void) GetNextToken(q,&q,extent,token);
start=q;
end=q;
(void) CopyMagickString(name,token,MagickPathExtent);
n=1;
for (p=q; *p != '\0'; )
{
(void) GetNextToken(p,&p,extent,token);
if (*token == '\0')
break;
if (LocaleCompare(token,"pop") == 0)
{
end=p-strlen(token)-1;
n--;
}
if (LocaleCompare(token,"push") == 0)
n++;
if ((n == 0) && (end > start))
{
/*
Extract macro.
*/
(void) GetNextToken(p,&p,extent,token);
(void) CopyMagickString(macro,start,(size_t) (end-start));
(void) AddValueToSplayTree(macros,ConstantString(name),
ConstantString(macro));
break;
}
}
}
}
}
token=DestroyString(token);
macro=DestroyString(macro);
return(macros);
}
static inline MagickBooleanType IsPoint(const char *point)
{
char
*p;
double
value;
value=StringToDouble(point,&p);
return((fabs(value) < MagickEpsilon) && (p == point) ? MagickFalse :
MagickTrue);
}
static inline MagickBooleanType TracePoint(PrimitiveInfo *primitive_info,
const PointInfo point)
{
primitive_info->coordinates=1;
primitive_info->closed_subpath=MagickFalse;
primitive_info->point=point;
return(MagickTrue);
}
static MagickBooleanType RenderMVGContent(Image *image,
const DrawInfo *draw_info,const size_t depth,ExceptionInfo *exception)
{
#define RenderImageTag "Render/Image"
AffineMatrix
affine,
current;
char
keyword[MagickPathExtent],
geometry[MagickPathExtent],
*next_token,
pattern[MagickPathExtent],
*primitive,
*token;
const char
*q;
double
angle,
coordinates,
cursor,
factor,
primitive_extent;
DrawInfo
*clone_info,
**graphic_context;
MagickBooleanType
proceed;
MagickStatusType
status;
MVGInfo
mvg_info;
PointInfo
point;
PrimitiveInfo
*primitive_info;
PrimitiveType
primitive_type;
register const char
*p;
register ssize_t
i,
x;
SegmentInfo
bounds;
size_t
extent,
number_points,
number_stops;
SplayTreeInfo
*macros;
ssize_t
defsDepth,
j,
k,
n,
symbolDepth;
StopInfo
*stops;
TypeMetric
metrics;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
if (depth > MagickMaxRecursionDepth)
ThrowBinaryException(DrawError,"VectorGraphicsNestedTooDeeply",
image->filename);
if ((draw_info->primitive == (char *) NULL) ||
(*draw_info->primitive == '\0'))
return(MagickFalse);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"begin draw-image");
if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse)
return(MagickFalse);
if (image->alpha_trait == UndefinedPixelTrait)
{
status=SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
if (status == MagickFalse)
return(MagickFalse);
}
if ((*draw_info->primitive == '@') && (strlen(draw_info->primitive) > 1) &&
(*(draw_info->primitive+1) != '-') && (depth == 0))
primitive=FileToString(draw_info->primitive+1,~0UL,exception);
else
primitive=AcquireString(draw_info->primitive);
if (primitive == (char *) NULL)
return(MagickFalse);
primitive_extent=(double) strlen(primitive);
(void) SetImageArtifact(image,"mvg:vector-graphics",primitive);
n=0;
number_stops=0;
stops=(StopInfo *) NULL;
/*
Allocate primitive info memory.
*/
graphic_context=(DrawInfo **) AcquireMagickMemory(sizeof(*graphic_context));
if (graphic_context == (DrawInfo **) NULL)
{
primitive=DestroyString(primitive);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
number_points=PrimitiveExtentPad;
primitive_info=(PrimitiveInfo *) AcquireQuantumMemory((size_t) number_points,
sizeof(*primitive_info));
if (primitive_info == (PrimitiveInfo *) NULL)
{
primitive=DestroyString(primitive);
for ( ; n >= 0; n--)
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
}
(void) memset(primitive_info,0,(size_t) number_points*
sizeof(*primitive_info));
(void) memset(&mvg_info,0,sizeof(mvg_info));
mvg_info.primitive_info=(&primitive_info);
mvg_info.extent=(&number_points);
mvg_info.exception=exception;
graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,draw_info);
graphic_context[n]->viewbox=image->page;
if ((image->page.width == 0) || (image->page.height == 0))
{
graphic_context[n]->viewbox.width=image->columns;
graphic_context[n]->viewbox.height=image->rows;
}
token=AcquireString(primitive);
extent=strlen(token)+MagickPathExtent;
defsDepth=0;
symbolDepth=0;
cursor=0.0;
macros=GetMVGMacros(primitive);
status=MagickTrue;
for (q=primitive; *q != '\0'; )
{
/*
Interpret graphic primitive.
*/
if (GetNextToken(q,&q,MagickPathExtent,keyword) < 1)
break;
if (*keyword == '\0')
break;
if (*keyword == '#')
{
/*
Comment.
*/
while ((*q != '\n') && (*q != '\0'))
q++;
continue;
}
p=q-strlen(keyword)-1;
primitive_type=UndefinedPrimitive;
current=graphic_context[n]->affine;
GetAffineMatrix(&affine);
*token='\0';
switch (*keyword)
{
case ';':
break;
case 'a':
case 'A':
{
if (LocaleCompare("affine",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
affine.sx=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
affine.rx=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
affine.ry=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
affine.sy=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
affine.tx=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
affine.ty=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
break;
}
if (LocaleCompare("alpha",keyword) == 0)
{
primitive_type=AlphaPrimitive;
break;
}
if (LocaleCompare("arc",keyword) == 0)
{
primitive_type=ArcPrimitive;
break;
}
status=MagickFalse;
break;
}
case 'b':
case 'B':
{
if (LocaleCompare("bezier",keyword) == 0)
{
primitive_type=BezierPrimitive;
break;
}
if (LocaleCompare("border-color",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
status&=QueryColorCompliance(token,AllCompliance,
&graphic_context[n]->border_color,exception);
break;
}
status=MagickFalse;
break;
}
case 'c':
case 'C':
{
if (LocaleCompare("class",keyword) == 0)
{
const char
*mvg_class;
(void) GetNextToken(q,&q,extent,token);
if (*token == '\0')
{
status=MagickFalse;
break;
}
mvg_class=(const char *) GetValueFromSplayTree(macros,token);
if (mvg_class != (const char *) NULL)
{
char
*elements;
ssize_t
offset;
/*
Inject class elements in stream.
*/
offset=(ssize_t) (p-primitive);
elements=AcquireString(primitive);
elements[offset]='\0';
(void) ConcatenateString(&elements,mvg_class);
(void) ConcatenateString(&elements,"\n");
(void) ConcatenateString(&elements,q);
primitive=DestroyString(primitive);
primitive=elements;
q=primitive+offset;
}
break;
}
if (LocaleCompare("clip-path",keyword) == 0)
{
const char
*clip_path;
/*
Take a node from within the MVG document, and duplicate it here.
*/
(void) GetNextToken(q,&q,extent,token);
if (*token == '\0')
{
status=MagickFalse;
break;
}
(void) CloneString(&graphic_context[n]->clip_mask,token);
clip_path=(const char *) GetValueFromSplayTree(macros,token);
if (clip_path != (const char *) NULL)
{
if (graphic_context[n]->clipping_mask != (Image *) NULL)
graphic_context[n]->clipping_mask=
DestroyImage(graphic_context[n]->clipping_mask);
graphic_context[n]->clipping_mask=DrawClippingMask(image,
graphic_context[n],token,clip_path,exception);
if (graphic_context[n]->compliance != SVGCompliance)
{
clip_path=(const char *) GetValueFromSplayTree(macros,
graphic_context[n]->clip_mask);
if (clip_path != (const char *) NULL)
(void) SetImageArtifact(image,
graphic_context[n]->clip_mask,clip_path);
status&=DrawClipPath(image,graphic_context[n],
graphic_context[n]->clip_mask,exception);
}
}
break;
}
if (LocaleCompare("clip-rule",keyword) == 0)
{
ssize_t
fill_rule;
(void) GetNextToken(q,&q,extent,token);
fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse,
token);
if (fill_rule == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->fill_rule=(FillRule) fill_rule;
break;
}
if (LocaleCompare("clip-units",keyword) == 0)
{
ssize_t
clip_units;
(void) GetNextToken(q,&q,extent,token);
clip_units=ParseCommandOption(MagickClipPathOptions,MagickFalse,
token);
if (clip_units == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->clip_units=(ClipPathUnits) clip_units;
if (clip_units == ObjectBoundingBox)
{
GetAffineMatrix(¤t);
affine.sx=draw_info->bounds.x2;
affine.sy=draw_info->bounds.y2;
affine.tx=draw_info->bounds.x1;
affine.ty=draw_info->bounds.y1;
break;
}
break;
}
if (LocaleCompare("circle",keyword) == 0)
{
primitive_type=CirclePrimitive;
break;
}
if (LocaleCompare("color",keyword) == 0)
{
primitive_type=ColorPrimitive;
break;
}
if (LocaleCompare("compliance",keyword) == 0)
{
/*
MVG compliance associates a clipping mask with an image; SVG
compliance associates a clipping mask with a graphics context.
*/
(void) GetNextToken(q,&q,extent,token);
graphic_context[n]->compliance=(ComplianceType) ParseCommandOption(
MagickComplianceOptions,MagickFalse,token);
break;
}
status=MagickFalse;
break;
}
case 'd':
case 'D':
{
if (LocaleCompare("decorate",keyword) == 0)
{
ssize_t
decorate;
(void) GetNextToken(q,&q,extent,token);
decorate=ParseCommandOption(MagickDecorateOptions,MagickFalse,
token);
if (decorate == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->decorate=(DecorationType) decorate;
break;
}
if (LocaleCompare("density",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->density,token);
break;
}
if (LocaleCompare("direction",keyword) == 0)
{
ssize_t
direction;
(void) GetNextToken(q,&q,extent,token);
direction=ParseCommandOption(MagickDirectionOptions,MagickFalse,
token);
if (direction == -1)
status=MagickFalse;
else
graphic_context[n]->direction=(DirectionType) direction;
break;
}
status=MagickFalse;
break;
}
case 'e':
case 'E':
{
if (LocaleCompare("ellipse",keyword) == 0)
{
primitive_type=EllipsePrimitive;
break;
}
if (LocaleCompare("encoding",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->encoding,token);
break;
}
status=MagickFalse;
break;
}
case 'f':
case 'F':
{
if (LocaleCompare("fill",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
if (graphic_context[n]->clip_path != MagickFalse)
break;
(void) FormatLocaleString(pattern,MagickPathExtent,"%s",token);
if (GetImageArtifact(image,pattern) != (const char *) NULL)
(void) DrawPatternPath(image,draw_info,token,
&graphic_context[n]->fill_pattern,exception);
else
{
status&=QueryColorCompliance(token,AllCompliance,
&graphic_context[n]->fill,exception);
if (graphic_context[n]->fill_alpha != OpaqueAlpha)
graphic_context[n]->fill.alpha=graphic_context[n]->fill_alpha;
}
break;
}
if (LocaleCompare("fill-opacity",keyword) == 0)
{
double
opacity;
(void) GetNextToken(q,&q,extent,token);
if (graphic_context[n]->clip_path != MagickFalse)
break;
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
opacity=MagickMin(MagickMax(factor*
StringToDouble(token,&next_token),0.0),1.0);
if (token == next_token)
ThrowPointExpectedException(token,exception);
graphic_context[n]->fill_alpha*=opacity;
if (graphic_context[n]->fill.alpha != TransparentAlpha)
graphic_context[n]->fill.alpha=graphic_context[n]->fill_alpha;
else
graphic_context[n]->fill.alpha=(MagickRealType)
ClampToQuantum(QuantumRange*(1.0-opacity));
break;
}
if (LocaleCompare("fill-rule",keyword) == 0)
{
ssize_t
fill_rule;
(void) GetNextToken(q,&q,extent,token);
fill_rule=ParseCommandOption(MagickFillRuleOptions,MagickFalse,
token);
if (fill_rule == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->fill_rule=(FillRule) fill_rule;
break;
}
if (LocaleCompare("font",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->font,token);
if (LocaleCompare("none",token) == 0)
graphic_context[n]->font=(char *) RelinquishMagickMemory(
graphic_context[n]->font);
break;
}
if (LocaleCompare("font-family",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
(void) CloneString(&graphic_context[n]->family,token);
break;
}
if (LocaleCompare("font-size",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
graphic_context[n]->pointsize=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
break;
}
if (LocaleCompare("font-stretch",keyword) == 0)
{
ssize_t
stretch;
(void) GetNextToken(q,&q,extent,token);
stretch=ParseCommandOption(MagickStretchOptions,MagickFalse,token);
if (stretch == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->stretch=(StretchType) stretch;
break;
}
if (LocaleCompare("font-style",keyword) == 0)
{
ssize_t
style;
(void) GetNextToken(q,&q,extent,token);
style=ParseCommandOption(MagickStyleOptions,MagickFalse,token);
if (style == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->style=(StyleType) style;
break;
}
if (LocaleCompare("font-weight",keyword) == 0)
{
ssize_t
weight;
(void) GetNextToken(q,&q,extent,token);
weight=ParseCommandOption(MagickWeightOptions,MagickFalse,token);
if (weight == -1)
weight=(ssize_t) StringToUnsignedLong(token);
graphic_context[n]->weight=(size_t) weight;
break;
}
status=MagickFalse;
break;
}
case 'g':
case 'G':
{
if (LocaleCompare("gradient-units",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("gravity",keyword) == 0)
{
ssize_t
gravity;
(void) GetNextToken(q,&q,extent,token);
gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,token);
if (gravity == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->gravity=(GravityType) gravity;
break;
}
status=MagickFalse;
break;
}
case 'i':
case 'I':
{
if (LocaleCompare("image",keyword) == 0)
{
ssize_t
compose;
primitive_type=ImagePrimitive;
(void) GetNextToken(q,&q,extent,token);
compose=ParseCommandOption(MagickComposeOptions,MagickFalse,token);
if (compose == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->compose=(CompositeOperator) compose;
break;
}
if (LocaleCompare("interline-spacing",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
graphic_context[n]->interline_spacing=StringToDouble(token,
&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
break;
}
if (LocaleCompare("interword-spacing",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
graphic_context[n]->interword_spacing=StringToDouble(token,
&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
break;
}
status=MagickFalse;
break;
}
case 'k':
case 'K':
{
if (LocaleCompare("kerning",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
graphic_context[n]->kerning=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
break;
}
status=MagickFalse;
break;
}
case 'l':
case 'L':
{
if (LocaleCompare("letter-spacing",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
clone_info=CloneDrawInfo((ImageInfo *) NULL,graphic_context[n]);
clone_info->text=AcquireString(" ");
status&=GetTypeMetrics(image,clone_info,&metrics,exception);
graphic_context[n]->kerning=metrics.width*
StringToDouble(token,&next_token);
clone_info=DestroyDrawInfo(clone_info);
if (token == next_token)
ThrowPointExpectedException(token,exception);
break;
}
if (LocaleCompare("line",keyword) == 0)
{
primitive_type=LinePrimitive;
break;
}
status=MagickFalse;
break;
}
case 'm':
case 'M':
{
if (LocaleCompare("mask",keyword) == 0)
{
const char
*mask_path;
/*
Take a node from within the MVG document, and duplicate it here.
*/
(void) GetNextToken(q,&q,extent,token);
mask_path=(const char *) GetValueFromSplayTree(macros,token);
if (mask_path != (const char *) NULL)
{
if (graphic_context[n]->composite_mask != (Image *) NULL)
graphic_context[n]->composite_mask=
DestroyImage(graphic_context[n]->composite_mask);
graphic_context[n]->composite_mask=DrawCompositeMask(image,
graphic_context[n],token,mask_path,exception);
if (graphic_context[n]->compliance != SVGCompliance)
status=SetImageMask(image,CompositePixelMask,
graphic_context[n]->composite_mask,exception);
}
break;
}
break;
}
case 'o':
case 'O':
{
if (LocaleCompare("offset",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("opacity",keyword) == 0)
{
double
opacity;
(void) GetNextToken(q,&q,extent,token);
if (graphic_context[n]->clip_path != MagickFalse)
break;
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
opacity=MagickMin(MagickMax(factor*
StringToDouble(token,&next_token),0.0),1.0);
if (token == next_token)
ThrowPointExpectedException(token,exception);
graphic_context[n]->fill_alpha*=opacity;
graphic_context[n]->stroke_alpha*=opacity;
break;
}
status=MagickFalse;
break;
}
case 'p':
case 'P':
{
if (LocaleCompare("path",keyword) == 0)
{
primitive_type=PathPrimitive;
break;
}
if (LocaleCompare("point",keyword) == 0)
{
primitive_type=PointPrimitive;
break;
}
if (LocaleCompare("polyline",keyword) == 0)
{
primitive_type=PolylinePrimitive;
break;
}
if (LocaleCompare("polygon",keyword) == 0)
{
primitive_type=PolygonPrimitive;
break;
}
if (LocaleCompare("pop",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
if (LocaleCompare("class",token) == 0)
break;
if (LocaleCompare("clip-path",token) == 0)
break;
if (LocaleCompare("defs",token) == 0)
{
defsDepth--;
graphic_context[n]->render=defsDepth > 0 ? MagickFalse :
MagickTrue;
break;
}
if (LocaleCompare("gradient",token) == 0)
break;
if (LocaleCompare("graphic-context",token) == 0)
{
if (n <= 0)
{
(void) ThrowMagickException(exception,GetMagickModule(),
DrawError,"UnbalancedGraphicContextPushPop","`%s'",token);
status=MagickFalse;
n=0;
break;
}
if ((graphic_context[n]->clip_mask != (char *) NULL) &&
(graphic_context[n]->compliance != SVGCompliance))
if (LocaleCompare(graphic_context[n]->clip_mask,
graphic_context[n-1]->clip_mask) != 0)
status=SetImageMask(image,WritePixelMask,(Image *) NULL,
exception);
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
n--;
break;
}
if (LocaleCompare("mask",token) == 0)
break;
if (LocaleCompare("pattern",token) == 0)
break;
if (LocaleCompare("symbol",token) == 0)
{
symbolDepth--;
graphic_context[n]->render=symbolDepth > 0 ? MagickFalse :
MagickTrue;
break;
}
status=MagickFalse;
break;
}
if (LocaleCompare("push",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
if (LocaleCompare("class",token) == 0)
{
/*
Class context.
*/
for (p=q; *q != '\0'; )
{
(void) GetNextToken(q,&q,extent,token);
if (LocaleCompare(token,"pop") != 0)
continue;
(void) GetNextToken(q,(const char **) NULL,extent,token);
if (LocaleCompare(token,"class") != 0)
continue;
break;
}
(void) GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("clip-path",token) == 0)
{
(void) GetNextToken(q,&q,extent,token);
for (p=q; *q != '\0'; )
{
(void) GetNextToken(q,&q,extent,token);
if (LocaleCompare(token,"pop") != 0)
continue;
(void) GetNextToken(q,(const char **) NULL,extent,token);
if (LocaleCompare(token,"clip-path") != 0)
continue;
break;
}
if ((q == (char *) NULL) || (p == (char *) NULL) || ((q-4) < p))
{
status=MagickFalse;
break;
}
(void) GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("defs",token) == 0)
{
defsDepth++;
graphic_context[n]->render=defsDepth > 0 ? MagickFalse :
MagickTrue;
break;
}
if (LocaleCompare("gradient",token) == 0)
{
char
key[2*MagickPathExtent],
name[MagickPathExtent],
type[MagickPathExtent];
SegmentInfo
segment;
(void) GetNextToken(q,&q,extent,token);
(void) CopyMagickString(name,token,MagickPathExtent);
(void) GetNextToken(q,&q,extent,token);
(void) CopyMagickString(type,token,MagickPathExtent);
(void) GetNextToken(q,&q,extent,token);
segment.x1=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
segment.y1=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
segment.x2=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
segment.y2=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
if (LocaleCompare(type,"radial") == 0)
{
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
}
for (p=q; *q != '\0'; )
{
(void) GetNextToken(q,&q,extent,token);
if (LocaleCompare(token,"pop") != 0)
continue;
(void) GetNextToken(q,(const char **) NULL,extent,token);
if (LocaleCompare(token,"gradient") != 0)
continue;
break;
}
if ((q == (char *) NULL) || (p == (char *) NULL) || ((q-4) < p))
{
status=MagickFalse;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
bounds.x1=graphic_context[n]->affine.sx*segment.x1+
graphic_context[n]->affine.ry*segment.y1+
graphic_context[n]->affine.tx;
bounds.y1=graphic_context[n]->affine.rx*segment.x1+
graphic_context[n]->affine.sy*segment.y1+
graphic_context[n]->affine.ty;
bounds.x2=graphic_context[n]->affine.sx*segment.x2+
graphic_context[n]->affine.ry*segment.y2+
graphic_context[n]->affine.tx;
bounds.y2=graphic_context[n]->affine.rx*segment.x2+
graphic_context[n]->affine.sy*segment.y2+
graphic_context[n]->affine.ty;
(void) FormatLocaleString(key,MagickPathExtent,"%s",name);
(void) SetImageArtifact(image,key,token);
(void) FormatLocaleString(key,MagickPathExtent,"%s-type",name);
(void) SetImageArtifact(image,key,type);
(void) FormatLocaleString(key,MagickPathExtent,"%s-geometry",
name);
(void) FormatLocaleString(geometry,MagickPathExtent,
"%gx%g%+.15g%+.15g",
MagickMax(fabs(bounds.x2-bounds.x1+1.0),1.0),
MagickMax(fabs(bounds.y2-bounds.y1+1.0),1.0),
bounds.x1,bounds.y1);
(void) SetImageArtifact(image,key,geometry);
(void) GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("graphic-context",token) == 0)
{
n++;
graphic_context=(DrawInfo **) ResizeQuantumMemory(
graphic_context,(size_t) (n+1),sizeof(*graphic_context));
if (graphic_context == (DrawInfo **) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
graphic_context[n]=CloneDrawInfo((ImageInfo *) NULL,
graphic_context[n-1]);
if (*q == '"')
(void) GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("mask",token) == 0)
{
(void) GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("pattern",token) == 0)
{
char
key[2*MagickPathExtent],
name[MagickPathExtent];
RectangleInfo
bounds;
(void) GetNextToken(q,&q,extent,token);
(void) CopyMagickString(name,token,MagickPathExtent);
(void) GetNextToken(q,&q,extent,token);
bounds.x=(ssize_t) ceil(StringToDouble(token,&next_token)-0.5);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
bounds.y=(ssize_t) ceil(StringToDouble(token,&next_token)-0.5);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
bounds.width=(size_t) floor(StringToDouble(token,&next_token)+
0.5);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
bounds.height=(size_t) floor(StringToDouble(token,&next_token)+
0.5);
if (token == next_token)
ThrowPointExpectedException(token,exception);
for (p=q; *q != '\0'; )
{
(void) GetNextToken(q,&q,extent,token);
if (LocaleCompare(token,"pop") != 0)
continue;
(void) GetNextToken(q,(const char **) NULL,extent,token);
if (LocaleCompare(token,"pattern") != 0)
continue;
break;
}
if ((q == (char *) NULL) || (p == (char *) NULL) || ((q-4) < p))
{
status=MagickFalse;
break;
}
(void) CopyMagickString(token,p,(size_t) (q-p-4+1));
(void) FormatLocaleString(key,MagickPathExtent,"%s",name);
(void) SetImageArtifact(image,key,token);
(void) FormatLocaleString(key,MagickPathExtent,"%s-geometry",
name);
(void) FormatLocaleString(geometry,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double) bounds.width,(double)
bounds.height,(double) bounds.x,(double) bounds.y);
(void) SetImageArtifact(image,key,geometry);
(void) GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("symbol",token) == 0)
{
symbolDepth++;
graphic_context[n]->render=symbolDepth > 0 ? MagickFalse :
MagickTrue;
break;
}
status=MagickFalse;
break;
}
status=MagickFalse;
break;
}
case 'r':
case 'R':
{
if (LocaleCompare("rectangle",keyword) == 0)
{
primitive_type=RectanglePrimitive;
break;
}
if (LocaleCompare("rotate",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
angle=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
affine.sx=cos(DegreesToRadians(fmod((double) angle,360.0)));
affine.rx=sin(DegreesToRadians(fmod((double) angle,360.0)));
affine.ry=(-sin(DegreesToRadians(fmod((double) angle,360.0))));
affine.sy=cos(DegreesToRadians(fmod((double) angle,360.0)));
break;
}
if (LocaleCompare("roundRectangle",keyword) == 0)
{
primitive_type=RoundRectanglePrimitive;
break;
}
status=MagickFalse;
break;
}
case 's':
case 'S':
{
if (LocaleCompare("scale",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
affine.sx=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
affine.sy=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
break;
}
if (LocaleCompare("skewX",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
angle=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
affine.ry=sin(DegreesToRadians(angle));
break;
}
if (LocaleCompare("skewY",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
angle=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
affine.rx=(-tan(DegreesToRadians(angle)/2.0));
break;
}
if (LocaleCompare("stop-color",keyword) == 0)
{
PixelInfo
stop_color;
number_stops++;
if (number_stops == 1)
stops=(StopInfo *) AcquireQuantumMemory(2,sizeof(*stops));
else
if (number_stops > 2)
stops=(StopInfo *) ResizeQuantumMemory(stops,number_stops,
sizeof(*stops));
if (stops == (StopInfo *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
(void) GetNextToken(q,&q,extent,token);
status&=QueryColorCompliance(token,AllCompliance,&stop_color,
exception);
stops[number_stops-1].color=stop_color;
(void) GetNextToken(q,&q,extent,token);
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
stops[number_stops-1].offset=factor*StringToDouble(token,
&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
break;
}
if (LocaleCompare("stroke",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
if (graphic_context[n]->clip_path != MagickFalse)
break;
(void) FormatLocaleString(pattern,MagickPathExtent,"%s",token);
if (GetImageArtifact(image,pattern) != (const char *) NULL)
(void) DrawPatternPath(image,draw_info,token,
&graphic_context[n]->stroke_pattern,exception);
else
{
status&=QueryColorCompliance(token,AllCompliance,
&graphic_context[n]->stroke,exception);
if (graphic_context[n]->stroke_alpha != OpaqueAlpha)
graphic_context[n]->stroke.alpha=
graphic_context[n]->stroke_alpha;
}
break;
}
if (LocaleCompare("stroke-antialias",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
graphic_context[n]->stroke_antialias=StringToLong(token) != 0 ?
MagickTrue : MagickFalse;
break;
}
if (LocaleCompare("stroke-dasharray",keyword) == 0)
{
if (graphic_context[n]->dash_pattern != (double *) NULL)
graphic_context[n]->dash_pattern=(double *)
RelinquishMagickMemory(graphic_context[n]->dash_pattern);
if (IsPoint(q) != MagickFalse)
{
const char
*r;
r=q;
(void) GetNextToken(r,&r,extent,token);
if (*token == ',')
(void) GetNextToken(r,&r,extent,token);
for (x=0; IsPoint(token) != MagickFalse; x++)
{
(void) GetNextToken(r,&r,extent,token);
if (*token == ',')
(void) GetNextToken(r,&r,extent,token);
}
graphic_context[n]->dash_pattern=(double *)
AcquireQuantumMemory((size_t) (2*x+2),
sizeof(*graphic_context[n]->dash_pattern));
if (graphic_context[n]->dash_pattern == (double *) NULL)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
status=MagickFalse;
break;
}
(void) memset(graphic_context[n]->dash_pattern,0,(size_t)
(2*x+2)*sizeof(*graphic_context[n]->dash_pattern));
for (j=0; j < x; j++)
{
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
graphic_context[n]->dash_pattern[j]=StringToDouble(token,
&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
if (graphic_context[n]->dash_pattern[j] < 0.0)
status=MagickFalse;
}
if ((x & 0x01) != 0)
for ( ; j < (2*x); j++)
graphic_context[n]->dash_pattern[j]=
graphic_context[n]->dash_pattern[j-x];
graphic_context[n]->dash_pattern[j]=0.0;
break;
}
(void) GetNextToken(q,&q,extent,token);
break;
}
if (LocaleCompare("stroke-dashoffset",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
graphic_context[n]->dash_offset=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
break;
}
if (LocaleCompare("stroke-linecap",keyword) == 0)
{
ssize_t
linecap;
(void) GetNextToken(q,&q,extent,token);
linecap=ParseCommandOption(MagickLineCapOptions,MagickFalse,token);
if (linecap == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->linecap=(LineCap) linecap;
break;
}
if (LocaleCompare("stroke-linejoin",keyword) == 0)
{
ssize_t
linejoin;
(void) GetNextToken(q,&q,extent,token);
linejoin=ParseCommandOption(MagickLineJoinOptions,MagickFalse,
token);
if (linejoin == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->linejoin=(LineJoin) linejoin;
break;
}
if (LocaleCompare("stroke-miterlimit",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
graphic_context[n]->miterlimit=StringToUnsignedLong(token);
break;
}
if (LocaleCompare("stroke-opacity",keyword) == 0)
{
double
opacity;
(void) GetNextToken(q,&q,extent,token);
if (graphic_context[n]->clip_path != MagickFalse)
break;
factor=strchr(token,'%') != (char *) NULL ? 0.01 : 1.0;
opacity=MagickMin(MagickMax(factor*
StringToDouble(token,&next_token),0.0),1.0);
if (token == next_token)
ThrowPointExpectedException(token,exception);
graphic_context[n]->stroke_alpha*=opacity;
if (graphic_context[n]->stroke.alpha != TransparentAlpha)
graphic_context[n]->stroke.alpha=graphic_context[n]->stroke_alpha;
else
graphic_context[n]->stroke.alpha=(MagickRealType)
ClampToQuantum(QuantumRange*(1.0-opacity));
break;
}
if (LocaleCompare("stroke-width",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
if (graphic_context[n]->clip_path != MagickFalse)
break;
graphic_context[n]->stroke_width=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
break;
}
status=MagickFalse;
break;
}
case 't':
case 'T':
{
if (LocaleCompare("text",keyword) == 0)
{
primitive_type=TextPrimitive;
break;
}
if (LocaleCompare("text-align",keyword) == 0)
{
ssize_t
align;
(void) GetNextToken(q,&q,extent,token);
align=ParseCommandOption(MagickAlignOptions,MagickFalse,token);
if (align == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->align=(AlignType) align;
break;
}
if (LocaleCompare("text-anchor",keyword) == 0)
{
ssize_t
align;
(void) GetNextToken(q,&q,extent,token);
align=ParseCommandOption(MagickAlignOptions,MagickFalse,token);
if (align == -1)
{
status=MagickFalse;
break;
}
graphic_context[n]->align=(AlignType) align;
break;
}
if (LocaleCompare("text-antialias",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
graphic_context[n]->text_antialias=StringToLong(token) != 0 ?
MagickTrue : MagickFalse;
break;
}
if (LocaleCompare("text-undercolor",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
status&=QueryColorCompliance(token,AllCompliance,
&graphic_context[n]->undercolor,exception);
break;
}
if (LocaleCompare("translate",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
affine.tx=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
affine.ty=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
cursor=0.0;
break;
}
status=MagickFalse;
break;
}
case 'u':
case 'U':
{
if (LocaleCompare("use",keyword) == 0)
{
const char
*use;
/*
Get a macro from the MVG document, and "use" it here.
*/
(void) GetNextToken(q,&q,extent,token);
use=(const char *) GetValueFromSplayTree(macros,token);
if (use != (const char *) NULL)
{
clone_info=CloneDrawInfo((ImageInfo *) NULL,graphic_context[n]);
(void) CloneString(&clone_info->primitive,use);
status=RenderMVGContent(image,clone_info,depth+1,exception);
clone_info=DestroyDrawInfo(clone_info);
}
break;
}
break;
}
case 'v':
case 'V':
{
if (LocaleCompare("viewbox",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.x=(ssize_t) ceil(StringToDouble(token,
&next_token)-0.5);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.y=(ssize_t) ceil(StringToDouble(token,
&next_token)-0.5);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.width=(size_t) floor(StringToDouble(
token,&next_token)+0.5);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
graphic_context[n]->viewbox.height=(size_t) floor(StringToDouble(
token,&next_token)+0.5);
if (token == next_token)
ThrowPointExpectedException(token,exception);
break;
}
status=MagickFalse;
break;
}
case 'w':
case 'W':
{
if (LocaleCompare("word-spacing",keyword) == 0)
{
(void) GetNextToken(q,&q,extent,token);
graphic_context[n]->interword_spacing=StringToDouble(token,
&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
break;
}
status=MagickFalse;
break;
}
default:
{
status=MagickFalse;
break;
}
}
if (status == MagickFalse)
break;
if ((fabs(affine.sx-1.0) >= MagickEpsilon) ||
(fabs(affine.rx) >= MagickEpsilon) || (fabs(affine.ry) >= MagickEpsilon) ||
(fabs(affine.sy-1.0) >= MagickEpsilon) ||
(fabs(affine.tx) >= MagickEpsilon) || (fabs(affine.ty) >= MagickEpsilon))
{
graphic_context[n]->affine.sx=current.sx*affine.sx+current.ry*affine.rx;
graphic_context[n]->affine.rx=current.rx*affine.sx+current.sy*affine.rx;
graphic_context[n]->affine.ry=current.sx*affine.ry+current.ry*affine.sy;
graphic_context[n]->affine.sy=current.rx*affine.ry+current.sy*affine.sy;
graphic_context[n]->affine.tx=current.sx*affine.tx+current.ry*affine.ty+
current.tx;
graphic_context[n]->affine.ty=current.rx*affine.tx+current.sy*affine.ty+
current.ty;
}
if (primitive_type == UndefinedPrimitive)
{
if (*q == '\0')
{
if (number_stops > 1)
{
GradientType
type;
type=LinearGradient;
if (draw_info->gradient.type == RadialGradient)
type=RadialGradient;
(void) GradientImage(image,type,PadSpread,stops,number_stops,
exception);
}
if (number_stops > 0)
stops=(StopInfo *) RelinquishMagickMemory(stops);
}
if ((image->debug != MagickFalse) && (q > p))
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int)
(q-p-1),p);
continue;
}
/*
Parse the primitive attributes.
*/
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
if ((primitive_info[i].primitive == TextPrimitive) ||
(primitive_info[i].primitive == ImagePrimitive))
if (primitive_info[i].text != (char *) NULL)
primitive_info[i].text=DestroyString(primitive_info[i].text);
i=0;
mvg_info.offset=i;
j=0;
primitive_info[0].point.x=0.0;
primitive_info[0].point.y=0.0;
primitive_info[0].coordinates=0;
primitive_info[0].method=FloodfillMethod;
primitive_info[0].closed_subpath=MagickFalse;
for (x=0; *q != '\0'; x++)
{
/*
Define points.
*/
if (IsPoint(q) == MagickFalse)
break;
(void) GetNextToken(q,&q,extent,token);
point.x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,&q,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
point.y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(q,(const char **) NULL,extent,token);
if (*token == ',')
(void) GetNextToken(q,&q,extent,token);
primitive_info[i].primitive=primitive_type;
primitive_info[i].point=point;
primitive_info[i].coordinates=0;
primitive_info[i].method=FloodfillMethod;
primitive_info[i].closed_subpath=MagickFalse;
i++;
mvg_info.offset=i;
if (i < (ssize_t) number_points)
continue;
status&=CheckPrimitiveExtent(&mvg_info,number_points);
}
if (status == MagickFalse)
break;
if ((primitive_info[j].primitive == TextPrimitive) ||
(primitive_info[j].primitive == ImagePrimitive))
if (primitive_info[j].text != (char *) NULL)
primitive_info[j].text=DestroyString(primitive_info[j].text);
primitive_info[j].primitive=primitive_type;
primitive_info[j].coordinates=(size_t) x;
primitive_info[j].method=FloodfillMethod;
primitive_info[j].closed_subpath=MagickFalse;
/*
Circumscribe primitive within a circle.
*/
bounds.x1=primitive_info[j].point.x;
bounds.y1=primitive_info[j].point.y;
bounds.x2=primitive_info[j].point.x;
bounds.y2=primitive_info[j].point.y;
for (k=1; k < (ssize_t) primitive_info[j].coordinates; k++)
{
point=primitive_info[j+k].point;
if (point.x < bounds.x1)
bounds.x1=point.x;
if (point.y < bounds.y1)
bounds.y1=point.y;
if (point.x > bounds.x2)
bounds.x2=point.x;
if (point.y > bounds.y2)
bounds.y2=point.y;
}
/*
Speculate how many points our primitive might consume.
*/
coordinates=(double) primitive_info[j].coordinates;
switch (primitive_type)
{
case RectanglePrimitive:
{
coordinates*=5.0;
break;
}
case RoundRectanglePrimitive:
{
double
alpha,
beta,
radius;
alpha=bounds.x2-bounds.x1;
beta=bounds.y2-bounds.y1;
radius=hypot((double) alpha,(double) beta);
coordinates*=5.0;
coordinates+=2.0*((size_t) ceil((double) MagickPI*radius))+6.0*
BezierQuantum+360.0;
break;
}
case BezierPrimitive:
{
coordinates=(double) (BezierQuantum*primitive_info[j].coordinates);
if (primitive_info[j].coordinates > (107*BezierQuantum))
{
(void) ThrowMagickException(exception,GetMagickModule(),DrawError,
"TooManyBezierCoordinates","`%s'",token);
status=MagickFalse;
break;
}
break;
}
case PathPrimitive:
{
char
*s,
*t;
(void) GetNextToken(q,&q,extent,token);
coordinates=1.0;
t=token;
for (s=token; *s != '\0'; s=t)
{
double
value;
value=StringToDouble(s,&t);
(void) value;
if (s == t)
{
t++;
continue;
}
coordinates++;
}
for (s=token; *s != '\0'; s++)
if (strspn(s,"AaCcQqSsTt") != 0)
coordinates+=(20.0*BezierQuantum)+360.0;
break;
}
case CirclePrimitive:
case ArcPrimitive:
case EllipsePrimitive:
{
double
alpha,
beta,
radius;
alpha=bounds.x2-bounds.x1;
beta=bounds.y2-bounds.y1;
radius=hypot(alpha,beta);
coordinates=2.0*(ceil(MagickPI*radius))+6.0*BezierQuantum+360.0;
break;
}
default:
break;
}
if (coordinates > MaxBezierCoordinates)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"TooManyBezierCoordinates","`%s'",token);
status=MagickFalse;
}
if (status == MagickFalse)
break;
if (((size_t) (i+coordinates)) >= number_points)
{
/*
Resize based on speculative points required by primitive.
*/
number_points+=coordinates+1;
if (number_points < (size_t) coordinates)
{
(void) ThrowMagickException(exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'",
image->filename);
break;
}
mvg_info.offset=i;
status&=CheckPrimitiveExtent(&mvg_info,number_points);
}
status&=CheckPrimitiveExtent(&mvg_info,PrimitiveExtentPad);
if (status == MagickFalse)
break;
mvg_info.offset=j;
switch (primitive_type)
{
case PointPrimitive:
default:
{
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
status&=TracePoint(primitive_info+j,primitive_info[j].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case LinePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
status&=TraceLine(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case RectanglePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
status&=TraceRectangle(primitive_info+j,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case RoundRectanglePrimitive:
{
if (primitive_info[j].coordinates != 3)
{
status=MagickFalse;
break;
}
if ((primitive_info[j+2].point.x < 0.0) ||
(primitive_info[j+2].point.y < 0.0))
{
status=MagickFalse;
break;
}
if ((primitive_info[j+1].point.x-primitive_info[j].point.x) < 0.0)
{
status=MagickFalse;
break;
}
if ((primitive_info[j+1].point.y-primitive_info[j].point.y) < 0.0)
{
status=MagickFalse;
break;
}
status&=TraceRoundRectangle(&mvg_info,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case ArcPrimitive:
{
if (primitive_info[j].coordinates != 3)
{
primitive_type=UndefinedPrimitive;
break;
}
status&=TraceArc(&mvg_info,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case EllipsePrimitive:
{
if (primitive_info[j].coordinates != 3)
{
status=MagickFalse;
break;
}
if ((primitive_info[j+1].point.x < 0.0) ||
(primitive_info[j+1].point.y < 0.0))
{
status=MagickFalse;
break;
}
status&=TraceEllipse(&mvg_info,primitive_info[j].point,
primitive_info[j+1].point,primitive_info[j+2].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case CirclePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
status&=TraceCircle(&mvg_info,primitive_info[j].point,
primitive_info[j+1].point);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case PolylinePrimitive:
{
if (primitive_info[j].coordinates < 1)
{
status=MagickFalse;
break;
}
break;
}
case PolygonPrimitive:
{
if (primitive_info[j].coordinates < 3)
{
status=MagickFalse;
break;
}
primitive_info[i]=primitive_info[j];
primitive_info[i].coordinates=0;
primitive_info[j].coordinates++;
primitive_info[j].closed_subpath=MagickTrue;
i++;
break;
}
case BezierPrimitive:
{
if (primitive_info[j].coordinates < 3)
{
status=MagickFalse;
break;
}
status&=TraceBezier(&mvg_info,primitive_info[j].coordinates);
i=(ssize_t) (j+primitive_info[j].coordinates);
break;
}
case PathPrimitive:
{
coordinates=(double) TracePath(&mvg_info,token,exception);
if (coordinates == 0.0)
{
status=MagickFalse;
break;
}
i=(ssize_t) (j+coordinates);
break;
}
case AlphaPrimitive:
case ColorPrimitive:
{
ssize_t
method;
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
(void) GetNextToken(q,&q,extent,token);
method=ParseCommandOption(MagickMethodOptions,MagickFalse,token);
if (method == -1)
{
status=MagickFalse;
break;
}
primitive_info[j].method=(PaintMethod) method;
break;
}
case TextPrimitive:
{
char
geometry[MagickPathExtent];
if (primitive_info[j].coordinates != 1)
{
status=MagickFalse;
break;
}
if (*token != ',')
(void) GetNextToken(q,&q,extent,token);
(void) CloneString(&primitive_info[j].text,token);
/*
Compute text cursor offset.
*/
clone_info=CloneDrawInfo((ImageInfo *) NULL,graphic_context[n]);
if ((fabs(mvg_info.point.x-primitive_info->point.x) < MagickEpsilon) &&
(fabs(mvg_info.point.y-primitive_info->point.y) < MagickEpsilon))
{
mvg_info.point=primitive_info->point;
primitive_info->point.x+=cursor;
}
else
{
mvg_info.point=primitive_info->point;
cursor=0.0;
}
(void) FormatLocaleString(geometry,MagickPathExtent,"%+f%+f",
primitive_info->point.x,primitive_info->point.y);
clone_info->render=MagickFalse;
clone_info->text=AcquireString(token);
status&=GetTypeMetrics(image,clone_info,&metrics,exception);
clone_info=DestroyDrawInfo(clone_info);
cursor+=metrics.width;
if (graphic_context[n]->compliance != SVGCompliance)
cursor=0.0;
break;
}
case ImagePrimitive:
{
if (primitive_info[j].coordinates != 2)
{
status=MagickFalse;
break;
}
(void) GetNextToken(q,&q,extent,token);
(void) CloneString(&primitive_info[j].text,token);
break;
}
}
mvg_info.offset=i;
if ((image->debug != MagickFalse) && (q > p))
(void) LogMagickEvent(DrawEvent,GetMagickModule()," %.*s",(int) (q-p-1),
p);
if (status == MagickFalse)
break;
primitive_info[i].primitive=UndefinedPrimitive;
if (i == 0)
continue;
/*
Transform points.
*/
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
point=primitive_info[i].point;
primitive_info[i].point.x=graphic_context[n]->affine.sx*point.x+
graphic_context[n]->affine.ry*point.y+graphic_context[n]->affine.tx;
primitive_info[i].point.y=graphic_context[n]->affine.rx*point.x+
graphic_context[n]->affine.sy*point.y+graphic_context[n]->affine.ty;
point=primitive_info[i].point;
if (point.x < graphic_context[n]->bounds.x1)
graphic_context[n]->bounds.x1=point.x;
if (point.y < graphic_context[n]->bounds.y1)
graphic_context[n]->bounds.y1=point.y;
if (point.x > graphic_context[n]->bounds.x2)
graphic_context[n]->bounds.x2=point.x;
if (point.y > graphic_context[n]->bounds.y2)
graphic_context[n]->bounds.y2=point.y;
if (primitive_info[i].primitive == ImagePrimitive)
break;
if (i >= (ssize_t) number_points)
ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed");
}
if (graphic_context[n]->render != MagickFalse)
{
if ((n != 0) && (graphic_context[n]->compliance != SVGCompliance) &&
(graphic_context[n]->clip_mask != (char *) NULL) &&
(LocaleCompare(graphic_context[n]->clip_mask,
graphic_context[n-1]->clip_mask) != 0))
{
const char
*clip_path;
clip_path=(const char *) GetValueFromSplayTree(macros,
graphic_context[n]->clip_mask);
if (clip_path != (const char *) NULL)
(void) SetImageArtifact(image,graphic_context[n]->clip_mask,
clip_path);
status&=DrawClipPath(image,graphic_context[n],
graphic_context[n]->clip_mask,exception);
}
status&=DrawPrimitive(image,graphic_context[n],primitive_info,
exception);
}
proceed=SetImageProgress(image,RenderImageTag,q-primitive,(MagickSizeType)
primitive_extent);
if (proceed == MagickFalse)
break;
if (status == 0)
break;
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end draw-image");
/*
Relinquish resources.
*/
macros=DestroySplayTree(macros);
token=DestroyString(token);
if (primitive_info != (PrimitiveInfo *) NULL)
{
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
if ((primitive_info[i].primitive == TextPrimitive) ||
(primitive_info[i].primitive == ImagePrimitive))
if (primitive_info[i].text != (char *) NULL)
primitive_info[i].text=DestroyString(primitive_info[i].text);
primitive_info=(PrimitiveInfo *) RelinquishMagickMemory(primitive_info);
}
primitive=DestroyString(primitive);
if (stops != (StopInfo *) NULL)
stops=(StopInfo *) RelinquishMagickMemory(stops);
for ( ; n >= 0; n--)
graphic_context[n]=DestroyDrawInfo(graphic_context[n]);
graphic_context=(DrawInfo **) RelinquishMagickMemory(graphic_context);
if (status == MagickFalse)
ThrowBinaryException(DrawError,"NonconformingDrawingPrimitiveDefinition",
keyword);
return(status != 0 ? MagickTrue : MagickFalse);
}
MagickExport MagickBooleanType DrawImage(Image *image,const DrawInfo *draw_info,
ExceptionInfo *exception)
{
return(RenderMVGContent(image,draw_info,0,exception));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w P a t t e r n P a t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPatternPath() draws a pattern.
%
% The format of the DrawPatternPath method is:
%
% MagickBooleanType DrawPatternPath(Image *image,const DrawInfo *draw_info,
% const char *name,Image **pattern,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o name: the pattern name.
%
% o image: the image.
%
% o exception: return any errors or warnings in this structure.
%
*/
MagickExport MagickBooleanType DrawPatternPath(Image *image,
const DrawInfo *draw_info,const char *name,Image **pattern,
ExceptionInfo *exception)
{
char
property[MagickPathExtent];
const char
*geometry,
*path,
*type;
DrawInfo
*clone_info;
ImageInfo
*image_info;
MagickBooleanType
status;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (const DrawInfo *) NULL);
assert(name != (const char *) NULL);
(void) FormatLocaleString(property,MagickPathExtent,"%s",name);
path=GetImageArtifact(image,property);
if (path == (const char *) NULL)
return(MagickFalse);
(void) FormatLocaleString(property,MagickPathExtent,"%s-geometry",name);
geometry=GetImageArtifact(image,property);
if (geometry == (const char *) NULL)
return(MagickFalse);
if ((*pattern) != (Image *) NULL)
*pattern=DestroyImage(*pattern);
image_info=AcquireImageInfo();
image_info->size=AcquireString(geometry);
*pattern=AcquireImage(image_info,exception);
image_info=DestroyImageInfo(image_info);
(void) QueryColorCompliance("#000000ff",AllCompliance,
&(*pattern)->background_color,exception);
(void) SetImageBackgroundColor(*pattern,exception);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"begin pattern-path %s %s",name,geometry);
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->fill_pattern=NewImageList();
clone_info->stroke_pattern=NewImageList();
(void) FormatLocaleString(property,MagickPathExtent,"%s-type",name);
type=GetImageArtifact(image,property);
if (type != (const char *) NULL)
clone_info->gradient.type=(GradientType) ParseCommandOption(
MagickGradientOptions,MagickFalse,type);
(void) CloneString(&clone_info->primitive,path);
status=RenderMVGContent(*pattern,clone_info,0,exception);
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),"end pattern-path");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w P o l y g o n P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPolygonPrimitive() draws a polygon on the image.
%
% The format of the DrawPolygonPrimitive method is:
%
% MagickBooleanType DrawPolygonPrimitive(Image *image,
% const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
% ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static PolygonInfo **DestroyPolygonThreadSet(PolygonInfo **polygon_info)
{
register ssize_t
i;
assert(polygon_info != (PolygonInfo **) NULL);
for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++)
if (polygon_info[i] != (PolygonInfo *) NULL)
polygon_info[i]=DestroyPolygonInfo(polygon_info[i]);
polygon_info=(PolygonInfo **) RelinquishMagickMemory(polygon_info);
return(polygon_info);
}
static PolygonInfo **AcquirePolygonThreadSet(
const PrimitiveInfo *primitive_info)
{
PathInfo
*magick_restrict path_info;
PolygonInfo
**polygon_info;
register ssize_t
i;
size_t
number_threads;
number_threads=(size_t) GetMagickResourceLimit(ThreadResource);
polygon_info=(PolygonInfo **) AcquireQuantumMemory(number_threads,
sizeof(*polygon_info));
if (polygon_info == (PolygonInfo **) NULL)
return((PolygonInfo **) NULL);
(void) memset(polygon_info,0,number_threads*sizeof(*polygon_info));
path_info=ConvertPrimitiveToPath(primitive_info);
if (path_info == (PathInfo *) NULL)
return(DestroyPolygonThreadSet(polygon_info));
for (i=0; i < (ssize_t) number_threads; i++)
{
polygon_info[i]=ConvertPathToPolygon(path_info);
if (polygon_info[i] == (PolygonInfo *) NULL)
return(DestroyPolygonThreadSet(polygon_info));
}
path_info=(PathInfo *) RelinquishMagickMemory(path_info);
return(polygon_info);
}
static double GetFillAlpha(PolygonInfo *polygon_info,const double mid,
const MagickBooleanType fill,const FillRule fill_rule,const ssize_t x,
const ssize_t y,double *stroke_alpha)
{
double
alpha,
beta,
distance,
subpath_alpha;
PointInfo
delta;
register const PointInfo
*q;
register EdgeInfo
*p;
register ssize_t
i;
ssize_t
j,
winding_number;
/*
Compute fill & stroke opacity for this (x,y) point.
*/
*stroke_alpha=0.0;
subpath_alpha=0.0;
p=polygon_info->edges;
for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)
{
if ((double) y <= (p->bounds.y1-mid-0.5))
break;
if ((double) y > (p->bounds.y2+mid+0.5))
{
(void) DestroyEdge(polygon_info,(size_t) j);
continue;
}
if (((double) x <= (p->bounds.x1-mid-0.5)) ||
((double) x > (p->bounds.x2+mid+0.5)))
continue;
i=(ssize_t) MagickMax((double) p->highwater,1.0);
for ( ; i < (ssize_t) p->number_points; i++)
{
if ((double) y <= (p->points[i-1].y-mid-0.5))
break;
if ((double) y > (p->points[i].y+mid+0.5))
continue;
if (p->scanline != (double) y)
{
p->scanline=(double) y;
p->highwater=(size_t) i;
}
/*
Compute distance between a point and an edge.
*/
q=p->points+i-1;
delta.x=(q+1)->x-q->x;
delta.y=(q+1)->y-q->y;
beta=delta.x*(x-q->x)+delta.y*(y-q->y);
if (beta <= 0.0)
{
delta.x=(double) x-q->x;
delta.y=(double) y-q->y;
distance=delta.x*delta.x+delta.y*delta.y;
}
else
{
alpha=delta.x*delta.x+delta.y*delta.y;
if (beta >= alpha)
{
delta.x=(double) x-(q+1)->x;
delta.y=(double) y-(q+1)->y;
distance=delta.x*delta.x+delta.y*delta.y;
}
else
{
alpha=PerceptibleReciprocal(alpha);
beta=delta.x*(y-q->y)-delta.y*(x-q->x);
distance=alpha*beta*beta;
}
}
/*
Compute stroke & subpath opacity.
*/
beta=0.0;
if (p->ghostline == MagickFalse)
{
alpha=mid+0.5;
if ((*stroke_alpha < 1.0) &&
(distance <= ((alpha+0.25)*(alpha+0.25))))
{
alpha=mid-0.5;
if (distance <= ((alpha+0.25)*(alpha+0.25)))
*stroke_alpha=1.0;
else
{
beta=1.0;
if (fabs(distance-1.0) >= MagickEpsilon)
beta=sqrt((double) distance);
alpha=beta-mid-0.5;
if (*stroke_alpha < ((alpha-0.25)*(alpha-0.25)))
*stroke_alpha=(alpha-0.25)*(alpha-0.25);
}
}
}
if ((fill == MagickFalse) || (distance > 1.0) || (subpath_alpha >= 1.0))
continue;
if (distance <= 0.0)
{
subpath_alpha=1.0;
continue;
}
if (distance > 1.0)
continue;
if (fabs(beta) < MagickEpsilon)
{
beta=1.0;
if (fabs(distance-1.0) >= MagickEpsilon)
beta=sqrt(distance);
}
alpha=beta-1.0;
if (subpath_alpha < (alpha*alpha))
subpath_alpha=alpha*alpha;
}
}
/*
Compute fill opacity.
*/
if (fill == MagickFalse)
return(0.0);
if (subpath_alpha >= 1.0)
return(1.0);
/*
Determine winding number.
*/
winding_number=0;
p=polygon_info->edges;
for (j=0; j < (ssize_t) polygon_info->number_edges; j++, p++)
{
if ((double) y <= p->bounds.y1)
break;
if (((double) y > p->bounds.y2) || ((double) x <= p->bounds.x1))
continue;
if ((double) x > p->bounds.x2)
{
winding_number+=p->direction ? 1 : -1;
continue;
}
i=(ssize_t) MagickMax((double) p->highwater,1.0);
for ( ; i < (ssize_t) (p->number_points-1); i++)
if ((double) y <= p->points[i].y)
break;
q=p->points+i-1;
if ((((q+1)->x-q->x)*(y-q->y)) <= (((q+1)->y-q->y)*(x-q->x)))
winding_number+=p->direction ? 1 : -1;
}
if (fill_rule != NonZeroRule)
{
if ((MagickAbsoluteValue(winding_number) & 0x01) != 0)
return(1.0);
}
else
if (MagickAbsoluteValue(winding_number) != 0)
return(1.0);
return(subpath_alpha);
}
static MagickBooleanType DrawPolygonPrimitive(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickBooleanType
fill,
status;
double
mid;
PolygonInfo
**magick_restrict polygon_info;
register EdgeInfo
*p;
register ssize_t
i;
SegmentInfo
bounds;
ssize_t
start_y,
stop_y,
y;
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
if (image->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
assert(draw_info != (DrawInfo *) NULL);
assert(draw_info->signature == MagickCoreSignature);
assert(primitive_info != (PrimitiveInfo *) NULL);
if (primitive_info->coordinates <= 1)
return(MagickTrue);
/*
Compute bounding box.
*/
polygon_info=AcquirePolygonThreadSet(primitive_info);
if (polygon_info == (PolygonInfo **) NULL)
return(MagickFalse);
DisableMSCWarning(4127)
if (0)
{
status=DrawBoundingRectangles(image,draw_info,polygon_info[0],exception);
if (status == MagickFalse)
{
polygon_info=DestroyPolygonThreadSet(polygon_info);
return(status);
}
}
RestoreMSCWarning
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," begin draw-polygon");
fill=(primitive_info->method == FillToBorderMethod) ||
(primitive_info->method == FloodfillMethod) ? MagickTrue : MagickFalse;
mid=ExpandAffine(&draw_info->affine)*SaneStrokeWidth(image,draw_info)/2.0;
bounds=polygon_info[0]->edges[0].bounds;
for (i=1; i < (ssize_t) polygon_info[0]->number_edges; i++)
{
p=polygon_info[0]->edges+i;
if (p->bounds.x1 < bounds.x1)
bounds.x1=p->bounds.x1;
if (p->bounds.y1 < bounds.y1)
bounds.y1=p->bounds.y1;
if (p->bounds.x2 > bounds.x2)
bounds.x2=p->bounds.x2;
if (p->bounds.y2 > bounds.y2)
bounds.y2=p->bounds.y2;
}
bounds.x1-=(mid+1.0);
bounds.y1-=(mid+1.0);
bounds.x2+=(mid+1.0);
bounds.y2+=(mid+1.0);
if ((bounds.x1 >= (double) image->columns) ||
(bounds.y1 >= (double) image->rows) ||
(bounds.x2 <= 0.0) || (bounds.y2 <= 0.0))
{
polygon_info=DestroyPolygonThreadSet(polygon_info);
return(MagickTrue); /* virtual polygon */
}
bounds.x1=bounds.x1 < 0.0 ? 0.0 : bounds.x1 >= (double) image->columns-1.0 ?
(double) image->columns-1.0 : bounds.x1;
bounds.y1=bounds.y1 < 0.0 ? 0.0 : bounds.y1 >= (double) image->rows-1.0 ?
(double) image->rows-1.0 : bounds.y1;
bounds.x2=bounds.x2 < 0.0 ? 0.0 : bounds.x2 >= (double) image->columns-1.0 ?
(double) image->columns-1.0 : bounds.x2;
bounds.y2=bounds.y2 < 0.0 ? 0.0 : bounds.y2 >= (double) image->rows-1.0 ?
(double) image->rows-1.0 : bounds.y2;
status=MagickTrue;
image_view=AcquireAuthenticCacheView(image,exception);
if ((primitive_info->coordinates == 1) ||
(polygon_info[0]->number_edges == 0))
{
/*
Draw point.
*/
start_y=(ssize_t) ceil(bounds.y1-0.5);
stop_y=(ssize_t) floor(bounds.y2+0.5);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,stop_y-start_y+1,1)
#endif
for (y=start_y; y <= stop_y; y++)
{
MagickBooleanType
sync;
PixelInfo
pixel;
register ssize_t
x;
register Quantum
*magick_restrict q;
ssize_t
start_x,
stop_x;
if (status == MagickFalse)
continue;
start_x=(ssize_t) ceil(bounds.x1-0.5);
stop_x=(ssize_t) floor(bounds.x2+0.5);
x=start_x;
q=GetCacheViewAuthenticPixels(image_view,x,y,(size_t) (stop_x-x+1),1,
exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
GetPixelInfo(image,&pixel);
for ( ; x <= stop_x; x++)
{
if ((x == (ssize_t) ceil(primitive_info->point.x-0.5)) &&
(y == (ssize_t) ceil(primitive_info->point.y-0.5)))
{
GetFillColor(draw_info,x-start_x,y-start_y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
}
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
polygon_info=DestroyPolygonThreadSet(polygon_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" end draw-polygon");
return(status);
}
/*
Draw polygon or line.
*/
start_y=(ssize_t) ceil(bounds.y1-0.5);
stop_y=(ssize_t) floor(bounds.y2+0.5);
#if defined(MAGICKCORE_OPENMP_SUPPORT)
#pragma omp parallel for schedule(static) shared(status) \
magick_number_threads(image,image,stop_y-start_y+1,1)
#endif
for (y=start_y; y <= stop_y; y++)
{
const int
id = GetOpenMPThreadId();
register Quantum
*magick_restrict q;
register ssize_t
x;
ssize_t
start_x,
stop_x;
if (status == MagickFalse)
continue;
start_x=(ssize_t) ceil(bounds.x1-0.5);
stop_x=(ssize_t) floor(bounds.x2+0.5);
q=GetCacheViewAuthenticPixels(image_view,start_x,y,(size_t) (stop_x-start_x+
1),1,exception);
if (q == (Quantum *) NULL)
{
status=MagickFalse;
continue;
}
for (x=start_x; x <= stop_x; x++)
{
double
fill_alpha,
stroke_alpha;
PixelInfo
fill_color,
stroke_color;
/*
Fill and/or stroke.
*/
fill_alpha=GetFillAlpha(polygon_info[id],mid,fill,draw_info->fill_rule,
x,y,&stroke_alpha);
if (draw_info->stroke_antialias == MagickFalse)
{
fill_alpha=fill_alpha > 0.25 ? 1.0 : 0.0;
stroke_alpha=stroke_alpha > 0.25 ? 1.0 : 0.0;
}
GetFillColor(draw_info,x-start_x,y-start_y,&fill_color,exception);
CompositePixelOver(image,&fill_color,fill_alpha*fill_color.alpha,q,
(double) GetPixelAlpha(image,q),q);
GetStrokeColor(draw_info,x-start_x,y-start_y,&stroke_color,exception);
CompositePixelOver(image,&stroke_color,stroke_alpha*stroke_color.alpha,q,
(double) GetPixelAlpha(image,q),q);
q+=GetPixelChannels(image);
}
if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse)
status=MagickFalse;
}
image_view=DestroyCacheView(image_view);
polygon_info=DestroyPolygonThreadSet(polygon_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-polygon");
return(status);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D r a w P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawPrimitive() draws a primitive (line, rectangle, ellipse) on the image.
%
% The format of the DrawPrimitive method is:
%
% MagickBooleanType DrawPrimitive(Image *image,const DrawInfo *draw_info,
% PrimitiveInfo *primitive_info,ExceptionInfo *exception)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static inline double ConstrainCoordinate(double x)
{
if (x < (double) -SSIZE_MAX)
return((double) -SSIZE_MAX);
if (x > (double) SSIZE_MAX)
return((double) SSIZE_MAX);
return(x);
}
static void LogPrimitiveInfo(const PrimitiveInfo *primitive_info)
{
const char
*methods[] =
{
"point",
"replace",
"floodfill",
"filltoborder",
"reset",
"?"
};
PointInfo
p,
point,
q;
register ssize_t
i,
x;
ssize_t
coordinates,
y;
x=(ssize_t) ceil(primitive_info->point.x-0.5);
y=(ssize_t) ceil(primitive_info->point.y-0.5);
switch (primitive_info->primitive)
{
case AlphaPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"AlphaPrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case ColorPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"ColorPrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case ImagePrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"ImagePrimitive %.20g,%.20g",(double) x,(double) y);
return;
}
case PointPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"PointPrimitive %.20g,%.20g %s",(double) x,(double) y,
methods[primitive_info->method]);
return;
}
case TextPrimitive:
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
"TextPrimitive %.20g,%.20g",(double) x,(double) y);
return;
}
default:
break;
}
coordinates=0;
p=primitive_info[0].point;
q.x=(-1.0);
q.y=(-1.0);
for (i=0; primitive_info[i].primitive != UndefinedPrimitive; i++)
{
point=primitive_info[i].point;
if (coordinates <= 0)
{
coordinates=(ssize_t) primitive_info[i].coordinates;
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin open (%.20g)",(double) coordinates);
p=point;
}
point=primitive_info[i].point;
if ((fabs(q.x-point.x) >= MagickEpsilon) ||
(fabs(q.y-point.y) >= MagickEpsilon))
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %.20g: %.18g,%.18g",(double) coordinates,point.x,point.y);
else
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" %.20g: %g %g (duplicate)",(double) coordinates,point.x,point.y);
q=point;
coordinates--;
if (coordinates > 0)
continue;
if ((fabs(p.x-point.x) >= MagickEpsilon) ||
(fabs(p.y-point.y) >= MagickEpsilon))
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end last (%.20g)",
(double) coordinates);
else
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end open (%.20g)",
(double) coordinates);
}
}
MagickExport MagickBooleanType DrawPrimitive(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
ExceptionInfo *exception)
{
CacheView
*image_view;
MagickStatusType
status;
register ssize_t
i,
x;
ssize_t
y;
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin draw-primitive");
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" affine: %g,%g,%g,%g,%g,%g",draw_info->affine.sx,
draw_info->affine.rx,draw_info->affine.ry,draw_info->affine.sy,
draw_info->affine.tx,draw_info->affine.ty);
}
status=MagickTrue;
if ((IsGrayColorspace(image->colorspace) != MagickFalse) &&
((IsPixelInfoGray(&draw_info->fill) == MagickFalse) ||
(IsPixelInfoGray(&draw_info->stroke) == MagickFalse)))
status=SetImageColorspace(image,sRGBColorspace,exception);
if (draw_info->compliance == SVGCompliance)
{
status&=SetImageMask(image,WritePixelMask,draw_info->clipping_mask,
exception);
status&=SetImageMask(image,CompositePixelMask,draw_info->composite_mask,
exception);
}
x=(ssize_t) ceil(ConstrainCoordinate(primitive_info->point.x-0.5));
y=(ssize_t) ceil(ConstrainCoordinate(primitive_info->point.y-0.5));
image_view=AcquireAuthenticCacheView(image,exception);
switch (primitive_info->primitive)
{
case AlphaPrimitive:
{
if (image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception);
switch (primitive_info->method)
{
case PointMethod:
default:
{
PixelInfo
pixel;
register Quantum
*q;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ReplaceMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel,
target;
(void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,
exception);
GetPixelInfo(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)
{
q+=GetPixelChannels(image);
continue;
}
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
ChannelType
channel_mask;
PixelInfo
target;
(void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,
&target,exception);
if (primitive_info->method == FillToBorderMethod)
{
target.red=(double) draw_info->border_color.red;
target.green=(double) draw_info->border_color.green;
target.blue=(double) draw_info->border_color.blue;
}
channel_mask=SetImageChannelMask(image,AlphaChannel);
status&=FloodfillPaintImage(image,draw_info,&target,x,y,
primitive_info->method == FloodfillMethod ? MagickFalse :
MagickTrue,exception);
(void) SetImageChannelMask(image,channel_mask);
break;
}
case ResetMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel;
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelAlpha(image,ClampToQuantum(pixel.alpha),q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
}
break;
}
case ColorPrimitive:
{
switch (primitive_info->method)
{
case PointMethod:
default:
{
PixelInfo
pixel;
register Quantum
*q;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetPixelInfo(image,&pixel);
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case ReplaceMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel,
target;
(void) GetOneCacheViewVirtualPixelInfo(image_view,x,y,&target,
exception);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetPixelInfoPixel(image,q,&pixel);
if (IsFuzzyEquivalencePixelInfo(&pixel,&target) == MagickFalse)
{
q+=GetPixelChannels(image);
continue;
}
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
case FloodfillMethod:
case FillToBorderMethod:
{
PixelInfo
target;
(void) GetOneVirtualPixelInfo(image,TileVirtualPixelMethod,x,y,
&target,exception);
if (primitive_info->method == FillToBorderMethod)
{
target.red=(double) draw_info->border_color.red;
target.green=(double) draw_info->border_color.green;
target.blue=(double) draw_info->border_color.blue;
}
status&=FloodfillPaintImage(image,draw_info,&target,x,y,
primitive_info->method == FloodfillMethod ? MagickFalse :
MagickTrue,exception);
break;
}
case ResetMethod:
{
MagickBooleanType
sync;
PixelInfo
pixel;
GetPixelInfo(image,&pixel);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
GetFillColor(draw_info,x,y,&pixel,exception);
SetPixelViaPixelInfo(image,&pixel,q);
q+=GetPixelChannels(image);
}
sync=SyncCacheViewAuthenticPixels(image_view,exception);
if (sync == MagickFalse)
break;
}
break;
}
}
break;
}
case ImagePrimitive:
{
AffineMatrix
affine;
char
composite_geometry[MagickPathExtent];
Image
*composite_image,
*composite_images;
ImageInfo
*clone_info;
RectangleInfo
geometry;
ssize_t
x1,
y1;
if (primitive_info->text == (char *) NULL)
break;
clone_info=AcquireImageInfo();
if (LocaleNCompare(primitive_info->text,"data:",5) == 0)
composite_images=ReadInlineImage(clone_info,primitive_info->text,
exception);
else
{
(void) CopyMagickString(clone_info->filename,primitive_info->text,
MagickPathExtent);
composite_images=ReadImage(clone_info,exception);
}
clone_info=DestroyImageInfo(clone_info);
if (composite_images == (Image *) NULL)
{
status=0;
break;
}
composite_image=RemoveFirstImageFromList(&composite_images);
composite_images=DestroyImageList(composite_images);
(void) SetImageProgressMonitor(composite_image,(MagickProgressMonitor)
NULL,(void *) NULL);
x1=(ssize_t) ceil(primitive_info[1].point.x-0.5);
y1=(ssize_t) ceil(primitive_info[1].point.y-0.5);
if (((x1 != 0L) && (x1 != (ssize_t) composite_image->columns)) ||
((y1 != 0L) && (y1 != (ssize_t) composite_image->rows)))
{
/*
Resize image.
*/
(void) FormatLocaleString(composite_geometry,MagickPathExtent,
"%gx%g!",primitive_info[1].point.x,primitive_info[1].point.y);
composite_image->filter=image->filter;
(void) TransformImage(&composite_image,(char *) NULL,
composite_geometry,exception);
}
if (composite_image->alpha_trait == UndefinedPixelTrait)
(void) SetImageAlphaChannel(composite_image,OpaqueAlphaChannel,
exception);
if (draw_info->alpha != OpaqueAlpha)
(void) SetImageAlpha(composite_image,draw_info->alpha,exception);
SetGeometry(image,&geometry);
image->gravity=draw_info->gravity;
geometry.x=x;
geometry.y=y;
(void) FormatLocaleString(composite_geometry,MagickPathExtent,
"%.20gx%.20g%+.20g%+.20g",(double) composite_image->columns,(double)
composite_image->rows,(double) geometry.x,(double) geometry.y);
(void) ParseGravityGeometry(image,composite_geometry,&geometry,exception);
affine=draw_info->affine;
affine.tx=(double) geometry.x;
affine.ty=(double) geometry.y;
composite_image->interpolate=image->interpolate;
if ((draw_info->compose == OverCompositeOp) ||
(draw_info->compose == SrcOverCompositeOp))
(void) DrawAffineImage(image,composite_image,&affine,exception);
else
(void) CompositeImage(image,composite_image,draw_info->compose,
MagickTrue,geometry.x,geometry.y,exception);
composite_image=DestroyImage(composite_image);
break;
}
case PointPrimitive:
{
PixelInfo
fill_color;
register Quantum
*q;
if ((y < 0) || (y >= (ssize_t) image->rows))
break;
if ((x < 0) || (x >= (ssize_t) image->columns))
break;
q=GetCacheViewAuthenticPixels(image_view,x,y,1,1,exception);
if (q == (Quantum *) NULL)
break;
GetFillColor(draw_info,x,y,&fill_color,exception);
CompositePixelOver(image,&fill_color,(double) fill_color.alpha,q,
(double) GetPixelAlpha(image,q),q);
(void) SyncCacheViewAuthenticPixels(image_view,exception);
break;
}
case TextPrimitive:
{
char
geometry[MagickPathExtent];
DrawInfo
*clone_info;
if (primitive_info->text == (char *) NULL)
break;
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
(void) CloneString(&clone_info->text,primitive_info->text);
(void) FormatLocaleString(geometry,MagickPathExtent,"%+f%+f",
primitive_info->point.x,primitive_info->point.y);
(void) CloneString(&clone_info->geometry,geometry);
status&=AnnotateImage(image,clone_info,exception);
clone_info=DestroyDrawInfo(clone_info);
break;
}
default:
{
double
mid,
scale;
DrawInfo
*clone_info;
if (IsEventLogging() != MagickFalse)
LogPrimitiveInfo(primitive_info);
scale=ExpandAffine(&draw_info->affine);
if ((draw_info->dash_pattern != (double *) NULL) &&
(fabs(draw_info->dash_pattern[0]) >= MagickEpsilon) &&
(fabs(scale*draw_info->stroke_width) >= MagickEpsilon) &&
(draw_info->stroke.alpha != (Quantum) TransparentAlpha))
{
/*
Draw dash polygon.
*/
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->stroke_width=0.0;
clone_info->stroke.alpha=(MagickRealType) TransparentAlpha;
status&=DrawPolygonPrimitive(image,clone_info,primitive_info,
exception);
clone_info=DestroyDrawInfo(clone_info);
status=DrawDashPolygon(draw_info,primitive_info,image,exception);
break;
}
mid=ExpandAffine(&draw_info->affine)*SaneStrokeWidth(image,draw_info)/2.0;
if ((mid > 1.0) &&
((draw_info->stroke.alpha != (Quantum) TransparentAlpha) ||
(draw_info->stroke_pattern != (Image *) NULL)))
{
double
x,
y;
MagickBooleanType
closed_path;
/*
Draw strokes while respecting line cap/join attributes.
*/
closed_path=primitive_info[0].closed_subpath;
i=(ssize_t) primitive_info[0].coordinates;
x=fabs(primitive_info[i-1].point.x-primitive_info[0].point.x);
y=fabs(primitive_info[i-1].point.y-primitive_info[0].point.y);
if ((x < MagickEpsilon) && (y < MagickEpsilon))
closed_path=MagickTrue;
if ((((draw_info->linecap == RoundCap) ||
(closed_path != MagickFalse)) &&
(draw_info->linejoin == RoundJoin)) ||
(primitive_info[i].primitive != UndefinedPrimitive))
{
status=DrawPolygonPrimitive(image,draw_info,primitive_info,
exception);
break;
}
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->stroke_width=0.0;
clone_info->stroke.alpha=(MagickRealType) TransparentAlpha;
status&=DrawPolygonPrimitive(image,clone_info,primitive_info,
exception);
clone_info=DestroyDrawInfo(clone_info);
status&=DrawStrokePolygon(image,draw_info,primitive_info,exception);
break;
}
status&=DrawPolygonPrimitive(image,draw_info,primitive_info,exception);
break;
}
}
image_view=DestroyCacheView(image_view);
if (draw_info->compliance == SVGCompliance)
{
status&=SetImageMask(image,WritePixelMask,(Image *) NULL,exception);
status&=SetImageMask(image,CompositePixelMask,(Image *) NULL,exception);
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule()," end draw-primitive");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ D r a w S t r o k e P o l y g o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DrawStrokePolygon() draws a stroked polygon (line, rectangle, ellipse) on
% the image while respecting the line cap and join attributes.
%
% The format of the DrawStrokePolygon method is:
%
% MagickBooleanType DrawStrokePolygon(Image *image,
% const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)
%
% A description of each parameter follows:
%
% o image: the image.
%
% o draw_info: the draw info.
%
% o primitive_info: Specifies a pointer to a PrimitiveInfo structure.
%
%
*/
static MagickBooleanType DrawRoundLinecap(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
ExceptionInfo *exception)
{
PrimitiveInfo
linecap[5];
register ssize_t
i;
for (i=0; i < 4; i++)
linecap[i]=(*primitive_info);
linecap[0].coordinates=4;
linecap[1].point.x+=2.0*MagickEpsilon;
linecap[2].point.x+=2.0*MagickEpsilon;
linecap[2].point.y+=2.0*MagickEpsilon;
linecap[3].point.y+=2.0*MagickEpsilon;
linecap[4].primitive=UndefinedPrimitive;
return(DrawPolygonPrimitive(image,draw_info,linecap,exception));
}
static MagickBooleanType DrawStrokePolygon(Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info,
ExceptionInfo *exception)
{
DrawInfo
*clone_info;
MagickBooleanType
closed_path;
MagickStatusType
status;
PrimitiveInfo
*stroke_polygon;
register const PrimitiveInfo
*p,
*q;
/*
Draw stroked polygon.
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" begin draw-stroke-polygon");
clone_info=CloneDrawInfo((ImageInfo *) NULL,draw_info);
clone_info->fill=draw_info->stroke;
if (clone_info->fill_pattern != (Image *) NULL)
clone_info->fill_pattern=DestroyImage(clone_info->fill_pattern);
if (clone_info->stroke_pattern != (Image *) NULL)
clone_info->fill_pattern=CloneImage(clone_info->stroke_pattern,0,0,
MagickTrue,exception);
clone_info->stroke.alpha=(MagickRealType) TransparentAlpha;
clone_info->stroke_width=0.0;
clone_info->fill_rule=NonZeroRule;
status=MagickTrue;
for (p=primitive_info; p->primitive != UndefinedPrimitive; p+=p->coordinates)
{
if (p->coordinates == 1)
continue;
stroke_polygon=TraceStrokePolygon(image,draw_info,p);
if (stroke_polygon == (PrimitiveInfo *) NULL)
{
status=0;
break;
}
status&=DrawPolygonPrimitive(image,clone_info,stroke_polygon,exception);
stroke_polygon=(PrimitiveInfo *) RelinquishMagickMemory(stroke_polygon);
if (status == 0)
break;
q=p+p->coordinates-1;
closed_path=p->closed_subpath;
if ((draw_info->linecap == RoundCap) && (closed_path == MagickFalse))
{
status&=DrawRoundLinecap(image,draw_info,p,exception);
status&=DrawRoundLinecap(image,draw_info,q,exception);
}
}
clone_info=DestroyDrawInfo(clone_info);
if (image->debug != MagickFalse)
(void) LogMagickEvent(DrawEvent,GetMagickModule(),
" end draw-stroke-polygon");
return(status != 0 ? MagickTrue : MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% G e t A f f i n e M a t r i x %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetAffineMatrix() returns an AffineMatrix initialized to the identity
% matrix.
%
% The format of the GetAffineMatrix method is:
%
% void GetAffineMatrix(AffineMatrix *affine_matrix)
%
% A description of each parameter follows:
%
% o affine_matrix: the affine matrix.
%
*/
MagickExport void GetAffineMatrix(AffineMatrix *affine_matrix)
{
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(affine_matrix != (AffineMatrix *) NULL);
(void) memset(affine_matrix,0,sizeof(*affine_matrix));
affine_matrix->sx=1.0;
affine_matrix->sy=1.0;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ G e t D r a w I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% GetDrawInfo() initializes draw_info to default values from image_info.
%
% The format of the GetDrawInfo method is:
%
% void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)
%
% A description of each parameter follows:
%
% o image_info: the image info..
%
% o draw_info: the draw info.
%
*/
MagickExport void GetDrawInfo(const ImageInfo *image_info,DrawInfo *draw_info)
{
char
*next_token;
const char
*option;
ExceptionInfo
*exception;
ImageInfo
*clone_info;
/*
Initialize draw attributes.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(draw_info != (DrawInfo *) NULL);
(void) memset(draw_info,0,sizeof(*draw_info));
clone_info=CloneImageInfo(image_info);
GetAffineMatrix(&draw_info->affine);
exception=AcquireExceptionInfo();
(void) QueryColorCompliance("#000F",AllCompliance,&draw_info->fill,
exception);
(void) QueryColorCompliance("#FFF0",AllCompliance,&draw_info->stroke,
exception);
draw_info->stroke_antialias=clone_info->antialias;
draw_info->stroke_width=1.0;
draw_info->fill_rule=EvenOddRule;
draw_info->alpha=OpaqueAlpha;
draw_info->fill_alpha=OpaqueAlpha;
draw_info->stroke_alpha=OpaqueAlpha;
draw_info->linecap=ButtCap;
draw_info->linejoin=MiterJoin;
draw_info->miterlimit=10;
draw_info->decorate=NoDecoration;
draw_info->pointsize=12.0;
draw_info->undercolor.alpha=(MagickRealType) TransparentAlpha;
draw_info->compose=OverCompositeOp;
draw_info->render=MagickTrue;
draw_info->clip_path=MagickFalse;
draw_info->debug=IsEventLogging();
if (clone_info->font != (char *) NULL)
draw_info->font=AcquireString(clone_info->font);
if (clone_info->density != (char *) NULL)
draw_info->density=AcquireString(clone_info->density);
draw_info->text_antialias=clone_info->antialias;
if (fabs(clone_info->pointsize) >= MagickEpsilon)
draw_info->pointsize=clone_info->pointsize;
draw_info->border_color=clone_info->border_color;
if (clone_info->server_name != (char *) NULL)
draw_info->server_name=AcquireString(clone_info->server_name);
option=GetImageOption(clone_info,"direction");
if (option != (const char *) NULL)
draw_info->direction=(DirectionType) ParseCommandOption(
MagickDirectionOptions,MagickFalse,option);
else
draw_info->direction=UndefinedDirection;
option=GetImageOption(clone_info,"encoding");
if (option != (const char *) NULL)
(void) CloneString(&draw_info->encoding,option);
option=GetImageOption(clone_info,"family");
if (option != (const char *) NULL)
(void) CloneString(&draw_info->family,option);
option=GetImageOption(clone_info,"fill");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->fill,
exception);
option=GetImageOption(clone_info,"gravity");
if (option != (const char *) NULL)
draw_info->gravity=(GravityType) ParseCommandOption(MagickGravityOptions,
MagickFalse,option);
option=GetImageOption(clone_info,"interline-spacing");
if (option != (const char *) NULL)
draw_info->interline_spacing=StringToDouble(option,&next_token);
option=GetImageOption(clone_info,"interword-spacing");
if (option != (const char *) NULL)
draw_info->interword_spacing=StringToDouble(option,&next_token);
option=GetImageOption(clone_info,"kerning");
if (option != (const char *) NULL)
draw_info->kerning=StringToDouble(option,&next_token);
option=GetImageOption(clone_info,"stroke");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->stroke,
exception);
option=GetImageOption(clone_info,"strokewidth");
if (option != (const char *) NULL)
draw_info->stroke_width=StringToDouble(option,&next_token);
option=GetImageOption(clone_info,"style");
if (option != (const char *) NULL)
draw_info->style=(StyleType) ParseCommandOption(MagickStyleOptions,
MagickFalse,option);
option=GetImageOption(clone_info,"undercolor");
if (option != (const char *) NULL)
(void) QueryColorCompliance(option,AllCompliance,&draw_info->undercolor,
exception);
option=GetImageOption(clone_info,"weight");
if (option != (const char *) NULL)
{
ssize_t
weight;
weight=ParseCommandOption(MagickWeightOptions,MagickFalse,option);
if (weight == -1)
weight=(ssize_t) StringToUnsignedLong(option);
draw_info->weight=(size_t) weight;
}
exception=DestroyExceptionInfo(exception);
draw_info->signature=MagickCoreSignature;
clone_info=DestroyImageInfo(clone_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ P e r m u t a t e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Permutate() returns the permuation of the (n,k).
%
% The format of the Permutate method is:
%
% void Permutate(ssize_t n,ssize_t k)
%
% A description of each parameter follows:
%
% o n:
%
% o k:
%
%
*/
static inline double Permutate(const ssize_t n,const ssize_t k)
{
double
r;
register ssize_t
i;
r=1.0;
for (i=k+1; i <= n; i++)
r*=i;
for (i=1; i <= (n-k); i++)
r/=i;
return(r);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ T r a c e P r i m i t i v e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% TracePrimitive is a collection of methods for generating graphic
% primitives such as arcs, ellipses, paths, etc.
%
*/
static MagickBooleanType TraceArc(MVGInfo *mvg_info,const PointInfo start,
const PointInfo end,const PointInfo degrees)
{
PointInfo
center,
radius;
center.x=0.5*(end.x+start.x);
center.y=0.5*(end.y+start.y);
radius.x=fabs(center.x-start.x);
radius.y=fabs(center.y-start.y);
return(TraceEllipse(mvg_info,center,radius,degrees));
}
static MagickBooleanType TraceArcPath(MVGInfo *mvg_info,const PointInfo start,
const PointInfo end,const PointInfo arc,const double angle,
const MagickBooleanType large_arc,const MagickBooleanType sweep)
{
double
alpha,
beta,
delta,
factor,
gamma,
theta;
MagickStatusType
status;
PointInfo
center,
points[3],
radii;
register double
cosine,
sine;
PrimitiveInfo
*primitive_info;
register PrimitiveInfo
*p;
register ssize_t
i;
size_t
arc_segments;
ssize_t
offset;
offset=mvg_info->offset;
primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;
primitive_info->coordinates=0;
if ((fabs(start.x-end.x) < MagickEpsilon) &&
(fabs(start.y-end.y) < MagickEpsilon))
return(TracePoint(primitive_info,end));
radii.x=fabs(arc.x);
radii.y=fabs(arc.y);
if ((fabs(radii.x) < MagickEpsilon) || (fabs(radii.y) < MagickEpsilon))
return(TraceLine(primitive_info,start,end));
cosine=cos(DegreesToRadians(fmod((double) angle,360.0)));
sine=sin(DegreesToRadians(fmod((double) angle,360.0)));
center.x=(double) (cosine*(end.x-start.x)/2+sine*(end.y-start.y)/2);
center.y=(double) (cosine*(end.y-start.y)/2-sine*(end.x-start.x)/2);
delta=(center.x*center.x)/(radii.x*radii.x)+(center.y*center.y)/
(radii.y*radii.y);
if (delta < MagickEpsilon)
return(TraceLine(primitive_info,start,end));
if (delta > 1.0)
{
radii.x*=sqrt((double) delta);
radii.y*=sqrt((double) delta);
}
points[0].x=(double) (cosine*start.x/radii.x+sine*start.y/radii.x);
points[0].y=(double) (cosine*start.y/radii.y-sine*start.x/radii.y);
points[1].x=(double) (cosine*end.x/radii.x+sine*end.y/radii.x);
points[1].y=(double) (cosine*end.y/radii.y-sine*end.x/radii.y);
alpha=points[1].x-points[0].x;
beta=points[1].y-points[0].y;
factor=PerceptibleReciprocal(alpha*alpha+beta*beta)-0.25;
if (factor <= 0.0)
factor=0.0;
else
{
factor=sqrt((double) factor);
if (sweep == large_arc)
factor=(-factor);
}
center.x=(double) ((points[0].x+points[1].x)/2-factor*beta);
center.y=(double) ((points[0].y+points[1].y)/2+factor*alpha);
alpha=atan2(points[0].y-center.y,points[0].x-center.x);
theta=atan2(points[1].y-center.y,points[1].x-center.x)-alpha;
if ((theta < 0.0) && (sweep != MagickFalse))
theta+=2.0*MagickPI;
else
if ((theta > 0.0) && (sweep == MagickFalse))
theta-=2.0*MagickPI;
arc_segments=(size_t) ceil(fabs((double) (theta/(0.5*MagickPI+
MagickEpsilon))));
status=MagickTrue;
p=primitive_info;
for (i=0; i < (ssize_t) arc_segments; i++)
{
beta=0.5*((alpha+(i+1)*theta/arc_segments)-(alpha+i*theta/arc_segments));
gamma=(8.0/3.0)*sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))*
sin(fmod((double) (0.5*beta),DegreesToRadians(360.0)))/
sin(fmod((double) beta,DegreesToRadians(360.0)));
points[0].x=(double) (center.x+cos(fmod((double) (alpha+(double) i*theta/
arc_segments),DegreesToRadians(360.0)))-gamma*sin(fmod((double) (alpha+
(double) i*theta/arc_segments),DegreesToRadians(360.0))));
points[0].y=(double) (center.y+sin(fmod((double) (alpha+(double) i*theta/
arc_segments),DegreesToRadians(360.0)))+gamma*cos(fmod((double) (alpha+
(double) i*theta/arc_segments),DegreesToRadians(360.0))));
points[2].x=(double) (center.x+cos(fmod((double) (alpha+(double) (i+1)*
theta/arc_segments),DegreesToRadians(360.0))));
points[2].y=(double) (center.y+sin(fmod((double) (alpha+(double) (i+1)*
theta/arc_segments),DegreesToRadians(360.0))));
points[1].x=(double) (points[2].x+gamma*sin(fmod((double) (alpha+(double)
(i+1)*theta/arc_segments),DegreesToRadians(360.0))));
points[1].y=(double) (points[2].y-gamma*cos(fmod((double) (alpha+(double)
(i+1)*theta/arc_segments),DegreesToRadians(360.0))));
p->point.x=(p == primitive_info) ? start.x : (p-1)->point.x;
p->point.y=(p == primitive_info) ? start.y : (p-1)->point.y;
(p+1)->point.x=(double) (cosine*radii.x*points[0].x-sine*radii.y*
points[0].y);
(p+1)->point.y=(double) (sine*radii.x*points[0].x+cosine*radii.y*
points[0].y);
(p+2)->point.x=(double) (cosine*radii.x*points[1].x-sine*radii.y*
points[1].y);
(p+2)->point.y=(double) (sine*radii.x*points[1].x+cosine*radii.y*
points[1].y);
(p+3)->point.x=(double) (cosine*radii.x*points[2].x-sine*radii.y*
points[2].y);
(p+3)->point.y=(double) (sine*radii.x*points[2].x+cosine*radii.y*
points[2].y);
if (i == (ssize_t) (arc_segments-1))
(p+3)->point=end;
status&=TraceBezier(mvg_info,4);
p=(*mvg_info->primitive_info)+mvg_info->offset;
mvg_info->offset+=p->coordinates;
p+=p->coordinates;
}
mvg_info->offset=offset;
primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;
primitive_info->coordinates=(size_t) (p-primitive_info);
primitive_info->closed_subpath=MagickFalse;
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
return(status == 0 ? MagickFalse : MagickTrue);
}
static MagickBooleanType TraceBezier(MVGInfo *mvg_info,
const size_t number_coordinates)
{
double
alpha,
*coefficients,
weight;
PointInfo
end,
point,
*points;
PrimitiveInfo
*primitive_info;
register PrimitiveInfo
*p;
register ssize_t
i,
j;
size_t
control_points,
quantum;
/*
Allocate coefficients.
*/
primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;
quantum=number_coordinates;
for (i=0; i < (ssize_t) number_coordinates; i++)
{
for (j=i+1; j < (ssize_t) number_coordinates; j++)
{
alpha=fabs(primitive_info[j].point.x-primitive_info[i].point.x);
if (alpha > (double) SSIZE_MAX)
{
(void) ThrowMagickException(mvg_info->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'","");
return(MagickFalse);
}
if (alpha > (double) quantum)
quantum=(size_t) alpha;
alpha=fabs(primitive_info[j].point.y-primitive_info[i].point.y);
if (alpha > (double) SSIZE_MAX)
{
(void) ThrowMagickException(mvg_info->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'","");
return(MagickFalse);
}
if (alpha > (double) quantum)
quantum=(size_t) alpha;
}
}
quantum=MagickMin(quantum/number_coordinates,BezierQuantum);
primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;
coefficients=(double *) AcquireQuantumMemory(number_coordinates,
sizeof(*coefficients));
points=(PointInfo *) AcquireQuantumMemory(quantum,number_coordinates*
sizeof(*points));
if ((coefficients == (double *) NULL) || (points == (PointInfo *) NULL))
{
if (points != (PointInfo *) NULL)
points=(PointInfo *) RelinquishMagickMemory(points);
if (coefficients != (double *) NULL)
coefficients=(double *) RelinquishMagickMemory(coefficients);
(void) ThrowMagickException(mvg_info->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'","");
return(MagickFalse);
}
control_points=quantum*number_coordinates;
if (CheckPrimitiveExtent(mvg_info,control_points+1) == MagickFalse)
{
points=(PointInfo *) RelinquishMagickMemory(points);
coefficients=(double *) RelinquishMagickMemory(coefficients);
return(MagickFalse);
}
/*
Compute bezier points.
*/
end=primitive_info[number_coordinates-1].point;
for (i=0; i < (ssize_t) number_coordinates; i++)
coefficients[i]=Permutate((ssize_t) number_coordinates-1,i);
weight=0.0;
for (i=0; i < (ssize_t) control_points; i++)
{
p=primitive_info;
point.x=0.0;
point.y=0.0;
alpha=pow((double) (1.0-weight),(double) number_coordinates-1.0);
for (j=0; j < (ssize_t) number_coordinates; j++)
{
point.x+=alpha*coefficients[j]*p->point.x;
point.y+=alpha*coefficients[j]*p->point.y;
alpha*=weight/(1.0-weight);
p++;
}
points[i]=point;
weight+=1.0/control_points;
}
/*
Bezier curves are just short segmented polys.
*/
p=primitive_info;
for (i=0; i < (ssize_t) control_points; i++)
{
if (TracePoint(p,points[i]) == MagickFalse)
{
points=(PointInfo *) RelinquishMagickMemory(points);
coefficients=(double *) RelinquishMagickMemory(coefficients);
return(MagickFalse);
}
p+=p->coordinates;
}
if (TracePoint(p,end) == MagickFalse)
{
points=(PointInfo *) RelinquishMagickMemory(points);
coefficients=(double *) RelinquishMagickMemory(coefficients);
return(MagickFalse);
}
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
primitive_info->closed_subpath=MagickFalse;
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
points=(PointInfo *) RelinquishMagickMemory(points);
coefficients=(double *) RelinquishMagickMemory(coefficients);
return(MagickTrue);
}
static MagickBooleanType TraceCircle(MVGInfo *mvg_info,const PointInfo start,
const PointInfo end)
{
double
alpha,
beta,
radius;
PointInfo
offset,
degrees;
alpha=end.x-start.x;
beta=end.y-start.y;
radius=hypot((double) alpha,(double) beta);
offset.x=(double) radius;
offset.y=(double) radius;
degrees.x=0.0;
degrees.y=360.0;
return(TraceEllipse(mvg_info,start,offset,degrees));
}
static MagickBooleanType TraceEllipse(MVGInfo *mvg_info,const PointInfo center,
const PointInfo radii,const PointInfo arc)
{
double
coordinates,
delta,
step,
x,
y;
PointInfo
angle,
point;
PrimitiveInfo
*primitive_info;
register PrimitiveInfo
*p;
register ssize_t
i;
/*
Ellipses are just short segmented polys.
*/
primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;
primitive_info->coordinates=0;
if ((fabs(radii.x) < MagickEpsilon) || (fabs(radii.y) < MagickEpsilon))
return(MagickTrue);
delta=2.0*PerceptibleReciprocal(MagickMax(radii.x,radii.y));
step=MagickPI/8.0;
if ((delta >= 0.0) && (delta < (MagickPI/8.0)))
step=MagickPI/4.0/(MagickPI*PerceptibleReciprocal(delta)/2.0);
angle.x=DegreesToRadians(arc.x);
y=arc.y;
while (y < arc.x)
y+=360.0;
angle.y=DegreesToRadians(y);
coordinates=ceil((angle.y-angle.x)/step+1.0);
if ((coordinates > (double) SSIZE_MAX) ||
(coordinates > (double) GetMaxMemoryRequest()))
{
(void) ThrowMagickException(mvg_info->exception,GetMagickModule(),
ResourceLimitError,"MemoryAllocationFailed","`%s'","");
return(MagickFalse);
}
if (CheckPrimitiveExtent(mvg_info,(size_t) coordinates) == MagickFalse)
return(MagickFalse);
primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;
for (p=primitive_info; angle.x < angle.y; angle.x+=step)
{
point.x=cos(fmod(angle.x,DegreesToRadians(360.0)))*radii.x+center.x;
point.y=sin(fmod(angle.x,DegreesToRadians(360.0)))*radii.y+center.y;
if (TracePoint(p,point) == MagickFalse)
return(MagickFalse);
p+=p->coordinates;
}
point.x=cos(fmod(angle.y,DegreesToRadians(360.0)))*radii.x+center.x;
point.y=sin(fmod(angle.y,DegreesToRadians(360.0)))*radii.y+center.y;
if (TracePoint(p,point) == MagickFalse)
return(MagickFalse);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
primitive_info->closed_subpath=MagickFalse;
x=fabs(primitive_info[0].point.x-
primitive_info[primitive_info->coordinates-1].point.x);
y=fabs(primitive_info[0].point.y-
primitive_info[primitive_info->coordinates-1].point.y);
if ((x < MagickEpsilon) && (y < MagickEpsilon))
primitive_info->closed_subpath=MagickTrue;
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
return(MagickTrue);
}
static MagickBooleanType TraceLine(PrimitiveInfo *primitive_info,
const PointInfo start,const PointInfo end)
{
if (TracePoint(primitive_info,start) == MagickFalse)
return(MagickFalse);
if ((fabs(start.x-end.x) < MagickEpsilon) &&
(fabs(start.y-end.y) < MagickEpsilon))
{
primitive_info->primitive=PointPrimitive;
primitive_info->coordinates=1;
return(MagickTrue);
}
if (TracePoint(primitive_info+1,end) == MagickFalse)
return(MagickFalse);
(primitive_info+1)->primitive=primitive_info->primitive;
primitive_info->coordinates=2;
primitive_info->closed_subpath=MagickFalse;
return(MagickTrue);
}
static size_t TracePath(MVGInfo *mvg_info,const char *path,
ExceptionInfo *exception)
{
char
*next_token,
token[MagickPathExtent];
const char
*p;
double
x,
y;
int
attribute,
last_attribute;
MagickBooleanType
status;
PointInfo
end = {0.0, 0.0},
points[4] = { {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0} },
point = {0.0, 0.0},
start = {0.0, 0.0};
PrimitiveInfo
*primitive_info;
PrimitiveType
primitive_type;
register PrimitiveInfo
*q;
register ssize_t
i;
size_t
number_coordinates,
z_count;
ssize_t
subpath_offset;
subpath_offset=mvg_info->offset;
primitive_info=(*mvg_info->primitive_info)+mvg_info->offset;
status=MagickTrue;
attribute=0;
number_coordinates=0;
z_count=0;
primitive_type=primitive_info->primitive;
q=primitive_info;
for (p=path; *p != '\0'; )
{
if (status == MagickFalse)
break;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == '\0')
break;
last_attribute=attribute;
attribute=(int) (*p++);
switch (attribute)
{
case 'a':
case 'A':
{
double
angle = 0.0;
MagickBooleanType
large_arc = MagickFalse,
sweep = MagickFalse;
PointInfo
arc = {0.0, 0.0};
/*
Elliptical arc.
*/
do
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
arc.x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
arc.y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
angle=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
large_arc=StringToLong(token) != 0 ? MagickTrue : MagickFalse;
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
sweep=StringToLong(token) != 0 ? MagickTrue : MagickFalse;
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
end.x=(double) (attribute == (int) 'A' ? x : point.x+x);
end.y=(double) (attribute == (int) 'A' ? y : point.y+y);
if (TraceArcPath(mvg_info,point,end,arc,angle,large_arc,sweep) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
point=end;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'c':
case 'C':
{
/*
Cubic Bézier curve.
*/
do
{
points[0]=point;
for (i=1; i < 4; i++)
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
end.x=(double) (attribute == (int) 'C' ? x : point.x+x);
end.y=(double) (attribute == (int) 'C' ? y : point.y+y);
points[i]=end;
}
for (i=0; i < 4; i++)
(q+i)->point=points[i];
if (TraceBezier(mvg_info,4) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
point=end;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'H':
case 'h':
{
do
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
point.x=(double) (attribute == (int) 'H' ? x: point.x+x);
if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
if (TracePoint(q,point) == MagickFalse)
return(0);
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'l':
case 'L':
{
/*
Line to.
*/
do
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
point.x=(double) (attribute == (int) 'L' ? x : point.x+x);
point.y=(double) (attribute == (int) 'L' ? y : point.y+y);
if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
if (TracePoint(q,point) == MagickFalse)
return(0);
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'M':
case 'm':
{
/*
Move to.
*/
if (mvg_info->offset != subpath_offset)
{
primitive_info=(*mvg_info->primitive_info)+subpath_offset;
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
primitive_info=q;
subpath_offset=mvg_info->offset;
}
i=0;
do
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
point.x=(double) (attribute == (int) 'M' ? x : point.x+x);
point.y=(double) (attribute == (int) 'M' ? y : point.y+y);
if (i == 0)
start=point;
i++;
if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
if (TracePoint(q,point) == MagickFalse)
return(0);
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'q':
case 'Q':
{
/*
Quadratic Bézier curve.
*/
do
{
points[0]=point;
for (i=1; i < 3; i++)
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
if (*p == ',')
p++;
end.x=(double) (attribute == (int) 'Q' ? x : point.x+x);
end.y=(double) (attribute == (int) 'Q' ? y : point.y+y);
points[i]=end;
}
for (i=0; i < 3; i++)
(q+i)->point=points[i];
if (TraceBezier(mvg_info,3) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
point=end;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 's':
case 'S':
{
/*
Cubic Bézier curve.
*/
do
{
points[0]=points[3];
points[1].x=2.0*points[3].x-points[2].x;
points[1].y=2.0*points[3].y-points[2].y;
for (i=2; i < 4; i++)
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
if (*p == ',')
p++;
end.x=(double) (attribute == (int) 'S' ? x : point.x+x);
end.y=(double) (attribute == (int) 'S' ? y : point.y+y);
points[i]=end;
}
if (strchr("CcSs",last_attribute) == (char *) NULL)
{
points[0]=point;
points[1]=point;
}
for (i=0; i < 4; i++)
(q+i)->point=points[i];
if (TraceBezier(mvg_info,4) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
point=end;
last_attribute=attribute;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 't':
case 'T':
{
/*
Quadratic Bézier curve.
*/
do
{
points[0]=points[2];
points[1].x=2.0*points[2].x-points[1].x;
points[1].y=2.0*points[2].y-points[1].y;
for (i=2; i < 3; i++)
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
x=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
end.x=(double) (attribute == (int) 'T' ? x : point.x+x);
end.y=(double) (attribute == (int) 'T' ? y : point.y+y);
points[i]=end;
}
if (status == MagickFalse)
break;
if (strchr("QqTt",last_attribute) == (char *) NULL)
{
points[0]=point;
points[1]=point;
}
for (i=0; i < 3; i++)
(q+i)->point=points[i];
if (TraceBezier(mvg_info,3) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
point=end;
last_attribute=attribute;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'v':
case 'V':
{
/*
Line to.
*/
do
{
(void) GetNextToken(p,&p,MagickPathExtent,token);
if (*token == ',')
(void) GetNextToken(p,&p,MagickPathExtent,token);
y=StringToDouble(token,&next_token);
if (token == next_token)
ThrowPointExpectedException(token,exception);
point.y=(double) (attribute == (int) 'V' ? y : point.y+y);
if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
if (TracePoint(q,point) == MagickFalse)
return(0);
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
while (isspace((int) ((unsigned char) *p)) != 0)
p++;
if (*p == ',')
p++;
} while (IsPoint(p) != MagickFalse);
break;
}
case 'z':
case 'Z':
{
/*
Close path.
*/
point=start;
if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse)
return(0);
q=(*mvg_info->primitive_info)+mvg_info->offset;
if (TracePoint(q,point) == MagickFalse)
return(0);
mvg_info->offset+=q->coordinates;
q+=q->coordinates;
primitive_info=(*mvg_info->primitive_info)+subpath_offset;
primitive_info->coordinates=(size_t) (q-primitive_info);
primitive_info->closed_subpath=MagickTrue;
number_coordinates+=primitive_info->coordinates;
primitive_info=q;
subpath_offset=mvg_info->offset;
z_count++;
break;
}
default:
{
ThrowPointExpectedException(token,exception);
break;
}
}
}
if (status == MagickFalse)
return(0);
primitive_info=(*mvg_info->primitive_info)+subpath_offset;
primitive_info->coordinates=(size_t) (q-primitive_info);
number_coordinates+=primitive_info->coordinates;
for (i=0; i < (ssize_t) number_coordinates; i++)
{
q--;
q->primitive=primitive_type;
if (z_count > 1)
q->method=FillToBorderMethod;
}
q=primitive_info;
return(number_coordinates);
}
static MagickBooleanType TraceRectangle(PrimitiveInfo *primitive_info,
const PointInfo start,const PointInfo end)
{
PointInfo
point;
register PrimitiveInfo
*p;
register ssize_t
i;
p=primitive_info;
if (TracePoint(p,start) == MagickFalse)
return(MagickFalse);
p+=p->coordinates;
point.x=start.x;
point.y=end.y;
if (TracePoint(p,point) == MagickFalse)
return(MagickFalse);
p+=p->coordinates;
if (TracePoint(p,end) == MagickFalse)
return(MagickFalse);
p+=p->coordinates;
point.x=end.x;
point.y=start.y;
if (TracePoint(p,point) == MagickFalse)
return(MagickFalse);
p+=p->coordinates;
if (TracePoint(p,start) == MagickFalse)
return(MagickFalse);
p+=p->coordinates;
primitive_info->coordinates=(size_t) (p-primitive_info);
primitive_info->closed_subpath=MagickTrue;
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
return(MagickTrue);
}
static MagickBooleanType TraceRoundRectangle(MVGInfo *mvg_info,
const PointInfo start,const PointInfo end,PointInfo arc)
{
PointInfo
degrees,
point,
segment;
PrimitiveInfo
*primitive_info;
register PrimitiveInfo
*p;
register ssize_t
i;
ssize_t
offset;
offset=mvg_info->offset;
segment.x=fabs(end.x-start.x);
segment.y=fabs(end.y-start.y);
if ((segment.x < MagickEpsilon) || (segment.y < MagickEpsilon))
{
(*mvg_info->primitive_info+mvg_info->offset)->coordinates=0;
return(MagickTrue);
}
if (arc.x > (0.5*segment.x))
arc.x=0.5*segment.x;
if (arc.y > (0.5*segment.y))
arc.y=0.5*segment.y;
point.x=start.x+segment.x-arc.x;
point.y=start.y+arc.y;
degrees.x=270.0;
degrees.y=360.0;
if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse)
return(MagickFalse);
p=(*mvg_info->primitive_info)+mvg_info->offset;
mvg_info->offset+=p->coordinates;
point.x=start.x+segment.x-arc.x;
point.y=start.y+segment.y-arc.y;
degrees.x=0.0;
degrees.y=90.0;
if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse)
return(MagickFalse);
p=(*mvg_info->primitive_info)+mvg_info->offset;
mvg_info->offset+=p->coordinates;
point.x=start.x+arc.x;
point.y=start.y+segment.y-arc.y;
degrees.x=90.0;
degrees.y=180.0;
if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse)
return(MagickFalse);
p=(*mvg_info->primitive_info)+mvg_info->offset;
mvg_info->offset+=p->coordinates;
point.x=start.x+arc.x;
point.y=start.y+arc.y;
degrees.x=180.0;
degrees.y=270.0;
if (TraceEllipse(mvg_info,point,arc,degrees) == MagickFalse)
return(MagickFalse);
p=(*mvg_info->primitive_info)+mvg_info->offset;
mvg_info->offset+=p->coordinates;
if (CheckPrimitiveExtent(mvg_info,PrimitiveExtentPad) == MagickFalse)
return(MagickFalse);
p=(*mvg_info->primitive_info)+mvg_info->offset;
if (TracePoint(p,(*mvg_info->primitive_info+offset)->point) == MagickFalse)
return(MagickFalse);
p+=p->coordinates;
mvg_info->offset=offset;
primitive_info=(*mvg_info->primitive_info)+offset;
primitive_info->coordinates=(size_t) (p-primitive_info);
primitive_info->closed_subpath=MagickTrue;
for (i=0; i < (ssize_t) primitive_info->coordinates; i++)
{
p->primitive=primitive_info->primitive;
p--;
}
return(MagickTrue);
}
static MagickBooleanType TraceSquareLinecap(PrimitiveInfo *primitive_info,
const size_t number_vertices,const double offset)
{
double
distance;
register double
dx,
dy;
register ssize_t
i;
ssize_t
j;
dx=0.0;
dy=0.0;
for (i=1; i < (ssize_t) number_vertices; i++)
{
dx=primitive_info[0].point.x-primitive_info[i].point.x;
dy=primitive_info[0].point.y-primitive_info[i].point.y;
if ((fabs((double) dx) >= MagickEpsilon) ||
(fabs((double) dy) >= MagickEpsilon))
break;
}
if (i == (ssize_t) number_vertices)
i=(ssize_t) number_vertices-1L;
distance=hypot((double) dx,(double) dy);
primitive_info[0].point.x=(double) (primitive_info[i].point.x+
dx*(distance+offset)/distance);
primitive_info[0].point.y=(double) (primitive_info[i].point.y+
dy*(distance+offset)/distance);
for (j=(ssize_t) number_vertices-2; j >= 0; j--)
{
dx=primitive_info[number_vertices-1].point.x-primitive_info[j].point.x;
dy=primitive_info[number_vertices-1].point.y-primitive_info[j].point.y;
if ((fabs((double) dx) >= MagickEpsilon) ||
(fabs((double) dy) >= MagickEpsilon))
break;
}
distance=hypot((double) dx,(double) dy);
primitive_info[number_vertices-1].point.x=(double) (primitive_info[j].point.x+
dx*(distance+offset)/distance);
primitive_info[number_vertices-1].point.y=(double) (primitive_info[j].point.y+
dy*(distance+offset)/distance);
return(MagickTrue);
}
static PrimitiveInfo *TraceStrokePolygon(const Image *image,
const DrawInfo *draw_info,const PrimitiveInfo *primitive_info)
{
#define CheckPathExtent(pad) \
if ((ssize_t) (q+(pad)) >= (ssize_t) max_strokes) \
{ \
if (~max_strokes < (pad)) \
{ \
path_p=(PointInfo *) RelinquishMagickMemory(path_p); \
path_q=(PointInfo *) RelinquishMagickMemory(path_q); \
} \
else \
{ \
max_strokes+=(pad); \
path_p=(PointInfo *) ResizeQuantumMemory(path_p,max_strokes, \
sizeof(*path_p)); \
path_q=(PointInfo *) ResizeQuantumMemory(path_q,max_strokes, \
sizeof(*path_q)); \
} \
if ((path_p == (PointInfo *) NULL) || (path_q == (PointInfo *) NULL)) \
{ \
if (path_p != (PointInfo *) NULL) \
path_p=(PointInfo *) RelinquishMagickMemory(path_p); \
if (path_q != (PointInfo *) NULL) \
path_q=(PointInfo *) RelinquishMagickMemory(path_q); \
polygon_primitive=(PrimitiveInfo *) \
RelinquishMagickMemory(polygon_primitive); \
return((PrimitiveInfo *) NULL); \
} \
}
typedef struct _LineSegment
{
double
p,
q;
} LineSegment;
double
delta_theta,
dot_product,
mid,
miterlimit;
LineSegment
dx = {0,0},
dy = {0,0},
inverse_slope = {0,0},
slope = {0,0},
theta = {0,0};
MagickBooleanType
closed_path;
PointInfo
box_p[5],
box_q[5],
center,
offset,
*path_p,
*path_q;
PrimitiveInfo
*polygon_primitive,
*stroke_polygon;
register ssize_t
i;
size_t
arc_segments,
max_strokes,
number_vertices;
ssize_t
j,
n,
p,
q;
/*
Allocate paths.
*/
number_vertices=primitive_info->coordinates;
max_strokes=2*number_vertices+6*BezierQuantum+360;
polygon_primitive=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
number_vertices+2UL,sizeof(*polygon_primitive));
if (polygon_primitive == (PrimitiveInfo *) NULL)
return((PrimitiveInfo *) NULL);
(void) memcpy(polygon_primitive,primitive_info,(size_t) number_vertices*
sizeof(*polygon_primitive));
closed_path=primitive_info[0].closed_subpath;
if (((draw_info->linejoin == RoundJoin) ||
(draw_info->linejoin == MiterJoin)) && (closed_path != MagickFalse))
{
polygon_primitive[number_vertices]=primitive_info[1];
number_vertices++;
}
polygon_primitive[number_vertices].primitive=UndefinedPrimitive;
/*
Compute the slope for the first line segment, p.
*/
dx.p=0.0;
dy.p=0.0;
for (n=1; n < (ssize_t) number_vertices; n++)
{
dx.p=polygon_primitive[n].point.x-polygon_primitive[0].point.x;
dy.p=polygon_primitive[n].point.y-polygon_primitive[0].point.y;
if ((fabs(dx.p) >= MagickEpsilon) || (fabs(dy.p) >= MagickEpsilon))
break;
}
if (n == (ssize_t) number_vertices)
{
if ((draw_info->linecap != RoundCap) || (closed_path != MagickFalse))
{
/*
Zero length subpath.
*/
stroke_polygon=(PrimitiveInfo *) AcquireCriticalMemory(
sizeof(*stroke_polygon));
stroke_polygon[0]=polygon_primitive[0];
stroke_polygon[0].coordinates=0;
polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(
polygon_primitive);
return(stroke_polygon);
}
n=(ssize_t) number_vertices-1L;
}
path_p=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,
sizeof(*path_p));
if (path_p == (PointInfo *) NULL)
{
polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(
polygon_primitive);
return((PrimitiveInfo *) NULL);
}
path_q=(PointInfo *) AcquireQuantumMemory((size_t) max_strokes,
sizeof(*path_q));
if (path_q == (PointInfo *) NULL)
{
path_p=(PointInfo *) RelinquishMagickMemory(path_p);
polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(
polygon_primitive);
return((PrimitiveInfo *) NULL);
}
slope.p=0.0;
inverse_slope.p=0.0;
if (fabs(dx.p) < MagickEpsilon)
{
if (dx.p >= 0.0)
slope.p=dy.p < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon;
else
slope.p=dy.p < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon;
}
else
if (fabs(dy.p) < MagickEpsilon)
{
if (dy.p >= 0.0)
inverse_slope.p=dx.p < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon;
else
inverse_slope.p=dx.p < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon;
}
else
{
slope.p=dy.p/dx.p;
inverse_slope.p=(-1.0/slope.p);
}
mid=ExpandAffine(&draw_info->affine)*SaneStrokeWidth(image,draw_info)/2.0;
miterlimit=(double) (draw_info->miterlimit*draw_info->miterlimit*mid*mid);
if ((draw_info->linecap == SquareCap) && (closed_path == MagickFalse))
(void) TraceSquareLinecap(polygon_primitive,number_vertices,mid);
offset.x=sqrt((double) (mid*mid/(inverse_slope.p*inverse_slope.p+1.0)));
offset.y=(double) (offset.x*inverse_slope.p);
if ((dy.p*offset.x-dx.p*offset.y) > 0.0)
{
box_p[0].x=polygon_primitive[0].point.x-offset.x;
box_p[0].y=polygon_primitive[0].point.y-offset.x*inverse_slope.p;
box_p[1].x=polygon_primitive[n].point.x-offset.x;
box_p[1].y=polygon_primitive[n].point.y-offset.x*inverse_slope.p;
box_q[0].x=polygon_primitive[0].point.x+offset.x;
box_q[0].y=polygon_primitive[0].point.y+offset.x*inverse_slope.p;
box_q[1].x=polygon_primitive[n].point.x+offset.x;
box_q[1].y=polygon_primitive[n].point.y+offset.x*inverse_slope.p;
}
else
{
box_p[0].x=polygon_primitive[0].point.x+offset.x;
box_p[0].y=polygon_primitive[0].point.y+offset.y;
box_p[1].x=polygon_primitive[n].point.x+offset.x;
box_p[1].y=polygon_primitive[n].point.y+offset.y;
box_q[0].x=polygon_primitive[0].point.x-offset.x;
box_q[0].y=polygon_primitive[0].point.y-offset.y;
box_q[1].x=polygon_primitive[n].point.x-offset.x;
box_q[1].y=polygon_primitive[n].point.y-offset.y;
}
/*
Create strokes for the line join attribute: bevel, miter, round.
*/
p=0;
q=0;
path_q[p++]=box_q[0];
path_p[q++]=box_p[0];
for (i=(ssize_t) n+1; i < (ssize_t) number_vertices; i++)
{
/*
Compute the slope for this line segment, q.
*/
dx.q=polygon_primitive[i].point.x-polygon_primitive[n].point.x;
dy.q=polygon_primitive[i].point.y-polygon_primitive[n].point.y;
dot_product=dx.q*dx.q+dy.q*dy.q;
if (dot_product < 0.25)
continue;
slope.q=0.0;
inverse_slope.q=0.0;
if (fabs(dx.q) < MagickEpsilon)
{
if (dx.q >= 0.0)
slope.q=dy.q < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon;
else
slope.q=dy.q < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon;
}
else
if (fabs(dy.q) < MagickEpsilon)
{
if (dy.q >= 0.0)
inverse_slope.q=dx.q < 0.0 ? -1.0/MagickEpsilon : 1.0/MagickEpsilon;
else
inverse_slope.q=dx.q < 0.0 ? 1.0/MagickEpsilon : -1.0/MagickEpsilon;
}
else
{
slope.q=dy.q/dx.q;
inverse_slope.q=(-1.0/slope.q);
}
offset.x=sqrt((double) (mid*mid/(inverse_slope.q*inverse_slope.q+1.0)));
offset.y=(double) (offset.x*inverse_slope.q);
dot_product=dy.q*offset.x-dx.q*offset.y;
if (dot_product > 0.0)
{
box_p[2].x=polygon_primitive[n].point.x-offset.x;
box_p[2].y=polygon_primitive[n].point.y-offset.y;
box_p[3].x=polygon_primitive[i].point.x-offset.x;
box_p[3].y=polygon_primitive[i].point.y-offset.y;
box_q[2].x=polygon_primitive[n].point.x+offset.x;
box_q[2].y=polygon_primitive[n].point.y+offset.y;
box_q[3].x=polygon_primitive[i].point.x+offset.x;
box_q[3].y=polygon_primitive[i].point.y+offset.y;
}
else
{
box_p[2].x=polygon_primitive[n].point.x+offset.x;
box_p[2].y=polygon_primitive[n].point.y+offset.y;
box_p[3].x=polygon_primitive[i].point.x+offset.x;
box_p[3].y=polygon_primitive[i].point.y+offset.y;
box_q[2].x=polygon_primitive[n].point.x-offset.x;
box_q[2].y=polygon_primitive[n].point.y-offset.y;
box_q[3].x=polygon_primitive[i].point.x-offset.x;
box_q[3].y=polygon_primitive[i].point.y-offset.y;
}
if (fabs((double) (slope.p-slope.q)) < MagickEpsilon)
{
box_p[4]=box_p[1];
box_q[4]=box_q[1];
}
else
{
box_p[4].x=(double) ((slope.p*box_p[0].x-box_p[0].y-slope.q*box_p[3].x+
box_p[3].y)/(slope.p-slope.q));
box_p[4].y=(double) (slope.p*(box_p[4].x-box_p[0].x)+box_p[0].y);
box_q[4].x=(double) ((slope.p*box_q[0].x-box_q[0].y-slope.q*box_q[3].x+
box_q[3].y)/(slope.p-slope.q));
box_q[4].y=(double) (slope.p*(box_q[4].x-box_q[0].x)+box_q[0].y);
}
CheckPathExtent(6*BezierQuantum+360);
dot_product=dx.q*dy.p-dx.p*dy.q;
if (dot_product <= 0.0)
switch (draw_info->linejoin)
{
case BevelJoin:
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_p[p++]=box_p[4];
else
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case MiterJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
{
path_q[q++]=box_q[4];
path_p[p++]=box_p[4];
}
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case RoundJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_p[p++]=box_p[4];
else
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
center=polygon_primitive[n].point;
theta.p=atan2(box_q[1].y-center.y,box_q[1].x-center.x);
theta.q=atan2(box_q[2].y-center.y,box_q[2].x-center.x);
if (theta.q < theta.p)
theta.q+=2.0*MagickPI;
arc_segments=(size_t) ceil((double) ((theta.q-theta.p)/
(2.0*sqrt((double) (1.0/mid)))));
CheckPathExtent(arc_segments+6*BezierQuantum+360);
path_q[q].x=box_q[1].x;
path_q[q].y=box_q[1].y;
q++;
for (j=1; j < (ssize_t) arc_segments; j++)
{
delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);
path_q[q].x=(double) (center.x+mid*cos(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
path_q[q].y=(double) (center.y+mid*sin(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
q++;
}
path_q[q++]=box_q[2];
break;
}
default:
break;
}
else
switch (draw_info->linejoin)
{
case BevelJoin:
{
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_q[q++]=box_q[4];
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
}
break;
}
case MiterJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
{
path_q[q++]=box_q[4];
path_p[p++]=box_p[4];
}
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
path_p[p++]=box_p[1];
path_p[p++]=box_p[2];
}
break;
}
case RoundJoin:
{
dot_product=(box_q[4].x-box_p[4].x)*(box_q[4].x-box_p[4].x)+
(box_q[4].y-box_p[4].y)*(box_q[4].y-box_p[4].y);
if (dot_product <= miterlimit)
path_q[q++]=box_q[4];
else
{
path_q[q++]=box_q[1];
path_q[q++]=box_q[2];
}
center=polygon_primitive[n].point;
theta.p=atan2(box_p[1].y-center.y,box_p[1].x-center.x);
theta.q=atan2(box_p[2].y-center.y,box_p[2].x-center.x);
if (theta.p < theta.q)
theta.p+=2.0*MagickPI;
arc_segments=(size_t) ceil((double) ((theta.p-theta.q)/
(2.0*sqrt((double) (1.0/mid)))));
CheckPathExtent(arc_segments+6*BezierQuantum+360);
path_p[p++]=box_p[1];
for (j=1; j < (ssize_t) arc_segments; j++)
{
delta_theta=(double) (j*(theta.q-theta.p)/arc_segments);
path_p[p].x=(double) (center.x+mid*cos(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
path_p[p].y=(double) (center.y+mid*sin(fmod((double)
(theta.p+delta_theta),DegreesToRadians(360.0))));
p++;
}
path_p[p++]=box_p[2];
break;
}
default:
break;
}
slope.p=slope.q;
inverse_slope.p=inverse_slope.q;
box_p[0]=box_p[2];
box_p[1]=box_p[3];
box_q[0]=box_q[2];
box_q[1]=box_q[3];
dx.p=dx.q;
dy.p=dy.q;
n=i;
}
path_p[p++]=box_p[1];
path_q[q++]=box_q[1];
/*
Trace stroked polygon.
*/
stroke_polygon=(PrimitiveInfo *) AcquireQuantumMemory((size_t)
(p+q+2UL*closed_path+2UL),sizeof(*stroke_polygon));
if (stroke_polygon != (PrimitiveInfo *) NULL)
{
for (i=0; i < (ssize_t) p; i++)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=path_p[i];
}
if (closed_path != MagickFalse)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[0].point;
i++;
}
for ( ; i < (ssize_t) (p+q+closed_path); i++)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=path_q[p+q+closed_path-(i+1)];
}
if (closed_path != MagickFalse)
{
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[p+closed_path].point;
i++;
}
stroke_polygon[i]=polygon_primitive[0];
stroke_polygon[i].point=stroke_polygon[0].point;
i++;
stroke_polygon[i].primitive=UndefinedPrimitive;
stroke_polygon[0].coordinates=(size_t) (p+q+2*closed_path+1);
}
path_p=(PointInfo *) RelinquishMagickMemory(path_p);
path_q=(PointInfo *) RelinquishMagickMemory(path_q);
polygon_primitive=(PrimitiveInfo *) RelinquishMagickMemory(polygon_primitive);
return(stroke_polygon);
}
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_1186_0 |
crossvul-cpp_data_bad_1017_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 "MagickCore/studio.h"
#include "MagickCore/attribute.h"
#include "MagickCore/blob.h"
#include "MagickCore/blob-private.h"
#include "MagickCore/cache.h"
#include "MagickCore/color-private.h"
#include "MagickCore/colormap.h"
#include "MagickCore/colorspace-private.h"
#include "MagickCore/distort.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/image-private.h"
#include "MagickCore/list.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/monitor.h"
#include "MagickCore/monitor-private.h"
#include "MagickCore/pixel-accessor.h"
#include "MagickCore/quantum.h"
#include "MagickCore/quantum-private.h"
#include "MagickCore/option.h"
#include "MagickCore/pixel.h"
#include "MagickCore/resource_.h"
#include "MagickCore/static.h"
#include "MagickCore/string_.h"
#include "MagickCore/module.h"
#include "MagickCore/timer-private.h"
#include "MagickCore/transform.h"
#include "MagickCore/utility-private.h"
#if defined(MAGICKCORE_ZLIB_DELEGATE)
#include "zlib.h"
#endif
/*
Forward declaration.
*/
static MagickBooleanType
WriteMATImage(const ImageInfo *,Image *,ExceptionInfo *);
/* 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 int DataType;
unsigned int ObjectSize;
unsigned int unknown1;
unsigned int unknown2;
unsigned short unknown5;
unsigned char StructureFlag;
unsigned char StructureClass;
unsigned int unknown3;
unsigned int unknown4;
unsigned int DimFlag;
unsigned int SizeX;
unsigned int 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=
#if defined(MAGICKCORE_WINDOWS_SUPPORT)
"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(Image *image,double *p,int y,double MinVal,
double MaxVal,ExceptionInfo *exception)
{
double f;
int x;
register Quantum *q;
if (MinVal >= 0)
MinVal = -1;
if (MaxVal <= 0)
MaxVal = 1;
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
return;
for (x = 0; x < (ssize_t) image->columns; x++)
{
if (*p > 0)
{
f=(*p/MaxVal)*(Quantum) (QuantumRange-GetPixelRed(image,q));
if ((f+GetPixelRed(image,q)) >= QuantumRange)
SetPixelRed(image,QuantumRange,q);
else
SetPixelRed(image,GetPixelRed(image,q)+ClampToQuantum(f),q);
f=GetPixelGreen(image,q)-f/2.0;
if (f <= 0.0)
{
SetPixelGreen(image,0,q);
SetPixelBlue(image,0,q);
}
else
{
SetPixelBlue(image,ClampToQuantum(f),q);
SetPixelGreen(image,ClampToQuantum(f),q);
}
}
if (*p < 0)
{
f=(*p/MinVal)*(Quantum) (QuantumRange-GetPixelBlue(image,q));
if ((f+GetPixelBlue(image,q)) >= QuantumRange)
SetPixelBlue(image,QuantumRange,q);
else
SetPixelBlue(image,GetPixelBlue(image,q)+ClampToQuantum(f),q);
f=GetPixelGreen(image,q)-f/2.0;
if (f <= 0.0)
{
SetPixelRed(image,0,q);
SetPixelGreen(image,0,q);
}
else
{
SetPixelRed(image,ClampToQuantum(f),q);
SetPixelGreen(image,ClampToQuantum(f),q);
}
}
p++;
q++;
}
if (!SyncAuthenticPixels(image,exception))
return;
return;
}
static void InsertComplexFloatRow(Image *image,float *p,int y,double MinVal,
double MaxVal,ExceptionInfo *exception)
{
double f;
int x;
register Quantum *q;
if (MinVal >= 0)
MinVal = -1;
if (MaxVal <= 0)
MaxVal = 1;
q = QueueAuthenticPixels(image, 0, y, image->columns, 1,exception);
if (q == (Quantum *) NULL)
return;
for (x = 0; x < (ssize_t) image->columns; x++)
{
if (*p > 0)
{
f=(*p/MaxVal)*(Quantum) (QuantumRange-GetPixelRed(image,q));
if ((f+GetPixelRed(image,q)) < QuantumRange)
SetPixelRed(image,GetPixelRed(image,q)+ClampToQuantum(f),q);
else
SetPixelRed(image,QuantumRange,q);
f/=2.0;
if (f < GetPixelGreen(image,q))
{
SetPixelBlue(image,GetPixelBlue(image,q)-ClampToQuantum(f),q);
SetPixelGreen(image,GetPixelBlue(image,q),q);
}
else
{
SetPixelGreen(image,0,q);
SetPixelBlue(image,0,q);
}
}
if (*p < 0)
{
f=(*p/MaxVal)*(Quantum) (QuantumRange-GetPixelBlue(image,q));
if ((f+GetPixelBlue(image,q)) < QuantumRange)
SetPixelBlue(image,GetPixelBlue(image,q)+ClampToQuantum(f),q);
else
SetPixelBlue(image,QuantumRange,q);
f/=2.0;
if (f < GetPixelGreen(image,q))
{
SetPixelRed(image,GetPixelRed(image,q)-ClampToQuantum(f),q);
SetPixelGreen(image,GetPixelRed(image,q),q);
}
else
{
SetPixelGreen(image,0,q);
SetPixelRed(image,0,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(const Image *image,Quantum *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(image,GetPixelRed(image,q)+QuantumRange/2+1,q);
SetPixelGreen(image,GetPixelGreen(image,q)+QuantumRange/2+1,q);
SetPixelBlue(image,GetPixelBlue(image,q)+QuantumRange/2+1,q);
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 *decompress_block(Image *orig, unsigned int *Size, ImageInfo *clone_info, ExceptionInfo *exception)
{
Image *image2;
void *cache_block, *decompress_block;
z_stream zip_info;
FILE *mat_file;
size_t magick_size;
size_t extent;
int file;
int status;
int zip_status;
ssize_t TotalSize = 0;
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);
}
cache_block = AcquireQuantumMemory((size_t)(*Size < 16384) ? *Size: 16384,sizeof(unsigned char *));
if(cache_block==NULL) return NULL;
decompress_block = AcquireQuantumMemory((size_t)(4096),sizeof(unsigned char *));
if(decompress_block==NULL)
{
RelinquishMagickMemory(cache_block);
return NULL;
}
mat_file=0;
file = AcquireUniqueFileResource(clone_info->filename);
if (file != -1)
mat_file = fdopen(file,"w");
if(!mat_file)
{
RelinquishMagickMemory(cache_block);
RelinquishMagickMemory(decompress_block);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"Cannot create file stream for decompressed image");
return NULL;
}
zip_info.zalloc=AcquireZIPMemory;
zip_info.zfree=RelinquishZIPMemory;
zip_info.opaque = (voidpf) NULL;
zip_status = inflateInit(&zip_info);
if (zip_status != Z_OK)
{
RelinquishMagickMemory(cache_block);
RelinquishMagickMemory(decompress_block);
(void) ThrowMagickException(exception,GetMagickModule(),CorruptImageError,
"UnableToUncompressImage","`%s'",clone_info->filename);
(void) fclose(mat_file);
RelinquishUniqueFileResource(clone_info->filename);
return NULL;
}
/* 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 *) cache_block);
if (magick_size == 0)
break;
zip_info.next_in = (Bytef *) cache_block;
zip_info.avail_in = (uInt) magick_size;
while(zip_info.avail_in>0)
{
zip_info.avail_out = 4096;
zip_info.next_out = (Bytef *) decompress_block;
zip_status = inflate(&zip_info,Z_NO_FLUSH);
if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END))
break;
extent=fwrite(decompress_block, 4096-zip_info.avail_out, 1, mat_file);
(void) extent;
TotalSize += 4096-zip_info.avail_out;
if(zip_status == Z_STREAM_END) goto DblBreak;
}
if ((zip_status != Z_OK) && (zip_status != Z_STREAM_END))
break;
*Size -= (unsigned int) magick_size;
}
DblBreak:
inflateEnd(&zip_info);
(void)fclose(mat_file);
RelinquishMagickMemory(cache_block);
RelinquishMagickMemory(decompress_block);
*Size = TotalSize;
if((clone_info->file=fopen(clone_info->filename,"rb"))==NULL) goto UnlinkFile;
if( (image2 = AcquireImage(clone_info,exception))==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:
RelinquishUniqueFileResource(clone_info->filename);
return NULL;
}
return image2;
}
#endif
static Image *ReadMATImageV4(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
typedef struct {
unsigned char Type[4];
unsigned int nRows;
unsigned int nCols;
unsigned int imagf;
unsigned int nameLen;
} MAT4_HDR;
long
ldblk;
EndianType
endian;
Image
*rotated_image;
MagickBooleanType
status;
MAT4_HDR
HDR;
QuantumInfo
*quantum_info;
QuantumFormatType
format_type;
register ssize_t
i;
ssize_t
count,
y;
unsigned char
*pixels;
unsigned int
depth;
quantum_info=(QuantumInfo *) NULL;
(void) SeekBlob(image,0,SEEK_SET);
status=MagickTrue;
while (EOFBlob(image) == MagickFalse)
{
/*
Object parser loop.
*/
ldblk=ReadBlobLSBLong(image);
if ((ldblk > 9999) || (ldblk < 0))
break;
HDR.Type[3]=ldblk % 10; ldblk /= 10; /* T digit */
HDR.Type[2]=ldblk % 10; ldblk /= 10; /* P digit */
HDR.Type[1]=ldblk % 10; ldblk /= 10; /* O digit */
HDR.Type[0]=ldblk; /* M digit */
if (HDR.Type[3] != 0)
break; /* Data format */
if (HDR.Type[2] != 0)
break; /* Always 0 */
if (HDR.Type[0] == 0)
{
HDR.nRows=ReadBlobLSBLong(image);
HDR.nCols=ReadBlobLSBLong(image);
HDR.imagf=ReadBlobLSBLong(image);
HDR.nameLen=ReadBlobLSBLong(image);
endian=LSBEndian;
}
else
{
HDR.nRows=ReadBlobMSBLong(image);
HDR.nCols=ReadBlobMSBLong(image);
HDR.imagf=ReadBlobMSBLong(image);
HDR.nameLen=ReadBlobMSBLong(image);
endian=MSBEndian;
}
if ((HDR.imagf != 0) && (HDR.imagf != 1))
break;
if (HDR.nameLen > 0xFFFF)
return(DestroyImageList(image));
for (i=0; i < (ssize_t) HDR.nameLen; i++)
{
int
byte;
/*
Skip matrix name.
*/
byte=ReadBlobByte(image);
if (byte == EOF)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
}
image->columns=(size_t) HDR.nRows;
image->rows=(size_t) HDR.nCols;
if ((image->columns == 0) || (image->rows == 0))
return(DestroyImageList(image));
if (image_info->ping != MagickFalse)
{
Swap(image->columns,image->rows);
if(HDR.imagf==1) ldblk *= 2;
SeekBlob(image, HDR.nCols*ldblk, SEEK_CUR);
if ((image->columns == 0) || (image->rows == 0))
return(image->previous == (Image *) NULL ? DestroyImageList(image)
: image);
goto skip_reading_current;
}
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
return(DestroyImageList(image));
(void) SetImageBackgroundColor(image,exception);
(void) SetImageColorspace(image,GRAYColorspace,exception);
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
return(DestroyImageList(image));
switch(HDR.Type[1])
{
case 0:
format_type=FloatingPointQuantumFormat;
depth=64;
break;
case 1:
format_type=FloatingPointQuantumFormat;
depth=32;
break;
case 2:
format_type=UnsignedQuantumFormat;
depth=16;
break;
case 3:
format_type=SignedQuantumFormat;
depth=16;
break;
case 4:
format_type=UnsignedQuantumFormat;
depth=8;
break;
default:
format_type=UnsignedQuantumFormat;
depth=8;
break;
}
image->depth=depth;
if (HDR.Type[0] != 0)
SetQuantumEndian(image,quantum_info,MSBEndian);
status=SetQuantumFormat(image,quantum_info,format_type);
status=SetQuantumDepth(image,quantum_info,depth);
status=SetQuantumEndian(image,quantum_info,endian);
SetQuantumScale(quantum_info,1.0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
for (y=0; y < (ssize_t) image->rows; y++)
{
register Quantum
*magick_restrict q;
count=ReadBlob(image,depth/8*image->columns,(char *) pixels);
if (count == -1)
break;
q=QueueAuthenticPixels(image,0,image->rows-y-1,image->columns,1,
exception);
if (q == (Quantum *) NULL)
break;
(void) ImportQuantumPixels(image,(CacheView *) NULL,quantum_info,
GrayQuantum,pixels,exception);
if ((HDR.Type[1] == 2) || (HDR.Type[1] == 3))
FixSignedValues(image,q,(int) image->columns);
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (HDR.imagf == 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
/*
Read complex pixels.
*/
count=ReadBlob(image,depth/8*image->columns,(char *) pixels);
if (count == -1)
break;
if (HDR.Type[1] == 0)
InsertComplexDoubleRow(image,(double *) pixels,y,0,0,exception);
else
InsertComplexFloatRow(image,(float *) pixels,y,0,0,exception);
}
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
rotated_image=RotateImage(image,90.0,exception);
if (rotated_image != (Image *) NULL)
{
rotated_image->page.x=0;
rotated_image->page.y=0;
rotated_image->colors = image->colors;
DestroyBlob(rotated_image);
rotated_image->blob=ReferenceBlob(image->blob);
AppendImageToList(&image,rotated_image);
DeleteImageFromList(&image);
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
/*
Allocate next image structure.
*/
skip_reading_current:
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
status=MagickFalse;
break;
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
(void) CloseBlob(image);
if (status == MagickFalse)
return(DestroyImageList(image));
return(GetFirstImageInList(image));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% 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;
register Quantum *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;
unsigned z, z2;
unsigned Frames;
int logging;
int sample_size;
MagickOffsetType filepos=0x80;
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 == MagickCoreSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
logging = LogMagickEvent(CoderEvent,GetMagickModule(),"enter");
/*
Open image file.
*/
image = AcquireImage(image_info,exception);
image2 = (Image *) NULL;
status = OpenBlob(image_info, image, ReadBinaryBlobMode, exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read MATLAB image.
*/
quantum_info=(QuantumInfo *) NULL;
clone_info=(ImageInfo *) NULL;
if (ReadBlob(image,124,(unsigned char *) &MATLAB_HDR.identific) != 124)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (strncmp(MATLAB_HDR.identific,"MATLAB",6) != 0)
{
image=ReadMATImageV4(image_info,image,exception);
if (image == NULL)
{
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
return((Image *) NULL);
}
goto END_OF_READING;
}
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
{
MATLAB_KO:
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
filepos = TellBlob(image);
while(!EOFBlob(image)) /* object parser loop */
{
Frames = 1;
if (filepos != (unsigned int) filepos)
break;
if(SeekBlob(image,filepos,SEEK_SET) != filepos) break;
/* printf("pos=%X\n",TellBlob(image)); */
MATLAB_HDR.DataType = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
MATLAB_HDR.ObjectSize = ReadBlobXXXLong(image);
if(EOFBlob(image)) break;
if((MagickSizeType) (MATLAB_HDR.ObjectSize+filepos) > GetBlobSize(image))
goto MATLAB_KO;
filepos += (MagickOffsetType) MATLAB_HDR.ObjectSize + 4 + 4;
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
clone_info=CloneImageInfo(image_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
image2 = image;
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if(MATLAB_HDR.DataType == miCOMPRESSED)
{
image2 = decompress_block(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)
{
clone_info=DestroyImageInfo(clone_info);
#if defined(MAGICKCORE_ZLIB_DELEGATE)
if (image2 != image)
DeleteImageFromList(&image2);
#endif
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*/
(void) ReadBlobXXXLong(image2);
if(z!=3)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CoderError,
"MultidimensionalMatricesAreNotSupported");
}
break;
case 16: z2=z = ReadBlobXXXLong(image2); /* 4D matrix animation */
if(z!=3 && z!=1)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CoderError,
"MultidimensionalMatricesAreNotSupported");
}
Frames = ReadBlobXXXLong(image2);
if (Frames == 0)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
if (AcquireMagickResource(ListLengthResource,Frames) == MagickFalse)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(ResourceLimitError,"ListLengthExceedsLimit");
}
break;
default:
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
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 */
{
if ((image2 != (Image*) NULL) && (image2 != image))
{
CloseBlob(image2);
DeleteImageFromList(&image2);
}
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CoderError,"UnsupportedCellTypeInTheMatrix");
}
switch (MATLAB_HDR.NameFlag)
{
case 0:
size = ReadBlobXXXLong(image2); /* Object name string size */
size = 4 * (((size_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);
/* data size */
if (ReadBlob(image2, 4, (unsigned char *) &size) != 4)
goto MATLAB_KO;
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
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(CoderError, "IncompatibleSizeOfDouble");
}
if (MATLAB_HDR.StructureFlag & FLAG_COMPLEX)
{ /* complex double type cell */
}
ldblk = (ssize_t) (8 * MATLAB_HDR.SizeX);
break;
default:
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
ThrowReaderException(CoderError, "UnsupportedCellTypeInTheMatrix");
}
(void) sample_size;
image->columns = MATLAB_HDR.SizeX;
image->rows = MATLAB_HDR.SizeY;
image->colors = GetQuantumRange(image->depth);
if (image->columns == 0 || image->rows == 0)
goto MATLAB_KO;
if((unsigned int)ldblk*MATLAB_HDR.SizeY > MATLAB_HDR.ObjectSize)
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))
{
image->type=GrayscaleType;
SetImageColorspace(image,GRAYColorspace,exception);
}
/*
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,exception);
if (status == MagickFalse)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
return(DestroyImageList(image));
}
(void) SetImageBackgroundColor(image,exception);
quantum_info=AcquireQuantumInfo(clone_info,image);
if (quantum_info == (QuantumInfo *) NULL)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
/* ----- Load raster data ----- */
BImgBuff = (unsigned char *) AcquireQuantumMemory((size_t) (ldblk),sizeof(double)); /* Ldblk was set in the check phase */
if (BImgBuff == NULL)
{
if (clone_info != (ImageInfo *) NULL)
clone_info=DestroyImageInfo(clone_info);
if ((image != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
}
(void) memset(BImgBuff,0,ldblk*sizeof(double));
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 == (Quantum *) 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(image,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:
if (i != (long) MATLAB_HDR.SizeY)
goto END_OF_READING;
/* 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);
if (EOFBlob(image) != MagickFalse)
break;
InsertComplexDoubleRow(image, (double *)BImgBuff, i, MinVal, MaxVal,
exception);
}
if (CellType==miSINGLE)
for (i = 0; i < (ssize_t) MATLAB_HDR.SizeY; i++)
{
ReadBlobFloatsXXX(image2, ldblk, (float *)BImgBuff);
if (EOFBlob(image) != MagickFalse)
break;
InsertComplexFloatRow(image,(float *)BImgBuff,i,MinVal,MaxVal,
exception);
}
}
/* 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;
rotated_image->colors = image->colors;
DestroyBlob(rotated_image);
rotated_image->blob=ReferenceBlob(image->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);
}
}
}
if (EOFBlob(image) != MagickFalse)
break;
/* Allocate next image structure. */
AcquireNextImage(image_info,image,exception);
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 (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if(--Frames>0)
{
z = z2;
if(image2==NULL) image2 = image;
if(!EOFBlob(image) && TellBlob(image)<filepos)
goto NEXT_FRAME;
}
if ((image2!=NULL) && (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) remove_utf8(clone_info->filename);
}
}
}
if (clone_info)
clone_info=DestroyImageInfo(clone_info);
}
END_OF_READING:
RelinquishMagickMemory(BImgBuff);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
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;
if (tmp == image2)
image2=(Image *) NULL;
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 != image2) && (image2 != (Image *) NULL))
image2=DestroyImage(image2);
if (image == (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=AcquireMagickInfo("MAT","MAT","MATLAB level 5 image format");
entry->decoder=(DecodeImageHandler *) ReadMATImage;
entry->encoder=(EncodeImageHandler *) WriteMATImage;
entry->flags^=CoderBlobSupportFlag;
entry->flags|=CoderDecoderSeekableStreamFlag;
(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:
%
% MagickBooleanType WriteMATImage(const ImageInfo *image_info,
% Image *image,ExceptionInfo *exception)
%
% A description of each parameter follows.
%
% o image_info: Specifies a pointer to a ImageInfo structure.
%
% o image: A pointer to an Image structure.
%
% o exception: return any errors or warnings in this structure.
%
*/
static MagickBooleanType WriteMATImage(const ImageInfo *image_info,Image *image,
ExceptionInfo *exception)
{
char
MATLAB_HDR[0x80];
MagickBooleanType
status;
MagickOffsetType
scene;
size_t
imageListLength;
struct tm
utc_time;
time_t
current_time;
/*
Open output image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
assert(image != (Image *) NULL);
assert(image->signature == MagickCoreSignature);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"enter MAT");
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
if (status == MagickFalse)
return(MagickFalse);
image->depth=8;
current_time=GetMagickTime();
GetMagickUTCtime(¤t_time,&utc_time);
(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[utc_time.tm_wday],MonthsTab[utc_time.tm_mon],
utc_time.tm_mday,utc_time.tm_hour,utc_time.tm_min,
utc_time.tm_sec,utc_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;
imageListLength=GetImageListLength(image);
do
{
char
padding;
MagickBooleanType
is_gray;
QuantumInfo
*quantum_info;
size_t
data_size;
unsigned char
*pixels;
unsigned int
z;
(void) TransformImageColorspace(image,sRGBColorspace,exception);
is_gray=SetImageGray(image,exception);
z=(is_gray != MagickFalse) ? 0 : 3;
/*
Store MAT header.
*/
data_size = image->rows * image->columns;
if (is_gray == MagickFalse)
data_size*=3;
padding=((unsigned char)(data_size-1) & 0x7) ^ 0x7;
(void) WriteBlobLSBLong(image,miMATRIX);
(void) WriteBlobLSBLong(image,(unsigned int) data_size+padding+
((is_gray != MagickFalse) ? 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 != MagickFalse) ? 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 == MagickFalse)
{
(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) data_size); /* 0xBC */
/*
Store image data.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
do
{
const Quantum
*p;
ssize_t
y;
for (y=0; y < (ssize_t) image->columns; y++)
{
size_t
length;
p=GetVirtualPixels(image,y,0,1,image->rows,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info,
z2qtype[z],pixels,exception);
if (length != image->columns)
break;
if (WriteBlob(image,image->rows,pixels) != (ssize_t) image->rows)
break;
}
if (y < (ssize_t) image->columns)
break;
if (SyncAuthenticPixels(image,exception) == MagickFalse)
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++,imageListLength);
if (status == MagickFalse)
break;
} while (image_info->adjoin != MagickFalse);
(void) CloseBlob(image);
return(status);
}
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_1017_0 |
crossvul-cpp_data_bad_5516_1 | /*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Jani Lehtimäki <jkl@njet.net> |
| Thies C. Arntzen <thies@thieso.net> |
| Sascha Schumann <sascha@schumann.cx> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
/* {{{ includes
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "php.h"
#include "php_string.h"
#include "php_var.h"
#include "zend_smart_str.h"
#include "basic_functions.h"
#include "php_incomplete_class.h"
#define COMMON (is_ref ? "&" : "")
/* }}} */
static void php_array_element_dump(zval *zv, zend_ulong index, zend_string *key, int level) /* {{{ */
{
if (key == NULL) { /* numeric key */
php_printf("%*c[" ZEND_LONG_FMT "]=>\n", level + 1, ' ', index);
} else { /* string key */
php_printf("%*c[\"", level + 1, ' ');
PHPWRITE(ZSTR_VAL(key), ZSTR_LEN(key));
php_printf("\"]=>\n");
}
php_var_dump(zv, level + 2);
}
/* }}} */
static void php_object_property_dump(zval *zv, zend_ulong index, zend_string *key, int level) /* {{{ */
{
const char *prop_name, *class_name;
if (key == NULL) { /* numeric key */
php_printf("%*c[" ZEND_LONG_FMT "]=>\n", level + 1, ' ', index);
} else { /* string key */
int unmangle = zend_unmangle_property_name(key, &class_name, &prop_name);
php_printf("%*c[", level + 1, ' ');
if (class_name && unmangle == SUCCESS) {
if (class_name[0] == '*') {
php_printf("\"%s\":protected", prop_name);
} else {
php_printf("\"%s\":\"%s\":private", prop_name, class_name);
}
} else {
php_printf("\"");
PHPWRITE(ZSTR_VAL(key), ZSTR_LEN(key));
php_printf("\"");
}
ZEND_PUTS("]=>\n");
}
php_var_dump(zv, level + 2);
}
/* }}} */
PHPAPI void php_var_dump(zval *struc, int level) /* {{{ */
{
HashTable *myht;
zend_string *class_name;
int is_temp;
int is_ref = 0;
zend_ulong num;
zend_string *key;
zval *val;
uint32_t count;
if (level > 1) {
php_printf("%*c", level - 1, ' ');
}
again:
switch (Z_TYPE_P(struc)) {
case IS_FALSE:
php_printf("%sbool(false)\n", COMMON);
break;
case IS_TRUE:
php_printf("%sbool(true)\n", COMMON);
break;
case IS_NULL:
php_printf("%sNULL\n", COMMON);
break;
case IS_LONG:
php_printf("%sint(" ZEND_LONG_FMT ")\n", COMMON, Z_LVAL_P(struc));
break;
case IS_DOUBLE:
php_printf("%sfloat(%.*G)\n", COMMON, (int) EG(precision), Z_DVAL_P(struc));
break;
case IS_STRING:
php_printf("%sstring(%zd) \"", COMMON, Z_STRLEN_P(struc));
PHPWRITE(Z_STRVAL_P(struc), Z_STRLEN_P(struc));
PUTS("\"\n");
break;
case IS_ARRAY:
myht = Z_ARRVAL_P(struc);
if (level > 1 && ZEND_HASH_APPLY_PROTECTION(myht) && ++myht->u.v.nApplyCount > 1) {
PUTS("*RECURSION*\n");
--myht->u.v.nApplyCount;
return;
}
count = zend_array_count(myht);
php_printf("%sarray(%d) {\n", COMMON, count);
is_temp = 0;
ZEND_HASH_FOREACH_KEY_VAL_IND(myht, num, key, val) {
php_array_element_dump(val, num, key, level);
} ZEND_HASH_FOREACH_END();
if (level > 1 && ZEND_HASH_APPLY_PROTECTION(myht)) {
--myht->u.v.nApplyCount;
}
if (is_temp) {
zend_hash_destroy(myht);
efree(myht);
}
if (level > 1) {
php_printf("%*c", level-1, ' ');
}
PUTS("}\n");
break;
case IS_OBJECT:
if (Z_OBJ_APPLY_COUNT_P(struc) > 0) {
PUTS("*RECURSION*\n");
return;
}
Z_OBJ_INC_APPLY_COUNT_P(struc);
myht = Z_OBJDEBUG_P(struc, is_temp);
class_name = Z_OBJ_HANDLER_P(struc, get_class_name)(Z_OBJ_P(struc));
php_printf("%sobject(%s)#%d (%d) {\n", COMMON, ZSTR_VAL(class_name), Z_OBJ_HANDLE_P(struc), myht ? zend_array_count(myht) : 0);
zend_string_release(class_name);
if (myht) {
zend_ulong num;
zend_string *key;
zval *val;
ZEND_HASH_FOREACH_KEY_VAL_IND(myht, num, key, val) {
php_object_property_dump(val, num, key, level);
} ZEND_HASH_FOREACH_END();
if (is_temp) {
zend_hash_destroy(myht);
efree(myht);
}
}
if (level > 1) {
php_printf("%*c", level-1, ' ');
}
PUTS("}\n");
Z_OBJ_DEC_APPLY_COUNT_P(struc);
break;
case IS_RESOURCE: {
const char *type_name = zend_rsrc_list_get_rsrc_type(Z_RES_P(struc));
php_printf("%sresource(%pd) of type (%s)\n", COMMON, Z_RES_P(struc)->handle, type_name ? type_name : "Unknown");
break;
}
case IS_REFERENCE:
//??? hide references with refcount==1 (for compatibility)
if (Z_REFCOUNT_P(struc) > 1) {
is_ref = 1;
}
struc = Z_REFVAL_P(struc);
goto again;
break;
default:
php_printf("%sUNKNOWN:0\n", COMMON);
break;
}
}
/* }}} */
/* {{{ proto void var_dump(mixed var)
Dumps a string representation of variable to output */
PHP_FUNCTION(var_dump)
{
zval *args;
int argc;
int i;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "+", &args, &argc) == FAILURE) {
return;
}
for (i = 0; i < argc; i++) {
php_var_dump(&args[i], 1);
}
}
/* }}} */
static void zval_array_element_dump(zval *zv, zend_ulong index, zend_string *key, int level) /* {{{ */
{
if (key == NULL) { /* numeric key */
php_printf("%*c[" ZEND_LONG_FMT "]=>\n", level + 1, ' ', index);
} else { /* string key */
php_printf("%*c[\"", level + 1, ' ');
PHPWRITE(ZSTR_VAL(key), ZSTR_LEN(key));
php_printf("\"]=>\n");
}
php_debug_zval_dump(zv, level + 2);
}
/* }}} */
static void zval_object_property_dump(zval *zv, zend_ulong index, zend_string *key, int level) /* {{{ */
{
const char *prop_name, *class_name;
if (key == NULL) { /* numeric key */
php_printf("%*c[" ZEND_LONG_FMT "]=>\n", level + 1, ' ', index);
} else { /* string key */
zend_unmangle_property_name(key, &class_name, &prop_name);
php_printf("%*c[", level + 1, ' ');
if (class_name) {
if (class_name[0] == '*') {
php_printf("\"%s\":protected", prop_name);
} else {
php_printf("\"%s\":\"%s\":private", prop_name, class_name);
}
} else {
php_printf("\"%s\"", prop_name);
}
ZEND_PUTS("]=>\n");
}
php_debug_zval_dump(zv, level + 2);
}
/* }}} */
PHPAPI void php_debug_zval_dump(zval *struc, int level) /* {{{ */
{
HashTable *myht = NULL;
zend_string *class_name;
int is_temp = 0;
int is_ref = 0;
zend_ulong index;
zend_string *key;
zval *val;
uint32_t count;
if (level > 1) {
php_printf("%*c", level - 1, ' ');
}
again:
switch (Z_TYPE_P(struc)) {
case IS_FALSE:
php_printf("%sbool(false)\n", COMMON);
break;
case IS_TRUE:
php_printf("%sbool(true)\n", COMMON);
break;
case IS_NULL:
php_printf("%sNULL\n", COMMON);
break;
case IS_LONG:
php_printf("%sint(" ZEND_LONG_FMT ")\n", COMMON, Z_LVAL_P(struc));
break;
case IS_DOUBLE:
php_printf("%sfloat(%.*G)\n", COMMON, (int) EG(precision), Z_DVAL_P(struc));
break;
case IS_STRING:
php_printf("%sstring(%zd) \"", COMMON, Z_STRLEN_P(struc));
PHPWRITE(Z_STRVAL_P(struc), Z_STRLEN_P(struc));
php_printf("\" refcount(%u)\n", Z_REFCOUNTED_P(struc) ? Z_REFCOUNT_P(struc) : 1);
break;
case IS_ARRAY:
myht = Z_ARRVAL_P(struc);
if (level > 1 && ZEND_HASH_APPLY_PROTECTION(myht) && myht->u.v.nApplyCount++ > 1) {
myht->u.v.nApplyCount--;
PUTS("*RECURSION*\n");
return;
}
count = zend_array_count(myht);
php_printf("%sarray(%d) refcount(%u){\n", COMMON, count, Z_REFCOUNTED_P(struc) ? Z_REFCOUNT_P(struc) : 1);
ZEND_HASH_FOREACH_KEY_VAL_IND(myht, index, key, val) {
zval_array_element_dump(val, index, key, level);
} ZEND_HASH_FOREACH_END();
if (level > 1 && ZEND_HASH_APPLY_PROTECTION(myht)) {
myht->u.v.nApplyCount--;
}
if (is_temp) {
zend_hash_destroy(myht);
efree(myht);
}
if (level > 1) {
php_printf("%*c", level - 1, ' ');
}
PUTS("}\n");
break;
case IS_OBJECT:
myht = Z_OBJDEBUG_P(struc, is_temp);
if (myht) {
if (myht->u.v.nApplyCount > 1) {
PUTS("*RECURSION*\n");
return;
} else {
myht->u.v.nApplyCount++;
}
}
class_name = Z_OBJ_HANDLER_P(struc, get_class_name)(Z_OBJ_P(struc));
php_printf("%sobject(%s)#%d (%d) refcount(%u){\n", COMMON, ZSTR_VAL(class_name), Z_OBJ_HANDLE_P(struc), myht ? zend_array_count(myht) : 0, Z_REFCOUNT_P(struc));
zend_string_release(class_name);
if (myht) {
ZEND_HASH_FOREACH_KEY_VAL_IND(myht, index, key, val) {
zval_object_property_dump(val, index, key, level);
} ZEND_HASH_FOREACH_END();
myht->u.v.nApplyCount--;
if (is_temp) {
zend_hash_destroy(myht);
efree(myht);
}
}
if (level > 1) {
php_printf("%*c", level - 1, ' ');
}
PUTS("}\n");
break;
case IS_RESOURCE: {
const char *type_name = zend_rsrc_list_get_rsrc_type(Z_RES_P(struc));
php_printf("%sresource(%d) of type (%s) refcount(%u)\n", COMMON, Z_RES_P(struc)->handle, type_name ? type_name : "Unknown", Z_REFCOUNT_P(struc));
break;
}
case IS_REFERENCE:
//??? hide references with refcount==1 (for compatibility)
if (Z_REFCOUNT_P(struc) > 1) {
is_ref = 1;
}
struc = Z_REFVAL_P(struc);
goto again;
default:
php_printf("%sUNKNOWN:0\n", COMMON);
break;
}
}
/* }}} */
/* {{{ proto void debug_zval_dump(mixed var)
Dumps a string representation of an internal zend value to output. */
PHP_FUNCTION(debug_zval_dump)
{
zval *args;
int argc;
int i;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "+", &args, &argc) == FAILURE) {
return;
}
for (i = 0; i < argc; i++) {
php_debug_zval_dump(&args[i], 1);
}
}
/* }}} */
#define buffer_append_spaces(buf, num_spaces) \
do { \
char *tmp_spaces; \
size_t tmp_spaces_len; \
tmp_spaces_len = spprintf(&tmp_spaces, 0,"%*c", num_spaces, ' '); \
smart_str_appendl(buf, tmp_spaces, tmp_spaces_len); \
efree(tmp_spaces); \
} while(0);
static void php_array_element_export(zval *zv, zend_ulong index, zend_string *key, int level, smart_str *buf) /* {{{ */
{
if (key == NULL) { /* numeric key */
buffer_append_spaces(buf, level+1);
smart_str_append_long(buf, (zend_long) index);
smart_str_appendl(buf, " => ", 4);
} else { /* string key */
zend_string *tmp_str;
zend_string *ckey = php_addcslashes(key, 0, "'\\", 2);
tmp_str = php_str_to_str(ZSTR_VAL(ckey), ZSTR_LEN(ckey), "\0", 1, "' . \"\\0\" . '", 12);
buffer_append_spaces(buf, level + 1);
smart_str_appendc(buf, '\'');
smart_str_append(buf, tmp_str);
smart_str_appendl(buf, "' => ", 5);
zend_string_free(ckey);
zend_string_free(tmp_str);
}
php_var_export_ex(zv, level + 2, buf);
smart_str_appendc(buf, ',');
smart_str_appendc(buf, '\n');
}
/* }}} */
static void php_object_element_export(zval *zv, zend_ulong index, zend_string *key, int level, smart_str *buf) /* {{{ */
{
buffer_append_spaces(buf, level + 2);
if (key != NULL) {
const char *class_name, *prop_name;
size_t prop_name_len;
zend_string *pname_esc;
zend_unmangle_property_name_ex(key, &class_name, &prop_name, &prop_name_len);
pname_esc = php_addcslashes(zend_string_init(prop_name, prop_name_len, 0), 1, "'\\", 2);
smart_str_appendc(buf, '\'');
smart_str_append(buf, pname_esc);
smart_str_appendc(buf, '\'');
zend_string_release(pname_esc);
} else {
smart_str_append_long(buf, (zend_long) index);
}
smart_str_appendl(buf, " => ", 4);
php_var_export_ex(zv, level + 2, buf);
smart_str_appendc(buf, ',');
smart_str_appendc(buf, '\n');
}
/* }}} */
PHPAPI void php_var_export_ex(zval *struc, int level, smart_str *buf) /* {{{ */
{
HashTable *myht;
char *tmp_str;
size_t tmp_len;
zend_string *ztmp, *ztmp2;
zend_ulong index;
zend_string *key;
zval *val;
again:
switch (Z_TYPE_P(struc)) {
case IS_FALSE:
smart_str_appendl(buf, "false", 5);
break;
case IS_TRUE:
smart_str_appendl(buf, "true", 4);
break;
case IS_NULL:
smart_str_appendl(buf, "NULL", 4);
break;
case IS_LONG:
smart_str_append_long(buf, Z_LVAL_P(struc));
break;
case IS_DOUBLE:
tmp_len = spprintf(&tmp_str, 0,"%.*H", PG(serialize_precision), Z_DVAL_P(struc));
smart_str_appendl(buf, tmp_str, tmp_len);
/* Without a decimal point, PHP treats a number literal as an int.
* This check even works for scientific notation, because the
* mantissa always contains a decimal point.
* We need to check for finiteness, because INF, -INF and NAN
* must not have a decimal point added.
*/
if (zend_finite(Z_DVAL_P(struc)) && NULL == strchr(tmp_str, '.')) {
smart_str_appendl(buf, ".0", 2);
}
efree(tmp_str);
break;
case IS_STRING:
ztmp = php_addcslashes(Z_STR_P(struc), 0, "'\\", 2);
ztmp2 = php_str_to_str(ZSTR_VAL(ztmp), ZSTR_LEN(ztmp), "\0", 1, "' . \"\\0\" . '", 12);
smart_str_appendc(buf, '\'');
smart_str_append(buf, ztmp2);
smart_str_appendc(buf, '\'');
zend_string_free(ztmp);
zend_string_free(ztmp2);
break;
case IS_ARRAY:
myht = Z_ARRVAL_P(struc);
if (ZEND_HASH_APPLY_PROTECTION(myht) && myht->u.v.nApplyCount++ > 0) {
myht->u.v.nApplyCount--;
smart_str_appendl(buf, "NULL", 4);
zend_error(E_WARNING, "var_export does not handle circular references");
return;
}
if (level > 1) {
smart_str_appendc(buf, '\n');
buffer_append_spaces(buf, level - 1);
}
smart_str_appendl(buf, "array (\n", 8);
ZEND_HASH_FOREACH_KEY_VAL_IND(myht, index, key, val) {
php_array_element_export(val, index, key, level, buf);
} ZEND_HASH_FOREACH_END();
if (ZEND_HASH_APPLY_PROTECTION(myht)) {
myht->u.v.nApplyCount--;
}
if (level > 1) {
buffer_append_spaces(buf, level - 1);
}
smart_str_appendc(buf, ')');
break;
case IS_OBJECT:
myht = Z_OBJPROP_P(struc);
if (myht) {
if (myht->u.v.nApplyCount > 0) {
smart_str_appendl(buf, "NULL", 4);
zend_error(E_WARNING, "var_export does not handle circular references");
return;
} else {
myht->u.v.nApplyCount++;
}
}
if (level > 1) {
smart_str_appendc(buf, '\n');
buffer_append_spaces(buf, level - 1);
}
smart_str_append(buf, Z_OBJCE_P(struc)->name);
smart_str_appendl(buf, "::__set_state(array(\n", 21);
if (myht) {
ZEND_HASH_FOREACH_KEY_VAL_IND(myht, index, key, val) {
php_object_element_export(val, index, key, level, buf);
} ZEND_HASH_FOREACH_END();
myht->u.v.nApplyCount--;
}
if (level > 1) {
buffer_append_spaces(buf, level - 1);
}
smart_str_appendl(buf, "))", 2);
break;
case IS_REFERENCE:
struc = Z_REFVAL_P(struc);
goto again;
break;
default:
smart_str_appendl(buf, "NULL", 4);
break;
}
}
/* }}} */
/* FOR BC reasons, this will always perform and then print */
PHPAPI void php_var_export(zval *struc, int level) /* {{{ */
{
smart_str buf = {0};
php_var_export_ex(struc, level, &buf);
smart_str_0(&buf);
PHPWRITE(ZSTR_VAL(buf.s), ZSTR_LEN(buf.s));
smart_str_free(&buf);
}
/* }}} */
/* {{{ proto mixed var_export(mixed var [, bool return])
Outputs or returns a string representation of a variable */
PHP_FUNCTION(var_export)
{
zval *var;
zend_bool return_output = 0;
smart_str buf = {0};
if (zend_parse_parameters(ZEND_NUM_ARGS(), "z|b", &var, &return_output) == FAILURE) {
return;
}
php_var_export_ex(var, 1, &buf);
smart_str_0 (&buf);
if (return_output) {
RETURN_NEW_STR(buf.s);
} else {
PHPWRITE(ZSTR_VAL(buf.s), ZSTR_LEN(buf.s));
smart_str_free(&buf);
}
}
/* }}} */
static void php_var_serialize_intern(smart_str *buf, zval *struc, php_serialize_data_t var_hash);
static inline zend_long php_add_var_hash(php_serialize_data_t data, zval *var) /* {{{ */
{
zval *zv;
zend_ulong key;
zend_bool is_ref = Z_ISREF_P(var);
data->n += 1;
if (!is_ref && Z_TYPE_P(var) != IS_OBJECT) {
return 0;
}
/* References to objects are treated as if the reference didn't exist */
if (is_ref && Z_TYPE_P(Z_REFVAL_P(var)) == IS_OBJECT) {
var = Z_REFVAL_P(var);
}
/* Index for the variable is stored using the numeric value of the pointer to
* the zend_refcounted struct */
key = (zend_ulong) (zend_uintptr_t) Z_COUNTED_P(var);
zv = zend_hash_index_find(&data->ht, key);
if (zv) {
/* References are only counted once, undo the data->n increment above */
if (is_ref) {
data->n -= 1;
}
return Z_LVAL_P(zv);
} else {
zval zv_n;
ZVAL_LONG(&zv_n, data->n);
zend_hash_index_add_new(&data->ht, key, &zv_n);
/* Additionally to the index, we also store the variable, to ensure that it is
* not destroyed during serialization and its pointer reused. The variable is
* stored at the numeric value of the pointer + 1, which cannot be the location
* of another zend_refcounted structure. */
zend_hash_index_add_new(&data->ht, key + 1, var);
Z_ADDREF_P(var);
return 0;
}
}
/* }}} */
static inline void php_var_serialize_long(smart_str *buf, zend_long val) /* {{{ */
{
smart_str_appendl(buf, "i:", 2);
smart_str_append_long(buf, val);
smart_str_appendc(buf, ';');
}
/* }}} */
static inline void php_var_serialize_string(smart_str *buf, char *str, size_t len) /* {{{ */
{
smart_str_appendl(buf, "s:", 2);
smart_str_append_unsigned(buf, len);
smart_str_appendl(buf, ":\"", 2);
smart_str_appendl(buf, str, len);
smart_str_appendl(buf, "\";", 2);
}
/* }}} */
static inline zend_bool php_var_serialize_class_name(smart_str *buf, zval *struc) /* {{{ */
{
PHP_CLASS_ATTRIBUTES;
PHP_SET_CLASS_ATTRIBUTES(struc);
smart_str_appendl(buf, "O:", 2);
smart_str_append_unsigned(buf, ZSTR_LEN(class_name));
smart_str_appendl(buf, ":\"", 2);
smart_str_append(buf, class_name);
smart_str_appendl(buf, "\":", 2);
PHP_CLEANUP_CLASS_ATTRIBUTES();
return incomplete_class;
}
/* }}} */
static HashTable *php_var_serialize_collect_names(HashTable *src, uint32_t count, zend_bool incomplete) /* {{{ */ {
zval *val;
HashTable *ht;
zend_string *key, *name;
ALLOC_HASHTABLE(ht);
zend_hash_init(ht, count, NULL, NULL, 0);
ZEND_HASH_FOREACH_STR_KEY_VAL(src, key, val) {
if (incomplete && strcmp(ZSTR_VAL(key), MAGIC_MEMBER) == 0) {
continue;
}
if (Z_TYPE_P(val) != IS_STRING) {
php_error_docref(NULL, E_NOTICE,
"__sleep should return an array only containing the names of instance-variables to serialize.");
}
name = zval_get_string(val);
if (zend_hash_exists(ht, name)) {
php_error_docref(NULL, E_NOTICE,
"\"%s\" is returned from __sleep multiple times", ZSTR_VAL(name));
zend_string_release(name);
continue;
}
zend_hash_add_empty_element(ht, name);
zend_string_release(name);
} ZEND_HASH_FOREACH_END();
return ht;
}
/* }}} */
static void php_var_serialize_class(smart_str *buf, zval *struc, zval *retval_ptr, php_serialize_data_t var_hash) /* {{{ */
{
uint32_t count;
zend_bool incomplete_class;
HashTable *ht;
incomplete_class = php_var_serialize_class_name(buf, struc);
/* count after serializing name, since php_var_serialize_class_name
* changes the count if the variable is incomplete class */
if (Z_TYPE_P(retval_ptr) == IS_ARRAY) {
ht = Z_ARRVAL_P(retval_ptr);
count = zend_array_count(ht);
} else if (Z_TYPE_P(retval_ptr) == IS_OBJECT) {
ht = Z_OBJPROP_P(retval_ptr);
count = zend_array_count(ht);
if (incomplete_class) {
--count;
}
} else {
count = 0;
ht = NULL;
}
if (count > 0) {
zval *d;
zval nval, *nvalp;
zend_string *name;
HashTable *names, *propers;
names = php_var_serialize_collect_names(ht, count, incomplete_class);
smart_str_append_unsigned(buf, zend_hash_num_elements(names));
smart_str_appendl(buf, ":{", 2);
ZVAL_NULL(&nval);
nvalp = &nval;
propers = Z_OBJPROP_P(struc);
ZEND_HASH_FOREACH_STR_KEY(names, name) {
if ((d = zend_hash_find(propers, name)) != NULL) {
if (Z_TYPE_P(d) == IS_INDIRECT) {
d = Z_INDIRECT_P(d);
if (Z_TYPE_P(d) == IS_UNDEF) {
continue;
}
}
php_var_serialize_string(buf, ZSTR_VAL(name), ZSTR_LEN(name));
php_var_serialize_intern(buf, d, var_hash);
} else {
zend_class_entry *ce = Z_OBJ_P(struc)->ce;
if (ce) {
zend_string *prot_name, *priv_name;
do {
priv_name = zend_mangle_property_name(
ZSTR_VAL(ce->name), ZSTR_LEN(ce->name), ZSTR_VAL(name), ZSTR_LEN(name), ce->type & ZEND_INTERNAL_CLASS);
if ((d = zend_hash_find(propers, priv_name)) != NULL) {
if (Z_TYPE_P(d) == IS_INDIRECT) {
d = Z_INDIRECT_P(d);
if (Z_ISUNDEF_P(d)) {
break;
}
}
php_var_serialize_string(buf, ZSTR_VAL(priv_name), ZSTR_LEN(priv_name));
zend_string_free(priv_name);
php_var_serialize_intern(buf, d, var_hash);
break;
}
zend_string_free(priv_name);
prot_name = zend_mangle_property_name(
"*", 1, ZSTR_VAL(name), ZSTR_LEN(name), ce->type & ZEND_INTERNAL_CLASS);
if ((d = zend_hash_find(propers, prot_name)) != NULL) {
if (Z_TYPE_P(d) == IS_INDIRECT) {
d = Z_INDIRECT_P(d);
if (Z_TYPE_P(d) == IS_UNDEF) {
zend_string_free(prot_name);
break;
}
}
php_var_serialize_string(buf, ZSTR_VAL(prot_name), ZSTR_LEN(prot_name));
zend_string_free(prot_name);
php_var_serialize_intern(buf, d, var_hash);
break;
}
zend_string_free(prot_name);
php_var_serialize_string(buf, ZSTR_VAL(name), ZSTR_LEN(name));
php_var_serialize_intern(buf, nvalp, var_hash);
php_error_docref(NULL, E_NOTICE,
"\"%s\" returned as member variable from __sleep() but does not exist", ZSTR_VAL(name));
} while (0);
} else {
php_var_serialize_string(buf, ZSTR_VAL(name), ZSTR_LEN(name));
php_var_serialize_intern(buf, nvalp, var_hash);
}
}
} ZEND_HASH_FOREACH_END();
smart_str_appendc(buf, '}');
zend_hash_destroy(names);
FREE_HASHTABLE(names);
} else {
smart_str_appendl(buf, "0:{}", 4);
}
}
/* }}} */
static void php_var_serialize_intern(smart_str *buf, zval *struc, php_serialize_data_t var_hash) /* {{{ */
{
zend_long var_already;
HashTable *myht;
if (EG(exception)) {
return;
}
if (var_hash && (var_already = php_add_var_hash(var_hash, struc))) {
if (Z_ISREF_P(struc)) {
smart_str_appendl(buf, "R:", 2);
smart_str_append_long(buf, var_already);
smart_str_appendc(buf, ';');
return;
} else if (Z_TYPE_P(struc) == IS_OBJECT) {
smart_str_appendl(buf, "r:", 2);
smart_str_append_long(buf, var_already);
smart_str_appendc(buf, ';');
return;
}
}
again:
switch (Z_TYPE_P(struc)) {
case IS_FALSE:
smart_str_appendl(buf, "b:0;", 4);
return;
case IS_TRUE:
smart_str_appendl(buf, "b:1;", 4);
return;
case IS_NULL:
smart_str_appendl(buf, "N;", 2);
return;
case IS_LONG:
php_var_serialize_long(buf, Z_LVAL_P(struc));
return;
case IS_DOUBLE: {
char *s;
smart_str_appendl(buf, "d:", 2);
s = (char *) safe_emalloc(PG(serialize_precision), 1, MAX_LENGTH_OF_DOUBLE + 1);
php_gcvt(Z_DVAL_P(struc), (int)PG(serialize_precision), '.', 'E', s);
smart_str_appends(buf, s);
smart_str_appendc(buf, ';');
efree(s);
return;
}
case IS_STRING:
php_var_serialize_string(buf, Z_STRVAL_P(struc), Z_STRLEN_P(struc));
return;
case IS_OBJECT: {
zval retval;
zval fname;
int res;
zend_class_entry *ce = Z_OBJCE_P(struc);
if (ce->serialize != NULL) {
/* has custom handler */
unsigned char *serialized_data = NULL;
size_t serialized_length;
if (ce->serialize(struc, &serialized_data, &serialized_length, (zend_serialize_data *)var_hash) == SUCCESS) {
smart_str_appendl(buf, "C:", 2);
smart_str_append_unsigned(buf, ZSTR_LEN(Z_OBJCE_P(struc)->name));
smart_str_appendl(buf, ":\"", 2);
smart_str_append(buf, Z_OBJCE_P(struc)->name);
smart_str_appendl(buf, "\":", 2);
smart_str_append_unsigned(buf, serialized_length);
smart_str_appendl(buf, ":{", 2);
smart_str_appendl(buf, (char *) serialized_data, serialized_length);
smart_str_appendc(buf, '}');
} else {
smart_str_appendl(buf, "N;", 2);
}
if (serialized_data) {
efree(serialized_data);
}
return;
}
if (ce != PHP_IC_ENTRY && zend_hash_str_exists(&ce->function_table, "__sleep", sizeof("__sleep")-1)) {
ZVAL_STRINGL(&fname, "__sleep", sizeof("__sleep") - 1);
BG(serialize_lock)++;
res = call_user_function_ex(CG(function_table), struc, &fname, &retval, 0, 0, 1, NULL);
BG(serialize_lock)--;
zval_dtor(&fname);
if (EG(exception)) {
zval_ptr_dtor(&retval);
return;
}
if (res == SUCCESS) {
if (Z_TYPE(retval) != IS_UNDEF) {
if (HASH_OF(&retval)) {
php_var_serialize_class(buf, struc, &retval, var_hash);
} else {
php_error_docref(NULL, E_NOTICE, "__sleep should return an array only containing the names of instance-variables to serialize");
/* we should still add element even if it's not OK,
* since we already wrote the length of the array before */
smart_str_appendl(buf,"N;", 2);
}
zval_ptr_dtor(&retval);
}
return;
}
zval_ptr_dtor(&retval);
}
/* fall-through */
}
case IS_ARRAY: {
uint32_t i;
zend_bool incomplete_class = 0;
if (Z_TYPE_P(struc) == IS_ARRAY) {
smart_str_appendl(buf, "a:", 2);
myht = Z_ARRVAL_P(struc);
i = zend_array_count(myht);
} else {
incomplete_class = php_var_serialize_class_name(buf, struc);
myht = Z_OBJPROP_P(struc);
/* count after serializing name, since php_var_serialize_class_name
* changes the count if the variable is incomplete class */
i = zend_array_count(myht);
if (i > 0 && incomplete_class) {
--i;
}
}
smart_str_append_unsigned(buf, i);
smart_str_appendl(buf, ":{", 2);
if (i > 0) {
zend_string *key;
zval *data;
zend_ulong index;
ZEND_HASH_FOREACH_KEY_VAL_IND(myht, index, key, data) {
if (incomplete_class && strcmp(ZSTR_VAL(key), MAGIC_MEMBER) == 0) {
continue;
}
if (!key) {
php_var_serialize_long(buf, index);
} else {
php_var_serialize_string(buf, ZSTR_VAL(key), ZSTR_LEN(key));
}
if (Z_ISREF_P(data) && Z_REFCOUNT_P(data) == 1) {
data = Z_REFVAL_P(data);
}
/* we should still add element even if it's not OK,
* since we already wrote the length of the array before */
if ((Z_TYPE_P(data) == IS_ARRAY && Z_TYPE_P(struc) == IS_ARRAY && Z_ARR_P(data) == Z_ARR_P(struc))
|| (Z_TYPE_P(data) == IS_ARRAY && Z_ARRVAL_P(data)->u.v.nApplyCount > 1)
) {
smart_str_appendl(buf, "N;", 2);
} else {
if (Z_TYPE_P(data) == IS_ARRAY && ZEND_HASH_APPLY_PROTECTION(Z_ARRVAL_P(data))) {
Z_ARRVAL_P(data)->u.v.nApplyCount++;
}
php_var_serialize_intern(buf, data, var_hash);
if (Z_TYPE_P(data) == IS_ARRAY && ZEND_HASH_APPLY_PROTECTION(Z_ARRVAL_P(data))) {
Z_ARRVAL_P(data)->u.v.nApplyCount--;
}
}
} ZEND_HASH_FOREACH_END();
}
smart_str_appendc(buf, '}');
return;
}
case IS_REFERENCE:
struc = Z_REFVAL_P(struc);
goto again;
default:
smart_str_appendl(buf, "i:0;", 4);
return;
}
}
/* }}} */
PHPAPI void php_var_serialize(smart_str *buf, zval *struc, php_serialize_data_t *data) /* {{{ */
{
php_var_serialize_intern(buf, struc, *data);
smart_str_0(buf);
}
/* }}} */
/* {{{ proto string serialize(mixed variable)
Returns a string representation of variable (which can later be unserialized) */
PHP_FUNCTION(serialize)
{
zval *struc;
php_serialize_data_t var_hash;
smart_str buf = {0};
if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &struc) == FAILURE) {
return;
}
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&buf, struc, &var_hash);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
if (EG(exception)) {
smart_str_free(&buf);
RETURN_FALSE;
}
if (buf.s) {
RETURN_NEW_STR(buf.s);
} else {
RETURN_NULL();
}
}
/* }}} */
/* {{{ proto mixed unserialize(string variable_representation[, array allowed_classes])
Takes a string representation of variable and recreates it */
PHP_FUNCTION(unserialize)
{
char *buf = NULL;
size_t buf_len;
const unsigned char *p;
php_unserialize_data_t var_hash;
zval *options = NULL, *classes = NULL;
HashTable *class_hash = NULL;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|a", &buf, &buf_len, &options) == FAILURE) {
RETURN_FALSE;
}
if (buf_len == 0) {
RETURN_FALSE;
}
p = (const unsigned char*) buf;
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if(options != NULL) {
classes = zend_hash_str_find(Z_ARRVAL_P(options), "allowed_classes", sizeof("allowed_classes")-1);
if(classes && (Z_TYPE_P(classes) == IS_ARRAY || !zend_is_true(classes))) {
ALLOC_HASHTABLE(class_hash);
zend_hash_init(class_hash, (Z_TYPE_P(classes) == IS_ARRAY)?zend_hash_num_elements(Z_ARRVAL_P(classes)):0, NULL, NULL, 0);
}
if(class_hash && Z_TYPE_P(classes) == IS_ARRAY) {
zval *entry;
zend_string *lcname;
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(classes), entry) {
convert_to_string_ex(entry);
lcname = zend_string_tolower(Z_STR_P(entry));
zend_hash_add_empty_element(class_hash, lcname);
zend_string_release(lcname);
} ZEND_HASH_FOREACH_END();
}
}
if (!php_var_unserialize_ex(return_value, &p, p + buf_len, &var_hash, class_hash)) {
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (class_hash) {
zend_hash_destroy(class_hash);
FREE_HASHTABLE(class_hash);
}
zval_ptr_dtor(return_value);
if (!EG(exception)) {
php_error_docref(NULL, E_NOTICE, "Error at offset " ZEND_LONG_FMT " of %zd bytes",
(zend_long)((char*)p - buf), buf_len);
}
RETURN_FALSE;
}
/* We should keep an reference to return_value to prevent it from being dtor
in case nesting calls to unserialize */
var_push_dtor(&var_hash, return_value);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
if (class_hash) {
zend_hash_destroy(class_hash);
FREE_HASHTABLE(class_hash);
}
}
/* }}} */
/* {{{ proto int memory_get_usage([bool real_usage])
Returns the allocated by PHP memory */
PHP_FUNCTION(memory_get_usage) {
zend_bool real_usage = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &real_usage) == FAILURE) {
RETURN_FALSE;
}
RETURN_LONG(zend_memory_usage(real_usage));
}
/* }}} */
/* {{{ proto int memory_get_peak_usage([bool real_usage])
Returns the peak allocated by PHP memory */
PHP_FUNCTION(memory_get_peak_usage) {
zend_bool real_usage = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &real_usage) == FAILURE) {
RETURN_FALSE;
}
RETURN_LONG(zend_memory_peak_usage(real_usage));
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_5516_1 |
crossvul-cpp_data_bad_466_0 | /*
* "Real" compatible demuxer.
* Copyright (c) 2000, 2001 Fabrice Bellard
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <inttypes.h>
#include "libavutil/avassert.h"
#include "libavutil/avstring.h"
#include "libavutil/channel_layout.h"
#include "libavutil/internal.h"
#include "libavutil/intreadwrite.h"
#include "libavutil/dict.h"
#include "avformat.h"
#include "avio_internal.h"
#include "internal.h"
#include "rmsipr.h"
#include "rm.h"
#define DEINT_ID_GENR MKTAG('g', 'e', 'n', 'r') ///< interleaving for Cooker/ATRAC
#define DEINT_ID_INT0 MKTAG('I', 'n', 't', '0') ///< no interleaving needed
#define DEINT_ID_INT4 MKTAG('I', 'n', 't', '4') ///< interleaving for 28.8
#define DEINT_ID_SIPR MKTAG('s', 'i', 'p', 'r') ///< interleaving for Sipro
#define DEINT_ID_VBRF MKTAG('v', 'b', 'r', 'f') ///< VBR case for AAC
#define DEINT_ID_VBRS MKTAG('v', 'b', 'r', 's') ///< VBR case for AAC
struct RMStream {
AVPacket pkt; ///< place to store merged video frame / reordered audio data
int videobufsize; ///< current assembled frame size
int videobufpos; ///< position for the next slice in the video buffer
int curpic_num; ///< picture number of current frame
int cur_slice, slices;
int64_t pktpos; ///< first slice position in file
/// Audio descrambling matrix parameters
int64_t audiotimestamp; ///< Audio packet timestamp
int sub_packet_cnt; // Subpacket counter, used while reading
int sub_packet_size, sub_packet_h, coded_framesize; ///< Descrambling parameters from container
int audio_framesize; /// Audio frame size from container
int sub_packet_lengths[16]; /// Length of each subpacket
int32_t deint_id; ///< deinterleaver used in audio stream
};
typedef struct RMDemuxContext {
int nb_packets;
int old_format;
int current_stream;
int remaining_len;
int audio_stream_num; ///< Stream number for audio packets
int audio_pkt_cnt; ///< Output packet counter
int data_end;
} RMDemuxContext;
static int rm_read_close(AVFormatContext *s);
static inline void get_strl(AVIOContext *pb, char *buf, int buf_size, int len)
{
int read = avio_get_str(pb, len, buf, buf_size);
if (read > 0)
avio_skip(pb, len - read);
}
static void get_str8(AVIOContext *pb, char *buf, int buf_size)
{
get_strl(pb, buf, buf_size, avio_r8(pb));
}
static int rm_read_extradata(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par, unsigned size)
{
if (size >= 1<<24) {
av_log(s, AV_LOG_ERROR, "extradata size %u too large\n", size);
return -1;
}
if (ff_get_extradata(s, par, pb, size) < 0)
return AVERROR(ENOMEM);
return 0;
}
static void rm_read_metadata(AVFormatContext *s, AVIOContext *pb, int wide)
{
char buf[1024];
int i;
for (i=0; i<FF_ARRAY_ELEMS(ff_rm_metadata); i++) {
int len = wide ? avio_rb16(pb) : avio_r8(pb);
if (len > 0) {
get_strl(pb, buf, sizeof(buf), len);
av_dict_set(&s->metadata, ff_rm_metadata[i], buf, 0);
}
}
}
RMStream *ff_rm_alloc_rmstream (void)
{
RMStream *rms = av_mallocz(sizeof(RMStream));
if (!rms)
return NULL;
rms->curpic_num = -1;
return rms;
}
void ff_rm_free_rmstream (RMStream *rms)
{
av_packet_unref(&rms->pkt);
}
static int rm_read_audio_stream_info(AVFormatContext *s, AVIOContext *pb,
AVStream *st, RMStream *ast, int read_all)
{
char buf[256];
uint32_t version;
int ret;
/* ra type header */
version = avio_rb16(pb); /* version */
if (version == 3) {
unsigned bytes_per_minute;
int header_size = avio_rb16(pb);
int64_t startpos = avio_tell(pb);
avio_skip(pb, 8);
bytes_per_minute = avio_rb16(pb);
avio_skip(pb, 4);
rm_read_metadata(s, pb, 0);
if ((startpos + header_size) >= avio_tell(pb) + 2) {
// fourcc (should always be "lpcJ")
avio_r8(pb);
get_str8(pb, buf, sizeof(buf));
}
// Skip extra header crap (this should never happen)
if ((startpos + header_size) > avio_tell(pb))
avio_skip(pb, header_size + startpos - avio_tell(pb));
if (bytes_per_minute)
st->codecpar->bit_rate = 8LL * bytes_per_minute / 60;
st->codecpar->sample_rate = 8000;
st->codecpar->channels = 1;
st->codecpar->channel_layout = AV_CH_LAYOUT_MONO;
st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
st->codecpar->codec_id = AV_CODEC_ID_RA_144;
ast->deint_id = DEINT_ID_INT0;
} else {
int flavor, sub_packet_h, coded_framesize, sub_packet_size;
int codecdata_length;
unsigned bytes_per_minute;
/* old version (4) */
avio_skip(pb, 2); /* unused */
avio_rb32(pb); /* .ra4 */
avio_rb32(pb); /* data size */
avio_rb16(pb); /* version2 */
avio_rb32(pb); /* header size */
flavor= avio_rb16(pb); /* add codec info / flavor */
ast->coded_framesize = coded_framesize = avio_rb32(pb); /* coded frame size */
avio_rb32(pb); /* ??? */
bytes_per_minute = avio_rb32(pb);
if (version == 4) {
if (bytes_per_minute)
st->codecpar->bit_rate = 8LL * bytes_per_minute / 60;
}
avio_rb32(pb); /* ??? */
ast->sub_packet_h = sub_packet_h = avio_rb16(pb); /* 1 */
st->codecpar->block_align= avio_rb16(pb); /* frame size */
ast->sub_packet_size = sub_packet_size = avio_rb16(pb); /* sub packet size */
avio_rb16(pb); /* ??? */
if (version == 5) {
avio_rb16(pb); avio_rb16(pb); avio_rb16(pb);
}
st->codecpar->sample_rate = avio_rb16(pb);
avio_rb32(pb);
st->codecpar->channels = avio_rb16(pb);
if (version == 5) {
ast->deint_id = avio_rl32(pb);
avio_read(pb, buf, 4);
buf[4] = 0;
} else {
AV_WL32(buf, 0);
get_str8(pb, buf, sizeof(buf)); /* desc */
ast->deint_id = AV_RL32(buf);
get_str8(pb, buf, sizeof(buf)); /* desc */
}
st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
st->codecpar->codec_tag = AV_RL32(buf);
st->codecpar->codec_id = ff_codec_get_id(ff_rm_codec_tags,
st->codecpar->codec_tag);
switch (st->codecpar->codec_id) {
case AV_CODEC_ID_AC3:
st->need_parsing = AVSTREAM_PARSE_FULL;
break;
case AV_CODEC_ID_RA_288:
st->codecpar->extradata_size= 0;
av_freep(&st->codecpar->extradata);
ast->audio_framesize = st->codecpar->block_align;
st->codecpar->block_align = coded_framesize;
break;
case AV_CODEC_ID_COOK:
st->need_parsing = AVSTREAM_PARSE_HEADERS;
case AV_CODEC_ID_ATRAC3:
case AV_CODEC_ID_SIPR:
if (read_all) {
codecdata_length = 0;
} else {
avio_rb16(pb); avio_r8(pb);
if (version == 5)
avio_r8(pb);
codecdata_length = avio_rb32(pb);
if(codecdata_length + AV_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){
av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");
return -1;
}
}
ast->audio_framesize = st->codecpar->block_align;
if (st->codecpar->codec_id == AV_CODEC_ID_SIPR) {
if (flavor > 3) {
av_log(s, AV_LOG_ERROR, "bad SIPR file flavor %d\n",
flavor);
return -1;
}
st->codecpar->block_align = ff_sipr_subpk_size[flavor];
st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
} else {
if(sub_packet_size <= 0){
av_log(s, AV_LOG_ERROR, "sub_packet_size is invalid\n");
return -1;
}
st->codecpar->block_align = ast->sub_packet_size;
}
if ((ret = rm_read_extradata(s, pb, st->codecpar, codecdata_length)) < 0)
return ret;
break;
case AV_CODEC_ID_AAC:
avio_rb16(pb); avio_r8(pb);
if (version == 5)
avio_r8(pb);
codecdata_length = avio_rb32(pb);
if(codecdata_length + AV_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){
av_log(s, AV_LOG_ERROR, "codecdata_length too large\n");
return -1;
}
if (codecdata_length >= 1) {
avio_r8(pb);
if ((ret = rm_read_extradata(s, pb, st->codecpar, codecdata_length - 1)) < 0)
return ret;
}
break;
}
switch (ast->deint_id) {
case DEINT_ID_INT4:
if (ast->coded_framesize > ast->audio_framesize ||
sub_packet_h <= 1 ||
ast->coded_framesize * sub_packet_h > (2 + (sub_packet_h & 1)) * ast->audio_framesize)
return AVERROR_INVALIDDATA;
if (ast->coded_framesize * sub_packet_h != 2*ast->audio_framesize) {
avpriv_request_sample(s, "mismatching interleaver parameters");
return AVERROR_INVALIDDATA;
}
break;
case DEINT_ID_GENR:
if (ast->sub_packet_size <= 0 ||
ast->sub_packet_size > ast->audio_framesize)
return AVERROR_INVALIDDATA;
if (ast->audio_framesize % ast->sub_packet_size)
return AVERROR_INVALIDDATA;
break;
case DEINT_ID_SIPR:
case DEINT_ID_INT0:
case DEINT_ID_VBRS:
case DEINT_ID_VBRF:
break;
default:
av_log(s, AV_LOG_ERROR ,"Unknown interleaver %"PRIX32"\n", ast->deint_id);
return AVERROR_INVALIDDATA;
}
if (ast->deint_id == DEINT_ID_INT4 ||
ast->deint_id == DEINT_ID_GENR ||
ast->deint_id == DEINT_ID_SIPR) {
if (st->codecpar->block_align <= 0 ||
ast->audio_framesize * sub_packet_h > (unsigned)INT_MAX ||
ast->audio_framesize * sub_packet_h < st->codecpar->block_align)
return AVERROR_INVALIDDATA;
if (av_new_packet(&ast->pkt, ast->audio_framesize * sub_packet_h) < 0)
return AVERROR(ENOMEM);
}
if (read_all) {
avio_r8(pb);
avio_r8(pb);
avio_r8(pb);
rm_read_metadata(s, pb, 0);
}
}
return 0;
}
int ff_rm_read_mdpr_codecdata(AVFormatContext *s, AVIOContext *pb,
AVStream *st, RMStream *rst,
unsigned int codec_data_size, const uint8_t *mime)
{
unsigned int v;
int size;
int64_t codec_pos;
int ret;
if (codec_data_size > INT_MAX)
return AVERROR_INVALIDDATA;
if (codec_data_size == 0)
return 0;
avpriv_set_pts_info(st, 64, 1, 1000);
codec_pos = avio_tell(pb);
v = avio_rb32(pb);
if (v == MKTAG(0xfd, 'a', 'r', '.')) {
/* ra type header */
if (rm_read_audio_stream_info(s, pb, st, rst, 0))
return -1;
} else if (v == MKBETAG('L', 'S', 'D', ':')) {
avio_seek(pb, -4, SEEK_CUR);
if ((ret = rm_read_extradata(s, pb, st->codecpar, codec_data_size)) < 0)
return ret;
st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
st->codecpar->codec_tag = AV_RL32(st->codecpar->extradata);
st->codecpar->codec_id = ff_codec_get_id(ff_rm_codec_tags,
st->codecpar->codec_tag);
} else if(mime && !strcmp(mime, "logical-fileinfo")){
int stream_count, rule_count, property_count, i;
ff_free_stream(s, st);
if (avio_rb16(pb) != 0) {
av_log(s, AV_LOG_WARNING, "Unsupported version\n");
goto skip;
}
stream_count = avio_rb16(pb);
avio_skip(pb, 6*stream_count);
rule_count = avio_rb16(pb);
avio_skip(pb, 2*rule_count);
property_count = avio_rb16(pb);
for(i=0; i<property_count; i++){
uint8_t name[128], val[128];
avio_rb32(pb);
if (avio_rb16(pb) != 0) {
av_log(s, AV_LOG_WARNING, "Unsupported Name value property version\n");
goto skip; //FIXME skip just this one
}
get_str8(pb, name, sizeof(name));
switch(avio_rb32(pb)) {
case 2: get_strl(pb, val, sizeof(val), avio_rb16(pb));
av_dict_set(&s->metadata, name, val, 0);
break;
default: avio_skip(pb, avio_rb16(pb));
}
}
} else {
int fps;
if (avio_rl32(pb) != MKTAG('V', 'I', 'D', 'O')) {
fail1:
av_log(s, AV_LOG_WARNING, "Unsupported stream type %08x\n", v);
goto skip;
}
st->codecpar->codec_tag = avio_rl32(pb);
st->codecpar->codec_id = ff_codec_get_id(ff_rm_codec_tags,
st->codecpar->codec_tag);
av_log(s, AV_LOG_TRACE, "%"PRIX32" %X\n",
st->codecpar->codec_tag, MKTAG('R', 'V', '2', '0'));
if (st->codecpar->codec_id == AV_CODEC_ID_NONE)
goto fail1;
st->codecpar->width = avio_rb16(pb);
st->codecpar->height = avio_rb16(pb);
avio_skip(pb, 2); // looks like bits per sample
avio_skip(pb, 4); // always zero?
st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO;
st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
fps = avio_rb32(pb);
if ((ret = rm_read_extradata(s, pb, st->codecpar, codec_data_size - (avio_tell(pb) - codec_pos))) < 0)
return ret;
if (fps > 0) {
av_reduce(&st->avg_frame_rate.den, &st->avg_frame_rate.num,
0x10000, fps, (1 << 30) - 1);
#if FF_API_R_FRAME_RATE
st->r_frame_rate = st->avg_frame_rate;
#endif
} else if (s->error_recognition & AV_EF_EXPLODE) {
av_log(s, AV_LOG_ERROR, "Invalid framerate\n");
return AVERROR_INVALIDDATA;
}
}
skip:
/* skip codec info */
size = avio_tell(pb) - codec_pos;
if (codec_data_size >= size) {
avio_skip(pb, codec_data_size - size);
} else {
av_log(s, AV_LOG_WARNING, "codec_data_size %u < size %d\n", codec_data_size, size);
}
return 0;
}
/** this function assumes that the demuxer has already seeked to the start
* of the INDX chunk, and will bail out if not. */
static int rm_read_index(AVFormatContext *s)
{
AVIOContext *pb = s->pb;
unsigned int size, n_pkts, str_id, next_off, n, pos, pts;
AVStream *st;
do {
if (avio_rl32(pb) != MKTAG('I','N','D','X'))
return -1;
size = avio_rb32(pb);
if (size < 20)
return -1;
avio_skip(pb, 2);
n_pkts = avio_rb32(pb);
str_id = avio_rb16(pb);
next_off = avio_rb32(pb);
for (n = 0; n < s->nb_streams; n++)
if (s->streams[n]->id == str_id) {
st = s->streams[n];
break;
}
if (n == s->nb_streams) {
av_log(s, AV_LOG_ERROR,
"Invalid stream index %d for index at pos %"PRId64"\n",
str_id, avio_tell(pb));
goto skip;
} else if ((avio_size(pb) - avio_tell(pb)) / 14 < n_pkts) {
av_log(s, AV_LOG_ERROR,
"Nr. of packets in packet index for stream index %d "
"exceeds filesize (%"PRId64" at %"PRId64" = %"PRId64")\n",
str_id, avio_size(pb), avio_tell(pb),
(avio_size(pb) - avio_tell(pb)) / 14);
goto skip;
}
for (n = 0; n < n_pkts; n++) {
avio_skip(pb, 2);
pts = avio_rb32(pb);
pos = avio_rb32(pb);
avio_skip(pb, 4); /* packet no. */
av_add_index_entry(st, pos, pts, 0, 0, AVINDEX_KEYFRAME);
}
skip:
if (next_off && avio_tell(pb) < next_off &&
avio_seek(pb, next_off, SEEK_SET) < 0) {
av_log(s, AV_LOG_ERROR,
"Non-linear index detected, not supported\n");
return -1;
}
} while (next_off);
return 0;
}
static int rm_read_header_old(AVFormatContext *s)
{
RMDemuxContext *rm = s->priv_data;
AVStream *st;
rm->old_format = 1;
st = avformat_new_stream(s, NULL);
if (!st)
return -1;
st->priv_data = ff_rm_alloc_rmstream();
if (!st->priv_data)
return AVERROR(ENOMEM);
return rm_read_audio_stream_info(s, s->pb, st, st->priv_data, 1);
}
static int rm_read_multi(AVFormatContext *s, AVIOContext *pb,
AVStream *st, char *mime)
{
int number_of_streams = avio_rb16(pb);
int number_of_mdpr;
int i, ret;
unsigned size2;
for (i = 0; i<number_of_streams; i++)
avio_rb16(pb);
number_of_mdpr = avio_rb16(pb);
if (number_of_mdpr != 1) {
avpriv_request_sample(s, "MLTI with multiple (%d) MDPR", number_of_mdpr);
}
for (i = 0; i < number_of_mdpr; i++) {
AVStream *st2;
if (i > 0) {
st2 = avformat_new_stream(s, NULL);
if (!st2) {
ret = AVERROR(ENOMEM);
return ret;
}
st2->id = st->id + (i<<16);
st2->codecpar->bit_rate = st->codecpar->bit_rate;
st2->start_time = st->start_time;
st2->duration = st->duration;
st2->codecpar->codec_type = AVMEDIA_TYPE_DATA;
st2->priv_data = ff_rm_alloc_rmstream();
if (!st2->priv_data)
return AVERROR(ENOMEM);
} else
st2 = st;
size2 = avio_rb32(pb);
ret = ff_rm_read_mdpr_codecdata(s, s->pb, st2, st2->priv_data,
size2, mime);
if (ret < 0)
return ret;
}
return 0;
}
static int rm_read_header(AVFormatContext *s)
{
RMDemuxContext *rm = s->priv_data;
AVStream *st;
AVIOContext *pb = s->pb;
unsigned int tag;
int tag_size;
unsigned int start_time, duration;
unsigned int data_off = 0, indx_off = 0;
char buf[128], mime[128];
int flags = 0;
int ret = -1;
unsigned size, v;
int64_t codec_pos;
tag = avio_rl32(pb);
if (tag == MKTAG('.', 'r', 'a', 0xfd)) {
/* very old .ra format */
return rm_read_header_old(s);
} else if (tag != MKTAG('.', 'R', 'M', 'F')) {
return AVERROR(EIO);
}
tag_size = avio_rb32(pb);
avio_skip(pb, tag_size - 8);
for(;;) {
if (avio_feof(pb))
goto fail;
tag = avio_rl32(pb);
tag_size = avio_rb32(pb);
avio_rb16(pb);
av_log(s, AV_LOG_TRACE, "tag=%s size=%d\n",
av_fourcc2str(tag), tag_size);
if (tag_size < 10 && tag != MKTAG('D', 'A', 'T', 'A'))
goto fail;
switch(tag) {
case MKTAG('P', 'R', 'O', 'P'):
/* file header */
avio_rb32(pb); /* max bit rate */
avio_rb32(pb); /* avg bit rate */
avio_rb32(pb); /* max packet size */
avio_rb32(pb); /* avg packet size */
avio_rb32(pb); /* nb packets */
duration = avio_rb32(pb); /* duration */
s->duration = av_rescale(duration, AV_TIME_BASE, 1000);
avio_rb32(pb); /* preroll */
indx_off = avio_rb32(pb); /* index offset */
data_off = avio_rb32(pb); /* data offset */
avio_rb16(pb); /* nb streams */
flags = avio_rb16(pb); /* flags */
break;
case MKTAG('C', 'O', 'N', 'T'):
rm_read_metadata(s, pb, 1);
break;
case MKTAG('M', 'D', 'P', 'R'):
st = avformat_new_stream(s, NULL);
if (!st) {
ret = AVERROR(ENOMEM);
goto fail;
}
st->id = avio_rb16(pb);
avio_rb32(pb); /* max bit rate */
st->codecpar->bit_rate = avio_rb32(pb); /* bit rate */
avio_rb32(pb); /* max packet size */
avio_rb32(pb); /* avg packet size */
start_time = avio_rb32(pb); /* start time */
avio_rb32(pb); /* preroll */
duration = avio_rb32(pb); /* duration */
st->start_time = start_time;
st->duration = duration;
if(duration>0)
s->duration = AV_NOPTS_VALUE;
get_str8(pb, buf, sizeof(buf)); /* desc */
get_str8(pb, mime, sizeof(mime)); /* mimetype */
st->codecpar->codec_type = AVMEDIA_TYPE_DATA;
st->priv_data = ff_rm_alloc_rmstream();
if (!st->priv_data)
return AVERROR(ENOMEM);
size = avio_rb32(pb);
codec_pos = avio_tell(pb);
ffio_ensure_seekback(pb, 4);
v = avio_rb32(pb);
if (v == MKBETAG('M', 'L', 'T', 'I')) {
ret = rm_read_multi(s, s->pb, st, mime);
if (ret < 0)
goto fail;
avio_seek(pb, codec_pos + size, SEEK_SET);
} else {
avio_skip(pb, -4);
if (ff_rm_read_mdpr_codecdata(s, s->pb, st, st->priv_data,
size, mime) < 0)
goto fail;
}
break;
case MKTAG('D', 'A', 'T', 'A'):
goto header_end;
default:
/* unknown tag: skip it */
avio_skip(pb, tag_size - 10);
break;
}
}
header_end:
rm->nb_packets = avio_rb32(pb); /* number of packets */
if (!rm->nb_packets && (flags & 4))
rm->nb_packets = 3600 * 25;
avio_rb32(pb); /* next data header */
if (!data_off)
data_off = avio_tell(pb) - 18;
if (indx_off && (pb->seekable & AVIO_SEEKABLE_NORMAL) &&
!(s->flags & AVFMT_FLAG_IGNIDX) &&
avio_seek(pb, indx_off, SEEK_SET) >= 0) {
rm_read_index(s);
avio_seek(pb, data_off + 18, SEEK_SET);
}
return 0;
fail:
rm_read_close(s);
return ret;
}
static int get_num(AVIOContext *pb, int *len)
{
int n, n1;
n = avio_rb16(pb);
(*len)-=2;
n &= 0x7FFF;
if (n >= 0x4000) {
return n - 0x4000;
} else {
n1 = avio_rb16(pb);
(*len)-=2;
return (n << 16) | n1;
}
}
/* multiple of 20 bytes for ra144 (ugly) */
#define RAW_PACKET_SIZE 1000
static int rm_sync(AVFormatContext *s, int64_t *timestamp, int *flags, int *stream_index, int64_t *pos){
RMDemuxContext *rm = s->priv_data;
AVIOContext *pb = s->pb;
AVStream *st;
uint32_t state=0xFFFFFFFF;
while(!avio_feof(pb)){
int len, num, i;
int mlti_id;
*pos= avio_tell(pb) - 3;
if(rm->remaining_len > 0){
num= rm->current_stream;
mlti_id = 0;
len= rm->remaining_len;
*timestamp = AV_NOPTS_VALUE;
*flags= 0;
}else{
state= (state<<8) + avio_r8(pb);
if(state == MKBETAG('I', 'N', 'D', 'X')){
int n_pkts, expected_len;
len = avio_rb32(pb);
avio_skip(pb, 2);
n_pkts = avio_rb32(pb);
expected_len = 20 + n_pkts * 14;
if (len == 20)
/* some files don't add index entries to chunk size... */
len = expected_len;
else if (len != expected_len)
av_log(s, AV_LOG_WARNING,
"Index size %d (%d pkts) is wrong, should be %d.\n",
len, n_pkts, expected_len);
len -= 14; // we already read part of the index header
if(len<0)
continue;
goto skip;
} else if (state == MKBETAG('D','A','T','A')) {
av_log(s, AV_LOG_WARNING,
"DATA tag in middle of chunk, file may be broken.\n");
}
if(state > (unsigned)0xFFFF || state <= 12)
continue;
len=state - 12;
state= 0xFFFFFFFF;
num = avio_rb16(pb);
*timestamp = avio_rb32(pb);
mlti_id = (avio_r8(pb)>>1)-1<<16;
mlti_id = FFMAX(mlti_id, 0);
*flags = avio_r8(pb); /* flags */
}
for(i=0;i<s->nb_streams;i++) {
st = s->streams[i];
if (mlti_id + num == st->id)
break;
}
if (i == s->nb_streams) {
skip:
/* skip packet if unknown number */
avio_skip(pb, len);
rm->remaining_len = 0;
continue;
}
*stream_index= i;
return len;
}
return -1;
}
static int rm_assemble_video_frame(AVFormatContext *s, AVIOContext *pb,
RMDemuxContext *rm, RMStream *vst,
AVPacket *pkt, int len, int *pseq,
int64_t *timestamp)
{
int hdr;
int seq = 0, pic_num = 0, len2 = 0, pos = 0; //init to silence compiler warning
int type;
int ret;
hdr = avio_r8(pb); len--;
type = hdr >> 6;
if(type != 3){ // not frame as a part of packet
seq = avio_r8(pb); len--;
}
if(type != 1){ // not whole frame
len2 = get_num(pb, &len);
pos = get_num(pb, &len);
pic_num = avio_r8(pb); len--;
}
if(len<0) {
av_log(s, AV_LOG_ERROR, "Insufficient data\n");
return -1;
}
rm->remaining_len = len;
if(type&1){ // frame, not slice
if(type == 3){ // frame as a part of packet
len= len2;
*timestamp = pos;
}
if(rm->remaining_len < len) {
av_log(s, AV_LOG_ERROR, "Insufficient remaining len\n");
return -1;
}
rm->remaining_len -= len;
if(av_new_packet(pkt, len + 9) < 0)
return AVERROR(EIO);
pkt->data[0] = 0;
AV_WL32(pkt->data + 1, 1);
AV_WL32(pkt->data + 5, 0);
if ((ret = avio_read(pb, pkt->data + 9, len)) != len) {
av_packet_unref(pkt);
av_log(s, AV_LOG_ERROR, "Failed to read %d bytes\n", len);
return ret < 0 ? ret : AVERROR(EIO);
}
return 0;
}
//now we have to deal with single slice
*pseq = seq;
if((seq & 0x7F) == 1 || vst->curpic_num != pic_num){
if (len2 > ffio_limit(pb, len2)) {
av_log(s, AV_LOG_ERROR, "Impossibly sized packet\n");
return AVERROR_INVALIDDATA;
}
vst->slices = ((hdr & 0x3F) << 1) + 1;
vst->videobufsize = len2 + 8*vst->slices + 1;
av_packet_unref(&vst->pkt); //FIXME this should be output.
if(av_new_packet(&vst->pkt, vst->videobufsize) < 0)
return AVERROR(ENOMEM);
memset(vst->pkt.data, 0, vst->pkt.size);
vst->videobufpos = 8*vst->slices + 1;
vst->cur_slice = 0;
vst->curpic_num = pic_num;
vst->pktpos = avio_tell(pb);
}
if(type == 2)
len = FFMIN(len, pos);
if(++vst->cur_slice > vst->slices) {
av_log(s, AV_LOG_ERROR, "cur slice %d, too large\n", vst->cur_slice);
return 1;
}
if(!vst->pkt.data)
return AVERROR(ENOMEM);
AV_WL32(vst->pkt.data - 7 + 8*vst->cur_slice, 1);
AV_WL32(vst->pkt.data - 3 + 8*vst->cur_slice, vst->videobufpos - 8*vst->slices - 1);
if(vst->videobufpos + len > vst->videobufsize) {
av_log(s, AV_LOG_ERROR, "outside videobufsize\n");
return 1;
}
if (avio_read(pb, vst->pkt.data + vst->videobufpos, len) != len)
return AVERROR(EIO);
vst->videobufpos += len;
rm->remaining_len-= len;
if (type == 2 || vst->videobufpos == vst->videobufsize) {
vst->pkt.data[0] = vst->cur_slice-1;
*pkt= vst->pkt;
vst->pkt.data= NULL;
vst->pkt.size= 0;
vst->pkt.buf = NULL;
if(vst->slices != vst->cur_slice) //FIXME find out how to set slices correct from the begin
memmove(pkt->data + 1 + 8*vst->cur_slice, pkt->data + 1 + 8*vst->slices,
vst->videobufpos - 1 - 8*vst->slices);
pkt->size = vst->videobufpos + 8*(vst->cur_slice - vst->slices);
pkt->pts = AV_NOPTS_VALUE;
pkt->pos = vst->pktpos;
vst->slices = 0;
return 0;
}
return 1;
}
static inline void
rm_ac3_swap_bytes (AVStream *st, AVPacket *pkt)
{
uint8_t *ptr;
int j;
if (st->codecpar->codec_id == AV_CODEC_ID_AC3) {
ptr = pkt->data;
for (j=0;j<pkt->size;j+=2) {
FFSWAP(int, ptr[0], ptr[1]);
ptr += 2;
}
}
}
static int readfull(AVFormatContext *s, AVIOContext *pb, uint8_t *dst, int n) {
int ret = avio_read(pb, dst, n);
if (ret != n) {
if (ret >= 0) memset(dst + ret, 0, n - ret);
else memset(dst , 0, n);
av_log(s, AV_LOG_ERROR, "Failed to fully read block\n");
}
return ret;
}
int
ff_rm_parse_packet (AVFormatContext *s, AVIOContext *pb,
AVStream *st, RMStream *ast, int len, AVPacket *pkt,
int *seq, int flags, int64_t timestamp)
{
RMDemuxContext *rm = s->priv_data;
int ret;
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
rm->current_stream= st->id;
ret = rm_assemble_video_frame(s, pb, rm, ast, pkt, len, seq, ×tamp);
if(ret)
return ret < 0 ? ret : -1; //got partial frame or error
} else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
if ((ast->deint_id == DEINT_ID_GENR) ||
(ast->deint_id == DEINT_ID_INT4) ||
(ast->deint_id == DEINT_ID_SIPR)) {
int x;
int sps = ast->sub_packet_size;
int cfs = ast->coded_framesize;
int h = ast->sub_packet_h;
int y = ast->sub_packet_cnt;
int w = ast->audio_framesize;
if (flags & 2)
y = ast->sub_packet_cnt = 0;
if (!y)
ast->audiotimestamp = timestamp;
switch (ast->deint_id) {
case DEINT_ID_INT4:
for (x = 0; x < h/2; x++)
readfull(s, pb, ast->pkt.data+x*2*w+y*cfs, cfs);
break;
case DEINT_ID_GENR:
for (x = 0; x < w/sps; x++)
readfull(s, pb, ast->pkt.data+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), sps);
break;
case DEINT_ID_SIPR:
readfull(s, pb, ast->pkt.data + y * w, w);
break;
}
if (++(ast->sub_packet_cnt) < h)
return -1;
if (ast->deint_id == DEINT_ID_SIPR)
ff_rm_reorder_sipr_data(ast->pkt.data, h, w);
ast->sub_packet_cnt = 0;
rm->audio_stream_num = st->index;
if (st->codecpar->block_align <= 0) {
av_log(s, AV_LOG_ERROR, "Invalid block alignment %d\n", st->codecpar->block_align);
return AVERROR_INVALIDDATA;
}
rm->audio_pkt_cnt = h * w / st->codecpar->block_align;
} else if ((ast->deint_id == DEINT_ID_VBRF) ||
(ast->deint_id == DEINT_ID_VBRS)) {
int x;
rm->audio_stream_num = st->index;
ast->sub_packet_cnt = (avio_rb16(pb) & 0xf0) >> 4;
if (ast->sub_packet_cnt) {
for (x = 0; x < ast->sub_packet_cnt; x++)
ast->sub_packet_lengths[x] = avio_rb16(pb);
rm->audio_pkt_cnt = ast->sub_packet_cnt;
ast->audiotimestamp = timestamp;
} else
return -1;
} else {
ret = av_get_packet(pb, pkt, len);
if (ret < 0)
return ret;
rm_ac3_swap_bytes(st, pkt);
}
} else {
ret = av_get_packet(pb, pkt, len);
if (ret < 0)
return ret;
}
pkt->stream_index = st->index;
pkt->pts = timestamp;
if (flags & 2)
pkt->flags |= AV_PKT_FLAG_KEY;
return st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ? rm->audio_pkt_cnt : 0;
}
int
ff_rm_retrieve_cache (AVFormatContext *s, AVIOContext *pb,
AVStream *st, RMStream *ast, AVPacket *pkt)
{
RMDemuxContext *rm = s->priv_data;
int ret;
av_assert0 (rm->audio_pkt_cnt > 0);
if (ast->deint_id == DEINT_ID_VBRF ||
ast->deint_id == DEINT_ID_VBRS) {
ret = av_get_packet(pb, pkt, ast->sub_packet_lengths[ast->sub_packet_cnt - rm->audio_pkt_cnt]);
if (ret < 0)
return ret;
} else {
ret = av_new_packet(pkt, st->codecpar->block_align);
if (ret < 0)
return ret;
memcpy(pkt->data, ast->pkt.data + st->codecpar->block_align * //FIXME avoid this
(ast->sub_packet_h * ast->audio_framesize / st->codecpar->block_align - rm->audio_pkt_cnt),
st->codecpar->block_align);
}
rm->audio_pkt_cnt--;
if ((pkt->pts = ast->audiotimestamp) != AV_NOPTS_VALUE) {
ast->audiotimestamp = AV_NOPTS_VALUE;
pkt->flags = AV_PKT_FLAG_KEY;
} else
pkt->flags = 0;
pkt->stream_index = st->index;
return rm->audio_pkt_cnt;
}
static int rm_read_packet(AVFormatContext *s, AVPacket *pkt)
{
RMDemuxContext *rm = s->priv_data;
AVStream *st = NULL; // init to silence compiler warning
int i, len, res, seq = 1;
int64_t timestamp, pos;
int flags;
for (;;) {
if (rm->audio_pkt_cnt) {
// If there are queued audio packet return them first
st = s->streams[rm->audio_stream_num];
res = ff_rm_retrieve_cache(s, s->pb, st, st->priv_data, pkt);
if(res < 0)
return res;
flags = 0;
} else {
if (rm->old_format) {
RMStream *ast;
st = s->streams[0];
ast = st->priv_data;
timestamp = AV_NOPTS_VALUE;
len = !ast->audio_framesize ? RAW_PACKET_SIZE :
ast->coded_framesize * ast->sub_packet_h / 2;
flags = (seq++ == 1) ? 2 : 0;
pos = avio_tell(s->pb);
} else {
len = rm_sync(s, ×tamp, &flags, &i, &pos);
if (len > 0)
st = s->streams[i];
}
if (avio_feof(s->pb))
return AVERROR_EOF;
if (len <= 0)
return AVERROR(EIO);
res = ff_rm_parse_packet (s, s->pb, st, st->priv_data, len, pkt,
&seq, flags, timestamp);
if (res < -1)
return res;
if((flags&2) && (seq&0x7F) == 1)
av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);
if (res)
continue;
}
if( (st->discard >= AVDISCARD_NONKEY && !(flags&2))
|| st->discard >= AVDISCARD_ALL){
av_packet_unref(pkt);
} else
break;
}
return 0;
}
static int rm_read_close(AVFormatContext *s)
{
int i;
for (i=0;i<s->nb_streams;i++)
ff_rm_free_rmstream(s->streams[i]->priv_data);
return 0;
}
static int rm_probe(AVProbeData *p)
{
/* check file header */
if ((p->buf[0] == '.' && p->buf[1] == 'R' &&
p->buf[2] == 'M' && p->buf[3] == 'F' &&
p->buf[4] == 0 && p->buf[5] == 0) ||
(p->buf[0] == '.' && p->buf[1] == 'r' &&
p->buf[2] == 'a' && p->buf[3] == 0xfd))
return AVPROBE_SCORE_MAX;
else
return 0;
}
static int64_t rm_read_dts(AVFormatContext *s, int stream_index,
int64_t *ppos, int64_t pos_limit)
{
RMDemuxContext *rm = s->priv_data;
int64_t pos, dts;
int stream_index2, flags, len, h;
pos = *ppos;
if(rm->old_format)
return AV_NOPTS_VALUE;
if (avio_seek(s->pb, pos, SEEK_SET) < 0)
return AV_NOPTS_VALUE;
rm->remaining_len=0;
for(;;){
int seq=1;
AVStream *st;
len = rm_sync(s, &dts, &flags, &stream_index2, &pos);
if(len<0)
return AV_NOPTS_VALUE;
st = s->streams[stream_index2];
if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
h= avio_r8(s->pb); len--;
if(!(h & 0x40)){
seq = avio_r8(s->pb); len--;
}
}
if((flags&2) && (seq&0x7F) == 1){
av_log(s, AV_LOG_TRACE, "%d %d-%d %"PRId64" %d\n",
flags, stream_index2, stream_index, dts, seq);
av_add_index_entry(st, pos, dts, 0, 0, AVINDEX_KEYFRAME);
if(stream_index2 == stream_index)
break;
}
avio_skip(s->pb, len);
}
*ppos = pos;
return dts;
}
static int rm_read_seek(AVFormatContext *s, int stream_index,
int64_t pts, int flags)
{
RMDemuxContext *rm = s->priv_data;
if (ff_seek_frame_binary(s, stream_index, pts, flags) < 0)
return -1;
rm->audio_pkt_cnt = 0;
return 0;
}
AVInputFormat ff_rm_demuxer = {
.name = "rm",
.long_name = NULL_IF_CONFIG_SMALL("RealMedia"),
.priv_data_size = sizeof(RMDemuxContext),
.read_probe = rm_probe,
.read_header = rm_read_header,
.read_packet = rm_read_packet,
.read_close = rm_read_close,
.read_timestamp = rm_read_dts,
.read_seek = rm_read_seek,
};
AVInputFormat ff_rdt_demuxer = {
.name = "rdt",
.long_name = NULL_IF_CONFIG_SMALL("RDT demuxer"),
.priv_data_size = sizeof(RMDemuxContext),
.read_close = rm_read_close,
.flags = AVFMT_NOFILE,
};
static int ivr_probe(AVProbeData *p)
{
if (memcmp(p->buf, ".R1M\x0\x1\x1", 7) &&
memcmp(p->buf, ".REC", 4))
return 0;
return AVPROBE_SCORE_MAX;
}
static int ivr_read_header(AVFormatContext *s)
{
unsigned tag, type, len, tlen, value;
int i, j, n, count, nb_streams = 0, ret;
uint8_t key[256], val[256];
AVIOContext *pb = s->pb;
AVStream *st;
int64_t pos, offset, temp;
pos = avio_tell(pb);
tag = avio_rl32(pb);
if (tag == MKTAG('.','R','1','M')) {
if (avio_rb16(pb) != 1)
return AVERROR_INVALIDDATA;
if (avio_r8(pb) != 1)
return AVERROR_INVALIDDATA;
len = avio_rb32(pb);
avio_skip(pb, len);
avio_skip(pb, 5);
temp = avio_rb64(pb);
while (!avio_feof(pb) && temp) {
offset = temp;
temp = avio_rb64(pb);
}
avio_skip(pb, offset - avio_tell(pb));
if (avio_r8(pb) != 1)
return AVERROR_INVALIDDATA;
len = avio_rb32(pb);
avio_skip(pb, len);
if (avio_r8(pb) != 2)
return AVERROR_INVALIDDATA;
avio_skip(pb, 16);
pos = avio_tell(pb);
tag = avio_rl32(pb);
}
if (tag != MKTAG('.','R','E','C'))
return AVERROR_INVALIDDATA;
if (avio_r8(pb) != 0)
return AVERROR_INVALIDDATA;
count = avio_rb32(pb);
for (i = 0; i < count; i++) {
if (avio_feof(pb))
return AVERROR_INVALIDDATA;
type = avio_r8(pb);
tlen = avio_rb32(pb);
avio_get_str(pb, tlen, key, sizeof(key));
len = avio_rb32(pb);
if (type == 5) {
avio_get_str(pb, len, val, sizeof(val));
av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val);
} else if (type == 4) {
av_log(s, AV_LOG_DEBUG, "%s = '0x", key);
for (j = 0; j < len; j++) {
if (avio_feof(pb))
return AVERROR_INVALIDDATA;
av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb));
}
av_log(s, AV_LOG_DEBUG, "'\n");
} else if (len == 4 && type == 3 && !strncmp(key, "StreamCount", tlen)) {
nb_streams = value = avio_rb32(pb);
} else if (len == 4 && type == 3) {
value = avio_rb32(pb);
av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value);
} else {
av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key);
avio_skip(pb, len);
}
}
for (n = 0; n < nb_streams; n++) {
st = avformat_new_stream(s, NULL);
if (!st)
return AVERROR(ENOMEM);
st->priv_data = ff_rm_alloc_rmstream();
if (!st->priv_data)
return AVERROR(ENOMEM);
if (avio_r8(pb) != 1)
return AVERROR_INVALIDDATA;
count = avio_rb32(pb);
for (i = 0; i < count; i++) {
if (avio_feof(pb))
return AVERROR_INVALIDDATA;
type = avio_r8(pb);
tlen = avio_rb32(pb);
avio_get_str(pb, tlen, key, sizeof(key));
len = avio_rb32(pb);
if (type == 5) {
avio_get_str(pb, len, val, sizeof(val));
av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val);
} else if (type == 4 && !strncmp(key, "OpaqueData", tlen)) {
ret = ffio_ensure_seekback(pb, 4);
if (ret < 0)
return ret;
if (avio_rb32(pb) == MKBETAG('M', 'L', 'T', 'I')) {
ret = rm_read_multi(s, pb, st, NULL);
} else {
avio_seek(pb, -4, SEEK_CUR);
ret = ff_rm_read_mdpr_codecdata(s, pb, st, st->priv_data, len, NULL);
}
if (ret < 0)
return ret;
} else if (type == 4) {
int j;
av_log(s, AV_LOG_DEBUG, "%s = '0x", key);
for (j = 0; j < len; j++)
av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb));
av_log(s, AV_LOG_DEBUG, "'\n");
} else if (len == 4 && type == 3 && !strncmp(key, "Duration", tlen)) {
st->duration = avio_rb32(pb);
} else if (len == 4 && type == 3) {
value = avio_rb32(pb);
av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value);
} else {
av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key);
avio_skip(pb, len);
}
}
}
if (avio_r8(pb) != 6)
return AVERROR_INVALIDDATA;
avio_skip(pb, 12);
avio_skip(pb, avio_rb64(pb) + pos - avio_tell(s->pb));
if (avio_r8(pb) != 8)
return AVERROR_INVALIDDATA;
avio_skip(pb, 8);
return 0;
}
static int ivr_read_packet(AVFormatContext *s, AVPacket *pkt)
{
RMDemuxContext *rm = s->priv_data;
int ret = AVERROR_EOF, opcode;
AVIOContext *pb = s->pb;
unsigned size, index;
int64_t pos, pts;
if (avio_feof(pb) || rm->data_end)
return AVERROR_EOF;
pos = avio_tell(pb);
for (;;) {
if (rm->audio_pkt_cnt) {
// If there are queued audio packet return them first
AVStream *st;
st = s->streams[rm->audio_stream_num];
ret = ff_rm_retrieve_cache(s, pb, st, st->priv_data, pkt);
if (ret < 0) {
return ret;
}
} else {
if (rm->remaining_len) {
avio_skip(pb, rm->remaining_len);
rm->remaining_len = 0;
}
if (avio_feof(pb))
return AVERROR_EOF;
opcode = avio_r8(pb);
if (opcode == 2) {
AVStream *st;
int seq = 1;
pts = avio_rb32(pb);
index = avio_rb16(pb);
if (index >= s->nb_streams)
return AVERROR_INVALIDDATA;
avio_skip(pb, 4);
size = avio_rb32(pb);
avio_skip(pb, 4);
if (size < 1 || size > INT_MAX/4) {
av_log(s, AV_LOG_ERROR, "size %u is invalid\n", size);
return AVERROR_INVALIDDATA;
}
st = s->streams[index];
ret = ff_rm_parse_packet(s, pb, st, st->priv_data, size, pkt,
&seq, 0, pts);
if (ret < -1) {
return ret;
} else if (ret) {
continue;
}
pkt->pos = pos;
pkt->pts = pts;
pkt->stream_index = index;
} else if (opcode == 7) {
pos = avio_rb64(pb);
if (!pos) {
rm->data_end = 1;
return AVERROR_EOF;
}
} else {
av_log(s, AV_LOG_ERROR, "Unsupported opcode=%d at %"PRIX64"\n", opcode, avio_tell(pb) - 1);
return AVERROR(EIO);
}
}
break;
}
return ret;
}
AVInputFormat ff_ivr_demuxer = {
.name = "ivr",
.long_name = NULL_IF_CONFIG_SMALL("IVR (Internet Video Recording)"),
.priv_data_size = sizeof(RMDemuxContext),
.read_probe = ivr_probe,
.read_header = ivr_read_header,
.read_packet = ivr_read_packet,
.read_close = rm_read_close,
.extensions = "ivr",
};
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_466_0 |
crossvul-cpp_data_good_832_1 | // SPDX-License-Identifier: GPL-2.0+
#include <linux/io.h>
#include "ipmi_si.h"
static unsigned char intf_mem_inb(const struct si_sm_io *io,
unsigned int offset)
{
return readb((io->addr)+(offset * io->regspacing));
}
static void intf_mem_outb(const struct si_sm_io *io, unsigned int offset,
unsigned char b)
{
writeb(b, (io->addr)+(offset * io->regspacing));
}
static unsigned char intf_mem_inw(const struct si_sm_io *io,
unsigned int offset)
{
return (readw((io->addr)+(offset * io->regspacing)) >> io->regshift)
& 0xff;
}
static void intf_mem_outw(const struct si_sm_io *io, unsigned int offset,
unsigned char b)
{
writeb(b << io->regshift, (io->addr)+(offset * io->regspacing));
}
static unsigned char intf_mem_inl(const struct si_sm_io *io,
unsigned int offset)
{
return (readl((io->addr)+(offset * io->regspacing)) >> io->regshift)
& 0xff;
}
static void intf_mem_outl(const struct si_sm_io *io, unsigned int offset,
unsigned char b)
{
writel(b << io->regshift, (io->addr)+(offset * io->regspacing));
}
#ifdef readq
static unsigned char mem_inq(const struct si_sm_io *io, unsigned int offset)
{
return (readq((io->addr)+(offset * io->regspacing)) >> io->regshift)
& 0xff;
}
static void mem_outq(const struct si_sm_io *io, unsigned int offset,
unsigned char b)
{
writeq((u64)b << io->regshift, (io->addr)+(offset * io->regspacing));
}
#endif
static void mem_region_cleanup(struct si_sm_io *io, int num)
{
unsigned long addr = io->addr_data;
int idx;
for (idx = 0; idx < num; idx++)
release_mem_region(addr + idx * io->regspacing,
io->regsize);
}
static void mem_cleanup(struct si_sm_io *io)
{
if (io->addr) {
iounmap(io->addr);
mem_region_cleanup(io, io->io_size);
}
}
int ipmi_si_mem_setup(struct si_sm_io *io)
{
unsigned long addr = io->addr_data;
int mapsize, idx;
if (!addr)
return -ENODEV;
/*
* Figure out the actual readb/readw/readl/etc routine to use based
* upon the register size.
*/
switch (io->regsize) {
case 1:
io->inputb = intf_mem_inb;
io->outputb = intf_mem_outb;
break;
case 2:
io->inputb = intf_mem_inw;
io->outputb = intf_mem_outw;
break;
case 4:
io->inputb = intf_mem_inl;
io->outputb = intf_mem_outl;
break;
#ifdef readq
case 8:
io->inputb = mem_inq;
io->outputb = mem_outq;
break;
#endif
default:
dev_warn(io->dev, "Invalid register size: %d\n",
io->regsize);
return -EINVAL;
}
/*
* Some BIOSes reserve disjoint memory regions in their ACPI
* tables. This causes problems when trying to request the
* entire region. Therefore we must request each register
* separately.
*/
for (idx = 0; idx < io->io_size; idx++) {
if (request_mem_region(addr + idx * io->regspacing,
io->regsize, DEVICE_NAME) == NULL) {
/* Undo allocations */
mem_region_cleanup(io, idx);
return -EIO;
}
}
/*
* Calculate the total amount of memory to claim. This is an
* unusual looking calculation, but it avoids claiming any
* more memory than it has to. It will claim everything
* between the first address to the end of the last full
* register.
*/
mapsize = ((io->io_size * io->regspacing)
- (io->regspacing - io->regsize));
io->addr = ioremap(addr, mapsize);
if (io->addr == NULL) {
mem_region_cleanup(io, io->io_size);
return -EIO;
}
io->io_cleanup = mem_cleanup;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-416/c/good_832_1 |
crossvul-cpp_data_bad_375_0 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2018, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
#include "curl_setup.h"
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_NETDB_H
#include <netdb.h>
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#ifdef HAVE_NET_IF_H
#include <net/if.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifdef __VMS
#include <in.h>
#include <inet.h>
#endif
#ifdef HAVE_SYS_UN_H
#include <sys/un.h>
#endif
#ifndef HAVE_SOCKET
#error "We can't compile without socket() support!"
#endif
#include <limits.h>
#ifdef USE_LIBIDN2
#include <idn2.h>
#elif defined(USE_WIN32_IDN)
/* prototype for curl_win32_idn_to_ascii() */
bool curl_win32_idn_to_ascii(const char *in, char **out);
#endif /* USE_LIBIDN2 */
#include "urldata.h"
#include "netrc.h"
#include "formdata.h"
#include "mime.h"
#include "vtls/vtls.h"
#include "hostip.h"
#include "transfer.h"
#include "sendf.h"
#include "progress.h"
#include "cookie.h"
#include "strcase.h"
#include "strerror.h"
#include "escape.h"
#include "strtok.h"
#include "share.h"
#include "content_encoding.h"
#include "http_digest.h"
#include "http_negotiate.h"
#include "select.h"
#include "multiif.h"
#include "easyif.h"
#include "speedcheck.h"
#include "warnless.h"
#include "non-ascii.h"
#include "inet_pton.h"
#include "getinfo.h"
#include "urlapi-int.h"
/* And now for the protocols */
#include "ftp.h"
#include "dict.h"
#include "telnet.h"
#include "tftp.h"
#include "http.h"
#include "http2.h"
#include "file.h"
#include "curl_ldap.h"
#include "ssh.h"
#include "imap.h"
#include "url.h"
#include "connect.h"
#include "inet_ntop.h"
#include "http_ntlm.h"
#include "curl_ntlm_wb.h"
#include "socks.h"
#include "curl_rtmp.h"
#include "gopher.h"
#include "http_proxy.h"
#include "conncache.h"
#include "multihandle.h"
#include "pipeline.h"
#include "dotdot.h"
#include "strdup.h"
#include "setopt.h"
/* The last 3 #include files should be in this order */
#include "curl_printf.h"
#include "curl_memory.h"
#include "memdebug.h"
static void conn_free(struct connectdata *conn);
static void free_fixed_hostname(struct hostname *host);
static unsigned int get_protocol_family(unsigned int protocol);
/* Some parts of the code (e.g. chunked encoding) assume this buffer has at
* more than just a few bytes to play with. Don't let it become too small or
* bad things will happen.
*/
#if READBUFFER_SIZE < READBUFFER_MIN
# error READBUFFER_SIZE is too small
#endif
/*
* Protocol table.
*/
static const struct Curl_handler * const protocols[] = {
#ifndef CURL_DISABLE_HTTP
&Curl_handler_http,
#endif
#if defined(USE_SSL) && !defined(CURL_DISABLE_HTTP)
&Curl_handler_https,
#endif
#ifndef CURL_DISABLE_FTP
&Curl_handler_ftp,
#endif
#if defined(USE_SSL) && !defined(CURL_DISABLE_FTP)
&Curl_handler_ftps,
#endif
#ifndef CURL_DISABLE_TELNET
&Curl_handler_telnet,
#endif
#ifndef CURL_DISABLE_DICT
&Curl_handler_dict,
#endif
#ifndef CURL_DISABLE_LDAP
&Curl_handler_ldap,
#if !defined(CURL_DISABLE_LDAPS) && \
((defined(USE_OPENLDAP) && defined(USE_SSL)) || \
(!defined(USE_OPENLDAP) && defined(HAVE_LDAP_SSL)))
&Curl_handler_ldaps,
#endif
#endif
#ifndef CURL_DISABLE_FILE
&Curl_handler_file,
#endif
#ifndef CURL_DISABLE_TFTP
&Curl_handler_tftp,
#endif
#if defined(USE_LIBSSH2) || defined(USE_LIBSSH)
&Curl_handler_scp,
#endif
#if defined(USE_LIBSSH2) || defined(USE_LIBSSH)
&Curl_handler_sftp,
#endif
#ifndef CURL_DISABLE_IMAP
&Curl_handler_imap,
#ifdef USE_SSL
&Curl_handler_imaps,
#endif
#endif
#ifndef CURL_DISABLE_POP3
&Curl_handler_pop3,
#ifdef USE_SSL
&Curl_handler_pop3s,
#endif
#endif
#if !defined(CURL_DISABLE_SMB) && defined(USE_NTLM) && \
(CURL_SIZEOF_CURL_OFF_T > 4) && \
(!defined(USE_WINDOWS_SSPI) || defined(USE_WIN32_CRYPTO))
&Curl_handler_smb,
#ifdef USE_SSL
&Curl_handler_smbs,
#endif
#endif
#ifndef CURL_DISABLE_SMTP
&Curl_handler_smtp,
#ifdef USE_SSL
&Curl_handler_smtps,
#endif
#endif
#ifndef CURL_DISABLE_RTSP
&Curl_handler_rtsp,
#endif
#ifndef CURL_DISABLE_GOPHER
&Curl_handler_gopher,
#endif
#ifdef USE_LIBRTMP
&Curl_handler_rtmp,
&Curl_handler_rtmpt,
&Curl_handler_rtmpe,
&Curl_handler_rtmpte,
&Curl_handler_rtmps,
&Curl_handler_rtmpts,
#endif
(struct Curl_handler *) NULL
};
/*
* Dummy handler for undefined protocol schemes.
*/
static const struct Curl_handler Curl_handler_dummy = {
"<no protocol>", /* scheme */
ZERO_NULL, /* setup_connection */
ZERO_NULL, /* do_it */
ZERO_NULL, /* done */
ZERO_NULL, /* do_more */
ZERO_NULL, /* connect_it */
ZERO_NULL, /* connecting */
ZERO_NULL, /* doing */
ZERO_NULL, /* proto_getsock */
ZERO_NULL, /* doing_getsock */
ZERO_NULL, /* domore_getsock */
ZERO_NULL, /* perform_getsock */
ZERO_NULL, /* disconnect */
ZERO_NULL, /* readwrite */
ZERO_NULL, /* connection_check */
0, /* defport */
0, /* protocol */
PROTOPT_NONE /* flags */
};
void Curl_freeset(struct Curl_easy *data)
{
/* Free all dynamic strings stored in the data->set substructure. */
enum dupstring i;
for(i = (enum dupstring)0; i < STRING_LAST; i++) {
Curl_safefree(data->set.str[i]);
}
if(data->change.referer_alloc) {
Curl_safefree(data->change.referer);
data->change.referer_alloc = FALSE;
}
data->change.referer = NULL;
if(data->change.url_alloc) {
Curl_safefree(data->change.url);
data->change.url_alloc = FALSE;
}
data->change.url = NULL;
Curl_mime_cleanpart(&data->set.mimepost);
}
/* free the URL pieces */
void Curl_up_free(struct Curl_easy *data)
{
struct urlpieces *up = &data->state.up;
Curl_safefree(up->scheme);
Curl_safefree(up->hostname);
Curl_safefree(up->port);
Curl_safefree(up->user);
Curl_safefree(up->password);
Curl_safefree(up->options);
Curl_safefree(up->path);
Curl_safefree(up->query);
curl_url_cleanup(data->state.uh);
data->state.uh = NULL;
}
/*
* This is the internal function curl_easy_cleanup() calls. This should
* cleanup and free all resources associated with this sessionhandle.
*
* NOTE: if we ever add something that attempts to write to a socket or
* similar here, we must ignore SIGPIPE first. It is currently only done
* when curl_easy_perform() is invoked.
*/
CURLcode Curl_close(struct Curl_easy *data)
{
struct Curl_multi *m;
if(!data)
return CURLE_OK;
Curl_expire_clear(data); /* shut off timers */
m = data->multi;
if(m)
/* This handle is still part of a multi handle, take care of this first
and detach this handle from there. */
curl_multi_remove_handle(data->multi, data);
if(data->multi_easy)
/* when curl_easy_perform() is used, it creates its own multi handle to
use and this is the one */
curl_multi_cleanup(data->multi_easy);
/* Destroy the timeout list that is held in the easy handle. It is
/normally/ done by curl_multi_remove_handle() but this is "just in
case" */
Curl_llist_destroy(&data->state.timeoutlist, NULL);
data->magic = 0; /* force a clear AFTER the possibly enforced removal from
the multi handle, since that function uses the magic
field! */
if(data->state.rangestringalloc)
free(data->state.range);
/* freed here just in case DONE wasn't called */
Curl_free_request_state(data);
/* Close down all open SSL info and sessions */
Curl_ssl_close_all(data);
Curl_safefree(data->state.first_host);
Curl_safefree(data->state.scratch);
Curl_ssl_free_certinfo(data);
/* Cleanup possible redirect junk */
free(data->req.newurl);
data->req.newurl = NULL;
if(data->change.referer_alloc) {
Curl_safefree(data->change.referer);
data->change.referer_alloc = FALSE;
}
data->change.referer = NULL;
Curl_up_free(data);
Curl_safefree(data->state.buffer);
Curl_safefree(data->state.headerbuff);
Curl_safefree(data->state.ulbuf);
Curl_flush_cookies(data, 1);
Curl_digest_cleanup(data);
Curl_safefree(data->info.contenttype);
Curl_safefree(data->info.wouldredirect);
/* this destroys the channel and we cannot use it anymore after this */
Curl_resolver_cleanup(data->state.resolver);
Curl_http2_cleanup_dependencies(data);
Curl_convert_close(data);
/* No longer a dirty share, if it exists */
if(data->share) {
Curl_share_lock(data, CURL_LOCK_DATA_SHARE, CURL_LOCK_ACCESS_SINGLE);
data->share->dirty--;
Curl_share_unlock(data, CURL_LOCK_DATA_SHARE);
}
/* destruct wildcard structures if it is needed */
Curl_wildcard_dtor(&data->wildcard);
Curl_freeset(data);
free(data);
return CURLE_OK;
}
/*
* Initialize the UserDefined fields within a Curl_easy.
* This may be safely called on a new or existing Curl_easy.
*/
CURLcode Curl_init_userdefined(struct Curl_easy *data)
{
struct UserDefined *set = &data->set;
CURLcode result = CURLE_OK;
set->out = stdout; /* default output to stdout */
set->in_set = stdin; /* default input from stdin */
set->err = stderr; /* default stderr to stderr */
/* use fwrite as default function to store output */
set->fwrite_func = (curl_write_callback)fwrite;
/* use fread as default function to read input */
set->fread_func_set = (curl_read_callback)fread;
set->is_fread_set = 0;
set->is_fwrite_set = 0;
set->seek_func = ZERO_NULL;
set->seek_client = ZERO_NULL;
/* conversion callbacks for non-ASCII hosts */
set->convfromnetwork = ZERO_NULL;
set->convtonetwork = ZERO_NULL;
set->convfromutf8 = ZERO_NULL;
set->filesize = -1; /* we don't know the size */
set->postfieldsize = -1; /* unknown size */
set->maxredirs = -1; /* allow any amount by default */
set->httpreq = HTTPREQ_GET; /* Default HTTP request */
set->rtspreq = RTSPREQ_OPTIONS; /* Default RTSP request */
set->ftp_use_epsv = TRUE; /* FTP defaults to EPSV operations */
set->ftp_use_eprt = TRUE; /* FTP defaults to EPRT operations */
set->ftp_use_pret = FALSE; /* mainly useful for drftpd servers */
set->ftp_filemethod = FTPFILE_MULTICWD;
set->dns_cache_timeout = 60; /* Timeout every 60 seconds by default */
/* Set the default size of the SSL session ID cache */
set->general_ssl.max_ssl_sessions = 5;
set->proxyport = 0;
set->proxytype = CURLPROXY_HTTP; /* defaults to HTTP proxy */
set->httpauth = CURLAUTH_BASIC; /* defaults to basic */
set->proxyauth = CURLAUTH_BASIC; /* defaults to basic */
/* SOCKS5 proxy auth defaults to username/password + GSS-API */
set->socks5auth = CURLAUTH_BASIC | CURLAUTH_GSSAPI;
/* make libcurl quiet by default: */
set->hide_progress = TRUE; /* CURLOPT_NOPROGRESS changes these */
Curl_mime_initpart(&set->mimepost, data);
/*
* libcurl 7.10 introduced SSL verification *by default*! This needs to be
* switched off unless wanted.
*/
set->ssl.primary.verifypeer = TRUE;
set->ssl.primary.verifyhost = TRUE;
#ifdef USE_TLS_SRP
set->ssl.authtype = CURL_TLSAUTH_NONE;
#endif
set->ssh_auth_types = CURLSSH_AUTH_DEFAULT; /* defaults to any auth
type */
set->ssl.primary.sessionid = TRUE; /* session ID caching enabled by
default */
set->proxy_ssl = set->ssl;
set->new_file_perms = 0644; /* Default permissions */
set->new_directory_perms = 0755; /* Default permissions */
/* for the *protocols fields we don't use the CURLPROTO_ALL convenience
define since we internally only use the lower 16 bits for the passed
in bitmask to not conflict with the private bits */
set->allowed_protocols = CURLPROTO_ALL;
set->redir_protocols = CURLPROTO_ALL & /* All except FILE, SCP and SMB */
~(CURLPROTO_FILE | CURLPROTO_SCP | CURLPROTO_SMB |
CURLPROTO_SMBS);
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
/*
* disallow unprotected protection negotiation NEC reference implementation
* seem not to follow rfc1961 section 4.3/4.4
*/
set->socks5_gssapi_nec = FALSE;
#endif
/* Set the default CA cert bundle/path detected/specified at build time.
*
* If Schannel (WinSSL) is the selected SSL backend then these locations
* are ignored. We allow setting CA location for schannel only when
* explicitly specified by the user via CURLOPT_CAINFO / --cacert.
*/
if(Curl_ssl_backend() != CURLSSLBACKEND_SCHANNEL) {
#if defined(CURL_CA_BUNDLE)
result = Curl_setstropt(&set->str[STRING_SSL_CAFILE_ORIG], CURL_CA_BUNDLE);
if(result)
return result;
result = Curl_setstropt(&set->str[STRING_SSL_CAFILE_PROXY],
CURL_CA_BUNDLE);
if(result)
return result;
#endif
#if defined(CURL_CA_PATH)
result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_ORIG], CURL_CA_PATH);
if(result)
return result;
result = Curl_setstropt(&set->str[STRING_SSL_CAPATH_PROXY], CURL_CA_PATH);
if(result)
return result;
#endif
}
set->wildcard_enabled = FALSE;
set->chunk_bgn = ZERO_NULL;
set->chunk_end = ZERO_NULL;
set->tcp_keepalive = FALSE;
set->tcp_keepintvl = 60;
set->tcp_keepidle = 60;
set->tcp_fastopen = FALSE;
set->tcp_nodelay = TRUE;
set->ssl_enable_npn = TRUE;
set->ssl_enable_alpn = TRUE;
set->expect_100_timeout = 1000L; /* Wait for a second by default. */
set->sep_headers = TRUE; /* separated header lists by default */
set->buffer_size = READBUFFER_SIZE;
set->upload_buffer_size = UPLOADBUFFER_DEFAULT;
set->happy_eyeballs_timeout = CURL_HET_DEFAULT;
set->fnmatch = ZERO_NULL;
set->upkeep_interval_ms = CURL_UPKEEP_INTERVAL_DEFAULT;
set->maxconnects = DEFAULT_CONNCACHE_SIZE; /* for easy handles */
set->httpversion =
#ifdef USE_NGHTTP2
CURL_HTTP_VERSION_2TLS
#else
CURL_HTTP_VERSION_1_1
#endif
;
Curl_http2_init_userset(set);
return result;
}
/**
* Curl_open()
*
* @param curl is a pointer to a sessionhandle pointer that gets set by this
* function.
* @return CURLcode
*/
CURLcode Curl_open(struct Curl_easy **curl)
{
CURLcode result;
struct Curl_easy *data;
/* Very simple start-up: alloc the struct, init it with zeroes and return */
data = calloc(1, sizeof(struct Curl_easy));
if(!data) {
/* this is a very serious error */
DEBUGF(fprintf(stderr, "Error: calloc of Curl_easy failed\n"));
return CURLE_OUT_OF_MEMORY;
}
data->magic = CURLEASY_MAGIC_NUMBER;
result = Curl_resolver_init(&data->state.resolver);
if(result) {
DEBUGF(fprintf(stderr, "Error: resolver_init failed\n"));
free(data);
return result;
}
/* We do some initial setup here, all those fields that can't be just 0 */
data->state.buffer = malloc(READBUFFER_SIZE + 1);
if(!data->state.buffer) {
DEBUGF(fprintf(stderr, "Error: malloc of buffer failed\n"));
result = CURLE_OUT_OF_MEMORY;
}
else {
data->state.headerbuff = malloc(HEADERSIZE);
if(!data->state.headerbuff) {
DEBUGF(fprintf(stderr, "Error: malloc of headerbuff failed\n"));
result = CURLE_OUT_OF_MEMORY;
}
else {
result = Curl_init_userdefined(data);
data->state.headersize = HEADERSIZE;
Curl_convert_init(data);
Curl_initinfo(data);
/* most recent connection is not yet defined */
data->state.lastconnect = NULL;
data->progress.flags |= PGRS_HIDE;
data->state.current_speed = -1; /* init to negative == impossible */
Curl_http2_init_state(&data->state);
}
}
if(result) {
Curl_resolver_cleanup(data->state.resolver);
free(data->state.buffer);
free(data->state.headerbuff);
Curl_freeset(data);
free(data);
data = NULL;
}
else
*curl = data;
return result;
}
#ifdef USE_RECV_BEFORE_SEND_WORKAROUND
static void conn_reset_postponed_data(struct connectdata *conn, int num)
{
struct postponed_data * const psnd = &(conn->postponed[num]);
if(psnd->buffer) {
DEBUGASSERT(psnd->allocated_size > 0);
DEBUGASSERT(psnd->recv_size <= psnd->allocated_size);
DEBUGASSERT(psnd->recv_size ?
(psnd->recv_processed < psnd->recv_size) :
(psnd->recv_processed == 0));
DEBUGASSERT(psnd->bindsock != CURL_SOCKET_BAD);
free(psnd->buffer);
psnd->buffer = NULL;
psnd->allocated_size = 0;
psnd->recv_size = 0;
psnd->recv_processed = 0;
#ifdef DEBUGBUILD
psnd->bindsock = CURL_SOCKET_BAD; /* used only for DEBUGASSERT */
#endif /* DEBUGBUILD */
}
else {
DEBUGASSERT(psnd->allocated_size == 0);
DEBUGASSERT(psnd->recv_size == 0);
DEBUGASSERT(psnd->recv_processed == 0);
DEBUGASSERT(psnd->bindsock == CURL_SOCKET_BAD);
}
}
static void conn_reset_all_postponed_data(struct connectdata *conn)
{
conn_reset_postponed_data(conn, 0);
conn_reset_postponed_data(conn, 1);
}
#else /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
/* Use "do-nothing" macro instead of function when workaround not used */
#define conn_reset_all_postponed_data(c) do {} WHILE_FALSE
#endif /* ! USE_RECV_BEFORE_SEND_WORKAROUND */
static void conn_free(struct connectdata *conn)
{
if(!conn)
return;
/* possible left-overs from the async name resolvers */
Curl_resolver_cancel(conn);
/* close the SSL stuff before we close any sockets since they will/may
write to the sockets */
Curl_ssl_close(conn, FIRSTSOCKET);
Curl_ssl_close(conn, SECONDARYSOCKET);
/* close possibly still open sockets */
if(CURL_SOCKET_BAD != conn->sock[SECONDARYSOCKET])
Curl_closesocket(conn, conn->sock[SECONDARYSOCKET]);
if(CURL_SOCKET_BAD != conn->sock[FIRSTSOCKET])
Curl_closesocket(conn, conn->sock[FIRSTSOCKET]);
if(CURL_SOCKET_BAD != conn->tempsock[0])
Curl_closesocket(conn, conn->tempsock[0]);
if(CURL_SOCKET_BAD != conn->tempsock[1])
Curl_closesocket(conn, conn->tempsock[1]);
#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
defined(NTLM_WB_ENABLED)
Curl_ntlm_wb_cleanup(conn);
#endif
Curl_safefree(conn->user);
Curl_safefree(conn->passwd);
Curl_safefree(conn->oauth_bearer);
Curl_safefree(conn->options);
Curl_safefree(conn->http_proxy.user);
Curl_safefree(conn->socks_proxy.user);
Curl_safefree(conn->http_proxy.passwd);
Curl_safefree(conn->socks_proxy.passwd);
Curl_safefree(conn->allocptr.proxyuserpwd);
Curl_safefree(conn->allocptr.uagent);
Curl_safefree(conn->allocptr.userpwd);
Curl_safefree(conn->allocptr.accept_encoding);
Curl_safefree(conn->allocptr.te);
Curl_safefree(conn->allocptr.rangeline);
Curl_safefree(conn->allocptr.ref);
Curl_safefree(conn->allocptr.host);
Curl_safefree(conn->allocptr.cookiehost);
Curl_safefree(conn->allocptr.rtsp_transport);
Curl_safefree(conn->trailer);
Curl_safefree(conn->host.rawalloc); /* host name buffer */
Curl_safefree(conn->conn_to_host.rawalloc); /* host name buffer */
Curl_safefree(conn->secondaryhostname);
Curl_safefree(conn->http_proxy.host.rawalloc); /* http proxy name buffer */
Curl_safefree(conn->socks_proxy.host.rawalloc); /* socks proxy name buffer */
Curl_safefree(conn->master_buffer);
Curl_safefree(conn->connect_state);
conn_reset_all_postponed_data(conn);
Curl_llist_destroy(&conn->send_pipe, NULL);
Curl_llist_destroy(&conn->recv_pipe, NULL);
Curl_safefree(conn->localdev);
Curl_free_primary_ssl_config(&conn->ssl_config);
Curl_free_primary_ssl_config(&conn->proxy_ssl_config);
#ifdef USE_UNIX_SOCKETS
Curl_safefree(conn->unix_domain_socket);
#endif
#ifdef USE_SSL
Curl_safefree(conn->ssl_extra);
#endif
free(conn); /* free all the connection oriented data */
}
/*
* Disconnects the given connection. Note the connection may not be the
* primary connection, like when freeing room in the connection cache or
* killing of a dead old connection.
*
* A connection needs an easy handle when closing down. We support this passed
* in separately since the connection to get closed here is often already
* disassociated from an easy handle.
*
* This function MUST NOT reset state in the Curl_easy struct if that
* isn't strictly bound to the life-time of *this* particular connection.
*
*/
CURLcode Curl_disconnect(struct Curl_easy *data,
struct connectdata *conn, bool dead_connection)
{
if(!conn)
return CURLE_OK; /* this is closed and fine already */
if(!data) {
DEBUGF(infof(data, "DISCONNECT without easy handle, ignoring\n"));
return CURLE_OK;
}
/*
* If this connection isn't marked to force-close, leave it open if there
* are other users of it
*/
if(CONN_INUSE(conn) && !dead_connection) {
DEBUGF(infof(data, "Curl_disconnect when inuse: %zu\n", CONN_INUSE(conn)));
return CURLE_OK;
}
conn->data = data;
if(conn->dns_entry != NULL) {
Curl_resolv_unlock(data, conn->dns_entry);
conn->dns_entry = NULL;
}
Curl_hostcache_prune(data); /* kill old DNS cache entries */
#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM)
/* Cleanup NTLM connection-related data */
Curl_http_ntlm_cleanup(conn);
#endif
if(conn->handler->disconnect)
/* This is set if protocol-specific cleanups should be made */
conn->handler->disconnect(conn, dead_connection);
/* unlink ourselves! */
infof(data, "Closing connection %ld\n", conn->connection_id);
Curl_conncache_remove_conn(conn, TRUE);
free_fixed_hostname(&conn->host);
free_fixed_hostname(&conn->conn_to_host);
free_fixed_hostname(&conn->http_proxy.host);
free_fixed_hostname(&conn->socks_proxy.host);
DEBUGASSERT(conn->data == data);
/* this assumes that the pointer is still there after the connection was
detected from the cache */
Curl_ssl_close(conn, FIRSTSOCKET);
conn_free(conn);
return CURLE_OK;
}
/*
* This function should return TRUE if the socket is to be assumed to
* be dead. Most commonly this happens when the server has closed the
* connection due to inactivity.
*/
static bool SocketIsDead(curl_socket_t sock)
{
int sval;
bool ret_val = TRUE;
sval = SOCKET_READABLE(sock, 0);
if(sval == 0)
/* timeout */
ret_val = FALSE;
return ret_val;
}
/*
* IsPipeliningPossible()
*
* Return a bitmask with the available pipelining and multiplexing options for
* the given requested connection.
*/
static int IsPipeliningPossible(const struct Curl_easy *handle,
const struct connectdata *conn)
{
int avail = 0;
/* If a HTTP protocol and pipelining is enabled */
if((conn->handler->protocol & PROTO_FAMILY_HTTP) &&
(!conn->bits.protoconnstart || !conn->bits.close)) {
if(Curl_pipeline_wanted(handle->multi, CURLPIPE_HTTP1) &&
(handle->set.httpversion != CURL_HTTP_VERSION_1_0) &&
(handle->set.httpreq == HTTPREQ_GET ||
handle->set.httpreq == HTTPREQ_HEAD))
/* didn't ask for HTTP/1.0 and a GET or HEAD */
avail |= CURLPIPE_HTTP1;
if(Curl_pipeline_wanted(handle->multi, CURLPIPE_MULTIPLEX) &&
(handle->set.httpversion >= CURL_HTTP_VERSION_2))
/* allows HTTP/2 */
avail |= CURLPIPE_MULTIPLEX;
}
return avail;
}
/* Returns non-zero if a handle was removed */
int Curl_removeHandleFromPipeline(struct Curl_easy *handle,
struct curl_llist *pipeline)
{
if(pipeline) {
struct curl_llist_element *curr;
curr = pipeline->head;
while(curr) {
if(curr->ptr == handle) {
Curl_llist_remove(pipeline, curr, NULL);
return 1; /* we removed a handle */
}
curr = curr->next;
}
}
return 0;
}
#if 0 /* this code is saved here as it is useful for debugging purposes */
static void Curl_printPipeline(struct curl_llist *pipeline)
{
struct curl_llist_element *curr;
curr = pipeline->head;
while(curr) {
struct Curl_easy *data = (struct Curl_easy *) curr->ptr;
infof(data, "Handle in pipeline: %s\n", data->state.path);
curr = curr->next;
}
}
#endif
static struct Curl_easy* gethandleathead(struct curl_llist *pipeline)
{
struct curl_llist_element *curr = pipeline->head;
#ifdef DEBUGBUILD
{
struct curl_llist_element *p = pipeline->head;
while(p) {
struct Curl_easy *e = p->ptr;
DEBUGASSERT(GOOD_EASY_HANDLE(e));
p = p->next;
}
}
#endif
if(curr) {
return (struct Curl_easy *) curr->ptr;
}
return NULL;
}
/* remove the specified connection from all (possible) pipelines and related
queues */
void Curl_getoff_all_pipelines(struct Curl_easy *data,
struct connectdata *conn)
{
if(!conn->bundle)
return;
if(conn->bundle->multiuse == BUNDLE_PIPELINING) {
bool recv_head = (conn->readchannel_inuse &&
Curl_recvpipe_head(data, conn));
bool send_head = (conn->writechannel_inuse &&
Curl_sendpipe_head(data, conn));
if(Curl_removeHandleFromPipeline(data, &conn->recv_pipe) && recv_head)
Curl_pipeline_leave_read(conn);
if(Curl_removeHandleFromPipeline(data, &conn->send_pipe) && send_head)
Curl_pipeline_leave_write(conn);
}
else {
(void)Curl_removeHandleFromPipeline(data, &conn->recv_pipe);
(void)Curl_removeHandleFromPipeline(data, &conn->send_pipe);
}
}
static bool
proxy_info_matches(const struct proxy_info* data,
const struct proxy_info* needle)
{
if((data->proxytype == needle->proxytype) &&
(data->port == needle->port) &&
Curl_safe_strcasecompare(data->host.name, needle->host.name))
return TRUE;
return FALSE;
}
/*
* This function checks if the given connection is dead and extracts it from
* the connection cache if so.
*
* When this is called as a Curl_conncache_foreach() callback, the connection
* cache lock is held!
*
* Returns TRUE if the connection was dead and extracted.
*/
static bool extract_if_dead(struct connectdata *conn,
struct Curl_easy *data)
{
size_t pipeLen = conn->send_pipe.size + conn->recv_pipe.size;
if(!pipeLen && !CONN_INUSE(conn)) {
/* The check for a dead socket makes sense only if there are no
handles in pipeline and the connection isn't already marked in
use */
bool dead;
conn->data = data;
if(conn->handler->connection_check) {
/* The protocol has a special method for checking the state of the
connection. Use it to check if the connection is dead. */
unsigned int state;
state = conn->handler->connection_check(conn, CONNCHECK_ISDEAD);
dead = (state & CONNRESULT_DEAD);
}
else {
/* Use the general method for determining the death of a connection */
dead = SocketIsDead(conn->sock[FIRSTSOCKET]);
}
if(dead) {
infof(data, "Connection %ld seems to be dead!\n", conn->connection_id);
Curl_conncache_remove_conn(conn, FALSE);
conn->data = NULL; /* detach */
return TRUE;
}
}
return FALSE;
}
struct prunedead {
struct Curl_easy *data;
struct connectdata *extracted;
};
/*
* Wrapper to use extract_if_dead() function in Curl_conncache_foreach()
*
*/
static int call_extract_if_dead(struct connectdata *conn, void *param)
{
struct prunedead *p = (struct prunedead *)param;
if(extract_if_dead(conn, p->data)) {
/* stop the iteration here, pass back the connection that was extracted */
p->extracted = conn;
return 1;
}
return 0; /* continue iteration */
}
/*
* This function scans the connection cache for half-open/dead connections,
* closes and removes them.
* The cleanup is done at most once per second.
*/
static void prune_dead_connections(struct Curl_easy *data)
{
struct curltime now = Curl_now();
time_t elapsed = Curl_timediff(now, data->state.conn_cache->last_cleanup);
if(elapsed >= 1000L) {
struct prunedead prune;
prune.data = data;
prune.extracted = NULL;
while(Curl_conncache_foreach(data, data->state.conn_cache, &prune,
call_extract_if_dead)) {
/* disconnect it */
(void)Curl_disconnect(data, prune.extracted, /* dead_connection */TRUE);
}
data->state.conn_cache->last_cleanup = now;
}
}
static size_t max_pipeline_length(struct Curl_multi *multi)
{
return multi ? multi->max_pipeline_length : 0;
}
/*
* Given one filled in connection struct (named needle), this function should
* detect if there already is one that has all the significant details
* exactly the same and thus should be used instead.
*
* If there is a match, this function returns TRUE - and has marked the
* connection as 'in-use'. It must later be called with ConnectionDone() to
* return back to 'idle' (unused) state.
*
* The force_reuse flag is set if the connection must be used, even if
* the pipelining strategy wants to open a new connection instead of reusing.
*/
static bool
ConnectionExists(struct Curl_easy *data,
struct connectdata *needle,
struct connectdata **usethis,
bool *force_reuse,
bool *waitpipe)
{
struct connectdata *check;
struct connectdata *chosen = 0;
bool foundPendingCandidate = FALSE;
int canpipe = IsPipeliningPossible(data, needle);
struct connectbundle *bundle;
#ifdef USE_NTLM
bool wantNTLMhttp = ((data->state.authhost.want &
(CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
(needle->handler->protocol & PROTO_FAMILY_HTTP));
bool wantProxyNTLMhttp = (needle->bits.proxy_user_passwd &&
((data->state.authproxy.want &
(CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
(needle->handler->protocol & PROTO_FAMILY_HTTP)));
#endif
*force_reuse = FALSE;
*waitpipe = FALSE;
/* We can't pipeline if the site is blacklisted */
if((canpipe & CURLPIPE_HTTP1) &&
Curl_pipeline_site_blacklisted(data, needle))
canpipe &= ~ CURLPIPE_HTTP1;
/* Look up the bundle with all the connections to this particular host.
Locks the connection cache, beware of early returns! */
bundle = Curl_conncache_find_bundle(needle, data->state.conn_cache);
if(bundle) {
/* Max pipe length is zero (unlimited) for multiplexed connections */
size_t max_pipe_len = (bundle->multiuse != BUNDLE_MULTIPLEX)?
max_pipeline_length(data->multi):0;
size_t best_pipe_len = max_pipe_len;
struct curl_llist_element *curr;
infof(data, "Found bundle for host %s: %p [%s]\n",
(needle->bits.conn_to_host ? needle->conn_to_host.name :
needle->host.name), (void *)bundle,
(bundle->multiuse == BUNDLE_PIPELINING ?
"can pipeline" :
(bundle->multiuse == BUNDLE_MULTIPLEX ?
"can multiplex" : "serially")));
/* We can't pipeline if we don't know anything about the server */
if(canpipe) {
if(bundle->multiuse <= BUNDLE_UNKNOWN) {
if((bundle->multiuse == BUNDLE_UNKNOWN) && data->set.pipewait) {
infof(data, "Server doesn't support multi-use yet, wait\n");
*waitpipe = TRUE;
Curl_conncache_unlock(needle);
return FALSE; /* no re-use */
}
infof(data, "Server doesn't support multi-use (yet)\n");
canpipe = 0;
}
if((bundle->multiuse == BUNDLE_PIPELINING) &&
!Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1)) {
/* not asked for, switch off */
infof(data, "Could pipeline, but not asked to!\n");
canpipe = 0;
}
else if((bundle->multiuse == BUNDLE_MULTIPLEX) &&
!Curl_pipeline_wanted(data->multi, CURLPIPE_MULTIPLEX)) {
infof(data, "Could multiplex, but not asked to!\n");
canpipe = 0;
}
}
curr = bundle->conn_list.head;
while(curr) {
bool match = FALSE;
size_t pipeLen;
/*
* Note that if we use a HTTP proxy in normal mode (no tunneling), we
* check connections to that proxy and not to the actual remote server.
*/
check = curr->ptr;
curr = curr->next;
if(extract_if_dead(check, data)) {
/* disconnect it */
(void)Curl_disconnect(data, check, /* dead_connection */TRUE);
continue;
}
pipeLen = check->send_pipe.size + check->recv_pipe.size;
if(canpipe) {
if(check->bits.protoconnstart && check->bits.close)
continue;
if(!check->bits.multiplex) {
/* If not multiplexing, make sure the connection is fine for HTTP/1
pipelining */
struct Curl_easy* sh = gethandleathead(&check->send_pipe);
struct Curl_easy* rh = gethandleathead(&check->recv_pipe);
if(sh) {
if(!(IsPipeliningPossible(sh, check) & CURLPIPE_HTTP1))
continue;
}
else if(rh) {
if(!(IsPipeliningPossible(rh, check) & CURLPIPE_HTTP1))
continue;
}
}
}
else {
if(pipeLen > 0) {
/* can only happen within multi handles, and means that another easy
handle is using this connection */
continue;
}
if(Curl_resolver_asynch()) {
/* ip_addr_str[0] is NUL only if the resolving of the name hasn't
completed yet and until then we don't re-use this connection */
if(!check->ip_addr_str[0]) {
infof(data,
"Connection #%ld is still name resolving, can't reuse\n",
check->connection_id);
continue;
}
}
if((check->sock[FIRSTSOCKET] == CURL_SOCKET_BAD) ||
check->bits.close) {
if(!check->bits.close)
foundPendingCandidate = TRUE;
/* Don't pick a connection that hasn't connected yet or that is going
to get closed. */
infof(data, "Connection #%ld isn't open enough, can't reuse\n",
check->connection_id);
#ifdef DEBUGBUILD
if(check->recv_pipe.size > 0) {
infof(data,
"BAD! Unconnected #%ld has a non-empty recv pipeline!\n",
check->connection_id);
}
#endif
continue;
}
}
#ifdef USE_UNIX_SOCKETS
if(needle->unix_domain_socket) {
if(!check->unix_domain_socket)
continue;
if(strcmp(needle->unix_domain_socket, check->unix_domain_socket))
continue;
if(needle->abstract_unix_socket != check->abstract_unix_socket)
continue;
}
else if(check->unix_domain_socket)
continue;
#endif
if((needle->handler->flags&PROTOPT_SSL) !=
(check->handler->flags&PROTOPT_SSL))
/* don't do mixed SSL and non-SSL connections */
if(get_protocol_family(check->handler->protocol) !=
needle->handler->protocol || !check->tls_upgraded)
/* except protocols that have been upgraded via TLS */
continue;
if(needle->bits.httpproxy != check->bits.httpproxy ||
needle->bits.socksproxy != check->bits.socksproxy)
continue;
if(needle->bits.socksproxy && !proxy_info_matches(&needle->socks_proxy,
&check->socks_proxy))
continue;
if(needle->bits.conn_to_host != check->bits.conn_to_host)
/* don't mix connections that use the "connect to host" feature and
* connections that don't use this feature */
continue;
if(needle->bits.conn_to_port != check->bits.conn_to_port)
/* don't mix connections that use the "connect to port" feature and
* connections that don't use this feature */
continue;
if(needle->bits.httpproxy) {
if(!proxy_info_matches(&needle->http_proxy, &check->http_proxy))
continue;
if(needle->bits.tunnel_proxy != check->bits.tunnel_proxy)
continue;
if(needle->http_proxy.proxytype == CURLPROXY_HTTPS) {
/* use https proxy */
if(needle->handler->flags&PROTOPT_SSL) {
/* use double layer ssl */
if(!Curl_ssl_config_matches(&needle->proxy_ssl_config,
&check->proxy_ssl_config))
continue;
if(check->proxy_ssl[FIRSTSOCKET].state != ssl_connection_complete)
continue;
}
else {
if(!Curl_ssl_config_matches(&needle->ssl_config,
&check->ssl_config))
continue;
if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete)
continue;
}
}
}
if(!canpipe && CONN_INUSE(check))
/* this request can't be pipelined but the checked connection is
already in use so we skip it */
continue;
if(CONN_INUSE(check) && (check->data->multi != needle->data->multi))
/* this could be subject for pipeline/multiplex use, but only
if they belong to the same multi handle */
continue;
if(needle->localdev || needle->localport) {
/* If we are bound to a specific local end (IP+port), we must not
re-use a random other one, although if we didn't ask for a
particular one we can reuse one that was bound.
This comparison is a bit rough and too strict. Since the input
parameters can be specified in numerous ways and still end up the
same it would take a lot of processing to make it really accurate.
Instead, this matching will assume that re-uses of bound connections
will most likely also re-use the exact same binding parameters and
missing out a few edge cases shouldn't hurt anyone very much.
*/
if((check->localport != needle->localport) ||
(check->localportrange != needle->localportrange) ||
(needle->localdev &&
(!check->localdev || strcmp(check->localdev, needle->localdev))))
continue;
}
if(!(needle->handler->flags & PROTOPT_CREDSPERREQUEST)) {
/* This protocol requires credentials per connection,
so verify that we're using the same name and password as well */
if(strcmp(needle->user, check->user) ||
strcmp(needle->passwd, check->passwd)) {
/* one of them was different */
continue;
}
}
if(!needle->bits.httpproxy || (needle->handler->flags&PROTOPT_SSL) ||
needle->bits.tunnel_proxy) {
/* The requested connection does not use a HTTP proxy or it uses SSL or
it is a non-SSL protocol tunneled or it is a non-SSL protocol which
is allowed to be upgraded via TLS */
if((strcasecompare(needle->handler->scheme, check->handler->scheme) ||
(get_protocol_family(check->handler->protocol) ==
needle->handler->protocol && check->tls_upgraded)) &&
(!needle->bits.conn_to_host || strcasecompare(
needle->conn_to_host.name, check->conn_to_host.name)) &&
(!needle->bits.conn_to_port ||
needle->conn_to_port == check->conn_to_port) &&
strcasecompare(needle->host.name, check->host.name) &&
needle->remote_port == check->remote_port) {
/* The schemes match or the the protocol family is the same and the
previous connection was TLS upgraded, and the hostname and host
port match */
if(needle->handler->flags & PROTOPT_SSL) {
/* This is a SSL connection so verify that we're using the same
SSL options as well */
if(!Curl_ssl_config_matches(&needle->ssl_config,
&check->ssl_config)) {
DEBUGF(infof(data,
"Connection #%ld has different SSL parameters, "
"can't reuse\n",
check->connection_id));
continue;
}
if(check->ssl[FIRSTSOCKET].state != ssl_connection_complete) {
foundPendingCandidate = TRUE;
DEBUGF(infof(data,
"Connection #%ld has not started SSL connect, "
"can't reuse\n",
check->connection_id));
continue;
}
}
match = TRUE;
}
}
else {
/* The requested connection is using the same HTTP proxy in normal
mode (no tunneling) */
match = TRUE;
}
if(match) {
#if defined(USE_NTLM)
/* If we are looking for an HTTP+NTLM connection, check if this is
already authenticating with the right credentials. If not, keep
looking so that we can reuse NTLM connections if
possible. (Especially we must not reuse the same connection if
partway through a handshake!) */
if(wantNTLMhttp) {
if(strcmp(needle->user, check->user) ||
strcmp(needle->passwd, check->passwd))
continue;
}
else if(check->ntlm.state != NTLMSTATE_NONE) {
/* Connection is using NTLM auth but we don't want NTLM */
continue;
}
/* Same for Proxy NTLM authentication */
if(wantProxyNTLMhttp) {
/* Both check->http_proxy.user and check->http_proxy.passwd can be
* NULL */
if(!check->http_proxy.user || !check->http_proxy.passwd)
continue;
if(strcmp(needle->http_proxy.user, check->http_proxy.user) ||
strcmp(needle->http_proxy.passwd, check->http_proxy.passwd))
continue;
}
else if(check->proxyntlm.state != NTLMSTATE_NONE) {
/* Proxy connection is using NTLM auth but we don't want NTLM */
continue;
}
if(wantNTLMhttp || wantProxyNTLMhttp) {
/* Credentials are already checked, we can use this connection */
chosen = check;
if((wantNTLMhttp &&
(check->ntlm.state != NTLMSTATE_NONE)) ||
(wantProxyNTLMhttp &&
(check->proxyntlm.state != NTLMSTATE_NONE))) {
/* We must use this connection, no other */
*force_reuse = TRUE;
break;
}
/* Continue look up for a better connection */
continue;
}
#endif
if(canpipe) {
/* We can pipeline if we want to. Let's continue looking for
the optimal connection to use, i.e the shortest pipe that is not
blacklisted. */
if(pipeLen == 0) {
/* We have the optimal connection. Let's stop looking. */
chosen = check;
break;
}
/* We can't use the connection if the pipe is full */
if(max_pipe_len && (pipeLen >= max_pipe_len)) {
infof(data, "Pipe is full, skip (%zu)\n", pipeLen);
continue;
}
#ifdef USE_NGHTTP2
/* If multiplexed, make sure we don't go over concurrency limit */
if(check->bits.multiplex) {
/* Multiplexed connections can only be HTTP/2 for now */
struct http_conn *httpc = &check->proto.httpc;
if(pipeLen >= httpc->settings.max_concurrent_streams) {
infof(data, "MAX_CONCURRENT_STREAMS reached, skip (%zu)\n",
pipeLen);
continue;
}
}
#endif
/* We can't use the connection if the pipe is penalized */
if(Curl_pipeline_penalized(data, check)) {
infof(data, "Penalized, skip\n");
continue;
}
if(max_pipe_len) {
if(pipeLen < best_pipe_len) {
/* This connection has a shorter pipe so far. We'll pick this
and continue searching */
chosen = check;
best_pipe_len = pipeLen;
continue;
}
}
else {
/* When not pipelining (== multiplexed), we have a match here! */
chosen = check;
infof(data, "Multiplexed connection found!\n");
break;
}
}
else {
/* We have found a connection. Let's stop searching. */
chosen = check;
break;
}
}
}
}
if(chosen) {
/* mark it as used before releasing the lock */
chosen->data = data; /* own it! */
Curl_conncache_unlock(needle);
*usethis = chosen;
return TRUE; /* yes, we found one to use! */
}
Curl_conncache_unlock(needle);
if(foundPendingCandidate && data->set.pipewait) {
infof(data,
"Found pending candidate for reuse and CURLOPT_PIPEWAIT is set\n");
*waitpipe = TRUE;
}
return FALSE; /* no matching connecting exists */
}
/* after a TCP connection to the proxy has been verified, this function does
the next magic step.
Note: this function's sub-functions call failf()
*/
CURLcode Curl_connected_proxy(struct connectdata *conn, int sockindex)
{
CURLcode result = CURLE_OK;
if(conn->bits.socksproxy) {
#ifndef CURL_DISABLE_PROXY
/* for the secondary socket (FTP), use the "connect to host"
* but ignore the "connect to port" (use the secondary port)
*/
const char * const host = conn->bits.httpproxy ?
conn->http_proxy.host.name :
conn->bits.conn_to_host ?
conn->conn_to_host.name :
sockindex == SECONDARYSOCKET ?
conn->secondaryhostname : conn->host.name;
const int port = conn->bits.httpproxy ? (int)conn->http_proxy.port :
sockindex == SECONDARYSOCKET ? conn->secondary_port :
conn->bits.conn_to_port ? conn->conn_to_port :
conn->remote_port;
conn->bits.socksproxy_connecting = TRUE;
switch(conn->socks_proxy.proxytype) {
case CURLPROXY_SOCKS5:
case CURLPROXY_SOCKS5_HOSTNAME:
result = Curl_SOCKS5(conn->socks_proxy.user, conn->socks_proxy.passwd,
host, port, sockindex, conn);
break;
case CURLPROXY_SOCKS4:
case CURLPROXY_SOCKS4A:
result = Curl_SOCKS4(conn->socks_proxy.user, host, port, sockindex,
conn);
break;
default:
failf(conn->data, "unknown proxytype option given");
result = CURLE_COULDNT_CONNECT;
} /* switch proxytype */
conn->bits.socksproxy_connecting = FALSE;
#else
(void)sockindex;
#endif /* CURL_DISABLE_PROXY */
}
return result;
}
/*
* verboseconnect() displays verbose information after a connect
*/
#ifndef CURL_DISABLE_VERBOSE_STRINGS
void Curl_verboseconnect(struct connectdata *conn)
{
if(conn->data->set.verbose)
infof(conn->data, "Connected to %s (%s) port %ld (#%ld)\n",
conn->bits.socksproxy ? conn->socks_proxy.host.dispname :
conn->bits.httpproxy ? conn->http_proxy.host.dispname :
conn->bits.conn_to_host ? conn->conn_to_host.dispname :
conn->host.dispname,
conn->ip_addr_str, conn->port, conn->connection_id);
}
#endif
int Curl_protocol_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks)
{
if(conn->handler->proto_getsock)
return conn->handler->proto_getsock(conn, socks, numsocks);
/* Backup getsock logic. Since there is a live socket in use, we must wait
for it or it will be removed from watching when the multi_socket API is
used. */
socks[0] = conn->sock[FIRSTSOCKET];
return GETSOCK_READSOCK(0) | GETSOCK_WRITESOCK(0);
}
int Curl_doing_getsock(struct connectdata *conn,
curl_socket_t *socks,
int numsocks)
{
if(conn && conn->handler->doing_getsock)
return conn->handler->doing_getsock(conn, socks, numsocks);
return GETSOCK_BLANK;
}
/*
* We are doing protocol-specific connecting and this is being called over and
* over from the multi interface until the connection phase is done on
* protocol layer.
*/
CURLcode Curl_protocol_connecting(struct connectdata *conn,
bool *done)
{
CURLcode result = CURLE_OK;
if(conn && conn->handler->connecting) {
*done = FALSE;
result = conn->handler->connecting(conn, done);
}
else
*done = TRUE;
return result;
}
/*
* We are DOING this is being called over and over from the multi interface
* until the DOING phase is done on protocol layer.
*/
CURLcode Curl_protocol_doing(struct connectdata *conn, bool *done)
{
CURLcode result = CURLE_OK;
if(conn && conn->handler->doing) {
*done = FALSE;
result = conn->handler->doing(conn, done);
}
else
*done = TRUE;
return result;
}
/*
* We have discovered that the TCP connection has been successful, we can now
* proceed with some action.
*
*/
CURLcode Curl_protocol_connect(struct connectdata *conn,
bool *protocol_done)
{
CURLcode result = CURLE_OK;
*protocol_done = FALSE;
if(conn->bits.tcpconnect[FIRSTSOCKET] && conn->bits.protoconnstart) {
/* We already are connected, get back. This may happen when the connect
worked fine in the first call, like when we connect to a local server
or proxy. Note that we don't know if the protocol is actually done.
Unless this protocol doesn't have any protocol-connect callback, as
then we know we're done. */
if(!conn->handler->connecting)
*protocol_done = TRUE;
return CURLE_OK;
}
if(!conn->bits.protoconnstart) {
result = Curl_proxy_connect(conn, FIRSTSOCKET);
if(result)
return result;
if(CONNECT_FIRSTSOCKET_PROXY_SSL())
/* wait for HTTPS proxy SSL initialization to complete */
return CURLE_OK;
if(conn->bits.tunnel_proxy && conn->bits.httpproxy &&
Curl_connect_ongoing(conn))
/* when using an HTTP tunnel proxy, await complete tunnel establishment
before proceeding further. Return CURLE_OK so we'll be called again */
return CURLE_OK;
if(conn->handler->connect_it) {
/* is there a protocol-specific connect() procedure? */
/* Call the protocol-specific connect function */
result = conn->handler->connect_it(conn, protocol_done);
}
else
*protocol_done = TRUE;
/* it has started, possibly even completed but that knowledge isn't stored
in this bit! */
if(!result)
conn->bits.protoconnstart = TRUE;
}
return result; /* pass back status */
}
/*
* Helpers for IDNA conversions.
*/
static bool is_ASCII_name(const char *hostname)
{
const unsigned char *ch = (const unsigned char *)hostname;
while(*ch) {
if(*ch++ & 0x80)
return FALSE;
}
return TRUE;
}
/*
* Perform any necessary IDN conversion of hostname
*/
static CURLcode fix_hostname(struct connectdata *conn, struct hostname *host)
{
size_t len;
struct Curl_easy *data = conn->data;
#ifndef USE_LIBIDN2
(void)data;
(void)conn;
#elif defined(CURL_DISABLE_VERBOSE_STRINGS)
(void)conn;
#endif
/* set the name we use to display the host name */
host->dispname = host->name;
len = strlen(host->name);
if(len && (host->name[len-1] == '.'))
/* strip off a single trailing dot if present, primarily for SNI but
there's no use for it */
host->name[len-1] = 0;
/* Check name for non-ASCII and convert hostname to ACE form if we can */
if(!is_ASCII_name(host->name)) {
#ifdef USE_LIBIDN2
if(idn2_check_version(IDN2_VERSION)) {
char *ace_hostname = NULL;
#if IDN2_VERSION_NUMBER >= 0x00140000
/* IDN2_NFC_INPUT: Normalize input string using normalization form C.
IDN2_NONTRANSITIONAL: Perform Unicode TR46 non-transitional
processing. */
int flags = IDN2_NFC_INPUT | IDN2_NONTRANSITIONAL;
#else
int flags = IDN2_NFC_INPUT;
#endif
int rc = idn2_lookup_ul((const char *)host->name, &ace_hostname, flags);
if(rc == IDN2_OK) {
host->encalloc = (char *)ace_hostname;
/* change the name pointer to point to the encoded hostname */
host->name = host->encalloc;
}
else {
failf(data, "Failed to convert %s to ACE; %s\n", host->name,
idn2_strerror(rc));
return CURLE_URL_MALFORMAT;
}
}
#elif defined(USE_WIN32_IDN)
char *ace_hostname = NULL;
if(curl_win32_idn_to_ascii(host->name, &ace_hostname)) {
host->encalloc = ace_hostname;
/* change the name pointer to point to the encoded hostname */
host->name = host->encalloc;
}
else {
failf(data, "Failed to convert %s to ACE;\n", host->name);
return CURLE_URL_MALFORMAT;
}
#else
infof(data, "IDN support not present, can't parse Unicode domains\n");
#endif
}
{
char *hostp;
for(hostp = host->name; *hostp; hostp++) {
if(*hostp <= 32) {
failf(data, "Host name '%s' contains bad letter", host->name);
return CURLE_URL_MALFORMAT;
}
}
}
return CURLE_OK;
}
/*
* Frees data allocated by fix_hostname()
*/
static void free_fixed_hostname(struct hostname *host)
{
#if defined(USE_LIBIDN2)
if(host->encalloc) {
idn2_free(host->encalloc); /* must be freed with idn2_free() since this was
allocated by libidn */
host->encalloc = NULL;
}
#elif defined(USE_WIN32_IDN)
free(host->encalloc); /* must be freed with free() since this was
allocated by curl_win32_idn_to_ascii */
host->encalloc = NULL;
#else
(void)host;
#endif
}
static void llist_dtor(void *user, void *element)
{
(void)user;
(void)element;
/* Do nothing */
}
/*
* Allocate and initialize a new connectdata object.
*/
static struct connectdata *allocate_conn(struct Curl_easy *data)
{
struct connectdata *conn = calloc(1, sizeof(struct connectdata));
if(!conn)
return NULL;
#ifdef USE_SSL
/* The SSL backend-specific data (ssl_backend_data) objects are allocated as
a separate array to ensure suitable alignment.
Note that these backend pointers can be swapped by vtls (eg ssl backend
data becomes proxy backend data). */
{
size_t sslsize = Curl_ssl->sizeof_ssl_backend_data;
char *ssl = calloc(4, sslsize);
if(!ssl) {
free(conn);
return NULL;
}
conn->ssl_extra = ssl;
conn->ssl[0].backend = (void *)ssl;
conn->ssl[1].backend = (void *)(ssl + sslsize);
conn->proxy_ssl[0].backend = (void *)(ssl + 2 * sslsize);
conn->proxy_ssl[1].backend = (void *)(ssl + 3 * sslsize);
}
#endif
conn->handler = &Curl_handler_dummy; /* Be sure we have a handler defined
already from start to avoid NULL
situations and checks */
/* and we setup a few fields in case we end up actually using this struct */
conn->sock[FIRSTSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD; /* no file descriptor */
conn->tempsock[0] = CURL_SOCKET_BAD; /* no file descriptor */
conn->tempsock[1] = CURL_SOCKET_BAD; /* no file descriptor */
conn->connection_id = -1; /* no ID */
conn->port = -1; /* unknown at this point */
conn->remote_port = -1; /* unknown at this point */
#if defined(USE_RECV_BEFORE_SEND_WORKAROUND) && defined(DEBUGBUILD)
conn->postponed[0].bindsock = CURL_SOCKET_BAD; /* no file descriptor */
conn->postponed[1].bindsock = CURL_SOCKET_BAD; /* no file descriptor */
#endif /* USE_RECV_BEFORE_SEND_WORKAROUND && DEBUGBUILD */
/* Default protocol-independent behavior doesn't support persistent
connections, so we set this to force-close. Protocols that support
this need to set this to FALSE in their "curl_do" functions. */
connclose(conn, "Default to force-close");
/* Store creation time to help future close decision making */
conn->created = Curl_now();
/* Store current time to give a baseline to keepalive connection times. */
conn->keepalive = Curl_now();
/* Store off the configured connection upkeep time. */
conn->upkeep_interval_ms = data->set.upkeep_interval_ms;
conn->data = data; /* Setup the association between this connection
and the Curl_easy */
conn->http_proxy.proxytype = data->set.proxytype;
conn->socks_proxy.proxytype = CURLPROXY_SOCKS4;
#ifdef CURL_DISABLE_PROXY
conn->bits.proxy = FALSE;
conn->bits.httpproxy = FALSE;
conn->bits.socksproxy = FALSE;
conn->bits.proxy_user_passwd = FALSE;
conn->bits.tunnel_proxy = FALSE;
#else /* CURL_DISABLE_PROXY */
/* note that these two proxy bits are now just on what looks to be
requested, they may be altered down the road */
conn->bits.proxy = (data->set.str[STRING_PROXY] &&
*data->set.str[STRING_PROXY]) ? TRUE : FALSE;
conn->bits.httpproxy = (conn->bits.proxy &&
(conn->http_proxy.proxytype == CURLPROXY_HTTP ||
conn->http_proxy.proxytype == CURLPROXY_HTTP_1_0 ||
conn->http_proxy.proxytype == CURLPROXY_HTTPS)) ?
TRUE : FALSE;
conn->bits.socksproxy = (conn->bits.proxy &&
!conn->bits.httpproxy) ? TRUE : FALSE;
if(data->set.str[STRING_PRE_PROXY] && *data->set.str[STRING_PRE_PROXY]) {
conn->bits.proxy = TRUE;
conn->bits.socksproxy = TRUE;
}
conn->bits.proxy_user_passwd =
(data->set.str[STRING_PROXYUSERNAME]) ? TRUE : FALSE;
conn->bits.tunnel_proxy = data->set.tunnel_thru_httpproxy;
#endif /* CURL_DISABLE_PROXY */
conn->bits.user_passwd = (data->set.str[STRING_USERNAME]) ? TRUE : FALSE;
conn->bits.ftp_use_epsv = data->set.ftp_use_epsv;
conn->bits.ftp_use_eprt = data->set.ftp_use_eprt;
conn->ssl_config.verifystatus = data->set.ssl.primary.verifystatus;
conn->ssl_config.verifypeer = data->set.ssl.primary.verifypeer;
conn->ssl_config.verifyhost = data->set.ssl.primary.verifyhost;
conn->proxy_ssl_config.verifystatus =
data->set.proxy_ssl.primary.verifystatus;
conn->proxy_ssl_config.verifypeer = data->set.proxy_ssl.primary.verifypeer;
conn->proxy_ssl_config.verifyhost = data->set.proxy_ssl.primary.verifyhost;
conn->ip_version = data->set.ipver;
#if !defined(CURL_DISABLE_HTTP) && defined(USE_NTLM) && \
defined(NTLM_WB_ENABLED)
conn->ntlm_auth_hlpr_socket = CURL_SOCKET_BAD;
conn->ntlm_auth_hlpr_pid = 0;
conn->challenge_header = NULL;
conn->response_header = NULL;
#endif
if(Curl_pipeline_wanted(data->multi, CURLPIPE_HTTP1) &&
!conn->master_buffer) {
/* Allocate master_buffer to be used for HTTP/1 pipelining */
conn->master_buffer = calloc(MASTERBUF_SIZE, sizeof(char));
if(!conn->master_buffer)
goto error;
}
/* Initialize the pipeline lists */
Curl_llist_init(&conn->send_pipe, (curl_llist_dtor) llist_dtor);
Curl_llist_init(&conn->recv_pipe, (curl_llist_dtor) llist_dtor);
#ifdef HAVE_GSSAPI
conn->data_prot = PROT_CLEAR;
#endif
/* Store the local bind parameters that will be used for this connection */
if(data->set.str[STRING_DEVICE]) {
conn->localdev = strdup(data->set.str[STRING_DEVICE]);
if(!conn->localdev)
goto error;
}
conn->localportrange = data->set.localportrange;
conn->localport = data->set.localport;
/* the close socket stuff needs to be copied to the connection struct as
it may live on without (this specific) Curl_easy */
conn->fclosesocket = data->set.fclosesocket;
conn->closesocket_client = data->set.closesocket_client;
return conn;
error:
Curl_llist_destroy(&conn->send_pipe, NULL);
Curl_llist_destroy(&conn->recv_pipe, NULL);
free(conn->master_buffer);
free(conn->localdev);
#ifdef USE_SSL
free(conn->ssl_extra);
#endif
free(conn);
return NULL;
}
/* returns the handler if the given scheme is built-in */
const struct Curl_handler *Curl_builtin_scheme(const char *scheme)
{
const struct Curl_handler * const *pp;
const struct Curl_handler *p;
/* Scan protocol handler table and match against 'scheme'. The handler may
be changed later when the protocol specific setup function is called. */
for(pp = protocols; (p = *pp) != NULL; pp++)
if(strcasecompare(p->scheme, scheme))
/* Protocol found in table. Check if allowed */
return p;
return NULL; /* not found */
}
static CURLcode findprotocol(struct Curl_easy *data,
struct connectdata *conn,
const char *protostr)
{
const struct Curl_handler *p = Curl_builtin_scheme(protostr);
if(p && /* Protocol found in table. Check if allowed */
(data->set.allowed_protocols & p->protocol)) {
/* it is allowed for "normal" request, now do an extra check if this is
the result of a redirect */
if(data->state.this_is_a_follow &&
!(data->set.redir_protocols & p->protocol))
/* nope, get out */
;
else {
/* Perform setup complement if some. */
conn->handler = conn->given = p;
/* 'port' and 'remote_port' are set in setup_connection_internals() */
return CURLE_OK;
}
}
/* The protocol was not found in the table, but we don't have to assign it
to anything since it is already assigned to a dummy-struct in the
create_conn() function when the connectdata struct is allocated. */
failf(data, "Protocol \"%s\" not supported or disabled in " LIBCURL_NAME,
protostr);
return CURLE_UNSUPPORTED_PROTOCOL;
}
CURLcode Curl_uc_to_curlcode(CURLUcode uc)
{
switch(uc) {
default:
return CURLE_URL_MALFORMAT;
case CURLUE_UNSUPPORTED_SCHEME:
return CURLE_UNSUPPORTED_PROTOCOL;
case CURLUE_OUT_OF_MEMORY:
return CURLE_OUT_OF_MEMORY;
case CURLUE_USER_NOT_ALLOWED:
return CURLE_LOGIN_DENIED;
}
}
/*
* Parse URL and fill in the relevant members of the connection struct.
*/
static CURLcode parseurlandfillconn(struct Curl_easy *data,
struct connectdata *conn)
{
CURLcode result;
CURLU *uh;
CURLUcode uc;
char *hostname;
Curl_up_free(data); /* cleanup previous leftovers first */
/* parse the URL */
uh = data->state.uh = curl_url();
if(!uh)
return CURLE_OUT_OF_MEMORY;
if(data->set.str[STRING_DEFAULT_PROTOCOL] &&
!Curl_is_absolute_url(data->change.url, NULL, MAX_SCHEME_LEN)) {
char *url;
if(data->change.url_alloc)
free(data->change.url);
url = aprintf("%s://%s", data->set.str[STRING_DEFAULT_PROTOCOL],
data->change.url);
if(!url)
return CURLE_OUT_OF_MEMORY;
data->change.url = url;
data->change.url_alloc = TRUE;
}
uc = curl_url_set(uh, CURLUPART_URL, data->change.url,
CURLU_GUESS_SCHEME |
CURLU_NON_SUPPORT_SCHEME |
(data->set.disallow_username_in_url ?
CURLU_DISALLOW_USER : 0) |
(data->set.path_as_is ? CURLU_PATH_AS_IS : 0));
if(uc)
return Curl_uc_to_curlcode(uc);
uc = curl_url_get(uh, CURLUPART_SCHEME, &data->state.up.scheme, 0);
if(uc)
return Curl_uc_to_curlcode(uc);
result = findprotocol(data, conn, data->state.up.scheme);
if(result)
return result;
uc = curl_url_get(uh, CURLUPART_USER, &data->state.up.user,
CURLU_URLDECODE);
if(!uc) {
conn->user = strdup(data->state.up.user);
if(!conn->user)
return CURLE_OUT_OF_MEMORY;
conn->bits.user_passwd = TRUE;
}
else if(uc != CURLUE_NO_USER)
return Curl_uc_to_curlcode(uc);
uc = curl_url_get(uh, CURLUPART_PASSWORD, &data->state.up.password,
CURLU_URLDECODE);
if(!uc) {
conn->passwd = strdup(data->state.up.password);
if(!conn->passwd)
return CURLE_OUT_OF_MEMORY;
conn->bits.user_passwd = TRUE;
}
else if(uc != CURLUE_NO_PASSWORD)
return Curl_uc_to_curlcode(uc);
uc = curl_url_get(uh, CURLUPART_OPTIONS, &data->state.up.options,
CURLU_URLDECODE);
if(!uc) {
conn->options = strdup(data->state.up.options);
if(!conn->options)
return CURLE_OUT_OF_MEMORY;
}
else if(uc != CURLUE_NO_OPTIONS)
return Curl_uc_to_curlcode(uc);
uc = curl_url_get(uh, CURLUPART_HOST, &data->state.up.hostname, 0);
if(uc) {
if(!strcasecompare("file", data->state.up.scheme))
return CURLE_OUT_OF_MEMORY;
}
uc = curl_url_get(uh, CURLUPART_PATH, &data->state.up.path, 0);
if(uc)
return Curl_uc_to_curlcode(uc);
uc = curl_url_get(uh, CURLUPART_PORT, &data->state.up.port,
CURLU_DEFAULT_PORT);
if(uc) {
if(!strcasecompare("file", data->state.up.scheme))
return CURLE_OUT_OF_MEMORY;
}
else {
unsigned long port = strtoul(data->state.up.port, NULL, 10);
conn->remote_port = curlx_ultous(port);
}
(void)curl_url_get(uh, CURLUPART_QUERY, &data->state.up.query, 0);
hostname = data->state.up.hostname;
if(!hostname)
/* this is for file:// transfers, get a dummy made */
hostname = (char *)"";
if(hostname[0] == '[') {
/* This looks like an IPv6 address literal. See if there is an address
scope. */
char *percent = strchr(++hostname, '%');
conn->bits.ipv6_ip = TRUE;
if(percent) {
unsigned int identifier_offset = 3;
char *endp;
unsigned long scope;
if(strncmp("%25", percent, 3) != 0) {
infof(data,
"Please URL encode %% as %%25, see RFC 6874.\n");
identifier_offset = 1;
}
scope = strtoul(percent + identifier_offset, &endp, 10);
if(*endp == ']') {
/* The address scope was well formed. Knock it out of the
hostname. */
memmove(percent, endp, strlen(endp) + 1);
conn->scope_id = (unsigned int)scope;
}
else {
/* Zone identifier is not numeric */
#if defined(HAVE_NET_IF_H) && defined(IFNAMSIZ) && defined(HAVE_IF_NAMETOINDEX)
char ifname[IFNAMSIZ + 2];
char *square_bracket;
unsigned int scopeidx = 0;
strncpy(ifname, percent + identifier_offset, IFNAMSIZ + 2);
/* Ensure nullbyte termination */
ifname[IFNAMSIZ + 1] = '\0';
square_bracket = strchr(ifname, ']');
if(square_bracket) {
/* Remove ']' */
*square_bracket = '\0';
scopeidx = if_nametoindex(ifname);
if(scopeidx == 0) {
infof(data, "Invalid network interface: %s; %s\n", ifname,
strerror(errno));
}
}
if(scopeidx > 0) {
char *p = percent + identifier_offset + strlen(ifname);
/* Remove zone identifier from hostname */
memmove(percent, p, strlen(p) + 1);
conn->scope_id = scopeidx;
}
else
#endif /* HAVE_NET_IF_H && IFNAMSIZ */
infof(data, "Invalid IPv6 address format\n");
}
}
percent = strchr(hostname, ']');
if(percent)
/* terminate IPv6 numerical at end bracket */
*percent = 0;
}
/* make sure the connect struct gets its own copy of the host name */
conn->host.rawalloc = strdup(hostname);
if(!conn->host.rawalloc)
return CURLE_OUT_OF_MEMORY;
conn->host.name = conn->host.rawalloc;
if(data->set.scope_id)
/* Override any scope that was set above. */
conn->scope_id = data->set.scope_id;
return CURLE_OK;
}
/*
* If we're doing a resumed transfer, we need to setup our stuff
* properly.
*/
static CURLcode setup_range(struct Curl_easy *data)
{
struct UrlState *s = &data->state;
s->resume_from = data->set.set_resume_from;
if(s->resume_from || data->set.str[STRING_SET_RANGE]) {
if(s->rangestringalloc)
free(s->range);
if(s->resume_from)
s->range = aprintf("%" CURL_FORMAT_CURL_OFF_T "-", s->resume_from);
else
s->range = strdup(data->set.str[STRING_SET_RANGE]);
s->rangestringalloc = (s->range) ? TRUE : FALSE;
if(!s->range)
return CURLE_OUT_OF_MEMORY;
/* tell ourselves to fetch this range */
s->use_range = TRUE; /* enable range download */
}
else
s->use_range = FALSE; /* disable range download */
return CURLE_OK;
}
/*
* setup_connection_internals() -
*
* Setup connection internals specific to the requested protocol in the
* Curl_easy. This is inited and setup before the connection is made but
* is about the particular protocol that is to be used.
*
* This MUST get called after proxy magic has been figured out.
*/
static CURLcode setup_connection_internals(struct connectdata *conn)
{
const struct Curl_handler * p;
CURLcode result;
conn->socktype = SOCK_STREAM; /* most of them are TCP streams */
/* Perform setup complement if some. */
p = conn->handler;
if(p->setup_connection) {
result = (*p->setup_connection)(conn);
if(result)
return result;
p = conn->handler; /* May have changed. */
}
if(conn->port < 0)
/* we check for -1 here since if proxy was detected already, this
was very likely already set to the proxy port */
conn->port = p->defport;
return CURLE_OK;
}
/*
* Curl_free_request_state() should free temp data that was allocated in the
* Curl_easy for this single request.
*/
void Curl_free_request_state(struct Curl_easy *data)
{
Curl_safefree(data->req.protop);
Curl_safefree(data->req.newurl);
}
#ifndef CURL_DISABLE_PROXY
/****************************************************************
* Checks if the host is in the noproxy list. returns true if it matches
* and therefore the proxy should NOT be used.
****************************************************************/
static bool check_noproxy(const char *name, const char *no_proxy)
{
/* no_proxy=domain1.dom,host.domain2.dom
* (a comma-separated list of hosts which should
* not be proxied, or an asterisk to override
* all proxy variables)
*/
if(no_proxy && no_proxy[0]) {
size_t tok_start;
size_t tok_end;
const char *separator = ", ";
size_t no_proxy_len;
size_t namelen;
char *endptr;
if(strcasecompare("*", no_proxy)) {
return TRUE;
}
/* NO_PROXY was specified and it wasn't just an asterisk */
no_proxy_len = strlen(no_proxy);
if(name[0] == '[') {
/* IPv6 numerical address */
endptr = strchr(name, ']');
if(!endptr)
return FALSE;
name++;
namelen = endptr - name;
}
else
namelen = strlen(name);
for(tok_start = 0; tok_start < no_proxy_len; tok_start = tok_end + 1) {
while(tok_start < no_proxy_len &&
strchr(separator, no_proxy[tok_start]) != NULL) {
/* Look for the beginning of the token. */
++tok_start;
}
if(tok_start == no_proxy_len)
break; /* It was all trailing separator chars, no more tokens. */
for(tok_end = tok_start; tok_end < no_proxy_len &&
strchr(separator, no_proxy[tok_end]) == NULL; ++tok_end)
/* Look for the end of the token. */
;
/* To match previous behaviour, where it was necessary to specify
* ".local.com" to prevent matching "notlocal.com", we will leave
* the '.' off.
*/
if(no_proxy[tok_start] == '.')
++tok_start;
if((tok_end - tok_start) <= namelen) {
/* Match the last part of the name to the domain we are checking. */
const char *checkn = name + namelen - (tok_end - tok_start);
if(strncasecompare(no_proxy + tok_start, checkn,
tok_end - tok_start)) {
if((tok_end - tok_start) == namelen || *(checkn - 1) == '.') {
/* We either have an exact match, or the previous character is a .
* so it is within the same domain, so no proxy for this host.
*/
return TRUE;
}
}
} /* if((tok_end - tok_start) <= namelen) */
} /* for(tok_start = 0; tok_start < no_proxy_len;
tok_start = tok_end + 1) */
} /* NO_PROXY was specified and it wasn't just an asterisk */
return FALSE;
}
#ifndef CURL_DISABLE_HTTP
/****************************************************************
* Detect what (if any) proxy to use. Remember that this selects a host
* name and is not limited to HTTP proxies only.
* The returned pointer must be freed by the caller (unless NULL)
****************************************************************/
static char *detect_proxy(struct connectdata *conn)
{
char *proxy = NULL;
/* If proxy was not specified, we check for default proxy environment
* variables, to enable i.e Lynx compliance:
*
* http_proxy=http://some.server.dom:port/
* https_proxy=http://some.server.dom:port/
* ftp_proxy=http://some.server.dom:port/
* no_proxy=domain1.dom,host.domain2.dom
* (a comma-separated list of hosts which should
* not be proxied, or an asterisk to override
* all proxy variables)
* all_proxy=http://some.server.dom:port/
* (seems to exist for the CERN www lib. Probably
* the first to check for.)
*
* For compatibility, the all-uppercase versions of these variables are
* checked if the lowercase versions don't exist.
*/
char proxy_env[128];
const char *protop = conn->handler->scheme;
char *envp = proxy_env;
char *prox;
/* Now, build <protocol>_proxy and check for such a one to use */
while(*protop)
*envp++ = (char)tolower((int)*protop++);
/* append _proxy */
strcpy(envp, "_proxy");
/* read the protocol proxy: */
prox = curl_getenv(proxy_env);
/*
* We don't try the uppercase version of HTTP_PROXY because of
* security reasons:
*
* When curl is used in a webserver application
* environment (cgi or php), this environment variable can
* be controlled by the web server user by setting the
* http header 'Proxy:' to some value.
*
* This can cause 'internal' http/ftp requests to be
* arbitrarily redirected by any external attacker.
*/
if(!prox && !strcasecompare("http_proxy", proxy_env)) {
/* There was no lowercase variable, try the uppercase version: */
Curl_strntoupper(proxy_env, proxy_env, sizeof(proxy_env));
prox = curl_getenv(proxy_env);
}
envp = proxy_env;
if(prox) {
proxy = prox; /* use this */
}
else {
envp = (char *)"all_proxy";
proxy = curl_getenv(envp); /* default proxy to use */
if(!proxy) {
envp = (char *)"ALL_PROXY";
proxy = curl_getenv(envp);
}
}
if(proxy)
infof(conn->data, "Uses proxy env variable %s == '%s'\n", envp, proxy);
return proxy;
}
#endif /* CURL_DISABLE_HTTP */
/*
* If this is supposed to use a proxy, we need to figure out the proxy
* host name, so that we can re-use an existing connection
* that may exist registered to the same proxy host.
*/
static CURLcode parse_proxy(struct Curl_easy *data,
struct connectdata *conn, char *proxy,
curl_proxytype proxytype)
{
char *prox_portno;
char *endofprot;
/* We use 'proxyptr' to point to the proxy name from now on... */
char *proxyptr;
char *portptr;
char *atsign;
long port = -1;
char *proxyuser = NULL;
char *proxypasswd = NULL;
bool sockstype;
/* We do the proxy host string parsing here. We want the host name and the
* port name. Accept a protocol:// prefix
*/
/* Parse the protocol part if present */
endofprot = strstr(proxy, "://");
if(endofprot) {
proxyptr = endofprot + 3;
if(checkprefix("https", proxy))
proxytype = CURLPROXY_HTTPS;
else if(checkprefix("socks5h", proxy))
proxytype = CURLPROXY_SOCKS5_HOSTNAME;
else if(checkprefix("socks5", proxy))
proxytype = CURLPROXY_SOCKS5;
else if(checkprefix("socks4a", proxy))
proxytype = CURLPROXY_SOCKS4A;
else if(checkprefix("socks4", proxy) || checkprefix("socks", proxy))
proxytype = CURLPROXY_SOCKS4;
else if(checkprefix("http:", proxy))
; /* leave it as HTTP or HTTP/1.0 */
else {
/* Any other xxx:// reject! */
failf(data, "Unsupported proxy scheme for \'%s\'", proxy);
return CURLE_COULDNT_CONNECT;
}
}
else
proxyptr = proxy; /* No xxx:// head: It's a HTTP proxy */
#ifdef USE_SSL
if(!(Curl_ssl->supports & SSLSUPP_HTTPS_PROXY))
#endif
if(proxytype == CURLPROXY_HTTPS) {
failf(data, "Unsupported proxy \'%s\', libcurl is built without the "
"HTTPS-proxy support.", proxy);
return CURLE_NOT_BUILT_IN;
}
sockstype = proxytype == CURLPROXY_SOCKS5_HOSTNAME ||
proxytype == CURLPROXY_SOCKS5 ||
proxytype == CURLPROXY_SOCKS4A ||
proxytype == CURLPROXY_SOCKS4;
/* Is there a username and password given in this proxy url? */
atsign = strchr(proxyptr, '@');
if(atsign) {
CURLcode result =
Curl_parse_login_details(proxyptr, atsign - proxyptr,
&proxyuser, &proxypasswd, NULL);
if(result)
return result;
proxyptr = atsign + 1;
}
/* start scanning for port number at this point */
portptr = proxyptr;
/* detect and extract RFC6874-style IPv6-addresses */
if(*proxyptr == '[') {
char *ptr = ++proxyptr; /* advance beyond the initial bracket */
while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
ptr++;
if(*ptr == '%') {
/* There might be a zone identifier */
if(strncmp("%25", ptr, 3))
infof(data, "Please URL encode %% as %%25, see RFC 6874.\n");
ptr++;
/* Allow unreserved characters as defined in RFC 3986 */
while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
(*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
ptr++;
}
if(*ptr == ']')
/* yeps, it ended nicely with a bracket as well */
*ptr++ = 0;
else
infof(data, "Invalid IPv6 address format\n");
portptr = ptr;
/* Note that if this didn't end with a bracket, we still advanced the
* proxyptr first, but I can't see anything wrong with that as no host
* name nor a numeric can legally start with a bracket.
*/
}
/* Get port number off proxy.server.com:1080 */
prox_portno = strchr(portptr, ':');
if(prox_portno) {
char *endp = NULL;
*prox_portno = 0x0; /* cut off number from host name */
prox_portno ++;
/* now set the local port number */
port = strtol(prox_portno, &endp, 10);
if((endp && *endp && (*endp != '/') && (*endp != ' ')) ||
(port < 0) || (port > 65535)) {
/* meant to detect for example invalid IPv6 numerical addresses without
brackets: "2a00:fac0:a000::7:13". Accept a trailing slash only
because we then allow "URL style" with the number followed by a
slash, used in curl test cases already. Space is also an acceptable
terminating symbol. */
infof(data, "No valid port number in proxy string (%s)\n",
prox_portno);
}
else
conn->port = port;
}
else {
if(proxyptr[0]=='/') {
/* If the first character in the proxy string is a slash, fail
immediately. The following code will otherwise clear the string which
will lead to code running as if no proxy was set! */
Curl_safefree(proxyuser);
Curl_safefree(proxypasswd);
return CURLE_COULDNT_RESOLVE_PROXY;
}
/* without a port number after the host name, some people seem to use
a slash so we strip everything from the first slash */
atsign = strchr(proxyptr, '/');
if(atsign)
*atsign = '\0'; /* cut off path part from host name */
if(data->set.proxyport)
/* None given in the proxy string, then get the default one if it is
given */
port = data->set.proxyport;
else {
if(proxytype == CURLPROXY_HTTPS)
port = CURL_DEFAULT_HTTPS_PROXY_PORT;
else
port = CURL_DEFAULT_PROXY_PORT;
}
}
if(*proxyptr) {
struct proxy_info *proxyinfo =
sockstype ? &conn->socks_proxy : &conn->http_proxy;
proxyinfo->proxytype = proxytype;
if(proxyuser) {
/* found user and password, rip them out. note that we are unescaping
them, as there is otherwise no way to have a username or password
with reserved characters like ':' in them. */
Curl_safefree(proxyinfo->user);
proxyinfo->user = curl_easy_unescape(data, proxyuser, 0, NULL);
Curl_safefree(proxyuser);
if(!proxyinfo->user) {
Curl_safefree(proxypasswd);
return CURLE_OUT_OF_MEMORY;
}
Curl_safefree(proxyinfo->passwd);
if(proxypasswd && strlen(proxypasswd) < MAX_CURL_PASSWORD_LENGTH)
proxyinfo->passwd = curl_easy_unescape(data, proxypasswd, 0, NULL);
else
proxyinfo->passwd = strdup("");
Curl_safefree(proxypasswd);
if(!proxyinfo->passwd)
return CURLE_OUT_OF_MEMORY;
conn->bits.proxy_user_passwd = TRUE; /* enable it */
}
if(port >= 0) {
proxyinfo->port = port;
if(conn->port < 0 || sockstype || !conn->socks_proxy.host.rawalloc)
conn->port = port;
}
/* now, clone the cleaned proxy host name */
Curl_safefree(proxyinfo->host.rawalloc);
proxyinfo->host.rawalloc = strdup(proxyptr);
proxyinfo->host.name = proxyinfo->host.rawalloc;
if(!proxyinfo->host.rawalloc)
return CURLE_OUT_OF_MEMORY;
}
Curl_safefree(proxyuser);
Curl_safefree(proxypasswd);
return CURLE_OK;
}
/*
* Extract the user and password from the authentication string
*/
static CURLcode parse_proxy_auth(struct Curl_easy *data,
struct connectdata *conn)
{
char proxyuser[MAX_CURL_USER_LENGTH]="";
char proxypasswd[MAX_CURL_PASSWORD_LENGTH]="";
CURLcode result;
if(data->set.str[STRING_PROXYUSERNAME] != NULL) {
strncpy(proxyuser, data->set.str[STRING_PROXYUSERNAME],
MAX_CURL_USER_LENGTH);
proxyuser[MAX_CURL_USER_LENGTH-1] = '\0'; /*To be on safe side*/
}
if(data->set.str[STRING_PROXYPASSWORD] != NULL) {
strncpy(proxypasswd, data->set.str[STRING_PROXYPASSWORD],
MAX_CURL_PASSWORD_LENGTH);
proxypasswd[MAX_CURL_PASSWORD_LENGTH-1] = '\0'; /*To be on safe side*/
}
result = Curl_urldecode(data, proxyuser, 0, &conn->http_proxy.user, NULL,
FALSE);
if(!result)
result = Curl_urldecode(data, proxypasswd, 0, &conn->http_proxy.passwd,
NULL, FALSE);
return result;
}
/* create_conn helper to parse and init proxy values. to be called after unix
socket init but before any proxy vars are evaluated. */
static CURLcode create_conn_helper_init_proxy(struct connectdata *conn)
{
char *proxy = NULL;
char *socksproxy = NULL;
char *no_proxy = NULL;
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
/*************************************************************
* Extract the user and password from the authentication string
*************************************************************/
if(conn->bits.proxy_user_passwd) {
result = parse_proxy_auth(data, conn);
if(result)
goto out;
}
/*************************************************************
* Detect what (if any) proxy to use
*************************************************************/
if(data->set.str[STRING_PROXY]) {
proxy = strdup(data->set.str[STRING_PROXY]);
/* if global proxy is set, this is it */
if(NULL == proxy) {
failf(data, "memory shortage");
result = CURLE_OUT_OF_MEMORY;
goto out;
}
}
if(data->set.str[STRING_PRE_PROXY]) {
socksproxy = strdup(data->set.str[STRING_PRE_PROXY]);
/* if global socks proxy is set, this is it */
if(NULL == socksproxy) {
failf(data, "memory shortage");
result = CURLE_OUT_OF_MEMORY;
goto out;
}
}
if(!data->set.str[STRING_NOPROXY]) {
const char *p = "no_proxy";
no_proxy = curl_getenv(p);
if(!no_proxy) {
p = "NO_PROXY";
no_proxy = curl_getenv(p);
}
if(no_proxy) {
infof(conn->data, "Uses proxy env variable %s == '%s'\n", p, no_proxy);
}
}
if(check_noproxy(conn->host.name, data->set.str[STRING_NOPROXY] ?
data->set.str[STRING_NOPROXY] : no_proxy)) {
Curl_safefree(proxy);
Curl_safefree(socksproxy);
}
#ifndef CURL_DISABLE_HTTP
else if(!proxy && !socksproxy)
/* if the host is not in the noproxy list, detect proxy. */
proxy = detect_proxy(conn);
#endif /* CURL_DISABLE_HTTP */
Curl_safefree(no_proxy);
#ifdef USE_UNIX_SOCKETS
/* For the time being do not mix proxy and unix domain sockets. See #1274 */
if(proxy && conn->unix_domain_socket) {
free(proxy);
proxy = NULL;
}
#endif
if(proxy && (!*proxy || (conn->handler->flags & PROTOPT_NONETWORK))) {
free(proxy); /* Don't bother with an empty proxy string or if the
protocol doesn't work with network */
proxy = NULL;
}
if(socksproxy && (!*socksproxy ||
(conn->handler->flags & PROTOPT_NONETWORK))) {
free(socksproxy); /* Don't bother with an empty socks proxy string or if
the protocol doesn't work with network */
socksproxy = NULL;
}
/***********************************************************************
* If this is supposed to use a proxy, we need to figure out the proxy host
* name, proxy type and port number, so that we can re-use an existing
* connection that may exist registered to the same proxy host.
***********************************************************************/
if(proxy || socksproxy) {
if(proxy) {
result = parse_proxy(data, conn, proxy, conn->http_proxy.proxytype);
Curl_safefree(proxy); /* parse_proxy copies the proxy string */
if(result)
goto out;
}
if(socksproxy) {
result = parse_proxy(data, conn, socksproxy,
conn->socks_proxy.proxytype);
/* parse_proxy copies the socks proxy string */
Curl_safefree(socksproxy);
if(result)
goto out;
}
if(conn->http_proxy.host.rawalloc) {
#ifdef CURL_DISABLE_HTTP
/* asking for a HTTP proxy is a bit funny when HTTP is disabled... */
result = CURLE_UNSUPPORTED_PROTOCOL;
goto out;
#else
/* force this connection's protocol to become HTTP if compatible */
if(!(conn->handler->protocol & PROTO_FAMILY_HTTP)) {
if((conn->handler->flags & PROTOPT_PROXY_AS_HTTP) &&
!conn->bits.tunnel_proxy)
conn->handler = &Curl_handler_http;
else
/* if not converting to HTTP over the proxy, enforce tunneling */
conn->bits.tunnel_proxy = TRUE;
}
conn->bits.httpproxy = TRUE;
#endif
}
else {
conn->bits.httpproxy = FALSE; /* not a HTTP proxy */
conn->bits.tunnel_proxy = FALSE; /* no tunneling if not HTTP */
}
if(conn->socks_proxy.host.rawalloc) {
if(!conn->http_proxy.host.rawalloc) {
/* once a socks proxy */
if(!conn->socks_proxy.user) {
conn->socks_proxy.user = conn->http_proxy.user;
conn->http_proxy.user = NULL;
Curl_safefree(conn->socks_proxy.passwd);
conn->socks_proxy.passwd = conn->http_proxy.passwd;
conn->http_proxy.passwd = NULL;
}
}
conn->bits.socksproxy = TRUE;
}
else
conn->bits.socksproxy = FALSE; /* not a socks proxy */
}
else {
conn->bits.socksproxy = FALSE;
conn->bits.httpproxy = FALSE;
}
conn->bits.proxy = conn->bits.httpproxy || conn->bits.socksproxy;
if(!conn->bits.proxy) {
/* we aren't using the proxy after all... */
conn->bits.proxy = FALSE;
conn->bits.httpproxy = FALSE;
conn->bits.socksproxy = FALSE;
conn->bits.proxy_user_passwd = FALSE;
conn->bits.tunnel_proxy = FALSE;
}
out:
free(socksproxy);
free(proxy);
return result;
}
#endif /* CURL_DISABLE_PROXY */
/*
* Curl_parse_login_details()
*
* This is used to parse a login string for user name, password and options in
* the following formats:
*
* user
* user:password
* user:password;options
* user;options
* user;options:password
* :password
* :password;options
* ;options
* ;options:password
*
* Parameters:
*
* login [in] - The login string.
* len [in] - The length of the login string.
* userp [in/out] - The address where a pointer to newly allocated memory
* holding the user will be stored upon completion.
* passwdp [in/out] - The address where a pointer to newly allocated memory
* holding the password will be stored upon completion.
* optionsp [in/out] - The address where a pointer to newly allocated memory
* holding the options will be stored upon completion.
*
* Returns CURLE_OK on success.
*/
CURLcode Curl_parse_login_details(const char *login, const size_t len,
char **userp, char **passwdp,
char **optionsp)
{
CURLcode result = CURLE_OK;
char *ubuf = NULL;
char *pbuf = NULL;
char *obuf = NULL;
const char *psep = NULL;
const char *osep = NULL;
size_t ulen;
size_t plen;
size_t olen;
/* Attempt to find the password separator */
if(passwdp) {
psep = strchr(login, ':');
/* Within the constraint of the login string */
if(psep >= login + len)
psep = NULL;
}
/* Attempt to find the options separator */
if(optionsp) {
osep = strchr(login, ';');
/* Within the constraint of the login string */
if(osep >= login + len)
osep = NULL;
}
/* Calculate the portion lengths */
ulen = (psep ?
(size_t)(osep && psep > osep ? osep - login : psep - login) :
(osep ? (size_t)(osep - login) : len));
plen = (psep ?
(osep && osep > psep ? (size_t)(osep - psep) :
(size_t)(login + len - psep)) - 1 : 0);
olen = (osep ?
(psep && psep > osep ? (size_t)(psep - osep) :
(size_t)(login + len - osep)) - 1 : 0);
/* Allocate the user portion buffer */
if(userp && ulen) {
ubuf = malloc(ulen + 1);
if(!ubuf)
result = CURLE_OUT_OF_MEMORY;
}
/* Allocate the password portion buffer */
if(!result && passwdp && plen) {
pbuf = malloc(plen + 1);
if(!pbuf) {
free(ubuf);
result = CURLE_OUT_OF_MEMORY;
}
}
/* Allocate the options portion buffer */
if(!result && optionsp && olen) {
obuf = malloc(olen + 1);
if(!obuf) {
free(pbuf);
free(ubuf);
result = CURLE_OUT_OF_MEMORY;
}
}
if(!result) {
/* Store the user portion if necessary */
if(ubuf) {
memcpy(ubuf, login, ulen);
ubuf[ulen] = '\0';
Curl_safefree(*userp);
*userp = ubuf;
}
/* Store the password portion if necessary */
if(pbuf) {
memcpy(pbuf, psep + 1, plen);
pbuf[plen] = '\0';
Curl_safefree(*passwdp);
*passwdp = pbuf;
}
/* Store the options portion if necessary */
if(obuf) {
memcpy(obuf, osep + 1, olen);
obuf[olen] = '\0';
Curl_safefree(*optionsp);
*optionsp = obuf;
}
}
return result;
}
/*************************************************************
* Figure out the remote port number and fix it in the URL
*
* No matter if we use a proxy or not, we have to figure out the remote
* port number of various reasons.
*
* The port number embedded in the URL is replaced, if necessary.
*************************************************************/
static CURLcode parse_remote_port(struct Curl_easy *data,
struct connectdata *conn)
{
if(data->set.use_port && data->state.allow_port) {
/* if set, we use this instead of the port possibly given in the URL */
char portbuf[16];
CURLUcode uc;
conn->remote_port = (unsigned short)data->set.use_port;
snprintf(portbuf, sizeof(portbuf), "%u", conn->remote_port);
uc = curl_url_set(data->state.uh, CURLUPART_PORT, portbuf, 0);
if(uc)
return CURLE_OUT_OF_MEMORY;
}
return CURLE_OK;
}
/*
* Override the login details from the URL with that in the CURLOPT_USERPWD
* option or a .netrc file, if applicable.
*/
static CURLcode override_login(struct Curl_easy *data,
struct connectdata *conn,
char **userp, char **passwdp, char **optionsp)
{
bool user_changed = FALSE;
bool passwd_changed = FALSE;
CURLUcode uc;
if(data->set.str[STRING_USERNAME]) {
free(*userp);
*userp = strdup(data->set.str[STRING_USERNAME]);
if(!*userp)
return CURLE_OUT_OF_MEMORY;
conn->bits.user_passwd = TRUE; /* enable user+password */
user_changed = TRUE;
}
if(data->set.str[STRING_PASSWORD]) {
free(*passwdp);
*passwdp = strdup(data->set.str[STRING_PASSWORD]);
if(!*passwdp)
return CURLE_OUT_OF_MEMORY;
conn->bits.user_passwd = TRUE; /* enable user+password */
passwd_changed = TRUE;
}
if(data->set.str[STRING_OPTIONS]) {
free(*optionsp);
*optionsp = strdup(data->set.str[STRING_OPTIONS]);
if(!*optionsp)
return CURLE_OUT_OF_MEMORY;
}
conn->bits.netrc = FALSE;
if(data->set.use_netrc != CURL_NETRC_IGNORED) {
char *nuser = NULL;
char *npasswd = NULL;
int ret;
if(data->set.use_netrc == CURL_NETRC_OPTIONAL)
nuser = *userp; /* to separate otherwise identical machines */
ret = Curl_parsenetrc(conn->host.name,
&nuser, &npasswd,
data->set.str[STRING_NETRC_FILE]);
if(ret > 0) {
infof(data, "Couldn't find host %s in the "
DOT_CHAR "netrc file; using defaults\n",
conn->host.name);
}
else if(ret < 0) {
return CURLE_OUT_OF_MEMORY;
}
else {
/* set bits.netrc TRUE to remember that we got the name from a .netrc
file, so that it is safe to use even if we followed a Location: to a
different host or similar. */
conn->bits.netrc = TRUE;
conn->bits.user_passwd = TRUE; /* enable user+password */
if(data->set.use_netrc == CURL_NETRC_OPTIONAL) {
/* prefer credentials outside netrc */
if(nuser && !*userp) {
free(*userp);
*userp = nuser;
user_changed = TRUE;
}
if(npasswd && !*passwdp) {
free(*passwdp);
*passwdp = npasswd;
passwd_changed = TRUE;
}
}
else {
/* prefer netrc credentials */
if(nuser) {
free(*userp);
*userp = nuser;
user_changed = TRUE;
}
if(npasswd) {
free(*passwdp);
*passwdp = npasswd;
passwd_changed = TRUE;
}
}
}
}
/* for updated strings, we update them in the URL */
if(user_changed) {
uc = curl_url_set(data->state.uh, CURLUPART_USER, *userp, 0);
if(uc)
return Curl_uc_to_curlcode(uc);
}
if(passwd_changed) {
uc = curl_url_set(data->state.uh, CURLUPART_PASSWORD, *passwdp, 0);
if(uc)
return Curl_uc_to_curlcode(uc);
}
return CURLE_OK;
}
/*
* Set the login details so they're available in the connection
*/
static CURLcode set_login(struct connectdata *conn)
{
CURLcode result = CURLE_OK;
const char *setuser = CURL_DEFAULT_USER;
const char *setpasswd = CURL_DEFAULT_PASSWORD;
/* If our protocol needs a password and we have none, use the defaults */
if((conn->handler->flags & PROTOPT_NEEDSPWD) && !conn->bits.user_passwd)
;
else {
setuser = "";
setpasswd = "";
}
/* Store the default user */
if(!conn->user) {
conn->user = strdup(setuser);
if(!conn->user)
return CURLE_OUT_OF_MEMORY;
}
/* Store the default password */
if(!conn->passwd) {
conn->passwd = strdup(setpasswd);
if(!conn->passwd)
result = CURLE_OUT_OF_MEMORY;
}
/* if there's a user without password, consider password blank */
if(conn->user && !conn->passwd) {
conn->passwd = strdup("");
if(!conn->passwd)
result = CURLE_OUT_OF_MEMORY;
}
return result;
}
/*
* Parses a "host:port" string to connect to.
* The hostname and the port may be empty; in this case, NULL is returned for
* the hostname and -1 for the port.
*/
static CURLcode parse_connect_to_host_port(struct Curl_easy *data,
const char *host,
char **hostname_result,
int *port_result)
{
char *host_dup;
char *hostptr;
char *host_portno;
char *portptr;
int port = -1;
#if defined(CURL_DISABLE_VERBOSE_STRINGS)
(void) data;
#endif
*hostname_result = NULL;
*port_result = -1;
if(!host || !*host)
return CURLE_OK;
host_dup = strdup(host);
if(!host_dup)
return CURLE_OUT_OF_MEMORY;
hostptr = host_dup;
/* start scanning for port number at this point */
portptr = hostptr;
/* detect and extract RFC6874-style IPv6-addresses */
if(*hostptr == '[') {
#ifdef ENABLE_IPV6
char *ptr = ++hostptr; /* advance beyond the initial bracket */
while(*ptr && (ISXDIGIT(*ptr) || (*ptr == ':') || (*ptr == '.')))
ptr++;
if(*ptr == '%') {
/* There might be a zone identifier */
if(strncmp("%25", ptr, 3))
infof(data, "Please URL encode %% as %%25, see RFC 6874.\n");
ptr++;
/* Allow unreserved characters as defined in RFC 3986 */
while(*ptr && (ISALPHA(*ptr) || ISXDIGIT(*ptr) || (*ptr == '-') ||
(*ptr == '.') || (*ptr == '_') || (*ptr == '~')))
ptr++;
}
if(*ptr == ']')
/* yeps, it ended nicely with a bracket as well */
*ptr++ = '\0';
else
infof(data, "Invalid IPv6 address format\n");
portptr = ptr;
/* Note that if this didn't end with a bracket, we still advanced the
* hostptr first, but I can't see anything wrong with that as no host
* name nor a numeric can legally start with a bracket.
*/
#else
failf(data, "Use of IPv6 in *_CONNECT_TO without IPv6 support built-in!");
free(host_dup);
return CURLE_NOT_BUILT_IN;
#endif
}
/* Get port number off server.com:1080 */
host_portno = strchr(portptr, ':');
if(host_portno) {
char *endp = NULL;
*host_portno = '\0'; /* cut off number from host name */
host_portno++;
if(*host_portno) {
long portparse = strtol(host_portno, &endp, 10);
if((endp && *endp) || (portparse < 0) || (portparse > 65535)) {
infof(data, "No valid port number in connect to host string (%s)\n",
host_portno);
hostptr = NULL;
port = -1;
}
else
port = (int)portparse; /* we know it will fit */
}
}
/* now, clone the cleaned host name */
if(hostptr) {
*hostname_result = strdup(hostptr);
if(!*hostname_result) {
free(host_dup);
return CURLE_OUT_OF_MEMORY;
}
}
*port_result = port;
free(host_dup);
return CURLE_OK;
}
/*
* Parses one "connect to" string in the form:
* "HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT".
*/
static CURLcode parse_connect_to_string(struct Curl_easy *data,
struct connectdata *conn,
const char *conn_to_host,
char **host_result,
int *port_result)
{
CURLcode result = CURLE_OK;
const char *ptr = conn_to_host;
int host_match = FALSE;
int port_match = FALSE;
*host_result = NULL;
*port_result = -1;
if(*ptr == ':') {
/* an empty hostname always matches */
host_match = TRUE;
ptr++;
}
else {
/* check whether the URL's hostname matches */
size_t hostname_to_match_len;
char *hostname_to_match = aprintf("%s%s%s",
conn->bits.ipv6_ip ? "[" : "",
conn->host.name,
conn->bits.ipv6_ip ? "]" : "");
if(!hostname_to_match)
return CURLE_OUT_OF_MEMORY;
hostname_to_match_len = strlen(hostname_to_match);
host_match = strncasecompare(ptr, hostname_to_match,
hostname_to_match_len);
free(hostname_to_match);
ptr += hostname_to_match_len;
host_match = host_match && *ptr == ':';
ptr++;
}
if(host_match) {
if(*ptr == ':') {
/* an empty port always matches */
port_match = TRUE;
ptr++;
}
else {
/* check whether the URL's port matches */
char *ptr_next = strchr(ptr, ':');
if(ptr_next) {
char *endp = NULL;
long port_to_match = strtol(ptr, &endp, 10);
if((endp == ptr_next) && (port_to_match == conn->remote_port)) {
port_match = TRUE;
ptr = ptr_next + 1;
}
}
}
}
if(host_match && port_match) {
/* parse the hostname and port to connect to */
result = parse_connect_to_host_port(data, ptr, host_result, port_result);
}
return result;
}
/*
* Processes all strings in the "connect to" slist, and uses the "connect
* to host" and "connect to port" of the first string that matches.
*/
static CURLcode parse_connect_to_slist(struct Curl_easy *data,
struct connectdata *conn,
struct curl_slist *conn_to_host)
{
CURLcode result = CURLE_OK;
char *host = NULL;
int port = -1;
while(conn_to_host && !host && port == -1) {
result = parse_connect_to_string(data, conn, conn_to_host->data,
&host, &port);
if(result)
return result;
if(host && *host) {
conn->conn_to_host.rawalloc = host;
conn->conn_to_host.name = host;
conn->bits.conn_to_host = TRUE;
infof(data, "Connecting to hostname: %s\n", host);
}
else {
/* no "connect to host" */
conn->bits.conn_to_host = FALSE;
Curl_safefree(host);
}
if(port >= 0) {
conn->conn_to_port = port;
conn->bits.conn_to_port = TRUE;
infof(data, "Connecting to port: %d\n", port);
}
else {
/* no "connect to port" */
conn->bits.conn_to_port = FALSE;
port = -1;
}
conn_to_host = conn_to_host->next;
}
return result;
}
/*************************************************************
* Resolve the address of the server or proxy
*************************************************************/
static CURLcode resolve_server(struct Curl_easy *data,
struct connectdata *conn,
bool *async)
{
CURLcode result = CURLE_OK;
timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
/*************************************************************
* Resolve the name of the server or proxy
*************************************************************/
if(conn->bits.reuse)
/* We're reusing the connection - no need to resolve anything, and
fix_hostname() was called already in create_conn() for the re-use
case. */
*async = FALSE;
else {
/* this is a fresh connect */
int rc;
struct Curl_dns_entry *hostaddr;
#ifdef USE_UNIX_SOCKETS
if(conn->unix_domain_socket) {
/* Unix domain sockets are local. The host gets ignored, just use the
* specified domain socket address. Do not cache "DNS entries". There is
* no DNS involved and we already have the filesystem path available */
const char *path = conn->unix_domain_socket;
hostaddr = calloc(1, sizeof(struct Curl_dns_entry));
if(!hostaddr)
result = CURLE_OUT_OF_MEMORY;
else {
bool longpath = FALSE;
hostaddr->addr = Curl_unix2addr(path, &longpath,
conn->abstract_unix_socket);
if(hostaddr->addr)
hostaddr->inuse++;
else {
/* Long paths are not supported for now */
if(longpath) {
failf(data, "Unix socket path too long: '%s'", path);
result = CURLE_COULDNT_RESOLVE_HOST;
}
else
result = CURLE_OUT_OF_MEMORY;
free(hostaddr);
hostaddr = NULL;
}
}
}
else
#endif
if(!conn->bits.proxy) {
struct hostname *connhost;
if(conn->bits.conn_to_host)
connhost = &conn->conn_to_host;
else
connhost = &conn->host;
/* If not connecting via a proxy, extract the port from the URL, if it is
* there, thus overriding any defaults that might have been set above. */
if(conn->bits.conn_to_port)
conn->port = conn->conn_to_port;
else
conn->port = conn->remote_port;
/* Resolve target host right on */
rc = Curl_resolv_timeout(conn, connhost->name, (int)conn->port,
&hostaddr, timeout_ms);
if(rc == CURLRESOLV_PENDING)
*async = TRUE;
else if(rc == CURLRESOLV_TIMEDOUT)
result = CURLE_OPERATION_TIMEDOUT;
else if(!hostaddr) {
failf(data, "Couldn't resolve host '%s'", connhost->dispname);
result = CURLE_COULDNT_RESOLVE_HOST;
/* don't return yet, we need to clean up the timeout first */
}
}
else {
/* This is a proxy that hasn't been resolved yet. */
struct hostname * const host = conn->bits.socksproxy ?
&conn->socks_proxy.host : &conn->http_proxy.host;
/* resolve proxy */
rc = Curl_resolv_timeout(conn, host->name, (int)conn->port,
&hostaddr, timeout_ms);
if(rc == CURLRESOLV_PENDING)
*async = TRUE;
else if(rc == CURLRESOLV_TIMEDOUT)
result = CURLE_OPERATION_TIMEDOUT;
else if(!hostaddr) {
failf(data, "Couldn't resolve proxy '%s'", host->dispname);
result = CURLE_COULDNT_RESOLVE_PROXY;
/* don't return yet, we need to clean up the timeout first */
}
}
DEBUGASSERT(conn->dns_entry == NULL);
conn->dns_entry = hostaddr;
}
return result;
}
/*
* Cleanup the connection just allocated before we can move along and use the
* previously existing one. All relevant data is copied over and old_conn is
* ready for freeing once this function returns.
*/
static void reuse_conn(struct connectdata *old_conn,
struct connectdata *conn)
{
free_fixed_hostname(&old_conn->http_proxy.host);
free_fixed_hostname(&old_conn->socks_proxy.host);
free(old_conn->http_proxy.host.rawalloc);
free(old_conn->socks_proxy.host.rawalloc);
/* free the SSL config struct from this connection struct as this was
allocated in vain and is targeted for destruction */
Curl_free_primary_ssl_config(&old_conn->ssl_config);
Curl_free_primary_ssl_config(&old_conn->proxy_ssl_config);
conn->data = old_conn->data;
/* get the user+password information from the old_conn struct since it may
* be new for this request even when we re-use an existing connection */
conn->bits.user_passwd = old_conn->bits.user_passwd;
if(conn->bits.user_passwd) {
/* use the new user name and password though */
Curl_safefree(conn->user);
Curl_safefree(conn->passwd);
conn->user = old_conn->user;
conn->passwd = old_conn->passwd;
old_conn->user = NULL;
old_conn->passwd = NULL;
}
conn->bits.proxy_user_passwd = old_conn->bits.proxy_user_passwd;
if(conn->bits.proxy_user_passwd) {
/* use the new proxy user name and proxy password though */
Curl_safefree(conn->http_proxy.user);
Curl_safefree(conn->socks_proxy.user);
Curl_safefree(conn->http_proxy.passwd);
Curl_safefree(conn->socks_proxy.passwd);
conn->http_proxy.user = old_conn->http_proxy.user;
conn->socks_proxy.user = old_conn->socks_proxy.user;
conn->http_proxy.passwd = old_conn->http_proxy.passwd;
conn->socks_proxy.passwd = old_conn->socks_proxy.passwd;
old_conn->http_proxy.user = NULL;
old_conn->socks_proxy.user = NULL;
old_conn->http_proxy.passwd = NULL;
old_conn->socks_proxy.passwd = NULL;
}
/* host can change, when doing keepalive with a proxy or if the case is
different this time etc */
free_fixed_hostname(&conn->host);
free_fixed_hostname(&conn->conn_to_host);
Curl_safefree(conn->host.rawalloc);
Curl_safefree(conn->conn_to_host.rawalloc);
conn->host = old_conn->host;
conn->conn_to_host = old_conn->conn_to_host;
conn->conn_to_port = old_conn->conn_to_port;
conn->remote_port = old_conn->remote_port;
/* persist connection info in session handle */
Curl_persistconninfo(conn);
conn_reset_all_postponed_data(old_conn); /* free buffers */
/* re-use init */
conn->bits.reuse = TRUE; /* yes, we're re-using here */
Curl_safefree(old_conn->user);
Curl_safefree(old_conn->passwd);
Curl_safefree(old_conn->options);
Curl_safefree(old_conn->http_proxy.user);
Curl_safefree(old_conn->socks_proxy.user);
Curl_safefree(old_conn->http_proxy.passwd);
Curl_safefree(old_conn->socks_proxy.passwd);
Curl_safefree(old_conn->localdev);
Curl_llist_destroy(&old_conn->send_pipe, NULL);
Curl_llist_destroy(&old_conn->recv_pipe, NULL);
Curl_safefree(old_conn->master_buffer);
#ifdef USE_UNIX_SOCKETS
Curl_safefree(old_conn->unix_domain_socket);
#endif
}
/**
* create_conn() sets up a new connectdata struct, or re-uses an already
* existing one, and resolves host name.
*
* if this function returns CURLE_OK and *async is set to TRUE, the resolve
* response will be coming asynchronously. If *async is FALSE, the name is
* already resolved.
*
* @param data The sessionhandle pointer
* @param in_connect is set to the next connection data pointer
* @param async is set TRUE when an async DNS resolution is pending
* @see Curl_setup_conn()
*
* *NOTE* this function assigns the conn->data pointer!
*/
static CURLcode create_conn(struct Curl_easy *data,
struct connectdata **in_connect,
bool *async)
{
CURLcode result = CURLE_OK;
struct connectdata *conn;
struct connectdata *conn_temp = NULL;
bool reuse;
bool connections_available = TRUE;
bool force_reuse = FALSE;
bool waitpipe = FALSE;
size_t max_host_connections = Curl_multi_max_host_connections(data->multi);
size_t max_total_connections = Curl_multi_max_total_connections(data->multi);
*async = FALSE;
/*************************************************************
* Check input data
*************************************************************/
if(!data->change.url) {
result = CURLE_URL_MALFORMAT;
goto out;
}
/* First, split up the current URL in parts so that we can use the
parts for checking against the already present connections. In order
to not have to modify everything at once, we allocate a temporary
connection data struct and fill in for comparison purposes. */
conn = allocate_conn(data);
if(!conn) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
/* We must set the return variable as soon as possible, so that our
parent can cleanup any possible allocs we may have done before
any failure */
*in_connect = conn;
result = parseurlandfillconn(data, conn);
if(result)
goto out;
if(data->set.str[STRING_BEARER]) {
conn->oauth_bearer = strdup(data->set.str[STRING_BEARER]);
if(!conn->oauth_bearer) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
}
#ifdef USE_UNIX_SOCKETS
if(data->set.str[STRING_UNIX_SOCKET_PATH]) {
conn->unix_domain_socket = strdup(data->set.str[STRING_UNIX_SOCKET_PATH]);
if(conn->unix_domain_socket == NULL) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
conn->abstract_unix_socket = data->set.abstract_unix_socket;
}
#endif
/* After the unix socket init but before the proxy vars are used, parse and
initialize the proxy vars */
#ifndef CURL_DISABLE_PROXY
result = create_conn_helper_init_proxy(conn);
if(result)
goto out;
#endif
/*************************************************************
* If the protocol is using SSL and HTTP proxy is used, we set
* the tunnel_proxy bit.
*************************************************************/
if((conn->given->flags&PROTOPT_SSL) && conn->bits.httpproxy)
conn->bits.tunnel_proxy = TRUE;
/*************************************************************
* Figure out the remote port number and fix it in the URL
*************************************************************/
result = parse_remote_port(data, conn);
if(result)
goto out;
/* Check for overridden login details and set them accordingly so they
they are known when protocol->setup_connection is called! */
result = override_login(data, conn, &conn->user, &conn->passwd,
&conn->options);
if(result)
goto out;
result = set_login(conn); /* default credentials */
if(result)
goto out;
/*************************************************************
* Process the "connect to" linked list of hostname/port mappings.
* Do this after the remote port number has been fixed in the URL.
*************************************************************/
result = parse_connect_to_slist(data, conn, data->set.connect_to);
if(result)
goto out;
/*************************************************************
* IDN-fix the hostnames
*************************************************************/
result = fix_hostname(conn, &conn->host);
if(result)
goto out;
if(conn->bits.conn_to_host) {
result = fix_hostname(conn, &conn->conn_to_host);
if(result)
goto out;
}
if(conn->bits.httpproxy) {
result = fix_hostname(conn, &conn->http_proxy.host);
if(result)
goto out;
}
if(conn->bits.socksproxy) {
result = fix_hostname(conn, &conn->socks_proxy.host);
if(result)
goto out;
}
/*************************************************************
* Check whether the host and the "connect to host" are equal.
* Do this after the hostnames have been IDN-fixed.
*************************************************************/
if(conn->bits.conn_to_host &&
strcasecompare(conn->conn_to_host.name, conn->host.name)) {
conn->bits.conn_to_host = FALSE;
}
/*************************************************************
* Check whether the port and the "connect to port" are equal.
* Do this after the remote port number has been fixed in the URL.
*************************************************************/
if(conn->bits.conn_to_port && conn->conn_to_port == conn->remote_port) {
conn->bits.conn_to_port = FALSE;
}
/*************************************************************
* If the "connect to" feature is used with an HTTP proxy,
* we set the tunnel_proxy bit.
*************************************************************/
if((conn->bits.conn_to_host || conn->bits.conn_to_port) &&
conn->bits.httpproxy)
conn->bits.tunnel_proxy = TRUE;
/*************************************************************
* Setup internals depending on protocol. Needs to be done after
* we figured out what/if proxy to use.
*************************************************************/
result = setup_connection_internals(conn);
if(result)
goto out;
conn->recv[FIRSTSOCKET] = Curl_recv_plain;
conn->send[FIRSTSOCKET] = Curl_send_plain;
conn->recv[SECONDARYSOCKET] = Curl_recv_plain;
conn->send[SECONDARYSOCKET] = Curl_send_plain;
conn->bits.tcp_fastopen = data->set.tcp_fastopen;
/***********************************************************************
* file: is a special case in that it doesn't need a network connection
***********************************************************************/
#ifndef CURL_DISABLE_FILE
if(conn->handler->flags & PROTOPT_NONETWORK) {
bool done;
/* this is supposed to be the connect function so we better at least check
that the file is present here! */
DEBUGASSERT(conn->handler->connect_it);
Curl_persistconninfo(conn);
result = conn->handler->connect_it(conn, &done);
/* Setup a "faked" transfer that'll do nothing */
if(!result) {
conn->data = data;
conn->bits.tcpconnect[FIRSTSOCKET] = TRUE; /* we are "connected */
result = Curl_conncache_add_conn(data->state.conn_cache, conn);
if(result)
goto out;
/*
* Setup whatever necessary for a resumed transfer
*/
result = setup_range(data);
if(result) {
DEBUGASSERT(conn->handler->done);
/* we ignore the return code for the protocol-specific DONE */
(void)conn->handler->done(conn, result, FALSE);
goto out;
}
Curl_setup_transfer(conn, -1, -1, FALSE, NULL, /* no download */
-1, NULL); /* no upload */
}
/* since we skip do_init() */
Curl_init_do(data, conn);
goto out;
}
#endif
/* Get a cloned copy of the SSL config situation stored in the
connection struct. But to get this going nicely, we must first make
sure that the strings in the master copy are pointing to the correct
strings in the session handle strings array!
Keep in mind that the pointers in the master copy are pointing to strings
that will be freed as part of the Curl_easy struct, but all cloned
copies will be separately allocated.
*/
data->set.ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_ORIG];
data->set.proxy_ssl.primary.CApath = data->set.str[STRING_SSL_CAPATH_PROXY];
data->set.ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_ORIG];
data->set.proxy_ssl.primary.CAfile = data->set.str[STRING_SSL_CAFILE_PROXY];
data->set.ssl.primary.random_file = data->set.str[STRING_SSL_RANDOM_FILE];
data->set.proxy_ssl.primary.random_file =
data->set.str[STRING_SSL_RANDOM_FILE];
data->set.ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
data->set.proxy_ssl.primary.egdsocket = data->set.str[STRING_SSL_EGDSOCKET];
data->set.ssl.primary.cipher_list =
data->set.str[STRING_SSL_CIPHER_LIST_ORIG];
data->set.proxy_ssl.primary.cipher_list =
data->set.str[STRING_SSL_CIPHER_LIST_PROXY];
data->set.ssl.primary.cipher_list13 =
data->set.str[STRING_SSL_CIPHER13_LIST_ORIG];
data->set.proxy_ssl.primary.cipher_list13 =
data->set.str[STRING_SSL_CIPHER13_LIST_PROXY];
data->set.ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_ORIG];
data->set.proxy_ssl.CRLfile = data->set.str[STRING_SSL_CRLFILE_PROXY];
data->set.ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_ORIG];
data->set.proxy_ssl.issuercert = data->set.str[STRING_SSL_ISSUERCERT_PROXY];
data->set.ssl.cert = data->set.str[STRING_CERT_ORIG];
data->set.proxy_ssl.cert = data->set.str[STRING_CERT_PROXY];
data->set.ssl.cert_type = data->set.str[STRING_CERT_TYPE_ORIG];
data->set.proxy_ssl.cert_type = data->set.str[STRING_CERT_TYPE_PROXY];
data->set.ssl.key = data->set.str[STRING_KEY_ORIG];
data->set.proxy_ssl.key = data->set.str[STRING_KEY_PROXY];
data->set.ssl.key_type = data->set.str[STRING_KEY_TYPE_ORIG];
data->set.proxy_ssl.key_type = data->set.str[STRING_KEY_TYPE_PROXY];
data->set.ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_ORIG];
data->set.proxy_ssl.key_passwd = data->set.str[STRING_KEY_PASSWD_PROXY];
data->set.ssl.primary.clientcert = data->set.str[STRING_CERT_ORIG];
data->set.proxy_ssl.primary.clientcert = data->set.str[STRING_CERT_PROXY];
#ifdef USE_TLS_SRP
data->set.ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_ORIG];
data->set.proxy_ssl.username = data->set.str[STRING_TLSAUTH_USERNAME_PROXY];
data->set.ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_ORIG];
data->set.proxy_ssl.password = data->set.str[STRING_TLSAUTH_PASSWORD_PROXY];
#endif
if(!Curl_clone_primary_ssl_config(&data->set.ssl.primary,
&conn->ssl_config)) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
if(!Curl_clone_primary_ssl_config(&data->set.proxy_ssl.primary,
&conn->proxy_ssl_config)) {
result = CURLE_OUT_OF_MEMORY;
goto out;
}
prune_dead_connections(data);
/*************************************************************
* Check the current list of connections to see if we can
* re-use an already existing one or if we have to create a
* new one.
*************************************************************/
DEBUGASSERT(conn->user);
DEBUGASSERT(conn->passwd);
/* reuse_fresh is TRUE if we are told to use a new connection by force, but
we only acknowledge this option if this is not a re-used connection
already (which happens due to follow-location or during a HTTP
authentication phase). */
if(data->set.reuse_fresh && !data->state.this_is_a_follow)
reuse = FALSE;
else
reuse = ConnectionExists(data, conn, &conn_temp, &force_reuse, &waitpipe);
/* If we found a reusable connection that is now marked as in use, we may
still want to open a new connection if we are pipelining. */
if(reuse && !force_reuse && IsPipeliningPossible(data, conn_temp)) {
size_t pipelen = conn_temp->send_pipe.size + conn_temp->recv_pipe.size;
if(pipelen > 0) {
infof(data, "Found connection %ld, with requests in the pipe (%zu)\n",
conn_temp->connection_id, pipelen);
if(Curl_conncache_bundle_size(conn_temp) < max_host_connections &&
Curl_conncache_size(data) < max_total_connections) {
/* We want a new connection anyway */
reuse = FALSE;
infof(data, "We can reuse, but we want a new connection anyway\n");
Curl_conncache_return_conn(conn_temp);
}
}
}
if(reuse) {
/*
* We already have a connection for this, we got the former connection
* in the conn_temp variable and thus we need to cleanup the one we
* just allocated before we can move along and use the previously
* existing one.
*/
reuse_conn(conn, conn_temp);
#ifdef USE_SSL
free(conn->ssl_extra);
#endif
free(conn); /* we don't need this anymore */
conn = conn_temp;
*in_connect = conn;
infof(data, "Re-using existing connection! (#%ld) with %s %s\n",
conn->connection_id,
conn->bits.proxy?"proxy":"host",
conn->socks_proxy.host.name ? conn->socks_proxy.host.dispname :
conn->http_proxy.host.name ? conn->http_proxy.host.dispname :
conn->host.dispname);
}
else {
/* We have decided that we want a new connection. However, we may not
be able to do that if we have reached the limit of how many
connections we are allowed to open. */
if(conn->handler->flags & PROTOPT_ALPN_NPN) {
/* The protocol wants it, so set the bits if enabled in the easy handle
(default) */
if(data->set.ssl_enable_alpn)
conn->bits.tls_enable_alpn = TRUE;
if(data->set.ssl_enable_npn)
conn->bits.tls_enable_npn = TRUE;
}
if(waitpipe)
/* There is a connection that *might* become usable for pipelining
"soon", and we wait for that */
connections_available = FALSE;
else {
/* this gets a lock on the conncache */
struct connectbundle *bundle =
Curl_conncache_find_bundle(conn, data->state.conn_cache);
if(max_host_connections > 0 && bundle &&
(bundle->num_connections >= max_host_connections)) {
struct connectdata *conn_candidate;
/* The bundle is full. Extract the oldest connection. */
conn_candidate = Curl_conncache_extract_bundle(data, bundle);
Curl_conncache_unlock(conn);
if(conn_candidate)
(void)Curl_disconnect(data, conn_candidate,
/* dead_connection */ FALSE);
else {
infof(data, "No more connections allowed to host: %zu\n",
max_host_connections);
connections_available = FALSE;
}
}
else
Curl_conncache_unlock(conn);
}
if(connections_available &&
(max_total_connections > 0) &&
(Curl_conncache_size(data) >= max_total_connections)) {
struct connectdata *conn_candidate;
/* The cache is full. Let's see if we can kill a connection. */
conn_candidate = Curl_conncache_extract_oldest(data);
if(conn_candidate)
(void)Curl_disconnect(data, conn_candidate,
/* dead_connection */ FALSE);
else {
infof(data, "No connections available in cache\n");
connections_available = FALSE;
}
}
if(!connections_available) {
infof(data, "No connections available.\n");
conn_free(conn);
*in_connect = NULL;
result = CURLE_NO_CONNECTION_AVAILABLE;
goto out;
}
else {
/*
* This is a brand new connection, so let's store it in the connection
* cache of ours!
*/
result = Curl_conncache_add_conn(data->state.conn_cache, conn);
if(result)
goto out;
}
#if defined(USE_NTLM)
/* If NTLM is requested in a part of this connection, make sure we don't
assume the state is fine as this is a fresh connection and NTLM is
connection based. */
if((data->state.authhost.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
data->state.authhost.done) {
infof(data, "NTLM picked AND auth done set, clear picked!\n");
data->state.authhost.picked = CURLAUTH_NONE;
data->state.authhost.done = FALSE;
}
if((data->state.authproxy.picked & (CURLAUTH_NTLM | CURLAUTH_NTLM_WB)) &&
data->state.authproxy.done) {
infof(data, "NTLM-proxy picked AND auth done set, clear picked!\n");
data->state.authproxy.picked = CURLAUTH_NONE;
data->state.authproxy.done = FALSE;
}
#endif
}
/* Setup and init stuff before DO starts, in preparing for the transfer. */
Curl_init_do(data, conn);
/*
* Setup whatever necessary for a resumed transfer
*/
result = setup_range(data);
if(result)
goto out;
/* Continue connectdata initialization here. */
/*
* Inherit the proper values from the urldata struct AFTER we have arranged
* the persistent connection stuff
*/
conn->seek_func = data->set.seek_func;
conn->seek_client = data->set.seek_client;
/*************************************************************
* Resolve the address of the server or proxy
*************************************************************/
result = resolve_server(data, conn, async);
out:
return result;
}
/* Curl_setup_conn() is called after the name resolve initiated in
* create_conn() is all done.
*
* Curl_setup_conn() also handles reused connections
*
* conn->data MUST already have been setup fine (in create_conn)
*/
CURLcode Curl_setup_conn(struct connectdata *conn,
bool *protocol_done)
{
CURLcode result = CURLE_OK;
struct Curl_easy *data = conn->data;
Curl_pgrsTime(data, TIMER_NAMELOOKUP);
if(conn->handler->flags & PROTOPT_NONETWORK) {
/* nothing to setup when not using a network */
*protocol_done = TRUE;
return result;
}
*protocol_done = FALSE; /* default to not done */
/* set proxy_connect_closed to false unconditionally already here since it
is used strictly to provide extra information to a parent function in the
case of proxy CONNECT failures and we must make sure we don't have it
lingering set from a previous invoke */
conn->bits.proxy_connect_closed = FALSE;
/*
* Set user-agent. Used for HTTP, but since we can attempt to tunnel
* basically anything through a http proxy we can't limit this based on
* protocol.
*/
if(data->set.str[STRING_USERAGENT]) {
Curl_safefree(conn->allocptr.uagent);
conn->allocptr.uagent =
aprintf("User-Agent: %s\r\n", data->set.str[STRING_USERAGENT]);
if(!conn->allocptr.uagent)
return CURLE_OUT_OF_MEMORY;
}
data->req.headerbytecount = 0;
#ifdef CURL_DO_LINEEND_CONV
data->state.crlf_conversions = 0; /* reset CRLF conversion counter */
#endif /* CURL_DO_LINEEND_CONV */
/* set start time here for timeout purposes in the connect procedure, it
is later set again for the progress meter purpose */
conn->now = Curl_now();
if(CURL_SOCKET_BAD == conn->sock[FIRSTSOCKET]) {
conn->bits.tcpconnect[FIRSTSOCKET] = FALSE;
result = Curl_connecthost(conn, conn->dns_entry);
if(result)
return result;
}
else {
Curl_pgrsTime(data, TIMER_CONNECT); /* we're connected already */
Curl_pgrsTime(data, TIMER_APPCONNECT); /* we're connected already */
conn->bits.tcpconnect[FIRSTSOCKET] = TRUE;
*protocol_done = TRUE;
Curl_updateconninfo(conn, conn->sock[FIRSTSOCKET]);
Curl_verboseconnect(conn);
}
conn->now = Curl_now(); /* time this *after* the connect is done, we set
this here perhaps a second time */
return result;
}
CURLcode Curl_connect(struct Curl_easy *data,
struct connectdata **in_connect,
bool *asyncp,
bool *protocol_done)
{
CURLcode result;
*asyncp = FALSE; /* assume synchronous resolves by default */
/* init the single-transfer specific data */
Curl_free_request_state(data);
memset(&data->req, 0, sizeof(struct SingleRequest));
data->req.maxdownload = -1;
/* call the stuff that needs to be called */
result = create_conn(data, in_connect, asyncp);
if(!result) {
if(CONN_INUSE(*in_connect))
/* pipelining */
*protocol_done = TRUE;
else if(!*asyncp) {
/* DNS resolution is done: that's either because this is a reused
connection, in which case DNS was unnecessary, or because DNS
really did finish already (synch resolver/fast async resolve) */
result = Curl_setup_conn(*in_connect, protocol_done);
}
}
if(result == CURLE_NO_CONNECTION_AVAILABLE) {
*in_connect = NULL;
return result;
}
else if(result && *in_connect) {
/* We're not allowed to return failure with memory left allocated in the
connectdata struct, free those here */
Curl_disconnect(data, *in_connect, TRUE);
*in_connect = NULL; /* return a NULL */
}
return result;
}
/*
* Curl_init_do() inits the readwrite session. This is inited each time (in
* the DO function before the protocol-specific DO functions are invoked) for
* a transfer, sometimes multiple times on the same Curl_easy. Make sure
* nothing in here depends on stuff that are setup dynamically for the
* transfer.
*
* Allow this function to get called with 'conn' set to NULL.
*/
CURLcode Curl_init_do(struct Curl_easy *data, struct connectdata *conn)
{
struct SingleRequest *k = &data->req;
if(conn) {
conn->bits.do_more = FALSE; /* by default there's no curl_do_more() to
use */
/* if the protocol used doesn't support wildcards, switch it off */
if(data->state.wildcardmatch &&
!(conn->handler->flags & PROTOPT_WILDCARD))
data->state.wildcardmatch = FALSE;
}
data->state.done = FALSE; /* *_done() is not called yet */
data->state.expect100header = FALSE;
if(data->set.opt_no_body)
/* in HTTP lingo, no body means using the HEAD request... */
data->set.httpreq = HTTPREQ_HEAD;
else if(HTTPREQ_HEAD == data->set.httpreq)
/* ... but if unset there really is no perfect method that is the
"opposite" of HEAD but in reality most people probably think GET
then. The important thing is that we can't let it remain HEAD if the
opt_no_body is set FALSE since then we'll behave wrong when getting
HTTP. */
data->set.httpreq = HTTPREQ_GET;
k->start = Curl_now(); /* start time */
k->now = k->start; /* current time is now */
k->header = TRUE; /* assume header */
k->bytecount = 0;
k->buf = data->state.buffer;
k->hbufp = data->state.headerbuff;
k->ignorebody = FALSE;
Curl_speedinit(data);
Curl_pgrsSetUploadCounter(data, 0);
Curl_pgrsSetDownloadCounter(data, 0);
return CURLE_OK;
}
/*
* get_protocol_family()
*
* This is used to return the protocol family for a given protocol.
*
* Parameters:
*
* protocol [in] - A single bit protocol identifier such as HTTP or HTTPS.
*
* Returns the family as a single bit protocol identifier.
*/
static unsigned int get_protocol_family(unsigned int protocol)
{
unsigned int family;
switch(protocol) {
case CURLPROTO_HTTP:
case CURLPROTO_HTTPS:
family = CURLPROTO_HTTP;
break;
case CURLPROTO_FTP:
case CURLPROTO_FTPS:
family = CURLPROTO_FTP;
break;
case CURLPROTO_SCP:
family = CURLPROTO_SCP;
break;
case CURLPROTO_SFTP:
family = CURLPROTO_SFTP;
break;
case CURLPROTO_TELNET:
family = CURLPROTO_TELNET;
break;
case CURLPROTO_LDAP:
case CURLPROTO_LDAPS:
family = CURLPROTO_LDAP;
break;
case CURLPROTO_DICT:
family = CURLPROTO_DICT;
break;
case CURLPROTO_FILE:
family = CURLPROTO_FILE;
break;
case CURLPROTO_TFTP:
family = CURLPROTO_TFTP;
break;
case CURLPROTO_IMAP:
case CURLPROTO_IMAPS:
family = CURLPROTO_IMAP;
break;
case CURLPROTO_POP3:
case CURLPROTO_POP3S:
family = CURLPROTO_POP3;
break;
case CURLPROTO_SMTP:
case CURLPROTO_SMTPS:
family = CURLPROTO_SMTP;
break;
case CURLPROTO_RTSP:
family = CURLPROTO_RTSP;
break;
case CURLPROTO_RTMP:
case CURLPROTO_RTMPS:
family = CURLPROTO_RTMP;
break;
case CURLPROTO_RTMPT:
case CURLPROTO_RTMPTS:
family = CURLPROTO_RTMPT;
break;
case CURLPROTO_RTMPE:
family = CURLPROTO_RTMPE;
break;
case CURLPROTO_RTMPTE:
family = CURLPROTO_RTMPTE;
break;
case CURLPROTO_GOPHER:
family = CURLPROTO_GOPHER;
break;
case CURLPROTO_SMB:
case CURLPROTO_SMBS:
family = CURLPROTO_SMB;
break;
default:
family = 0;
break;
}
return family;
}
/*
* Wrapper to call functions in Curl_conncache_foreach()
*
* Returns always 0.
*/
static int conn_upkeep(struct connectdata *conn,
void *param)
{
/* Param is unused. */
(void)param;
if(conn->handler->connection_check) {
/* Do a protocol-specific keepalive check on the connection. */
conn->handler->connection_check(conn, CONNCHECK_KEEPALIVE);
}
return 0; /* continue iteration */
}
CURLcode Curl_upkeep(struct conncache *conn_cache,
void *data)
{
/* Loop over every connection and make connection alive. */
Curl_conncache_foreach(data,
conn_cache,
data,
conn_upkeep);
return CURLE_OK;
}
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_375_0 |
crossvul-cpp_data_good_2840_0 | /*
* fs/userfaultfd.c
*
* Copyright (C) 2007 Davide Libenzi <davidel@xmailserver.org>
* Copyright (C) 2008-2009 Red Hat, Inc.
* Copyright (C) 2015 Red Hat, Inc.
*
* This work is licensed under the terms of the GNU GPL, version 2. See
* the COPYING file in the top-level directory.
*
* Some part derived from fs/eventfd.c (anon inode setup) and
* mm/ksm.c (mm hashing).
*/
#include <linux/list.h>
#include <linux/hashtable.h>
#include <linux/sched/signal.h>
#include <linux/sched/mm.h>
#include <linux/mm.h>
#include <linux/poll.h>
#include <linux/slab.h>
#include <linux/seq_file.h>
#include <linux/file.h>
#include <linux/bug.h>
#include <linux/anon_inodes.h>
#include <linux/syscalls.h>
#include <linux/userfaultfd_k.h>
#include <linux/mempolicy.h>
#include <linux/ioctl.h>
#include <linux/security.h>
#include <linux/hugetlb.h>
static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
enum userfaultfd_state {
UFFD_STATE_WAIT_API,
UFFD_STATE_RUNNING,
};
/*
* Start with fault_pending_wqh and fault_wqh so they're more likely
* to be in the same cacheline.
*/
struct userfaultfd_ctx {
/* waitqueue head for the pending (i.e. not read) userfaults */
wait_queue_head_t fault_pending_wqh;
/* waitqueue head for the userfaults */
wait_queue_head_t fault_wqh;
/* waitqueue head for the pseudo fd to wakeup poll/read */
wait_queue_head_t fd_wqh;
/* waitqueue head for events */
wait_queue_head_t event_wqh;
/* a refile sequence protected by fault_pending_wqh lock */
struct seqcount refile_seq;
/* pseudo fd refcounting */
atomic_t refcount;
/* userfaultfd syscall flags */
unsigned int flags;
/* features requested from the userspace */
unsigned int features;
/* state machine */
enum userfaultfd_state state;
/* released */
bool released;
/* mm with one ore more vmas attached to this userfaultfd_ctx */
struct mm_struct *mm;
};
struct userfaultfd_fork_ctx {
struct userfaultfd_ctx *orig;
struct userfaultfd_ctx *new;
struct list_head list;
};
struct userfaultfd_unmap_ctx {
struct userfaultfd_ctx *ctx;
unsigned long start;
unsigned long end;
struct list_head list;
};
struct userfaultfd_wait_queue {
struct uffd_msg msg;
wait_queue_entry_t wq;
struct userfaultfd_ctx *ctx;
bool waken;
};
struct userfaultfd_wake_range {
unsigned long start;
unsigned long len;
};
static int userfaultfd_wake_function(wait_queue_entry_t *wq, unsigned mode,
int wake_flags, void *key)
{
struct userfaultfd_wake_range *range = key;
int ret;
struct userfaultfd_wait_queue *uwq;
unsigned long start, len;
uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
ret = 0;
/* len == 0 means wake all */
start = range->start;
len = range->len;
if (len && (start > uwq->msg.arg.pagefault.address ||
start + len <= uwq->msg.arg.pagefault.address))
goto out;
WRITE_ONCE(uwq->waken, true);
/*
* The Program-Order guarantees provided by the scheduler
* ensure uwq->waken is visible before the task is woken.
*/
ret = wake_up_state(wq->private, mode);
if (ret) {
/*
* Wake only once, autoremove behavior.
*
* After the effect of list_del_init is visible to the other
* CPUs, the waitqueue may disappear from under us, see the
* !list_empty_careful() in handle_userfault().
*
* try_to_wake_up() has an implicit smp_mb(), and the
* wq->private is read before calling the extern function
* "wake_up_state" (which in turns calls try_to_wake_up).
*/
list_del_init(&wq->entry);
}
out:
return ret;
}
/**
* userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
* context.
* @ctx: [in] Pointer to the userfaultfd context.
*/
static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
{
if (!atomic_inc_not_zero(&ctx->refcount))
BUG();
}
/**
* userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
* context.
* @ctx: [in] Pointer to userfaultfd context.
*
* The userfaultfd context reference must have been previously acquired either
* with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
*/
static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
{
if (atomic_dec_and_test(&ctx->refcount)) {
VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));
VM_BUG_ON(waitqueue_active(&ctx->event_wqh));
VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
mmdrop(ctx->mm);
kmem_cache_free(userfaultfd_ctx_cachep, ctx);
}
}
static inline void msg_init(struct uffd_msg *msg)
{
BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
/*
* Must use memset to zero out the paddings or kernel data is
* leaked to userland.
*/
memset(msg, 0, sizeof(struct uffd_msg));
}
static inline struct uffd_msg userfault_msg(unsigned long address,
unsigned int flags,
unsigned long reason,
unsigned int features)
{
struct uffd_msg msg;
msg_init(&msg);
msg.event = UFFD_EVENT_PAGEFAULT;
msg.arg.pagefault.address = address;
if (flags & FAULT_FLAG_WRITE)
/*
* If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
* uffdio_api.features and UFFD_PAGEFAULT_FLAG_WRITE
* was not set in a UFFD_EVENT_PAGEFAULT, it means it
* was a read fault, otherwise if set it means it's
* a write fault.
*/
msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
if (reason & VM_UFFD_WP)
/*
* If UFFD_FEATURE_PAGEFAULT_FLAG_WP was set in the
* uffdio_api.features and UFFD_PAGEFAULT_FLAG_WP was
* not set in a UFFD_EVENT_PAGEFAULT, it means it was
* a missing fault, otherwise if set it means it's a
* write protect fault.
*/
msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
if (features & UFFD_FEATURE_THREAD_ID)
msg.arg.pagefault.feat.ptid = task_pid_vnr(current);
return msg;
}
#ifdef CONFIG_HUGETLB_PAGE
/*
* Same functionality as userfaultfd_must_wait below with modifications for
* hugepmd ranges.
*/
static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
struct vm_area_struct *vma,
unsigned long address,
unsigned long flags,
unsigned long reason)
{
struct mm_struct *mm = ctx->mm;
pte_t *pte;
bool ret = true;
VM_BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
pte = huge_pte_offset(mm, address, vma_mmu_pagesize(vma));
if (!pte)
goto out;
ret = false;
/*
* Lockless access: we're in a wait_event so it's ok if it
* changes under us.
*/
if (huge_pte_none(*pte))
ret = true;
if (!huge_pte_write(*pte) && (reason & VM_UFFD_WP))
ret = true;
out:
return ret;
}
#else
static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
struct vm_area_struct *vma,
unsigned long address,
unsigned long flags,
unsigned long reason)
{
return false; /* should never get here */
}
#endif /* CONFIG_HUGETLB_PAGE */
/*
* Verify the pagetables are still not ok after having reigstered into
* the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
* userfault that has already been resolved, if userfaultfd_read and
* UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
* threads.
*/
static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
unsigned long address,
unsigned long flags,
unsigned long reason)
{
struct mm_struct *mm = ctx->mm;
pgd_t *pgd;
p4d_t *p4d;
pud_t *pud;
pmd_t *pmd, _pmd;
pte_t *pte;
bool ret = true;
VM_BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
pgd = pgd_offset(mm, address);
if (!pgd_present(*pgd))
goto out;
p4d = p4d_offset(pgd, address);
if (!p4d_present(*p4d))
goto out;
pud = pud_offset(p4d, address);
if (!pud_present(*pud))
goto out;
pmd = pmd_offset(pud, address);
/*
* READ_ONCE must function as a barrier with narrower scope
* and it must be equivalent to:
* _pmd = *pmd; barrier();
*
* This is to deal with the instability (as in
* pmd_trans_unstable) of the pmd.
*/
_pmd = READ_ONCE(*pmd);
if (!pmd_present(_pmd))
goto out;
ret = false;
if (pmd_trans_huge(_pmd))
goto out;
/*
* the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
* and use the standard pte_offset_map() instead of parsing _pmd.
*/
pte = pte_offset_map(pmd, address);
/*
* Lockless access: we're in a wait_event so it's ok if it
* changes under us.
*/
if (pte_none(*pte))
ret = true;
pte_unmap(pte);
out:
return ret;
}
/*
* The locking rules involved in returning VM_FAULT_RETRY depending on
* FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
* FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
* recommendation in __lock_page_or_retry is not an understatement.
*
* If FAULT_FLAG_ALLOW_RETRY is set, the mmap_sem must be released
* before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
* not set.
*
* If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
* set, VM_FAULT_RETRY can still be returned if and only if there are
* fatal_signal_pending()s, and the mmap_sem must be released before
* returning it.
*/
int handle_userfault(struct vm_fault *vmf, unsigned long reason)
{
struct mm_struct *mm = vmf->vma->vm_mm;
struct userfaultfd_ctx *ctx;
struct userfaultfd_wait_queue uwq;
int ret;
bool must_wait, return_to_userland;
long blocking_state;
ret = VM_FAULT_SIGBUS;
/*
* We don't do userfault handling for the final child pid update.
*
* We also don't do userfault handling during
* coredumping. hugetlbfs has the special
* follow_hugetlb_page() to skip missing pages in the
* FOLL_DUMP case, anon memory also checks for FOLL_DUMP with
* the no_page_table() helper in follow_page_mask(), but the
* shmem_vm_ops->fault method is invoked even during
* coredumping without mmap_sem and it ends up here.
*/
if (current->flags & (PF_EXITING|PF_DUMPCORE))
goto out;
/*
* Coredumping runs without mmap_sem so we can only check that
* the mmap_sem is held, if PF_DUMPCORE was not set.
*/
WARN_ON_ONCE(!rwsem_is_locked(&mm->mmap_sem));
ctx = vmf->vma->vm_userfaultfd_ctx.ctx;
if (!ctx)
goto out;
BUG_ON(ctx->mm != mm);
VM_BUG_ON(reason & ~(VM_UFFD_MISSING|VM_UFFD_WP));
VM_BUG_ON(!(reason & VM_UFFD_MISSING) ^ !!(reason & VM_UFFD_WP));
if (ctx->features & UFFD_FEATURE_SIGBUS)
goto out;
/*
* If it's already released don't get it. This avoids to loop
* in __get_user_pages if userfaultfd_release waits on the
* caller of handle_userfault to release the mmap_sem.
*/
if (unlikely(ACCESS_ONCE(ctx->released))) {
/*
* Don't return VM_FAULT_SIGBUS in this case, so a non
* cooperative manager can close the uffd after the
* last UFFDIO_COPY, without risking to trigger an
* involuntary SIGBUS if the process was starting the
* userfaultfd while the userfaultfd was still armed
* (but after the last UFFDIO_COPY). If the uffd
* wasn't already closed when the userfault reached
* this point, that would normally be solved by
* userfaultfd_must_wait returning 'false'.
*
* If we were to return VM_FAULT_SIGBUS here, the non
* cooperative manager would be instead forced to
* always call UFFDIO_UNREGISTER before it can safely
* close the uffd.
*/
ret = VM_FAULT_NOPAGE;
goto out;
}
/*
* Check that we can return VM_FAULT_RETRY.
*
* NOTE: it should become possible to return VM_FAULT_RETRY
* even if FAULT_FLAG_TRIED is set without leading to gup()
* -EBUSY failures, if the userfaultfd is to be extended for
* VM_UFFD_WP tracking and we intend to arm the userfault
* without first stopping userland access to the memory. For
* VM_UFFD_MISSING userfaults this is enough for now.
*/
if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
/*
* Validate the invariant that nowait must allow retry
* to be sure not to return SIGBUS erroneously on
* nowait invocations.
*/
BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
#ifdef CONFIG_DEBUG_VM
if (printk_ratelimit()) {
printk(KERN_WARNING
"FAULT_FLAG_ALLOW_RETRY missing %x\n",
vmf->flags);
dump_stack();
}
#endif
goto out;
}
/*
* Handle nowait, not much to do other than tell it to retry
* and wait.
*/
ret = VM_FAULT_RETRY;
if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
goto out;
/* take the reference before dropping the mmap_sem */
userfaultfd_ctx_get(ctx);
init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
uwq.wq.private = current;
uwq.msg = userfault_msg(vmf->address, vmf->flags, reason,
ctx->features);
uwq.ctx = ctx;
uwq.waken = false;
return_to_userland =
(vmf->flags & (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE)) ==
(FAULT_FLAG_USER|FAULT_FLAG_KILLABLE);
blocking_state = return_to_userland ? TASK_INTERRUPTIBLE :
TASK_KILLABLE;
spin_lock(&ctx->fault_pending_wqh.lock);
/*
* After the __add_wait_queue the uwq is visible to userland
* through poll/read().
*/
__add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
/*
* The smp_mb() after __set_current_state prevents the reads
* following the spin_unlock to happen before the list_add in
* __add_wait_queue.
*/
set_current_state(blocking_state);
spin_unlock(&ctx->fault_pending_wqh.lock);
if (!is_vm_hugetlb_page(vmf->vma))
must_wait = userfaultfd_must_wait(ctx, vmf->address, vmf->flags,
reason);
else
must_wait = userfaultfd_huge_must_wait(ctx, vmf->vma,
vmf->address,
vmf->flags, reason);
up_read(&mm->mmap_sem);
if (likely(must_wait && !ACCESS_ONCE(ctx->released) &&
(return_to_userland ? !signal_pending(current) :
!fatal_signal_pending(current)))) {
wake_up_poll(&ctx->fd_wqh, POLLIN);
schedule();
ret |= VM_FAULT_MAJOR;
/*
* False wakeups can orginate even from rwsem before
* up_read() however userfaults will wait either for a
* targeted wakeup on the specific uwq waitqueue from
* wake_userfault() or for signals or for uffd
* release.
*/
while (!READ_ONCE(uwq.waken)) {
/*
* This needs the full smp_store_mb()
* guarantee as the state write must be
* visible to other CPUs before reading
* uwq.waken from other CPUs.
*/
set_current_state(blocking_state);
if (READ_ONCE(uwq.waken) ||
READ_ONCE(ctx->released) ||
(return_to_userland ? signal_pending(current) :
fatal_signal_pending(current)))
break;
schedule();
}
}
__set_current_state(TASK_RUNNING);
if (return_to_userland) {
if (signal_pending(current) &&
!fatal_signal_pending(current)) {
/*
* If we got a SIGSTOP or SIGCONT and this is
* a normal userland page fault, just let
* userland return so the signal will be
* handled and gdb debugging works. The page
* fault code immediately after we return from
* this function is going to release the
* mmap_sem and it's not depending on it
* (unlike gup would if we were not to return
* VM_FAULT_RETRY).
*
* If a fatal signal is pending we still take
* the streamlined VM_FAULT_RETRY failure path
* and there's no need to retake the mmap_sem
* in such case.
*/
down_read(&mm->mmap_sem);
ret = VM_FAULT_NOPAGE;
}
}
/*
* Here we race with the list_del; list_add in
* userfaultfd_ctx_read(), however because we don't ever run
* list_del_init() to refile across the two lists, the prev
* and next pointers will never point to self. list_add also
* would never let any of the two pointers to point to
* self. So list_empty_careful won't risk to see both pointers
* pointing to self at any time during the list refile. The
* only case where list_del_init() is called is the full
* removal in the wake function and there we don't re-list_add
* and it's fine not to block on the spinlock. The uwq on this
* kernel stack can be released after the list_del_init.
*/
if (!list_empty_careful(&uwq.wq.entry)) {
spin_lock(&ctx->fault_pending_wqh.lock);
/*
* No need of list_del_init(), the uwq on the stack
* will be freed shortly anyway.
*/
list_del(&uwq.wq.entry);
spin_unlock(&ctx->fault_pending_wqh.lock);
}
/*
* ctx may go away after this if the userfault pseudo fd is
* already released.
*/
userfaultfd_ctx_put(ctx);
out:
return ret;
}
static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
struct userfaultfd_wait_queue *ewq)
{
if (WARN_ON_ONCE(current->flags & PF_EXITING))
goto out;
ewq->ctx = ctx;
init_waitqueue_entry(&ewq->wq, current);
spin_lock(&ctx->event_wqh.lock);
/*
* After the __add_wait_queue the uwq is visible to userland
* through poll/read().
*/
__add_wait_queue(&ctx->event_wqh, &ewq->wq);
for (;;) {
set_current_state(TASK_KILLABLE);
if (ewq->msg.event == 0)
break;
if (ACCESS_ONCE(ctx->released) ||
fatal_signal_pending(current)) {
/*
* &ewq->wq may be queued in fork_event, but
* __remove_wait_queue ignores the head
* parameter. It would be a problem if it
* didn't.
*/
__remove_wait_queue(&ctx->event_wqh, &ewq->wq);
if (ewq->msg.event == UFFD_EVENT_FORK) {
struct userfaultfd_ctx *new;
new = (struct userfaultfd_ctx *)
(unsigned long)
ewq->msg.arg.reserved.reserved1;
userfaultfd_ctx_put(new);
}
break;
}
spin_unlock(&ctx->event_wqh.lock);
wake_up_poll(&ctx->fd_wqh, POLLIN);
schedule();
spin_lock(&ctx->event_wqh.lock);
}
__set_current_state(TASK_RUNNING);
spin_unlock(&ctx->event_wqh.lock);
/*
* ctx may go away after this if the userfault pseudo fd is
* already released.
*/
out:
userfaultfd_ctx_put(ctx);
}
static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
struct userfaultfd_wait_queue *ewq)
{
ewq->msg.event = 0;
wake_up_locked(&ctx->event_wqh);
__remove_wait_queue(&ctx->event_wqh, &ewq->wq);
}
int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
{
struct userfaultfd_ctx *ctx = NULL, *octx;
struct userfaultfd_fork_ctx *fctx;
octx = vma->vm_userfaultfd_ctx.ctx;
if (!octx || !(octx->features & UFFD_FEATURE_EVENT_FORK)) {
vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
vma->vm_flags &= ~(VM_UFFD_WP | VM_UFFD_MISSING);
return 0;
}
list_for_each_entry(fctx, fcs, list)
if (fctx->orig == octx) {
ctx = fctx->new;
break;
}
if (!ctx) {
fctx = kmalloc(sizeof(*fctx), GFP_KERNEL);
if (!fctx)
return -ENOMEM;
ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
if (!ctx) {
kfree(fctx);
return -ENOMEM;
}
atomic_set(&ctx->refcount, 1);
ctx->flags = octx->flags;
ctx->state = UFFD_STATE_RUNNING;
ctx->features = octx->features;
ctx->released = false;
ctx->mm = vma->vm_mm;
atomic_inc(&ctx->mm->mm_count);
userfaultfd_ctx_get(octx);
fctx->orig = octx;
fctx->new = ctx;
list_add_tail(&fctx->list, fcs);
}
vma->vm_userfaultfd_ctx.ctx = ctx;
return 0;
}
static void dup_fctx(struct userfaultfd_fork_ctx *fctx)
{
struct userfaultfd_ctx *ctx = fctx->orig;
struct userfaultfd_wait_queue ewq;
msg_init(&ewq.msg);
ewq.msg.event = UFFD_EVENT_FORK;
ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
userfaultfd_event_wait_completion(ctx, &ewq);
}
void dup_userfaultfd_complete(struct list_head *fcs)
{
struct userfaultfd_fork_ctx *fctx, *n;
list_for_each_entry_safe(fctx, n, fcs, list) {
dup_fctx(fctx);
list_del(&fctx->list);
kfree(fctx);
}
}
void mremap_userfaultfd_prep(struct vm_area_struct *vma,
struct vm_userfaultfd_ctx *vm_ctx)
{
struct userfaultfd_ctx *ctx;
ctx = vma->vm_userfaultfd_ctx.ctx;
if (ctx && (ctx->features & UFFD_FEATURE_EVENT_REMAP)) {
vm_ctx->ctx = ctx;
userfaultfd_ctx_get(ctx);
}
}
void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
unsigned long from, unsigned long to,
unsigned long len)
{
struct userfaultfd_ctx *ctx = vm_ctx->ctx;
struct userfaultfd_wait_queue ewq;
if (!ctx)
return;
if (to & ~PAGE_MASK) {
userfaultfd_ctx_put(ctx);
return;
}
msg_init(&ewq.msg);
ewq.msg.event = UFFD_EVENT_REMAP;
ewq.msg.arg.remap.from = from;
ewq.msg.arg.remap.to = to;
ewq.msg.arg.remap.len = len;
userfaultfd_event_wait_completion(ctx, &ewq);
}
bool userfaultfd_remove(struct vm_area_struct *vma,
unsigned long start, unsigned long end)
{
struct mm_struct *mm = vma->vm_mm;
struct userfaultfd_ctx *ctx;
struct userfaultfd_wait_queue ewq;
ctx = vma->vm_userfaultfd_ctx.ctx;
if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_REMOVE))
return true;
userfaultfd_ctx_get(ctx);
up_read(&mm->mmap_sem);
msg_init(&ewq.msg);
ewq.msg.event = UFFD_EVENT_REMOVE;
ewq.msg.arg.remove.start = start;
ewq.msg.arg.remove.end = end;
userfaultfd_event_wait_completion(ctx, &ewq);
return false;
}
static bool has_unmap_ctx(struct userfaultfd_ctx *ctx, struct list_head *unmaps,
unsigned long start, unsigned long end)
{
struct userfaultfd_unmap_ctx *unmap_ctx;
list_for_each_entry(unmap_ctx, unmaps, list)
if (unmap_ctx->ctx == ctx && unmap_ctx->start == start &&
unmap_ctx->end == end)
return true;
return false;
}
int userfaultfd_unmap_prep(struct vm_area_struct *vma,
unsigned long start, unsigned long end,
struct list_head *unmaps)
{
for ( ; vma && vma->vm_start < end; vma = vma->vm_next) {
struct userfaultfd_unmap_ctx *unmap_ctx;
struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_UNMAP) ||
has_unmap_ctx(ctx, unmaps, start, end))
continue;
unmap_ctx = kzalloc(sizeof(*unmap_ctx), GFP_KERNEL);
if (!unmap_ctx)
return -ENOMEM;
userfaultfd_ctx_get(ctx);
unmap_ctx->ctx = ctx;
unmap_ctx->start = start;
unmap_ctx->end = end;
list_add_tail(&unmap_ctx->list, unmaps);
}
return 0;
}
void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf)
{
struct userfaultfd_unmap_ctx *ctx, *n;
struct userfaultfd_wait_queue ewq;
list_for_each_entry_safe(ctx, n, uf, list) {
msg_init(&ewq.msg);
ewq.msg.event = UFFD_EVENT_UNMAP;
ewq.msg.arg.remove.start = ctx->start;
ewq.msg.arg.remove.end = ctx->end;
userfaultfd_event_wait_completion(ctx->ctx, &ewq);
list_del(&ctx->list);
kfree(ctx);
}
}
static int userfaultfd_release(struct inode *inode, struct file *file)
{
struct userfaultfd_ctx *ctx = file->private_data;
struct mm_struct *mm = ctx->mm;
struct vm_area_struct *vma, *prev;
/* len == 0 means wake all */
struct userfaultfd_wake_range range = { .len = 0, };
unsigned long new_flags;
ACCESS_ONCE(ctx->released) = true;
if (!mmget_not_zero(mm))
goto wakeup;
/*
* Flush page faults out of all CPUs. NOTE: all page faults
* must be retried without returning VM_FAULT_SIGBUS if
* userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
* changes while handle_userfault released the mmap_sem. So
* it's critical that released is set to true (above), before
* taking the mmap_sem for writing.
*/
down_write(&mm->mmap_sem);
prev = NULL;
for (vma = mm->mmap; vma; vma = vma->vm_next) {
cond_resched();
BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
!!(vma->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
if (vma->vm_userfaultfd_ctx.ctx != ctx) {
prev = vma;
continue;
}
new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
new_flags, vma->anon_vma,
vma->vm_file, vma->vm_pgoff,
vma_policy(vma),
NULL_VM_UFFD_CTX);
if (prev)
vma = prev;
else
prev = vma;
vma->vm_flags = new_flags;
vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
}
up_write(&mm->mmap_sem);
mmput(mm);
wakeup:
/*
* After no new page faults can wait on this fault_*wqh, flush
* the last page faults that may have been already waiting on
* the fault_*wqh.
*/
spin_lock(&ctx->fault_pending_wqh.lock);
__wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
__wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, &range);
spin_unlock(&ctx->fault_pending_wqh.lock);
/* Flush pending events that may still wait on event_wqh */
wake_up_all(&ctx->event_wqh);
wake_up_poll(&ctx->fd_wqh, POLLHUP);
userfaultfd_ctx_put(ctx);
return 0;
}
/* fault_pending_wqh.lock must be hold by the caller */
static inline struct userfaultfd_wait_queue *find_userfault_in(
wait_queue_head_t *wqh)
{
wait_queue_entry_t *wq;
struct userfaultfd_wait_queue *uwq;
VM_BUG_ON(!spin_is_locked(&wqh->lock));
uwq = NULL;
if (!waitqueue_active(wqh))
goto out;
/* walk in reverse to provide FIFO behavior to read userfaults */
wq = list_last_entry(&wqh->head, typeof(*wq), entry);
uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
out:
return uwq;
}
static inline struct userfaultfd_wait_queue *find_userfault(
struct userfaultfd_ctx *ctx)
{
return find_userfault_in(&ctx->fault_pending_wqh);
}
static inline struct userfaultfd_wait_queue *find_userfault_evt(
struct userfaultfd_ctx *ctx)
{
return find_userfault_in(&ctx->event_wqh);
}
static unsigned int userfaultfd_poll(struct file *file, poll_table *wait)
{
struct userfaultfd_ctx *ctx = file->private_data;
unsigned int ret;
poll_wait(file, &ctx->fd_wqh, wait);
switch (ctx->state) {
case UFFD_STATE_WAIT_API:
return POLLERR;
case UFFD_STATE_RUNNING:
/*
* poll() never guarantees that read won't block.
* userfaults can be waken before they're read().
*/
if (unlikely(!(file->f_flags & O_NONBLOCK)))
return POLLERR;
/*
* lockless access to see if there are pending faults
* __pollwait last action is the add_wait_queue but
* the spin_unlock would allow the waitqueue_active to
* pass above the actual list_add inside
* add_wait_queue critical section. So use a full
* memory barrier to serialize the list_add write of
* add_wait_queue() with the waitqueue_active read
* below.
*/
ret = 0;
smp_mb();
if (waitqueue_active(&ctx->fault_pending_wqh))
ret = POLLIN;
else if (waitqueue_active(&ctx->event_wqh))
ret = POLLIN;
return ret;
default:
WARN_ON_ONCE(1);
return POLLERR;
}
}
static const struct file_operations userfaultfd_fops;
static int resolve_userfault_fork(struct userfaultfd_ctx *ctx,
struct userfaultfd_ctx *new,
struct uffd_msg *msg)
{
int fd;
struct file *file;
unsigned int flags = new->flags & UFFD_SHARED_FCNTL_FLAGS;
fd = get_unused_fd_flags(flags);
if (fd < 0)
return fd;
file = anon_inode_getfile("[userfaultfd]", &userfaultfd_fops, new,
O_RDWR | flags);
if (IS_ERR(file)) {
put_unused_fd(fd);
return PTR_ERR(file);
}
fd_install(fd, file);
msg->arg.reserved.reserved1 = 0;
msg->arg.fork.ufd = fd;
return 0;
}
static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
struct uffd_msg *msg)
{
ssize_t ret;
DECLARE_WAITQUEUE(wait, current);
struct userfaultfd_wait_queue *uwq;
/*
* Handling fork event requires sleeping operations, so
* we drop the event_wqh lock, then do these ops, then
* lock it back and wake up the waiter. While the lock is
* dropped the ewq may go away so we keep track of it
* carefully.
*/
LIST_HEAD(fork_event);
struct userfaultfd_ctx *fork_nctx = NULL;
/* always take the fd_wqh lock before the fault_pending_wqh lock */
spin_lock(&ctx->fd_wqh.lock);
__add_wait_queue(&ctx->fd_wqh, &wait);
for (;;) {
set_current_state(TASK_INTERRUPTIBLE);
spin_lock(&ctx->fault_pending_wqh.lock);
uwq = find_userfault(ctx);
if (uwq) {
/*
* Use a seqcount to repeat the lockless check
* in wake_userfault() to avoid missing
* wakeups because during the refile both
* waitqueue could become empty if this is the
* only userfault.
*/
write_seqcount_begin(&ctx->refile_seq);
/*
* The fault_pending_wqh.lock prevents the uwq
* to disappear from under us.
*
* Refile this userfault from
* fault_pending_wqh to fault_wqh, it's not
* pending anymore after we read it.
*
* Use list_del() by hand (as
* userfaultfd_wake_function also uses
* list_del_init() by hand) to be sure nobody
* changes __remove_wait_queue() to use
* list_del_init() in turn breaking the
* !list_empty_careful() check in
* handle_userfault(). The uwq->wq.head list
* must never be empty at any time during the
* refile, or the waitqueue could disappear
* from under us. The "wait_queue_head_t"
* parameter of __remove_wait_queue() is unused
* anyway.
*/
list_del(&uwq->wq.entry);
__add_wait_queue(&ctx->fault_wqh, &uwq->wq);
write_seqcount_end(&ctx->refile_seq);
/* careful to always initialize msg if ret == 0 */
*msg = uwq->msg;
spin_unlock(&ctx->fault_pending_wqh.lock);
ret = 0;
break;
}
spin_unlock(&ctx->fault_pending_wqh.lock);
spin_lock(&ctx->event_wqh.lock);
uwq = find_userfault_evt(ctx);
if (uwq) {
*msg = uwq->msg;
if (uwq->msg.event == UFFD_EVENT_FORK) {
fork_nctx = (struct userfaultfd_ctx *)
(unsigned long)
uwq->msg.arg.reserved.reserved1;
list_move(&uwq->wq.entry, &fork_event);
/*
* fork_nctx can be freed as soon as
* we drop the lock, unless we take a
* reference on it.
*/
userfaultfd_ctx_get(fork_nctx);
spin_unlock(&ctx->event_wqh.lock);
ret = 0;
break;
}
userfaultfd_event_complete(ctx, uwq);
spin_unlock(&ctx->event_wqh.lock);
ret = 0;
break;
}
spin_unlock(&ctx->event_wqh.lock);
if (signal_pending(current)) {
ret = -ERESTARTSYS;
break;
}
if (no_wait) {
ret = -EAGAIN;
break;
}
spin_unlock(&ctx->fd_wqh.lock);
schedule();
spin_lock(&ctx->fd_wqh.lock);
}
__remove_wait_queue(&ctx->fd_wqh, &wait);
__set_current_state(TASK_RUNNING);
spin_unlock(&ctx->fd_wqh.lock);
if (!ret && msg->event == UFFD_EVENT_FORK) {
ret = resolve_userfault_fork(ctx, fork_nctx, msg);
spin_lock(&ctx->event_wqh.lock);
if (!list_empty(&fork_event)) {
/*
* The fork thread didn't abort, so we can
* drop the temporary refcount.
*/
userfaultfd_ctx_put(fork_nctx);
uwq = list_first_entry(&fork_event,
typeof(*uwq),
wq.entry);
/*
* If fork_event list wasn't empty and in turn
* the event wasn't already released by fork
* (the event is allocated on fork kernel
* stack), put the event back to its place in
* the event_wq. fork_event head will be freed
* as soon as we return so the event cannot
* stay queued there no matter the current
* "ret" value.
*/
list_del(&uwq->wq.entry);
__add_wait_queue(&ctx->event_wqh, &uwq->wq);
/*
* Leave the event in the waitqueue and report
* error to userland if we failed to resolve
* the userfault fork.
*/
if (likely(!ret))
userfaultfd_event_complete(ctx, uwq);
} else {
/*
* Here the fork thread aborted and the
* refcount from the fork thread on fork_nctx
* has already been released. We still hold
* the reference we took before releasing the
* lock above. If resolve_userfault_fork
* failed we've to drop it because the
* fork_nctx has to be freed in such case. If
* it succeeded we'll hold it because the new
* uffd references it.
*/
if (ret)
userfaultfd_ctx_put(fork_nctx);
}
spin_unlock(&ctx->event_wqh.lock);
}
return ret;
}
static ssize_t userfaultfd_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct userfaultfd_ctx *ctx = file->private_data;
ssize_t _ret, ret = 0;
struct uffd_msg msg;
int no_wait = file->f_flags & O_NONBLOCK;
if (ctx->state == UFFD_STATE_WAIT_API)
return -EINVAL;
for (;;) {
if (count < sizeof(msg))
return ret ? ret : -EINVAL;
_ret = userfaultfd_ctx_read(ctx, no_wait, &msg);
if (_ret < 0)
return ret ? ret : _ret;
if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
return ret ? ret : -EFAULT;
ret += sizeof(msg);
buf += sizeof(msg);
count -= sizeof(msg);
/*
* Allow to read more than one fault at time but only
* block if waiting for the very first one.
*/
no_wait = O_NONBLOCK;
}
}
static void __wake_userfault(struct userfaultfd_ctx *ctx,
struct userfaultfd_wake_range *range)
{
spin_lock(&ctx->fault_pending_wqh.lock);
/* wake all in the range and autoremove */
if (waitqueue_active(&ctx->fault_pending_wqh))
__wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
range);
if (waitqueue_active(&ctx->fault_wqh))
__wake_up_locked_key(&ctx->fault_wqh, TASK_NORMAL, range);
spin_unlock(&ctx->fault_pending_wqh.lock);
}
static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
struct userfaultfd_wake_range *range)
{
unsigned seq;
bool need_wakeup;
/*
* To be sure waitqueue_active() is not reordered by the CPU
* before the pagetable update, use an explicit SMP memory
* barrier here. PT lock release or up_read(mmap_sem) still
* have release semantics that can allow the
* waitqueue_active() to be reordered before the pte update.
*/
smp_mb();
/*
* Use waitqueue_active because it's very frequent to
* change the address space atomically even if there are no
* userfaults yet. So we take the spinlock only when we're
* sure we've userfaults to wake.
*/
do {
seq = read_seqcount_begin(&ctx->refile_seq);
need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
waitqueue_active(&ctx->fault_wqh);
cond_resched();
} while (read_seqcount_retry(&ctx->refile_seq, seq));
if (need_wakeup)
__wake_userfault(ctx, range);
}
static __always_inline int validate_range(struct mm_struct *mm,
__u64 start, __u64 len)
{
__u64 task_size = mm->task_size;
if (start & ~PAGE_MASK)
return -EINVAL;
if (len & ~PAGE_MASK)
return -EINVAL;
if (!len)
return -EINVAL;
if (start < mmap_min_addr)
return -EINVAL;
if (start >= task_size)
return -EINVAL;
if (len > task_size - start)
return -EINVAL;
return 0;
}
static inline bool vma_can_userfault(struct vm_area_struct *vma)
{
return vma_is_anonymous(vma) || is_vm_hugetlb_page(vma) ||
vma_is_shmem(vma);
}
static int userfaultfd_register(struct userfaultfd_ctx *ctx,
unsigned long arg)
{
struct mm_struct *mm = ctx->mm;
struct vm_area_struct *vma, *prev, *cur;
int ret;
struct uffdio_register uffdio_register;
struct uffdio_register __user *user_uffdio_register;
unsigned long vm_flags, new_flags;
bool found;
bool basic_ioctls;
unsigned long start, end, vma_end;
user_uffdio_register = (struct uffdio_register __user *) arg;
ret = -EFAULT;
if (copy_from_user(&uffdio_register, user_uffdio_register,
sizeof(uffdio_register)-sizeof(__u64)))
goto out;
ret = -EINVAL;
if (!uffdio_register.mode)
goto out;
if (uffdio_register.mode & ~(UFFDIO_REGISTER_MODE_MISSING|
UFFDIO_REGISTER_MODE_WP))
goto out;
vm_flags = 0;
if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
vm_flags |= VM_UFFD_MISSING;
if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
vm_flags |= VM_UFFD_WP;
/*
* FIXME: remove the below error constraint by
* implementing the wprotect tracking mode.
*/
ret = -EINVAL;
goto out;
}
ret = validate_range(mm, uffdio_register.range.start,
uffdio_register.range.len);
if (ret)
goto out;
start = uffdio_register.range.start;
end = start + uffdio_register.range.len;
ret = -ENOMEM;
if (!mmget_not_zero(mm))
goto out;
down_write(&mm->mmap_sem);
vma = find_vma_prev(mm, start, &prev);
if (!vma)
goto out_unlock;
/* check that there's at least one vma in the range */
ret = -EINVAL;
if (vma->vm_start >= end)
goto out_unlock;
/*
* If the first vma contains huge pages, make sure start address
* is aligned to huge page size.
*/
if (is_vm_hugetlb_page(vma)) {
unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
if (start & (vma_hpagesize - 1))
goto out_unlock;
}
/*
* Search for not compatible vmas.
*/
found = false;
basic_ioctls = false;
for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
cond_resched();
BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
!!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
/* check not compatible vmas */
ret = -EINVAL;
if (!vma_can_userfault(cur))
goto out_unlock;
/*
* If this vma contains ending address, and huge pages
* check alignment.
*/
if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
end > cur->vm_start) {
unsigned long vma_hpagesize = vma_kernel_pagesize(cur);
ret = -EINVAL;
if (end & (vma_hpagesize - 1))
goto out_unlock;
}
/*
* Check that this vma isn't already owned by a
* different userfaultfd. We can't allow more than one
* userfaultfd to own a single vma simultaneously or we
* wouldn't know which one to deliver the userfaults to.
*/
ret = -EBUSY;
if (cur->vm_userfaultfd_ctx.ctx &&
cur->vm_userfaultfd_ctx.ctx != ctx)
goto out_unlock;
/*
* Note vmas containing huge pages
*/
if (is_vm_hugetlb_page(cur))
basic_ioctls = true;
found = true;
}
BUG_ON(!found);
if (vma->vm_start < start)
prev = vma;
ret = 0;
do {
cond_resched();
BUG_ON(!vma_can_userfault(vma));
BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
vma->vm_userfaultfd_ctx.ctx != ctx);
/*
* Nothing to do: this vma is already registered into this
* userfaultfd and with the right tracking mode too.
*/
if (vma->vm_userfaultfd_ctx.ctx == ctx &&
(vma->vm_flags & vm_flags) == vm_flags)
goto skip;
if (vma->vm_start > start)
start = vma->vm_start;
vma_end = min(end, vma->vm_end);
new_flags = (vma->vm_flags & ~vm_flags) | vm_flags;
prev = vma_merge(mm, prev, start, vma_end, new_flags,
vma->anon_vma, vma->vm_file, vma->vm_pgoff,
vma_policy(vma),
((struct vm_userfaultfd_ctx){ ctx }));
if (prev) {
vma = prev;
goto next;
}
if (vma->vm_start < start) {
ret = split_vma(mm, vma, start, 1);
if (ret)
break;
}
if (vma->vm_end > end) {
ret = split_vma(mm, vma, end, 0);
if (ret)
break;
}
next:
/*
* In the vma_merge() successful mprotect-like case 8:
* the next vma was merged into the current one and
* the current one has not been updated yet.
*/
vma->vm_flags = new_flags;
vma->vm_userfaultfd_ctx.ctx = ctx;
skip:
prev = vma;
start = vma->vm_end;
vma = vma->vm_next;
} while (vma && vma->vm_start < end);
out_unlock:
up_write(&mm->mmap_sem);
mmput(mm);
if (!ret) {
/*
* Now that we scanned all vmas we can already tell
* userland which ioctls methods are guaranteed to
* succeed on this range.
*/
if (put_user(basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC :
UFFD_API_RANGE_IOCTLS,
&user_uffdio_register->ioctls))
ret = -EFAULT;
}
out:
return ret;
}
static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
unsigned long arg)
{
struct mm_struct *mm = ctx->mm;
struct vm_area_struct *vma, *prev, *cur;
int ret;
struct uffdio_range uffdio_unregister;
unsigned long new_flags;
bool found;
unsigned long start, end, vma_end;
const void __user *buf = (void __user *)arg;
ret = -EFAULT;
if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
goto out;
ret = validate_range(mm, uffdio_unregister.start,
uffdio_unregister.len);
if (ret)
goto out;
start = uffdio_unregister.start;
end = start + uffdio_unregister.len;
ret = -ENOMEM;
if (!mmget_not_zero(mm))
goto out;
down_write(&mm->mmap_sem);
vma = find_vma_prev(mm, start, &prev);
if (!vma)
goto out_unlock;
/* check that there's at least one vma in the range */
ret = -EINVAL;
if (vma->vm_start >= end)
goto out_unlock;
/*
* If the first vma contains huge pages, make sure start address
* is aligned to huge page size.
*/
if (is_vm_hugetlb_page(vma)) {
unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
if (start & (vma_hpagesize - 1))
goto out_unlock;
}
/*
* Search for not compatible vmas.
*/
found = false;
ret = -EINVAL;
for (cur = vma; cur && cur->vm_start < end; cur = cur->vm_next) {
cond_resched();
BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
!!(cur->vm_flags & (VM_UFFD_MISSING | VM_UFFD_WP)));
/*
* Check not compatible vmas, not strictly required
* here as not compatible vmas cannot have an
* userfaultfd_ctx registered on them, but this
* provides for more strict behavior to notice
* unregistration errors.
*/
if (!vma_can_userfault(cur))
goto out_unlock;
found = true;
}
BUG_ON(!found);
if (vma->vm_start < start)
prev = vma;
ret = 0;
do {
cond_resched();
BUG_ON(!vma_can_userfault(vma));
/*
* Nothing to do: this vma is already registered into this
* userfaultfd and with the right tracking mode too.
*/
if (!vma->vm_userfaultfd_ctx.ctx)
goto skip;
if (vma->vm_start > start)
start = vma->vm_start;
vma_end = min(end, vma->vm_end);
if (userfaultfd_missing(vma)) {
/*
* Wake any concurrent pending userfault while
* we unregister, so they will not hang
* permanently and it avoids userland to call
* UFFDIO_WAKE explicitly.
*/
struct userfaultfd_wake_range range;
range.start = start;
range.len = vma_end - start;
wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
}
new_flags = vma->vm_flags & ~(VM_UFFD_MISSING | VM_UFFD_WP);
prev = vma_merge(mm, prev, start, vma_end, new_flags,
vma->anon_vma, vma->vm_file, vma->vm_pgoff,
vma_policy(vma),
NULL_VM_UFFD_CTX);
if (prev) {
vma = prev;
goto next;
}
if (vma->vm_start < start) {
ret = split_vma(mm, vma, start, 1);
if (ret)
break;
}
if (vma->vm_end > end) {
ret = split_vma(mm, vma, end, 0);
if (ret)
break;
}
next:
/*
* In the vma_merge() successful mprotect-like case 8:
* the next vma was merged into the current one and
* the current one has not been updated yet.
*/
vma->vm_flags = new_flags;
vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
skip:
prev = vma;
start = vma->vm_end;
vma = vma->vm_next;
} while (vma && vma->vm_start < end);
out_unlock:
up_write(&mm->mmap_sem);
mmput(mm);
out:
return ret;
}
/*
* userfaultfd_wake may be used in combination with the
* UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
*/
static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
unsigned long arg)
{
int ret;
struct uffdio_range uffdio_wake;
struct userfaultfd_wake_range range;
const void __user *buf = (void __user *)arg;
ret = -EFAULT;
if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
goto out;
ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
if (ret)
goto out;
range.start = uffdio_wake.start;
range.len = uffdio_wake.len;
/*
* len == 0 means wake all and we don't want to wake all here,
* so check it again to be sure.
*/
VM_BUG_ON(!range.len);
wake_userfault(ctx, &range);
ret = 0;
out:
return ret;
}
static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
unsigned long arg)
{
__s64 ret;
struct uffdio_copy uffdio_copy;
struct uffdio_copy __user *user_uffdio_copy;
struct userfaultfd_wake_range range;
user_uffdio_copy = (struct uffdio_copy __user *) arg;
ret = -EFAULT;
if (copy_from_user(&uffdio_copy, user_uffdio_copy,
/* don't copy "copy" last field */
sizeof(uffdio_copy)-sizeof(__s64)))
goto out;
ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
if (ret)
goto out;
/*
* double check for wraparound just in case. copy_from_user()
* will later check uffdio_copy.src + uffdio_copy.len to fit
* in the userland range.
*/
ret = -EINVAL;
if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
goto out;
if (uffdio_copy.mode & ~UFFDIO_COPY_MODE_DONTWAKE)
goto out;
if (mmget_not_zero(ctx->mm)) {
ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
uffdio_copy.len);
mmput(ctx->mm);
} else {
return -ESRCH;
}
if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
return -EFAULT;
if (ret < 0)
goto out;
BUG_ON(!ret);
/* len == 0 would wake all */
range.len = ret;
if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
range.start = uffdio_copy.dst;
wake_userfault(ctx, &range);
}
ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
out:
return ret;
}
static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
unsigned long arg)
{
__s64 ret;
struct uffdio_zeropage uffdio_zeropage;
struct uffdio_zeropage __user *user_uffdio_zeropage;
struct userfaultfd_wake_range range;
user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
ret = -EFAULT;
if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
/* don't copy "zeropage" last field */
sizeof(uffdio_zeropage)-sizeof(__s64)))
goto out;
ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
uffdio_zeropage.range.len);
if (ret)
goto out;
ret = -EINVAL;
if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
goto out;
if (mmget_not_zero(ctx->mm)) {
ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
uffdio_zeropage.range.len);
mmput(ctx->mm);
} else {
return -ESRCH;
}
if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
return -EFAULT;
if (ret < 0)
goto out;
/* len == 0 would wake all */
BUG_ON(!ret);
range.len = ret;
if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
range.start = uffdio_zeropage.range.start;
wake_userfault(ctx, &range);
}
ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
out:
return ret;
}
static inline unsigned int uffd_ctx_features(__u64 user_features)
{
/*
* For the current set of features the bits just coincide
*/
return (unsigned int)user_features;
}
/*
* userland asks for a certain API version and we return which bits
* and ioctl commands are implemented in this kernel for such API
* version or -EINVAL if unknown.
*/
static int userfaultfd_api(struct userfaultfd_ctx *ctx,
unsigned long arg)
{
struct uffdio_api uffdio_api;
void __user *buf = (void __user *)arg;
int ret;
__u64 features;
ret = -EINVAL;
if (ctx->state != UFFD_STATE_WAIT_API)
goto out;
ret = -EFAULT;
if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
goto out;
features = uffdio_api.features;
if (uffdio_api.api != UFFD_API || (features & ~UFFD_API_FEATURES)) {
memset(&uffdio_api, 0, sizeof(uffdio_api));
if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
goto out;
ret = -EINVAL;
goto out;
}
/* report all available features and ioctls to userland */
uffdio_api.features = UFFD_API_FEATURES;
uffdio_api.ioctls = UFFD_API_IOCTLS;
ret = -EFAULT;
if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
goto out;
ctx->state = UFFD_STATE_RUNNING;
/* only enable the requested features for this uffd context */
ctx->features = uffd_ctx_features(features);
ret = 0;
out:
return ret;
}
static long userfaultfd_ioctl(struct file *file, unsigned cmd,
unsigned long arg)
{
int ret = -EINVAL;
struct userfaultfd_ctx *ctx = file->private_data;
if (cmd != UFFDIO_API && ctx->state == UFFD_STATE_WAIT_API)
return -EINVAL;
switch(cmd) {
case UFFDIO_API:
ret = userfaultfd_api(ctx, arg);
break;
case UFFDIO_REGISTER:
ret = userfaultfd_register(ctx, arg);
break;
case UFFDIO_UNREGISTER:
ret = userfaultfd_unregister(ctx, arg);
break;
case UFFDIO_WAKE:
ret = userfaultfd_wake(ctx, arg);
break;
case UFFDIO_COPY:
ret = userfaultfd_copy(ctx, arg);
break;
case UFFDIO_ZEROPAGE:
ret = userfaultfd_zeropage(ctx, arg);
break;
}
return ret;
}
#ifdef CONFIG_PROC_FS
static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
{
struct userfaultfd_ctx *ctx = f->private_data;
wait_queue_entry_t *wq;
struct userfaultfd_wait_queue *uwq;
unsigned long pending = 0, total = 0;
spin_lock(&ctx->fault_pending_wqh.lock);
list_for_each_entry(wq, &ctx->fault_pending_wqh.head, entry) {
uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
pending++;
total++;
}
list_for_each_entry(wq, &ctx->fault_wqh.head, entry) {
uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
total++;
}
spin_unlock(&ctx->fault_pending_wqh.lock);
/*
* If more protocols will be added, there will be all shown
* separated by a space. Like this:
* protocols: aa:... bb:...
*/
seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
pending, total, UFFD_API, ctx->features,
UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
}
#endif
static const struct file_operations userfaultfd_fops = {
#ifdef CONFIG_PROC_FS
.show_fdinfo = userfaultfd_show_fdinfo,
#endif
.release = userfaultfd_release,
.poll = userfaultfd_poll,
.read = userfaultfd_read,
.unlocked_ioctl = userfaultfd_ioctl,
.compat_ioctl = userfaultfd_ioctl,
.llseek = noop_llseek,
};
static void init_once_userfaultfd_ctx(void *mem)
{
struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
init_waitqueue_head(&ctx->fault_pending_wqh);
init_waitqueue_head(&ctx->fault_wqh);
init_waitqueue_head(&ctx->event_wqh);
init_waitqueue_head(&ctx->fd_wqh);
seqcount_init(&ctx->refile_seq);
}
/**
* userfaultfd_file_create - Creates a userfaultfd file pointer.
* @flags: Flags for the userfaultfd file.
*
* This function creates a userfaultfd file pointer, w/out installing
* it into the fd table. This is useful when the userfaultfd file is
* used during the initialization of data structures that require
* extra setup after the userfaultfd creation. So the userfaultfd
* creation is split into the file pointer creation phase, and the
* file descriptor installation phase. In this way races with
* userspace closing the newly installed file descriptor can be
* avoided. Returns a userfaultfd file pointer, or a proper error
* pointer.
*/
static struct file *userfaultfd_file_create(int flags)
{
struct file *file;
struct userfaultfd_ctx *ctx;
BUG_ON(!current->mm);
/* Check the UFFD_* constants for consistency. */
BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
file = ERR_PTR(-EINVAL);
if (flags & ~UFFD_SHARED_FCNTL_FLAGS)
goto out;
file = ERR_PTR(-ENOMEM);
ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
if (!ctx)
goto out;
atomic_set(&ctx->refcount, 1);
ctx->flags = flags;
ctx->features = 0;
ctx->state = UFFD_STATE_WAIT_API;
ctx->released = false;
ctx->mm = current->mm;
/* prevent the mm struct to be freed */
mmgrab(ctx->mm);
file = anon_inode_getfile("[userfaultfd]", &userfaultfd_fops, ctx,
O_RDWR | (flags & UFFD_SHARED_FCNTL_FLAGS));
if (IS_ERR(file)) {
mmdrop(ctx->mm);
kmem_cache_free(userfaultfd_ctx_cachep, ctx);
}
out:
return file;
}
SYSCALL_DEFINE1(userfaultfd, int, flags)
{
int fd, error;
struct file *file;
error = get_unused_fd_flags(flags & UFFD_SHARED_FCNTL_FLAGS);
if (error < 0)
return error;
fd = error;
file = userfaultfd_file_create(flags);
if (IS_ERR(file)) {
error = PTR_ERR(file);
goto err_put_unused_fd;
}
fd_install(fd, file);
return fd;
err_put_unused_fd:
put_unused_fd(fd);
return error;
}
static int __init userfaultfd_init(void)
{
userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
sizeof(struct userfaultfd_ctx),
0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC,
init_once_userfaultfd_ctx);
return 0;
}
__initcall(userfaultfd_init);
| ./CrossVul/dataset_final_sorted/CWE-416/c/good_2840_0 |
crossvul-cpp_data_bad_888_0 | /* MDIO Bus interface
*
* Author: Andy Fleming
*
* Copyright (c) 2004 Freescale Semiconductor, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/unistd.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/gpio.h>
#include <linux/gpio/consumer.h>
#include <linux/of_device.h>
#include <linux/of_mdio.h>
#include <linux/of_gpio.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/spinlock.h>
#include <linux/mm.h>
#include <linux/module.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/phy.h>
#include <linux/io.h>
#include <linux/uaccess.h>
#include <asm/irq.h>
#define CREATE_TRACE_POINTS
#include <trace/events/mdio.h>
#include "mdio-boardinfo.h"
static int mdiobus_register_gpiod(struct mdio_device *mdiodev)
{
struct gpio_desc *gpiod = NULL;
/* Deassert the optional reset signal */
if (mdiodev->dev.of_node)
gpiod = fwnode_get_named_gpiod(&mdiodev->dev.of_node->fwnode,
"reset-gpios", 0, GPIOD_OUT_LOW,
"PHY reset");
if (PTR_ERR(gpiod) == -ENOENT ||
PTR_ERR(gpiod) == -ENOSYS)
gpiod = NULL;
else if (IS_ERR(gpiod))
return PTR_ERR(gpiod);
mdiodev->reset = gpiod;
/* Assert the reset signal again */
mdio_device_reset(mdiodev, 1);
return 0;
}
int mdiobus_register_device(struct mdio_device *mdiodev)
{
int err;
if (mdiodev->bus->mdio_map[mdiodev->addr])
return -EBUSY;
if (mdiodev->flags & MDIO_DEVICE_FLAG_PHY) {
err = mdiobus_register_gpiod(mdiodev);
if (err)
return err;
}
mdiodev->bus->mdio_map[mdiodev->addr] = mdiodev;
return 0;
}
EXPORT_SYMBOL(mdiobus_register_device);
int mdiobus_unregister_device(struct mdio_device *mdiodev)
{
if (mdiodev->bus->mdio_map[mdiodev->addr] != mdiodev)
return -EINVAL;
mdiodev->bus->mdio_map[mdiodev->addr] = NULL;
return 0;
}
EXPORT_SYMBOL(mdiobus_unregister_device);
struct phy_device *mdiobus_get_phy(struct mii_bus *bus, int addr)
{
struct mdio_device *mdiodev = bus->mdio_map[addr];
if (!mdiodev)
return NULL;
if (!(mdiodev->flags & MDIO_DEVICE_FLAG_PHY))
return NULL;
return container_of(mdiodev, struct phy_device, mdio);
}
EXPORT_SYMBOL(mdiobus_get_phy);
bool mdiobus_is_registered_device(struct mii_bus *bus, int addr)
{
return bus->mdio_map[addr];
}
EXPORT_SYMBOL(mdiobus_is_registered_device);
/**
* mdiobus_alloc_size - allocate a mii_bus structure
* @size: extra amount of memory to allocate for private storage.
* If non-zero, then bus->priv is points to that memory.
*
* Description: called by a bus driver to allocate an mii_bus
* structure to fill in.
*/
struct mii_bus *mdiobus_alloc_size(size_t size)
{
struct mii_bus *bus;
size_t aligned_size = ALIGN(sizeof(*bus), NETDEV_ALIGN);
size_t alloc_size;
int i;
/* If we alloc extra space, it should be aligned */
if (size)
alloc_size = aligned_size + size;
else
alloc_size = sizeof(*bus);
bus = kzalloc(alloc_size, GFP_KERNEL);
if (!bus)
return NULL;
bus->state = MDIOBUS_ALLOCATED;
if (size)
bus->priv = (void *)bus + aligned_size;
/* Initialise the interrupts to polling */
for (i = 0; i < PHY_MAX_ADDR; i++)
bus->irq[i] = PHY_POLL;
return bus;
}
EXPORT_SYMBOL(mdiobus_alloc_size);
static void _devm_mdiobus_free(struct device *dev, void *res)
{
mdiobus_free(*(struct mii_bus **)res);
}
static int devm_mdiobus_match(struct device *dev, void *res, void *data)
{
struct mii_bus **r = res;
if (WARN_ON(!r || !*r))
return 0;
return *r == data;
}
/**
* devm_mdiobus_alloc_size - Resource-managed mdiobus_alloc_size()
* @dev: Device to allocate mii_bus for
* @sizeof_priv: Space to allocate for private structure.
*
* Managed mdiobus_alloc_size. mii_bus allocated with this function is
* automatically freed on driver detach.
*
* If an mii_bus allocated with this function needs to be freed separately,
* devm_mdiobus_free() must be used.
*
* RETURNS:
* Pointer to allocated mii_bus on success, NULL on failure.
*/
struct mii_bus *devm_mdiobus_alloc_size(struct device *dev, int sizeof_priv)
{
struct mii_bus **ptr, *bus;
ptr = devres_alloc(_devm_mdiobus_free, sizeof(*ptr), GFP_KERNEL);
if (!ptr)
return NULL;
/* use raw alloc_dr for kmalloc caller tracing */
bus = mdiobus_alloc_size(sizeof_priv);
if (bus) {
*ptr = bus;
devres_add(dev, ptr);
} else {
devres_free(ptr);
}
return bus;
}
EXPORT_SYMBOL_GPL(devm_mdiobus_alloc_size);
/**
* devm_mdiobus_free - Resource-managed mdiobus_free()
* @dev: Device this mii_bus belongs to
* @bus: the mii_bus associated with the device
*
* Free mii_bus allocated with devm_mdiobus_alloc_size().
*/
void devm_mdiobus_free(struct device *dev, struct mii_bus *bus)
{
int rc;
rc = devres_release(dev, _devm_mdiobus_free,
devm_mdiobus_match, bus);
WARN_ON(rc);
}
EXPORT_SYMBOL_GPL(devm_mdiobus_free);
/**
* mdiobus_release - mii_bus device release callback
* @d: the target struct device that contains the mii_bus
*
* Description: called when the last reference to an mii_bus is
* dropped, to free the underlying memory.
*/
static void mdiobus_release(struct device *d)
{
struct mii_bus *bus = to_mii_bus(d);
BUG_ON(bus->state != MDIOBUS_RELEASED &&
/* for compatibility with error handling in drivers */
bus->state != MDIOBUS_ALLOCATED);
kfree(bus);
}
static struct class mdio_bus_class = {
.name = "mdio_bus",
.dev_release = mdiobus_release,
};
#if IS_ENABLED(CONFIG_OF_MDIO)
/* Helper function for of_mdio_find_bus */
static int of_mdio_bus_match(struct device *dev, const void *mdio_bus_np)
{
return dev->of_node == mdio_bus_np;
}
/**
* of_mdio_find_bus - Given an mii_bus node, find the mii_bus.
* @mdio_bus_np: Pointer to the mii_bus.
*
* Returns a reference to the mii_bus, or NULL if none found. The
* embedded struct device will have its reference count incremented,
* and this must be put once the bus is finished with.
*
* Because the association of a device_node and mii_bus is made via
* of_mdiobus_register(), the mii_bus cannot be found before it is
* registered with of_mdiobus_register().
*
*/
struct mii_bus *of_mdio_find_bus(struct device_node *mdio_bus_np)
{
struct device *d;
if (!mdio_bus_np)
return NULL;
d = class_find_device(&mdio_bus_class, NULL, mdio_bus_np,
of_mdio_bus_match);
return d ? to_mii_bus(d) : NULL;
}
EXPORT_SYMBOL(of_mdio_find_bus);
/* Walk the list of subnodes of a mdio bus and look for a node that
* matches the mdio device's address with its 'reg' property. If
* found, set the of_node pointer for the mdio device. This allows
* auto-probed phy devices to be supplied with information passed in
* via DT.
*/
static void of_mdiobus_link_mdiodev(struct mii_bus *bus,
struct mdio_device *mdiodev)
{
struct device *dev = &mdiodev->dev;
struct device_node *child;
if (dev->of_node || !bus->dev.of_node)
return;
for_each_available_child_of_node(bus->dev.of_node, child) {
int addr;
addr = of_mdio_parse_addr(dev, child);
if (addr < 0)
continue;
if (addr == mdiodev->addr) {
dev->of_node = child;
dev->fwnode = of_fwnode_handle(child);
return;
}
}
}
#else /* !IS_ENABLED(CONFIG_OF_MDIO) */
static inline void of_mdiobus_link_mdiodev(struct mii_bus *mdio,
struct mdio_device *mdiodev)
{
}
#endif
/**
* mdiobus_create_device_from_board_info - create a full MDIO device given
* a mdio_board_info structure
* @bus: MDIO bus to create the devices on
* @bi: mdio_board_info structure describing the devices
*
* Returns 0 on success or < 0 on error.
*/
static int mdiobus_create_device(struct mii_bus *bus,
struct mdio_board_info *bi)
{
struct mdio_device *mdiodev;
int ret = 0;
mdiodev = mdio_device_create(bus, bi->mdio_addr);
if (IS_ERR(mdiodev))
return -ENODEV;
strncpy(mdiodev->modalias, bi->modalias,
sizeof(mdiodev->modalias));
mdiodev->bus_match = mdio_device_bus_match;
mdiodev->dev.platform_data = (void *)bi->platform_data;
ret = mdio_device_register(mdiodev);
if (ret)
mdio_device_free(mdiodev);
return ret;
}
/**
* __mdiobus_register - bring up all the PHYs on a given bus and attach them to bus
* @bus: target mii_bus
* @owner: module containing bus accessor functions
*
* Description: Called by a bus driver to bring up all the PHYs
* on a given bus, and attach them to the bus. Drivers should use
* mdiobus_register() rather than __mdiobus_register() unless they
* need to pass a specific owner module. MDIO devices which are not
* PHYs will not be brought up by this function. They are expected to
* to be explicitly listed in DT and instantiated by of_mdiobus_register().
*
* Returns 0 on success or < 0 on error.
*/
int __mdiobus_register(struct mii_bus *bus, struct module *owner)
{
struct mdio_device *mdiodev;
int i, err;
struct gpio_desc *gpiod;
if (NULL == bus || NULL == bus->name ||
NULL == bus->read || NULL == bus->write)
return -EINVAL;
BUG_ON(bus->state != MDIOBUS_ALLOCATED &&
bus->state != MDIOBUS_UNREGISTERED);
bus->owner = owner;
bus->dev.parent = bus->parent;
bus->dev.class = &mdio_bus_class;
bus->dev.groups = NULL;
dev_set_name(&bus->dev, "%s", bus->id);
err = device_register(&bus->dev);
if (err) {
pr_err("mii_bus %s failed to register\n", bus->id);
put_device(&bus->dev);
return -EINVAL;
}
mutex_init(&bus->mdio_lock);
/* de-assert bus level PHY GPIO reset */
gpiod = devm_gpiod_get_optional(&bus->dev, "reset", GPIOD_OUT_LOW);
if (IS_ERR(gpiod)) {
dev_err(&bus->dev, "mii_bus %s couldn't get reset GPIO\n",
bus->id);
device_del(&bus->dev);
return PTR_ERR(gpiod);
} else if (gpiod) {
bus->reset_gpiod = gpiod;
gpiod_set_value_cansleep(gpiod, 1);
udelay(bus->reset_delay_us);
gpiod_set_value_cansleep(gpiod, 0);
}
if (bus->reset)
bus->reset(bus);
for (i = 0; i < PHY_MAX_ADDR; i++) {
if ((bus->phy_mask & (1 << i)) == 0) {
struct phy_device *phydev;
phydev = mdiobus_scan(bus, i);
if (IS_ERR(phydev) && (PTR_ERR(phydev) != -ENODEV)) {
err = PTR_ERR(phydev);
goto error;
}
}
}
mdiobus_setup_mdiodev_from_board_info(bus, mdiobus_create_device);
bus->state = MDIOBUS_REGISTERED;
pr_info("%s: probed\n", bus->name);
return 0;
error:
while (--i >= 0) {
mdiodev = bus->mdio_map[i];
if (!mdiodev)
continue;
mdiodev->device_remove(mdiodev);
mdiodev->device_free(mdiodev);
}
/* Put PHYs in RESET to save power */
if (bus->reset_gpiod)
gpiod_set_value_cansleep(bus->reset_gpiod, 1);
device_del(&bus->dev);
return err;
}
EXPORT_SYMBOL(__mdiobus_register);
void mdiobus_unregister(struct mii_bus *bus)
{
struct mdio_device *mdiodev;
int i;
BUG_ON(bus->state != MDIOBUS_REGISTERED);
bus->state = MDIOBUS_UNREGISTERED;
for (i = 0; i < PHY_MAX_ADDR; i++) {
mdiodev = bus->mdio_map[i];
if (!mdiodev)
continue;
if (mdiodev->reset)
gpiod_put(mdiodev->reset);
mdiodev->device_remove(mdiodev);
mdiodev->device_free(mdiodev);
}
/* Put PHYs in RESET to save power */
if (bus->reset_gpiod)
gpiod_set_value_cansleep(bus->reset_gpiod, 1);
device_del(&bus->dev);
}
EXPORT_SYMBOL(mdiobus_unregister);
/**
* mdiobus_free - free a struct mii_bus
* @bus: mii_bus to free
*
* This function releases the reference to the underlying device
* object in the mii_bus. If this is the last reference, the mii_bus
* will be freed.
*/
void mdiobus_free(struct mii_bus *bus)
{
/* For compatibility with error handling in drivers. */
if (bus->state == MDIOBUS_ALLOCATED) {
kfree(bus);
return;
}
BUG_ON(bus->state != MDIOBUS_UNREGISTERED);
bus->state = MDIOBUS_RELEASED;
put_device(&bus->dev);
}
EXPORT_SYMBOL(mdiobus_free);
/**
* mdiobus_scan - scan a bus for MDIO devices.
* @bus: mii_bus to scan
* @addr: address on bus to scan
*
* This function scans the MDIO bus, looking for devices which can be
* identified using a vendor/product ID in registers 2 and 3. Not all
* MDIO devices have such registers, but PHY devices typically
* do. Hence this function assumes anything found is a PHY, or can be
* treated as a PHY. Other MDIO devices, such as switches, will
* probably not be found during the scan.
*/
struct phy_device *mdiobus_scan(struct mii_bus *bus, int addr)
{
struct phy_device *phydev;
int err;
phydev = get_phy_device(bus, addr, false);
if (IS_ERR(phydev))
return phydev;
/*
* For DT, see if the auto-probed phy has a correspoding child
* in the bus node, and set the of_node pointer in this case.
*/
of_mdiobus_link_mdiodev(bus, &phydev->mdio);
err = phy_device_register(phydev);
if (err) {
phy_device_free(phydev);
return ERR_PTR(-ENODEV);
}
return phydev;
}
EXPORT_SYMBOL(mdiobus_scan);
/**
* __mdiobus_read - Unlocked version of the mdiobus_read function
* @bus: the mii_bus struct
* @addr: the phy address
* @regnum: register number to read
*
* Read a MDIO bus register. Caller must hold the mdio bus lock.
*
* NOTE: MUST NOT be called from interrupt context.
*/
int __mdiobus_read(struct mii_bus *bus, int addr, u32 regnum)
{
int retval;
WARN_ON_ONCE(!mutex_is_locked(&bus->mdio_lock));
retval = bus->read(bus, addr, regnum);
trace_mdio_access(bus, 1, addr, regnum, retval, retval);
return retval;
}
EXPORT_SYMBOL(__mdiobus_read);
/**
* __mdiobus_write - Unlocked version of the mdiobus_write function
* @bus: the mii_bus struct
* @addr: the phy address
* @regnum: register number to write
* @val: value to write to @regnum
*
* Write a MDIO bus register. Caller must hold the mdio bus lock.
*
* NOTE: MUST NOT be called from interrupt context.
*/
int __mdiobus_write(struct mii_bus *bus, int addr, u32 regnum, u16 val)
{
int err;
WARN_ON_ONCE(!mutex_is_locked(&bus->mdio_lock));
err = bus->write(bus, addr, regnum, val);
trace_mdio_access(bus, 0, addr, regnum, val, err);
return err;
}
EXPORT_SYMBOL(__mdiobus_write);
/**
* mdiobus_read_nested - Nested version of the mdiobus_read function
* @bus: the mii_bus struct
* @addr: the phy address
* @regnum: register number to read
*
* In case of nested MDIO bus access avoid lockdep false positives by
* using mutex_lock_nested().
*
* NOTE: MUST NOT be called from interrupt context,
* because the bus read/write functions may wait for an interrupt
* to conclude the operation.
*/
int mdiobus_read_nested(struct mii_bus *bus, int addr, u32 regnum)
{
int retval;
BUG_ON(in_interrupt());
mutex_lock_nested(&bus->mdio_lock, MDIO_MUTEX_NESTED);
retval = __mdiobus_read(bus, addr, regnum);
mutex_unlock(&bus->mdio_lock);
return retval;
}
EXPORT_SYMBOL(mdiobus_read_nested);
/**
* mdiobus_read - Convenience function for reading a given MII mgmt register
* @bus: the mii_bus struct
* @addr: the phy address
* @regnum: register number to read
*
* NOTE: MUST NOT be called from interrupt context,
* because the bus read/write functions may wait for an interrupt
* to conclude the operation.
*/
int mdiobus_read(struct mii_bus *bus, int addr, u32 regnum)
{
int retval;
BUG_ON(in_interrupt());
mutex_lock(&bus->mdio_lock);
retval = __mdiobus_read(bus, addr, regnum);
mutex_unlock(&bus->mdio_lock);
return retval;
}
EXPORT_SYMBOL(mdiobus_read);
/**
* mdiobus_write_nested - Nested version of the mdiobus_write function
* @bus: the mii_bus struct
* @addr: the phy address
* @regnum: register number to write
* @val: value to write to @regnum
*
* In case of nested MDIO bus access avoid lockdep false positives by
* using mutex_lock_nested().
*
* NOTE: MUST NOT be called from interrupt context,
* because the bus read/write functions may wait for an interrupt
* to conclude the operation.
*/
int mdiobus_write_nested(struct mii_bus *bus, int addr, u32 regnum, u16 val)
{
int err;
BUG_ON(in_interrupt());
mutex_lock_nested(&bus->mdio_lock, MDIO_MUTEX_NESTED);
err = __mdiobus_write(bus, addr, regnum, val);
mutex_unlock(&bus->mdio_lock);
return err;
}
EXPORT_SYMBOL(mdiobus_write_nested);
/**
* mdiobus_write - Convenience function for writing a given MII mgmt register
* @bus: the mii_bus struct
* @addr: the phy address
* @regnum: register number to write
* @val: value to write to @regnum
*
* NOTE: MUST NOT be called from interrupt context,
* because the bus read/write functions may wait for an interrupt
* to conclude the operation.
*/
int mdiobus_write(struct mii_bus *bus, int addr, u32 regnum, u16 val)
{
int err;
BUG_ON(in_interrupt());
mutex_lock(&bus->mdio_lock);
err = __mdiobus_write(bus, addr, regnum, val);
mutex_unlock(&bus->mdio_lock);
return err;
}
EXPORT_SYMBOL(mdiobus_write);
/**
* mdio_bus_match - determine if given MDIO driver supports the given
* MDIO device
* @dev: target MDIO device
* @drv: given MDIO driver
*
* Description: Given a MDIO device, and a MDIO driver, return 1 if
* the driver supports the device. Otherwise, return 0. This may
* require calling the devices own match function, since different classes
* of MDIO devices have different match criteria.
*/
static int mdio_bus_match(struct device *dev, struct device_driver *drv)
{
struct mdio_device *mdio = to_mdio_device(dev);
if (of_driver_match_device(dev, drv))
return 1;
if (mdio->bus_match)
return mdio->bus_match(dev, drv);
return 0;
}
static int mdio_uevent(struct device *dev, struct kobj_uevent_env *env)
{
int rc;
/* Some devices have extra OF data and an OF-style MODALIAS */
rc = of_device_uevent_modalias(dev, env);
if (rc != -ENODEV)
return rc;
return 0;
}
struct bus_type mdio_bus_type = {
.name = "mdio_bus",
.match = mdio_bus_match,
.uevent = mdio_uevent,
};
EXPORT_SYMBOL(mdio_bus_type);
int __init mdio_bus_init(void)
{
int ret;
ret = class_register(&mdio_bus_class);
if (!ret) {
ret = bus_register(&mdio_bus_type);
if (ret)
class_unregister(&mdio_bus_class);
}
return ret;
}
EXPORT_SYMBOL_GPL(mdio_bus_init);
#if IS_ENABLED(CONFIG_PHYLIB)
void mdio_bus_exit(void)
{
class_unregister(&mdio_bus_class);
bus_unregister(&mdio_bus_type);
}
EXPORT_SYMBOL_GPL(mdio_bus_exit);
#else
module_init(mdio_bus_init);
/* no module_exit, intentional */
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("MDIO bus/device layer");
#endif
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_888_0 |
crossvul-cpp_data_bad_1390_2 | /* libcomps - C alternative to yum.comps library
* Copyright (C) 2013 Jindrich Luza
*
* 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
* 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 Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA
*/
#include "comps_objradix.h"
#include "comps_set.h"
#include <stdio.h>
void comps_objrtree_data_destroy(COMPS_ObjRTreeData * rtd) {
free(rtd->key);
comps_object_destroy(rtd->data);
comps_hslist_destroy(&rtd->subnodes);
free(rtd);
}
inline void comps_objrtree_data_destroy_v(void * rtd) {
comps_objrtree_data_destroy((COMPS_ObjRTreeData*)rtd);
}
inline COMPS_ObjRTreeData * __comps_objrtree_data_create(char *key,
size_t keylen,
COMPS_Object *data){
COMPS_ObjRTreeData * rtd;
if ((rtd = malloc(sizeof(*rtd))) == NULL)
return NULL;
if ((rtd->key = malloc(sizeof(char) * (keylen+1))) == NULL) {
free(rtd);
return NULL;
}
memcpy(rtd->key, key, sizeof(char)*keylen);
rtd->key[keylen] = 0;
rtd->data = data;
if (data != NULL) {
rtd->is_leaf = 1;
}
rtd->subnodes = comps_hslist_create();
comps_hslist_init(rtd->subnodes, NULL, NULL, &comps_objrtree_data_destroy_v);
return rtd;
}
COMPS_ObjRTreeData * comps_objrtree_data_create(char *key, COMPS_Object *data) {
COMPS_ObjRTreeData * rtd;
rtd = __comps_objrtree_data_create(key, strlen(key), data);
return rtd;
}
COMPS_ObjRTreeData * comps_objrtree_data_create_n(char *key, size_t keylen,
COMPS_Object *data) {
COMPS_ObjRTreeData * rtd;
rtd = __comps_objrtree_data_create(key, keylen, data);
return rtd;
}
static void comps_objrtree_create(COMPS_ObjRTree *rtree, COMPS_Object **args) {
(void)args;
rtree->subnodes = comps_hslist_create();
comps_hslist_init(rtree->subnodes, NULL, NULL, &comps_objrtree_data_destroy_v);
if (rtree->subnodes == NULL) {
COMPS_OBJECT_DESTROY(rtree);
return;
}
rtree->len = 0;
}
void comps_objrtree_create_u(COMPS_Object * obj, COMPS_Object **args) {
(void)args;
comps_objrtree_create((COMPS_ObjRTree*)obj, NULL);
}
static void comps_objrtree_destroy(COMPS_ObjRTree * rt) {
comps_hslist_destroy(&(rt->subnodes));
}
void comps_objrtree_destroy_u(COMPS_Object *obj) {
comps_objrtree_destroy((COMPS_ObjRTree*)obj);
}
COMPS_ObjRTree * comps_objrtree_clone(COMPS_ObjRTree *rt) {
COMPS_HSList *to_clone, *tmplist, *new_subnodes;
COMPS_ObjRTree *ret;
COMPS_HSListItem *it, *it2;
COMPS_ObjRTreeData *rtdata;
COMPS_Object *new_data;
if (!rt) return NULL;
to_clone = comps_hslist_create();
comps_hslist_init(to_clone, NULL, NULL, NULL);
ret = COMPS_OBJECT_CREATE(COMPS_ObjRTree, NULL);
ret->len = rt->len;
for (it = rt->subnodes->first; it != NULL; it = it->next) {
rtdata = comps_objrtree_data_create(
((COMPS_ObjRTreeData*)it->data)->key, NULL);
if (((COMPS_ObjRTreeData*)it->data)->data != NULL)
new_data = comps_object_copy(((COMPS_ObjRTreeData*)it->data)->data);
else
new_data = NULL;
comps_hslist_destroy(&rtdata->subnodes);
rtdata->subnodes = ((COMPS_ObjRTreeData*)it->data)->subnodes;
rtdata->data = new_data;
comps_hslist_append(ret->subnodes, rtdata, 0);
comps_hslist_append(to_clone, rtdata, 0);
}
while (to_clone->first) {
it2 = to_clone->first;
tmplist = ((COMPS_ObjRTreeData*)it2->data)->subnodes;
comps_hslist_remove(to_clone, to_clone->first);
new_subnodes = comps_hslist_create();
comps_hslist_init(new_subnodes, NULL, NULL, &comps_objrtree_data_destroy_v);
for (it = tmplist->first; it != NULL; it = it->next) {
rtdata = comps_objrtree_data_create(
((COMPS_ObjRTreeData*)it->data)->key, NULL);
if (((COMPS_ObjRTreeData*)it->data)->data != NULL)
new_data = comps_object_copy(((COMPS_ObjRTreeData*)it->data)->data);
else
new_data = NULL;
comps_hslist_destroy(&rtdata->subnodes);
rtdata->subnodes = ((COMPS_ObjRTreeData*)it->data)->subnodes;
rtdata->data = new_data;
comps_hslist_append(new_subnodes, rtdata, 0);
comps_hslist_append(to_clone, rtdata, 0);
}
((COMPS_ObjRTreeData*)it2->data)->subnodes = new_subnodes;
free(it2);
}
comps_hslist_destroy(&to_clone);
return ret;
}
void comps_objrtree_copy(COMPS_ObjRTree *rt1, COMPS_ObjRTree *rt2){
COMPS_HSList *to_clone, *tmplist, *new_subnodes;
COMPS_HSListItem *it, *it2;
COMPS_ObjRTreeData *rtdata;
COMPS_Object *new_data;
rt1->subnodes = comps_hslist_create();
comps_hslist_init(rt1->subnodes, NULL, NULL, &comps_objrtree_data_destroy_v);
if (rt1->subnodes == NULL) {
COMPS_OBJECT_DESTROY(rt1);
return;
}
rt1->len = 0;
to_clone = comps_hslist_create();
comps_hslist_init(to_clone, NULL, NULL, NULL);
for (it = rt2->subnodes->first; it != NULL; it = it->next) {
rtdata = comps_objrtree_data_create(
((COMPS_ObjRTreeData*)it->data)->key, NULL);
if (((COMPS_ObjRTreeData*)it->data)->data != NULL)
new_data = comps_object_copy(((COMPS_ObjRTreeData*)it->data)->data);
else
new_data = NULL;
comps_hslist_destroy(&rtdata->subnodes);
rtdata->subnodes = ((COMPS_ObjRTreeData*)it->data)->subnodes;
rtdata->data = new_data;
comps_hslist_append(rt1->subnodes, rtdata, 0);
comps_hslist_append(to_clone, rtdata, 0);
}
while (to_clone->first) {
it2 = to_clone->first;
tmplist = ((COMPS_ObjRTreeData*)it2->data)->subnodes;
comps_hslist_remove(to_clone, to_clone->first);
new_subnodes = comps_hslist_create();
comps_hslist_init(new_subnodes, NULL, NULL, &comps_objrtree_data_destroy_v);
for (it = tmplist->first; it != NULL; it = it->next) {
rtdata = comps_objrtree_data_create(
((COMPS_ObjRTreeData*)it->data)->key, NULL);
if (((COMPS_ObjRTreeData*)it->data)->data != NULL)
new_data = comps_object_copy(((COMPS_ObjRTreeData*)it->data)->data);
else
new_data = NULL;
comps_hslist_destroy(&rtdata->subnodes);
rtdata->subnodes = ((COMPS_ObjRTreeData*)it->data)->subnodes;
rtdata->data = new_data;
comps_hslist_append(new_subnodes, rtdata, 0);
comps_hslist_append(to_clone, rtdata, 0);
}
((COMPS_ObjRTreeData*)it2->data)->subnodes = new_subnodes;
free(it2);
}
comps_hslist_destroy(&to_clone);
}
COMPS_COPY_u(objrtree, COMPS_ObjRTree) /*comps_utils.h macro*/
void comps_objrtree_copy_shallow(COMPS_ObjRTree *rt1, COMPS_ObjRTree *rt2){
COMPS_HSList *to_clone, *tmplist, *new_subnodes;
COMPS_HSListItem *it, *it2;
COMPS_ObjRTreeData *rtdata;
COMPS_Object *new_data;
rt1->subnodes = comps_hslist_create();
comps_hslist_init(rt1->subnodes, NULL, NULL, &comps_objrtree_data_destroy_v);
if (rt1->subnodes == NULL) {
COMPS_OBJECT_DESTROY(rt1);
return;
}
rt1->len = 0;
to_clone = comps_hslist_create();
comps_hslist_init(to_clone, NULL, NULL, NULL);
for (it = rt2->subnodes->first; it != NULL; it = it->next) {
rtdata = comps_objrtree_data_create(
((COMPS_ObjRTreeData*)it->data)->key, NULL);
if (((COMPS_ObjRTreeData*)it->data)->data != NULL)
new_data = COMPS_OBJECT_INCREF(((COMPS_ObjRTreeData*)it->data)->data);
else
new_data = NULL;
comps_hslist_destroy(&rtdata->subnodes);
rtdata->subnodes = ((COMPS_ObjRTreeData*)it->data)->subnodes;
rtdata->data = new_data;
comps_hslist_append(rt1->subnodes, rtdata, 0);
comps_hslist_append(to_clone, rtdata, 0);
}
while (to_clone->first) {
it2 = to_clone->first;
tmplist = ((COMPS_ObjRTreeData*)it2->data)->subnodes;
comps_hslist_remove(to_clone, to_clone->first);
new_subnodes = comps_hslist_create();
comps_hslist_init(new_subnodes, NULL, NULL, &comps_objrtree_data_destroy_v);
for (it = tmplist->first; it != NULL; it = it->next) {
rtdata = comps_objrtree_data_create(
((COMPS_ObjRTreeData*)it->data)->key, NULL);
if (((COMPS_ObjRTreeData*)it->data)->data != NULL)
new_data = comps_object_incref(((COMPS_ObjRTreeData*)it->data)->data);
else
new_data = NULL;
comps_hslist_destroy(&rtdata->subnodes);
rtdata->subnodes = ((COMPS_ObjRTreeData*)it->data)->subnodes;
rtdata->data = new_data;
comps_hslist_append(new_subnodes, rtdata, 0);
comps_hslist_append(to_clone, rtdata, 0);
}
((COMPS_ObjRTreeData*)it2->data)->subnodes = new_subnodes;
free(it2);
}
comps_hslist_destroy(&to_clone);
}
void comps_objrtree_values_walk(COMPS_ObjRTree * rt, void* udata,
void (*walk_f)(void*, COMPS_Object*)) {
COMPS_HSList *tmplist, *tmp_subnodes;
COMPS_HSListItem *it;
tmplist = comps_hslist_create();
comps_hslist_init(tmplist, NULL, NULL, NULL);
comps_hslist_append(tmplist, rt->subnodes, 0);
while (tmplist->first != NULL) {
it = tmplist->first;
comps_hslist_remove(tmplist, tmplist->first);
tmp_subnodes = (COMPS_HSList*)it->data;
for (it = tmp_subnodes->first; it != NULL; it=it->next) {
if (((COMPS_ObjRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist,
((COMPS_ObjRTreeData*)it->data)->subnodes, 0);
}
if (((COMPS_ObjRTreeData*)it->data)->data != NULL) {
walk_f(udata, ((COMPS_ObjRTreeData*)it->data)->data);
}
}
}
comps_hslist_destroy(&tmplist);
}
char comps_objrtree_paircmp(void *obj1, void *obj2) {
//printf("comparing %s with %s\n", ((COMPS_ObjRTreePair*)obj1)->key,
// ((COMPS_ObjRTreePair*)obj2)->key);
if (strcmp(((COMPS_ObjRTreePair*)obj1)->key,
((COMPS_ObjRTreePair*)obj2)->key) != 0)
return 0;
return comps_object_cmp(((COMPS_ObjRTreePair*)obj1)->data,
((COMPS_ObjRTreePair*)obj2)->data);
}
signed char comps_objrtree_cmp(COMPS_ObjRTree *ort1, COMPS_ObjRTree *ort2) {
COMPS_HSList *values1, *values2;
COMPS_HSListItem *it;
COMPS_Set *set1, *set2;
signed char ret;
values1 = comps_objrtree_pairs(ort1);
values2 = comps_objrtree_pairs(ort2);
set1 = comps_set_create();
comps_set_init(set1, NULL, NULL, NULL, &comps_objrtree_paircmp);
set2 = comps_set_create();
comps_set_init(set2, NULL, NULL, NULL, &comps_objrtree_paircmp);
for (it = values1->first; it != NULL; it = it->next) {
comps_set_add(set1, it->data);
}
for (it = values2->first; it != NULL; it = it->next) {
comps_set_add(set2, it->data);
}
ret = comps_set_cmp(set1, set2);
comps_set_destroy(&set1);
comps_set_destroy(&set2);
//printf("objrtree cmp %d\n", !ret);
//char *str;
/*for (it = values1->first; it != NULL; it = it->next) {
str = comps_object_tostr(((COMPS_ObjRTreePair*)it->data)->data);
printf("dict item %s=%s\n", ((COMPS_ObjRTreePair*)it->data)->key, str);
free(str);
}
printf("----------\n");
for (it = values2->first; it != NULL; it = it->next) {
str = comps_object_tostr(((COMPS_ObjRTreePair*)it->data)->data);
printf("dict item %s=%s\n", ((COMPS_ObjRTreePair*)it->data)->key, str);
free(str);
}
printf("cmp objrtree ret:%d\n", ret);*/
comps_hslist_destroy(&values1);
comps_hslist_destroy(&values2);
return ret==0;
}
COMPS_CMP_u(objrtree, COMPS_ObjRTree)
void __comps_objrtree_set(COMPS_ObjRTree *rt, char *key, size_t len,
COMPS_Object *ndata) {
COMPS_HSListItem *it, *lesser;
COMPS_HSList *subnodes;
COMPS_ObjRTreeData *rtd;
static COMPS_ObjRTreeData *rtdata;
size_t _len, offset=0;
unsigned x, found = 0;
char ended;
//len = strlen(key);
if (rt->subnodes == NULL)
return;
subnodes = rt->subnodes;
while (offset != len)
{
found = 0;
lesser = NULL;
for (it = subnodes->first; it != NULL; it=it->next) {
if (((COMPS_ObjRTreeData*)it->data)->key[0] == key[offset]) {
found = 1;
break;
} else if (((COMPS_ObjRTreeData*)it->data)->key[0] < key[offset]) {
lesser = it;
}
}
if (!found) { // not found in subnodes; create new subnode
rtd = comps_objrtree_data_create_n(key+offset, len-offset, ndata);
if (!lesser) {
comps_hslist_prepend(subnodes, rtd, 0);
} else {
comps_hslist_insert_after(subnodes, lesser, rtd, 0);
}
rt->len++;
return;
} else {
rtdata = (COMPS_ObjRTreeData*)it->data;
ended = 0;
for (x=1; ;x++) {
if (rtdata->key[x] == 0) ended += 1;
if (x == len - offset) ended += 2;
if (ended != 0) break;
if (key[offset+x] != rtdata->key[x]) break;
}
if (ended == 3) { //keys equals; data replacement
comps_object_destroy(rtdata->data);
rtdata->data = ndata;
return;
} else if (ended == 2) { //global key ends first; make global leaf
//printf("ended2\n");
comps_hslist_remove(subnodes, it);
it->next = NULL;
rtd = comps_objrtree_data_create_n(key+offset, len-offset, ndata);
comps_hslist_append(subnodes, rtd, 0);
((COMPS_ObjRTreeData*)subnodes->last->data)->subnodes->last = it;
((COMPS_ObjRTreeData*)subnodes->last->data)->subnodes->first = it;
_len = len - offset;
memmove(rtdata->key,rtdata->key+_len,
strlen(rtdata->key) - _len);
rtdata->key[strlen(rtdata->key) - _len] = 0;
rtdata->key = realloc(rtdata->key,
sizeof(char)* (strlen(rtdata->key)+1));
rt->len++;
return;
} else if (ended == 1) { //local key ends first; go deeper
subnodes = rtdata->subnodes;
offset += x;
} else {
COMPS_Object *tmpdata = rtdata->data;
COMPS_HSList *tmphslist = rtdata->subnodes;
//tmpch = rtdata->key[x]; // split mutual key
rtdata->subnodes = comps_hslist_create();
comps_hslist_init(rtdata->subnodes, NULL, NULL,
&comps_objrtree_data_destroy_v);
int cmpret = strcmp(key+offset+x, rtdata->key+x);
rtdata->data = NULL;
if (cmpret > 0) {
rtd = comps_objrtree_data_create(rtdata->key+x, tmpdata);
comps_hslist_destroy(&rtd->subnodes);
rtd->subnodes = tmphslist;
comps_hslist_append(rtdata->subnodes,rtd, 0);
rtd = comps_objrtree_data_create(key+offset+x, ndata);
comps_hslist_append(rtdata->subnodes, rtd, 0);
} else {
rtd = comps_objrtree_data_create(key+offset+x, ndata);
comps_hslist_append(rtdata->subnodes, rtd, 0);
rtd = comps_objrtree_data_create(rtdata->key+x, tmpdata);
comps_hslist_destroy(&rtd->subnodes);
rtd->subnodes = tmphslist;
comps_hslist_append(rtdata->subnodes, rtd, 0);
}
rtdata->key = realloc(rtdata->key, sizeof(char)*(x+1));
rtdata->key[x] = 0;
rt->len++;
return;
}
}
}
}
void comps_objrtree_set_x(COMPS_ObjRTree *rt, char *key, COMPS_Object *data) {
__comps_objrtree_set(rt, key, strlen(key), data);
}
void comps_objrtree_set(COMPS_ObjRTree *rt, char *key, COMPS_Object *data) {
__comps_objrtree_set(rt, key, strlen(key), comps_object_incref(data));
}
void comps_objrtree_set_n(COMPS_ObjRTree *rt, char *key, size_t len,
COMPS_Object *data) {
__comps_objrtree_set(rt, key, len, data);
}
void comps_objrtree_set_nx(COMPS_ObjRTree *rt, char *key, size_t len,
COMPS_Object *data) {
__comps_objrtree_set(rt, key, len, comps_object_incref(data));
}
COMPS_Object* __comps_objrtree_get(COMPS_ObjRTree * rt, const char * key) {
COMPS_HSList * subnodes;
COMPS_HSListItem * it = NULL;
COMPS_ObjRTreeData * rtdata;
unsigned int offset, len, x;
char found, ended;
len = strlen(key);
offset = 0;
subnodes = rt->subnodes;
while (offset != len) {
found = 0;
for (it = subnodes->first; it != NULL; it=it->next) {
if (((COMPS_ObjRTreeData*)it->data)->key[0] == key[offset]) {
found = 1;
break;
}
}
if (!found) {
return NULL;
}
rtdata = (COMPS_ObjRTreeData*)it->data;
for (x=1; ;x++) {
ended=0;
if (x == strlen(rtdata->key)) ended += 1;
if (x == len-offset) ended += 2;
if (ended != 0) break;
if (key[offset+x] != rtdata->key[x]) break;
}
if (ended == 3) {
return rtdata->data;
}
else if (ended == 1) offset+=x;
else {
return NULL;
}
subnodes = ((COMPS_ObjRTreeData*)it->data)->subnodes;
}
if (it != NULL) {
return ((COMPS_ObjRTreeData*)it->data)->data;
}
else {
return NULL;
}
}
COMPS_Object* comps_objrtree_get(COMPS_ObjRTree * rt, const char * key) {
return comps_object_incref(__comps_objrtree_get(rt, key));
}
COMPS_Object* comps_objrtree_get_x(COMPS_ObjRTree * rt, const char * key) {
return __comps_objrtree_get(rt, key);
}
void comps_objrtree_unset(COMPS_ObjRTree * rt, const char * key) {
COMPS_HSList * subnodes;
COMPS_HSListItem * it;
COMPS_ObjRTreeData * rtdata;
unsigned int offset, len, x;
char found, ended;
COMPS_HSList * path;
struct Relation {
COMPS_HSList * parent_nodes;
COMPS_HSListItem * child_it;
} *relation;
path = comps_hslist_create();
comps_hslist_init(path, NULL, NULL, &free);
len = strlen(key);
offset = 0;
subnodes = rt->subnodes;
while (offset != len) {
found = 0;
for (it = subnodes->first; it != NULL; it=it->next) {
if (((COMPS_ObjRTreeData*)it->data)->key[0] == key[offset]) {
found = 1;
break;
}
}
if (!found) {
comps_hslist_destroy(&path);
return;
}
rtdata = (COMPS_ObjRTreeData*)it->data;
for (x=1; ;x++) {
ended=0;
if (rtdata->key[x] == 0) ended += 1;
if (x == len - offset) ended += 2;
if (ended != 0) break;
if (key[offset+x] != rtdata->key[x]) break;
}
if (ended == 3) {
/* remove node from tree only if there's no descendant*/
if (rtdata->subnodes->last == NULL) {
//printf("removing all\n");
comps_hslist_remove(subnodes, it);
comps_objrtree_data_destroy(rtdata);
free(it);
}
else {
//printf("removing data only\n");
comps_object_destroy(rtdata->data);
rtdata->is_leaf = 0;
rtdata->data = NULL;
}
if (path->last == NULL) {
comps_hslist_destroy(&path);
return;
}
rtdata = (COMPS_ObjRTreeData*)
((struct Relation*)path->last->data)->child_it->data;
/*remove all predecessor of deleted node (recursive) with no childs*/
while (rtdata->subnodes->last == NULL) {
//printf("removing '%s'\n", rtdata->key);
comps_objrtree_data_destroy(rtdata);
comps_hslist_remove(
((struct Relation*)path->last->data)->parent_nodes,
((struct Relation*)path->last->data)->child_it);
free(((struct Relation*)path->last->data)->child_it);
it = path->last;
comps_hslist_remove(path, path->last);
free(it);
rtdata = (COMPS_ObjRTreeData*)
((struct Relation*)path->last->data)->child_it->data;
}
comps_hslist_destroy(&path);
return;
}
else if (ended == 1) offset+=x;
else {
comps_hslist_destroy(&path);
return;
}
if ((relation = malloc(sizeof(struct Relation))) == NULL) {
comps_hslist_destroy(&path);
return;
}
subnodes = ((COMPS_ObjRTreeData*)it->data)->subnodes;
relation->parent_nodes = subnodes;
relation->child_it = it;
comps_hslist_append(path, (void*)relation, 0);
}
comps_hslist_destroy(&path);
return;
}
void comps_objrtree_clear(COMPS_ObjRTree * rt) {
COMPS_HSListItem *it, *oldit;
if (rt==NULL) return;
if (rt->subnodes == NULL) return;
oldit = rt->subnodes->first;
it = (oldit)?oldit->next:NULL;
for (;it != NULL; it=it->next) {
comps_object_destroy(oldit->data);
free(oldit);
oldit = it;
}
if (oldit) {
comps_object_destroy(oldit->data);
free(oldit);
}
}
inline COMPS_HSList* __comps_objrtree_all(COMPS_ObjRTree * rt, char keyvalpair) {
COMPS_HSList *to_process, *ret;
COMPS_HSListItem *hsit, *oldit;
size_t x;
struct Pair {
char *key;
void *data;
COMPS_HSList *subnodes;
} *pair, *current_pair=NULL;//, *oldpair=NULL;
COMPS_ObjRTreePair *rtpair;
to_process = comps_hslist_create();
comps_hslist_init(to_process, NULL, NULL, &free);
ret = comps_hslist_create();
if (keyvalpair == 0)
comps_hslist_init(ret, NULL, NULL, &free);
else if (keyvalpair == 1)
comps_hslist_init(ret, NULL, NULL, NULL);
else
comps_hslist_init(ret, NULL, NULL, &comps_objrtree_pair_destroy_v);
for (hsit = rt->subnodes->first; hsit != NULL; hsit = hsit->next) {
pair = malloc(sizeof(struct Pair));
pair->key = __comps_strcpy(((COMPS_ObjRTreeData*)hsit->data)->key);
pair->data = ((COMPS_ObjRTreeData*)hsit->data)->data;
pair->subnodes = ((COMPS_ObjRTreeData*)hsit->data)->subnodes;
comps_hslist_append(to_process, pair, 0);
}
while (to_process->first) {
//oldpair = current_pair;
current_pair = to_process->first->data;
oldit = to_process->first;
comps_hslist_remove(to_process, to_process->first);
if (current_pair->data) {
if (keyvalpair == 0) {
comps_hslist_append(ret, __comps_strcpy(current_pair->key), 0);
} else if (keyvalpair == 1) {
comps_hslist_append(ret, current_pair->data, 0);
} else {
rtpair = malloc(sizeof(COMPS_ObjRTreePair));
rtpair->key = __comps_strcpy(current_pair->key);
rtpair->data = current_pair->data;
comps_hslist_append(ret, rtpair, 0);
}
}
for (hsit = current_pair->subnodes->first, x = 0;
hsit != NULL; hsit = hsit->next, x++) {
pair = malloc(sizeof(struct Pair));
pair->key = __comps_strcat(current_pair->key,
((COMPS_ObjRTreeData*)hsit->data)->key);
pair->data = ((COMPS_ObjRTreeData*)hsit->data)->data;
pair->subnodes = ((COMPS_ObjRTreeData*)hsit->data)->subnodes;
comps_hslist_insert_at(to_process, x, pair, 0);
}
free(current_pair->key);
free(current_pair);
free(oldit);
}
comps_hslist_destroy(&to_process);
return ret;
}
void comps_objrtree_unite(COMPS_ObjRTree *rt1, COMPS_ObjRTree *rt2) {
COMPS_HSList *tmplist, *tmp_subnodes;
COMPS_HSListItem *it;
struct Pair {
COMPS_HSList * subnodes;
char * key;
char added;
} *pair, *parent_pair;
pair = malloc(sizeof(struct Pair));
pair->subnodes = rt2->subnodes;
pair->key = NULL;
tmplist = comps_hslist_create();
comps_hslist_init(tmplist, NULL, NULL, &free);
comps_hslist_append(tmplist, pair, 0);
while (tmplist->first != NULL) {
it = tmplist->first;
comps_hslist_remove(tmplist, tmplist->first);
tmp_subnodes = ((struct Pair*)it->data)->subnodes;
parent_pair = (struct Pair*) it->data;
//printf("key-part:%s\n", parent_pair->key);
free(it);
//pair->added = 0;
for (it = tmp_subnodes->first; it != NULL; it=it->next) {
pair = malloc(sizeof(struct Pair));
pair->subnodes = ((COMPS_ObjRTreeData*)it->data)->subnodes;
if (parent_pair->key != NULL) {
pair->key = malloc(sizeof(char)
* (strlen(((COMPS_ObjRTreeData*)it->data)->key)
+ strlen(parent_pair->key) + 1));
memcpy(pair->key, parent_pair->key,
sizeof(char) * strlen(parent_pair->key));
memcpy(pair->key + strlen(parent_pair->key),
((COMPS_ObjRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_ObjRTreeData*)it->data)->key)+1));
} else {
pair->key = malloc(sizeof(char)*
(strlen(((COMPS_ObjRTreeData*)it->data)->key) +1));
memcpy(pair->key, ((COMPS_ObjRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_ObjRTreeData*)it->data)->key)+1));
}
/* current node has data */
if (((COMPS_ObjRTreeData*)it->data)->data != NULL) {
comps_objrtree_set(rt1, pair->key,
(((COMPS_ObjRTreeData*)it->data)->data));
}
if (((COMPS_ObjRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair->key);
free(pair);
}
}
free(parent_pair->key);
free(parent_pair);
}
comps_hslist_destroy(&tmplist);
}
COMPS_ObjRTree* comps_objrtree_union(COMPS_ObjRTree *rt1, COMPS_ObjRTree *rt2){
COMPS_ObjRTree *ret;
ret = comps_objrtree_clone(rt1);
comps_objrtree_unite(ret, rt2);
return ret;
}
COMPS_HSList* comps_objrtree_keys(COMPS_ObjRTree * rt) {
return __comps_objrtree_all(rt, 0);
}
COMPS_HSList* comps_objrtree_values(COMPS_ObjRTree * rt) {
return __comps_objrtree_all(rt, 1);
}
COMPS_HSList* comps_objrtree_pairs(COMPS_ObjRTree * rt) {
return __comps_objrtree_all(rt, 2);
}
inline void comps_objrtree_pair_destroy(COMPS_ObjRTreePair * pair) {
free(pair->key);
free(pair);
}
inline void comps_objrtree_pair_destroy_v(void * pair) {
free(((COMPS_ObjRTreePair *)pair)->key);
free(pair);
}
COMPS_ObjectInfo COMPS_ObjRTree_ObjInfo = {
.obj_size = sizeof(COMPS_ObjRTree),
.constructor = &comps_objrtree_create_u,
.destructor = &comps_objrtree_destroy_u,
.copy = &comps_objrtree_copy_u,
.obj_cmp = &comps_objrtree_cmp_u
};
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_1390_2 |
crossvul-cpp_data_bad_4841_0 | /*
* L2TPv3 IP encapsulation support
*
* Copyright (c) 2008,2009,2010 Katalix Systems Ltd
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/icmp.h>
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/random.h>
#include <linux/socket.h>
#include <linux/l2tp.h>
#include <linux/in.h>
#include <net/sock.h>
#include <net/ip.h>
#include <net/icmp.h>
#include <net/udp.h>
#include <net/inet_common.h>
#include <net/inet_hashtables.h>
#include <net/tcp_states.h>
#include <net/protocol.h>
#include <net/xfrm.h>
#include "l2tp_core.h"
struct l2tp_ip_sock {
/* inet_sock has to be the first member of l2tp_ip_sock */
struct inet_sock inet;
u32 conn_id;
u32 peer_conn_id;
};
static DEFINE_RWLOCK(l2tp_ip_lock);
static struct hlist_head l2tp_ip_table;
static struct hlist_head l2tp_ip_bind_table;
static inline struct l2tp_ip_sock *l2tp_ip_sk(const struct sock *sk)
{
return (struct l2tp_ip_sock *)sk;
}
static struct sock *__l2tp_ip_bind_lookup(struct net *net, __be32 laddr, int dif, u32 tunnel_id)
{
struct sock *sk;
sk_for_each_bound(sk, &l2tp_ip_bind_table) {
struct inet_sock *inet = inet_sk(sk);
struct l2tp_ip_sock *l2tp = l2tp_ip_sk(sk);
if (l2tp == NULL)
continue;
if ((l2tp->conn_id == tunnel_id) &&
net_eq(sock_net(sk), net) &&
!(inet->inet_rcv_saddr && inet->inet_rcv_saddr != laddr) &&
!(sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif))
goto found;
}
sk = NULL;
found:
return sk;
}
static inline struct sock *l2tp_ip_bind_lookup(struct net *net, __be32 laddr, int dif, u32 tunnel_id)
{
struct sock *sk = __l2tp_ip_bind_lookup(net, laddr, dif, tunnel_id);
if (sk)
sock_hold(sk);
return sk;
}
/* When processing receive frames, there are two cases to
* consider. Data frames consist of a non-zero session-id and an
* optional cookie. Control frames consist of a regular L2TP header
* preceded by 32-bits of zeros.
*
* L2TPv3 Session Header Over IP
*
* 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
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Session ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Cookie (optional, maximum 64 bits)...
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* L2TPv3 Control Message Header Over IP
*
* 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
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | (32 bits of zeros) |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |T|L|x|x|S|x|x|x|x|x|x|x| Ver | Length |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Control Connection ID |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Ns | Nr |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
* All control frames are passed to userspace.
*/
static int l2tp_ip_recv(struct sk_buff *skb)
{
struct net *net = dev_net(skb->dev);
struct sock *sk;
u32 session_id;
u32 tunnel_id;
unsigned char *ptr, *optr;
struct l2tp_session *session;
struct l2tp_tunnel *tunnel = NULL;
int length;
if (!pskb_may_pull(skb, 4))
goto discard;
/* Point to L2TP header */
optr = ptr = skb->data;
session_id = ntohl(*((__be32 *) ptr));
ptr += 4;
/* RFC3931: L2TP/IP packets have the first 4 bytes containing
* the session_id. If it is 0, the packet is a L2TP control
* frame and the session_id value can be discarded.
*/
if (session_id == 0) {
__skb_pull(skb, 4);
goto pass_up;
}
/* Ok, this is a data packet. Lookup the session. */
session = l2tp_session_find(net, NULL, session_id);
if (session == NULL)
goto discard;
tunnel = session->tunnel;
if (tunnel == NULL)
goto discard;
/* Trace packet contents, if enabled */
if (tunnel->debug & L2TP_MSG_DATA) {
length = min(32u, skb->len);
if (!pskb_may_pull(skb, length))
goto discard;
/* Point to L2TP header */
optr = ptr = skb->data;
ptr += 4;
pr_debug("%s: ip recv\n", tunnel->name);
print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, ptr, length);
}
l2tp_recv_common(session, skb, ptr, optr, 0, skb->len, tunnel->recv_payload_hook);
return 0;
pass_up:
/* Get the tunnel_id from the L2TP header */
if (!pskb_may_pull(skb, 12))
goto discard;
if ((skb->data[0] & 0xc0) != 0xc0)
goto discard;
tunnel_id = ntohl(*(__be32 *) &skb->data[4]);
tunnel = l2tp_tunnel_find(net, tunnel_id);
if (tunnel != NULL)
sk = tunnel->sock;
else {
struct iphdr *iph = (struct iphdr *) skb_network_header(skb);
read_lock_bh(&l2tp_ip_lock);
sk = __l2tp_ip_bind_lookup(net, iph->daddr, 0, tunnel_id);
read_unlock_bh(&l2tp_ip_lock);
}
if (sk == NULL)
goto discard;
sock_hold(sk);
if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb))
goto discard_put;
nf_reset(skb);
return sk_receive_skb(sk, skb, 1);
discard_put:
sock_put(sk);
discard:
kfree_skb(skb);
return 0;
}
static int l2tp_ip_open(struct sock *sk)
{
/* Prevent autobind. We don't have ports. */
inet_sk(sk)->inet_num = IPPROTO_L2TP;
write_lock_bh(&l2tp_ip_lock);
sk_add_node(sk, &l2tp_ip_table);
write_unlock_bh(&l2tp_ip_lock);
return 0;
}
static void l2tp_ip_close(struct sock *sk, long timeout)
{
write_lock_bh(&l2tp_ip_lock);
hlist_del_init(&sk->sk_bind_node);
sk_del_node_init(sk);
write_unlock_bh(&l2tp_ip_lock);
sk_common_release(sk);
}
static void l2tp_ip_destroy_sock(struct sock *sk)
{
struct sk_buff *skb;
struct l2tp_tunnel *tunnel = l2tp_sock_to_tunnel(sk);
while ((skb = __skb_dequeue_tail(&sk->sk_write_queue)) != NULL)
kfree_skb(skb);
if (tunnel) {
l2tp_tunnel_closeall(tunnel);
sock_put(sk);
}
sk_refcnt_debug_dec(sk);
}
static int l2tp_ip_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct inet_sock *inet = inet_sk(sk);
struct sockaddr_l2tpip *addr = (struct sockaddr_l2tpip *) uaddr;
struct net *net = sock_net(sk);
int ret;
int chk_addr_ret;
if (!sock_flag(sk, SOCK_ZAPPED))
return -EINVAL;
if (addr_len < sizeof(struct sockaddr_l2tpip))
return -EINVAL;
if (addr->l2tp_family != AF_INET)
return -EINVAL;
ret = -EADDRINUSE;
read_lock_bh(&l2tp_ip_lock);
if (__l2tp_ip_bind_lookup(net, addr->l2tp_addr.s_addr,
sk->sk_bound_dev_if, addr->l2tp_conn_id))
goto out_in_use;
read_unlock_bh(&l2tp_ip_lock);
lock_sock(sk);
if (sk->sk_state != TCP_CLOSE || addr_len < sizeof(struct sockaddr_l2tpip))
goto out;
chk_addr_ret = inet_addr_type(net, addr->l2tp_addr.s_addr);
ret = -EADDRNOTAVAIL;
if (addr->l2tp_addr.s_addr && chk_addr_ret != RTN_LOCAL &&
chk_addr_ret != RTN_MULTICAST && chk_addr_ret != RTN_BROADCAST)
goto out;
if (addr->l2tp_addr.s_addr)
inet->inet_rcv_saddr = inet->inet_saddr = addr->l2tp_addr.s_addr;
if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST)
inet->inet_saddr = 0; /* Use device */
sk_dst_reset(sk);
l2tp_ip_sk(sk)->conn_id = addr->l2tp_conn_id;
write_lock_bh(&l2tp_ip_lock);
sk_add_bind_node(sk, &l2tp_ip_bind_table);
sk_del_node_init(sk);
write_unlock_bh(&l2tp_ip_lock);
ret = 0;
sock_reset_flag(sk, SOCK_ZAPPED);
out:
release_sock(sk);
return ret;
out_in_use:
read_unlock_bh(&l2tp_ip_lock);
return ret;
}
static int l2tp_ip_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
{
struct sockaddr_l2tpip *lsa = (struct sockaddr_l2tpip *) uaddr;
int rc;
if (sock_flag(sk, SOCK_ZAPPED)) /* Must bind first - autobinding does not work */
return -EINVAL;
if (addr_len < sizeof(*lsa))
return -EINVAL;
if (ipv4_is_multicast(lsa->l2tp_addr.s_addr))
return -EINVAL;
rc = ip4_datagram_connect(sk, uaddr, addr_len);
if (rc < 0)
return rc;
lock_sock(sk);
l2tp_ip_sk(sk)->peer_conn_id = lsa->l2tp_conn_id;
write_lock_bh(&l2tp_ip_lock);
hlist_del_init(&sk->sk_bind_node);
sk_add_bind_node(sk, &l2tp_ip_bind_table);
write_unlock_bh(&l2tp_ip_lock);
release_sock(sk);
return rc;
}
static int l2tp_ip_disconnect(struct sock *sk, int flags)
{
if (sock_flag(sk, SOCK_ZAPPED))
return 0;
return __udp_disconnect(sk, flags);
}
static int l2tp_ip_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct sock *sk = sock->sk;
struct inet_sock *inet = inet_sk(sk);
struct l2tp_ip_sock *lsk = l2tp_ip_sk(sk);
struct sockaddr_l2tpip *lsa = (struct sockaddr_l2tpip *)uaddr;
memset(lsa, 0, sizeof(*lsa));
lsa->l2tp_family = AF_INET;
if (peer) {
if (!inet->inet_dport)
return -ENOTCONN;
lsa->l2tp_conn_id = lsk->peer_conn_id;
lsa->l2tp_addr.s_addr = inet->inet_daddr;
} else {
__be32 addr = inet->inet_rcv_saddr;
if (!addr)
addr = inet->inet_saddr;
lsa->l2tp_conn_id = lsk->conn_id;
lsa->l2tp_addr.s_addr = addr;
}
*uaddr_len = sizeof(*lsa);
return 0;
}
static int l2tp_ip_backlog_recv(struct sock *sk, struct sk_buff *skb)
{
int rc;
/* Charge it to the socket, dropping if the queue is full. */
rc = sock_queue_rcv_skb(sk, skb);
if (rc < 0)
goto drop;
return 0;
drop:
IP_INC_STATS(sock_net(sk), IPSTATS_MIB_INDISCARDS);
kfree_skb(skb);
return -1;
}
/* Userspace will call sendmsg() on the tunnel socket to send L2TP
* control frames.
*/
static int l2tp_ip_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct sk_buff *skb;
int rc;
struct inet_sock *inet = inet_sk(sk);
struct rtable *rt = NULL;
struct flowi4 *fl4;
int connected = 0;
__be32 daddr;
lock_sock(sk);
rc = -ENOTCONN;
if (sock_flag(sk, SOCK_DEAD))
goto out;
/* Get and verify the address. */
if (msg->msg_name) {
DECLARE_SOCKADDR(struct sockaddr_l2tpip *, lip, msg->msg_name);
rc = -EINVAL;
if (msg->msg_namelen < sizeof(*lip))
goto out;
if (lip->l2tp_family != AF_INET) {
rc = -EAFNOSUPPORT;
if (lip->l2tp_family != AF_UNSPEC)
goto out;
}
daddr = lip->l2tp_addr.s_addr;
} else {
rc = -EDESTADDRREQ;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
daddr = inet->inet_daddr;
connected = 1;
}
/* Allocate a socket buffer */
rc = -ENOMEM;
skb = sock_wmalloc(sk, 2 + NET_SKB_PAD + sizeof(struct iphdr) +
4 + len, 0, GFP_KERNEL);
if (!skb)
goto error;
/* Reserve space for headers, putting IP header on 4-byte boundary. */
skb_reserve(skb, 2 + NET_SKB_PAD);
skb_reset_network_header(skb);
skb_reserve(skb, sizeof(struct iphdr));
skb_reset_transport_header(skb);
/* Insert 0 session_id */
*((__be32 *) skb_put(skb, 4)) = 0;
/* Copy user data into skb */
rc = memcpy_from_msg(skb_put(skb, len), msg, len);
if (rc < 0) {
kfree_skb(skb);
goto error;
}
fl4 = &inet->cork.fl.u.ip4;
if (connected)
rt = (struct rtable *) __sk_dst_check(sk, 0);
rcu_read_lock();
if (rt == NULL) {
const struct ip_options_rcu *inet_opt;
inet_opt = rcu_dereference(inet->inet_opt);
/* Use correct destination address if we have options. */
if (inet_opt && inet_opt->opt.srr)
daddr = inet_opt->opt.faddr;
/* If this fails, retransmit mechanism of transport layer will
* keep trying until route appears or the connection times
* itself out.
*/
rt = ip_route_output_ports(sock_net(sk), fl4, sk,
daddr, inet->inet_saddr,
inet->inet_dport, inet->inet_sport,
sk->sk_protocol, RT_CONN_FLAGS(sk),
sk->sk_bound_dev_if);
if (IS_ERR(rt))
goto no_route;
if (connected) {
sk_setup_caps(sk, &rt->dst);
} else {
skb_dst_set(skb, &rt->dst);
goto xmit;
}
}
/* We dont need to clone dst here, it is guaranteed to not disappear.
* __dev_xmit_skb() might force a refcount if needed.
*/
skb_dst_set_noref(skb, &rt->dst);
xmit:
/* Queue the packet to IP for output */
rc = ip_queue_xmit(sk, skb, &inet->cork.fl);
rcu_read_unlock();
error:
if (rc >= 0)
rc = len;
out:
release_sock(sk);
return rc;
no_route:
rcu_read_unlock();
IP_INC_STATS(sock_net(sk), IPSTATS_MIB_OUTNOROUTES);
kfree_skb(skb);
rc = -EHOSTUNREACH;
goto out;
}
static int l2tp_ip_recvmsg(struct sock *sk, struct msghdr *msg,
size_t len, int noblock, int flags, int *addr_len)
{
struct inet_sock *inet = inet_sk(sk);
size_t copied = 0;
int err = -EOPNOTSUPP;
DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
struct sk_buff *skb;
if (flags & MSG_OOB)
goto out;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (!skb)
goto out;
copied = skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
err = skb_copy_datagram_msg(skb, 0, msg, copied);
if (err)
goto done;
sock_recv_timestamp(msg, sk, skb);
/* Copy the address. */
if (sin) {
sin->sin_family = AF_INET;
sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
sin->sin_port = 0;
memset(&sin->sin_zero, 0, sizeof(sin->sin_zero));
*addr_len = sizeof(*sin);
}
if (inet->cmsg_flags)
ip_cmsg_recv(msg, skb);
if (flags & MSG_TRUNC)
copied = skb->len;
done:
skb_free_datagram(sk, skb);
out:
return err ? err : copied;
}
static struct proto l2tp_ip_prot = {
.name = "L2TP/IP",
.owner = THIS_MODULE,
.init = l2tp_ip_open,
.close = l2tp_ip_close,
.bind = l2tp_ip_bind,
.connect = l2tp_ip_connect,
.disconnect = l2tp_ip_disconnect,
.ioctl = udp_ioctl,
.destroy = l2tp_ip_destroy_sock,
.setsockopt = ip_setsockopt,
.getsockopt = ip_getsockopt,
.sendmsg = l2tp_ip_sendmsg,
.recvmsg = l2tp_ip_recvmsg,
.backlog_rcv = l2tp_ip_backlog_recv,
.hash = inet_hash,
.unhash = inet_unhash,
.obj_size = sizeof(struct l2tp_ip_sock),
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_ip_setsockopt,
.compat_getsockopt = compat_ip_getsockopt,
#endif
};
static const struct proto_ops l2tp_ip_ops = {
.family = PF_INET,
.owner = THIS_MODULE,
.release = inet_release,
.bind = inet_bind,
.connect = inet_dgram_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = l2tp_ip_getname,
.poll = datagram_poll,
.ioctl = inet_ioctl,
.listen = sock_no_listen,
.shutdown = inet_shutdown,
.setsockopt = sock_common_setsockopt,
.getsockopt = sock_common_getsockopt,
.sendmsg = inet_sendmsg,
.recvmsg = sock_common_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_sock_common_setsockopt,
.compat_getsockopt = compat_sock_common_getsockopt,
#endif
};
static struct inet_protosw l2tp_ip_protosw = {
.type = SOCK_DGRAM,
.protocol = IPPROTO_L2TP,
.prot = &l2tp_ip_prot,
.ops = &l2tp_ip_ops,
};
static struct net_protocol l2tp_ip_protocol __read_mostly = {
.handler = l2tp_ip_recv,
.netns_ok = 1,
};
static int __init l2tp_ip_init(void)
{
int err;
pr_info("L2TP IP encapsulation support (L2TPv3)\n");
err = proto_register(&l2tp_ip_prot, 1);
if (err != 0)
goto out;
err = inet_add_protocol(&l2tp_ip_protocol, IPPROTO_L2TP);
if (err)
goto out1;
inet_register_protosw(&l2tp_ip_protosw);
return 0;
out1:
proto_unregister(&l2tp_ip_prot);
out:
return err;
}
static void __exit l2tp_ip_exit(void)
{
inet_unregister_protosw(&l2tp_ip_protosw);
inet_del_protocol(&l2tp_ip_protocol, IPPROTO_L2TP);
proto_unregister(&l2tp_ip_prot);
}
module_init(l2tp_ip_init);
module_exit(l2tp_ip_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("James Chapman <jchapman@katalix.com>");
MODULE_DESCRIPTION("L2TP over IP");
MODULE_VERSION("1.0");
/* Use the value of SOCK_DGRAM (2) directory, because __stringify doesn't like
* enums
*/
MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET, 2, IPPROTO_L2TP);
MODULE_ALIAS_NET_PF_PROTO(PF_INET, IPPROTO_L2TP);
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_4841_0 |
crossvul-cpp_data_bad_4797_0 | /*
* bsg.c - block layer implementation of the sg v4 interface
*
* Copyright (C) 2004 Jens Axboe <axboe@suse.de> SUSE Labs
* Copyright (C) 2004 Peter M. Jones <pjones@redhat.com>
*
* This file is subject to the terms and conditions of the GNU General Public
* License version 2. See the file "COPYING" in the main directory of this
* archive for more details.
*
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/file.h>
#include <linux/blkdev.h>
#include <linux/poll.h>
#include <linux/cdev.h>
#include <linux/jiffies.h>
#include <linux/percpu.h>
#include <linux/uio.h>
#include <linux/idr.h>
#include <linux/bsg.h>
#include <linux/slab.h>
#include <scsi/scsi.h>
#include <scsi/scsi_ioctl.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_driver.h>
#include <scsi/sg.h>
#define BSG_DESCRIPTION "Block layer SCSI generic (bsg) driver"
#define BSG_VERSION "0.4"
struct bsg_device {
struct request_queue *queue;
spinlock_t lock;
struct list_head busy_list;
struct list_head done_list;
struct hlist_node dev_list;
atomic_t ref_count;
int queued_cmds;
int done_cmds;
wait_queue_head_t wq_done;
wait_queue_head_t wq_free;
char name[20];
int max_queue;
unsigned long flags;
};
enum {
BSG_F_BLOCK = 1,
};
#define BSG_DEFAULT_CMDS 64
#define BSG_MAX_DEVS 32768
#undef BSG_DEBUG
#ifdef BSG_DEBUG
#define dprintk(fmt, args...) printk(KERN_ERR "%s: " fmt, __func__, ##args)
#else
#define dprintk(fmt, args...)
#endif
static DEFINE_MUTEX(bsg_mutex);
static DEFINE_IDR(bsg_minor_idr);
#define BSG_LIST_ARRAY_SIZE 8
static struct hlist_head bsg_device_list[BSG_LIST_ARRAY_SIZE];
static struct class *bsg_class;
static int bsg_major;
static struct kmem_cache *bsg_cmd_cachep;
/*
* our internal command type
*/
struct bsg_command {
struct bsg_device *bd;
struct list_head list;
struct request *rq;
struct bio *bio;
struct bio *bidi_bio;
int err;
struct sg_io_v4 hdr;
char sense[SCSI_SENSE_BUFFERSIZE];
};
static void bsg_free_command(struct bsg_command *bc)
{
struct bsg_device *bd = bc->bd;
unsigned long flags;
kmem_cache_free(bsg_cmd_cachep, bc);
spin_lock_irqsave(&bd->lock, flags);
bd->queued_cmds--;
spin_unlock_irqrestore(&bd->lock, flags);
wake_up(&bd->wq_free);
}
static struct bsg_command *bsg_alloc_command(struct bsg_device *bd)
{
struct bsg_command *bc = ERR_PTR(-EINVAL);
spin_lock_irq(&bd->lock);
if (bd->queued_cmds >= bd->max_queue)
goto out;
bd->queued_cmds++;
spin_unlock_irq(&bd->lock);
bc = kmem_cache_zalloc(bsg_cmd_cachep, GFP_KERNEL);
if (unlikely(!bc)) {
spin_lock_irq(&bd->lock);
bd->queued_cmds--;
bc = ERR_PTR(-ENOMEM);
goto out;
}
bc->bd = bd;
INIT_LIST_HEAD(&bc->list);
dprintk("%s: returning free cmd %p\n", bd->name, bc);
return bc;
out:
spin_unlock_irq(&bd->lock);
return bc;
}
static inline struct hlist_head *bsg_dev_idx_hash(int index)
{
return &bsg_device_list[index & (BSG_LIST_ARRAY_SIZE - 1)];
}
static int blk_fill_sgv4_hdr_rq(struct request_queue *q, struct request *rq,
struct sg_io_v4 *hdr, struct bsg_device *bd,
fmode_t has_write_perm)
{
if (hdr->request_len > BLK_MAX_CDB) {
rq->cmd = kzalloc(hdr->request_len, GFP_KERNEL);
if (!rq->cmd)
return -ENOMEM;
}
if (copy_from_user(rq->cmd, (void __user *)(unsigned long)hdr->request,
hdr->request_len))
return -EFAULT;
if (hdr->subprotocol == BSG_SUB_PROTOCOL_SCSI_CMD) {
if (blk_verify_command(rq->cmd, has_write_perm))
return -EPERM;
} else if (!capable(CAP_SYS_RAWIO))
return -EPERM;
/*
* fill in request structure
*/
rq->cmd_len = hdr->request_len;
rq->timeout = msecs_to_jiffies(hdr->timeout);
if (!rq->timeout)
rq->timeout = q->sg_timeout;
if (!rq->timeout)
rq->timeout = BLK_DEFAULT_SG_TIMEOUT;
if (rq->timeout < BLK_MIN_SG_TIMEOUT)
rq->timeout = BLK_MIN_SG_TIMEOUT;
return 0;
}
/*
* Check if sg_io_v4 from user is allowed and valid
*/
static int
bsg_validate_sgv4_hdr(struct sg_io_v4 *hdr, int *rw)
{
int ret = 0;
if (hdr->guard != 'Q')
return -EINVAL;
switch (hdr->protocol) {
case BSG_PROTOCOL_SCSI:
switch (hdr->subprotocol) {
case BSG_SUB_PROTOCOL_SCSI_CMD:
case BSG_SUB_PROTOCOL_SCSI_TRANSPORT:
break;
default:
ret = -EINVAL;
}
break;
default:
ret = -EINVAL;
}
*rw = hdr->dout_xfer_len ? WRITE : READ;
return ret;
}
/*
* map sg_io_v4 to a request.
*/
static struct request *
bsg_map_hdr(struct bsg_device *bd, struct sg_io_v4 *hdr, fmode_t has_write_perm,
u8 *sense)
{
struct request_queue *q = bd->queue;
struct request *rq, *next_rq = NULL;
int ret, rw;
unsigned int dxfer_len;
void __user *dxferp = NULL;
struct bsg_class_device *bcd = &q->bsg_dev;
/* if the LLD has been removed then the bsg_unregister_queue will
* eventually be called and the class_dev was freed, so we can no
* longer use this request_queue. Return no such address.
*/
if (!bcd->class_dev)
return ERR_PTR(-ENXIO);
dprintk("map hdr %llx/%u %llx/%u\n", (unsigned long long) hdr->dout_xferp,
hdr->dout_xfer_len, (unsigned long long) hdr->din_xferp,
hdr->din_xfer_len);
ret = bsg_validate_sgv4_hdr(hdr, &rw);
if (ret)
return ERR_PTR(ret);
/*
* map scatter-gather elements separately and string them to request
*/
rq = blk_get_request(q, rw, GFP_KERNEL);
if (IS_ERR(rq))
return rq;
blk_rq_set_block_pc(rq);
ret = blk_fill_sgv4_hdr_rq(q, rq, hdr, bd, has_write_perm);
if (ret)
goto out;
if (rw == WRITE && hdr->din_xfer_len) {
if (!test_bit(QUEUE_FLAG_BIDI, &q->queue_flags)) {
ret = -EOPNOTSUPP;
goto out;
}
next_rq = blk_get_request(q, READ, GFP_KERNEL);
if (IS_ERR(next_rq)) {
ret = PTR_ERR(next_rq);
next_rq = NULL;
goto out;
}
rq->next_rq = next_rq;
next_rq->cmd_type = rq->cmd_type;
dxferp = (void __user *)(unsigned long)hdr->din_xferp;
ret = blk_rq_map_user(q, next_rq, NULL, dxferp,
hdr->din_xfer_len, GFP_KERNEL);
if (ret)
goto out;
}
if (hdr->dout_xfer_len) {
dxfer_len = hdr->dout_xfer_len;
dxferp = (void __user *)(unsigned long)hdr->dout_xferp;
} else if (hdr->din_xfer_len) {
dxfer_len = hdr->din_xfer_len;
dxferp = (void __user *)(unsigned long)hdr->din_xferp;
} else
dxfer_len = 0;
if (dxfer_len) {
ret = blk_rq_map_user(q, rq, NULL, dxferp, dxfer_len,
GFP_KERNEL);
if (ret)
goto out;
}
rq->sense = sense;
rq->sense_len = 0;
return rq;
out:
if (rq->cmd != rq->__cmd)
kfree(rq->cmd);
blk_put_request(rq);
if (next_rq) {
blk_rq_unmap_user(next_rq->bio);
blk_put_request(next_rq);
}
return ERR_PTR(ret);
}
/*
* async completion call-back from the block layer, when scsi/ide/whatever
* calls end_that_request_last() on a request
*/
static void bsg_rq_end_io(struct request *rq, int uptodate)
{
struct bsg_command *bc = rq->end_io_data;
struct bsg_device *bd = bc->bd;
unsigned long flags;
dprintk("%s: finished rq %p bc %p, bio %p stat %d\n",
bd->name, rq, bc, bc->bio, uptodate);
bc->hdr.duration = jiffies_to_msecs(jiffies - bc->hdr.duration);
spin_lock_irqsave(&bd->lock, flags);
list_move_tail(&bc->list, &bd->done_list);
bd->done_cmds++;
spin_unlock_irqrestore(&bd->lock, flags);
wake_up(&bd->wq_done);
}
/*
* do final setup of a 'bc' and submit the matching 'rq' to the block
* layer for io
*/
static void bsg_add_command(struct bsg_device *bd, struct request_queue *q,
struct bsg_command *bc, struct request *rq)
{
int at_head = (0 == (bc->hdr.flags & BSG_FLAG_Q_AT_TAIL));
/*
* add bc command to busy queue and submit rq for io
*/
bc->rq = rq;
bc->bio = rq->bio;
if (rq->next_rq)
bc->bidi_bio = rq->next_rq->bio;
bc->hdr.duration = jiffies;
spin_lock_irq(&bd->lock);
list_add_tail(&bc->list, &bd->busy_list);
spin_unlock_irq(&bd->lock);
dprintk("%s: queueing rq %p, bc %p\n", bd->name, rq, bc);
rq->end_io_data = bc;
blk_execute_rq_nowait(q, NULL, rq, at_head, bsg_rq_end_io);
}
static struct bsg_command *bsg_next_done_cmd(struct bsg_device *bd)
{
struct bsg_command *bc = NULL;
spin_lock_irq(&bd->lock);
if (bd->done_cmds) {
bc = list_first_entry(&bd->done_list, struct bsg_command, list);
list_del(&bc->list);
bd->done_cmds--;
}
spin_unlock_irq(&bd->lock);
return bc;
}
/*
* Get a finished command from the done list
*/
static struct bsg_command *bsg_get_done_cmd(struct bsg_device *bd)
{
struct bsg_command *bc;
int ret;
do {
bc = bsg_next_done_cmd(bd);
if (bc)
break;
if (!test_bit(BSG_F_BLOCK, &bd->flags)) {
bc = ERR_PTR(-EAGAIN);
break;
}
ret = wait_event_interruptible(bd->wq_done, bd->done_cmds);
if (ret) {
bc = ERR_PTR(-ERESTARTSYS);
break;
}
} while (1);
dprintk("%s: returning done %p\n", bd->name, bc);
return bc;
}
static int blk_complete_sgv4_hdr_rq(struct request *rq, struct sg_io_v4 *hdr,
struct bio *bio, struct bio *bidi_bio)
{
int ret = 0;
dprintk("rq %p bio %p 0x%x\n", rq, bio, rq->errors);
/*
* fill in all the output members
*/
hdr->device_status = rq->errors & 0xff;
hdr->transport_status = host_byte(rq->errors);
hdr->driver_status = driver_byte(rq->errors);
hdr->info = 0;
if (hdr->device_status || hdr->transport_status || hdr->driver_status)
hdr->info |= SG_INFO_CHECK;
hdr->response_len = 0;
if (rq->sense_len && hdr->response) {
int len = min_t(unsigned int, hdr->max_response_len,
rq->sense_len);
ret = copy_to_user((void __user *)(unsigned long)hdr->response,
rq->sense, len);
if (!ret)
hdr->response_len = len;
else
ret = -EFAULT;
}
if (rq->next_rq) {
hdr->dout_resid = rq->resid_len;
hdr->din_resid = rq->next_rq->resid_len;
blk_rq_unmap_user(bidi_bio);
blk_put_request(rq->next_rq);
} else if (rq_data_dir(rq) == READ)
hdr->din_resid = rq->resid_len;
else
hdr->dout_resid = rq->resid_len;
/*
* If the request generated a negative error number, return it
* (providing we aren't already returning an error); if it's
* just a protocol response (i.e. non negative), that gets
* processed above.
*/
if (!ret && rq->errors < 0)
ret = rq->errors;
blk_rq_unmap_user(bio);
if (rq->cmd != rq->__cmd)
kfree(rq->cmd);
blk_put_request(rq);
return ret;
}
static bool bsg_complete(struct bsg_device *bd)
{
bool ret = false;
bool spin;
do {
spin_lock_irq(&bd->lock);
BUG_ON(bd->done_cmds > bd->queued_cmds);
/*
* All commands consumed.
*/
if (bd->done_cmds == bd->queued_cmds)
ret = true;
spin = !test_bit(BSG_F_BLOCK, &bd->flags);
spin_unlock_irq(&bd->lock);
} while (!ret && spin);
return ret;
}
static int bsg_complete_all_commands(struct bsg_device *bd)
{
struct bsg_command *bc;
int ret, tret;
dprintk("%s: entered\n", bd->name);
/*
* wait for all commands to complete
*/
io_wait_event(bd->wq_done, bsg_complete(bd));
/*
* discard done commands
*/
ret = 0;
do {
spin_lock_irq(&bd->lock);
if (!bd->queued_cmds) {
spin_unlock_irq(&bd->lock);
break;
}
spin_unlock_irq(&bd->lock);
bc = bsg_get_done_cmd(bd);
if (IS_ERR(bc))
break;
tret = blk_complete_sgv4_hdr_rq(bc->rq, &bc->hdr, bc->bio,
bc->bidi_bio);
if (!ret)
ret = tret;
bsg_free_command(bc);
} while (1);
return ret;
}
static int
__bsg_read(char __user *buf, size_t count, struct bsg_device *bd,
const struct iovec *iov, ssize_t *bytes_read)
{
struct bsg_command *bc;
int nr_commands, ret;
if (count % sizeof(struct sg_io_v4))
return -EINVAL;
ret = 0;
nr_commands = count / sizeof(struct sg_io_v4);
while (nr_commands) {
bc = bsg_get_done_cmd(bd);
if (IS_ERR(bc)) {
ret = PTR_ERR(bc);
break;
}
/*
* this is the only case where we need to copy data back
* after completing the request. so do that here,
* bsg_complete_work() cannot do that for us
*/
ret = blk_complete_sgv4_hdr_rq(bc->rq, &bc->hdr, bc->bio,
bc->bidi_bio);
if (copy_to_user(buf, &bc->hdr, sizeof(bc->hdr)))
ret = -EFAULT;
bsg_free_command(bc);
if (ret)
break;
buf += sizeof(struct sg_io_v4);
*bytes_read += sizeof(struct sg_io_v4);
nr_commands--;
}
return ret;
}
static inline void bsg_set_block(struct bsg_device *bd, struct file *file)
{
if (file->f_flags & O_NONBLOCK)
clear_bit(BSG_F_BLOCK, &bd->flags);
else
set_bit(BSG_F_BLOCK, &bd->flags);
}
/*
* Check if the error is a "real" error that we should return.
*/
static inline int err_block_err(int ret)
{
if (ret && ret != -ENOSPC && ret != -ENODATA && ret != -EAGAIN)
return 1;
return 0;
}
static ssize_t
bsg_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
{
struct bsg_device *bd = file->private_data;
int ret;
ssize_t bytes_read;
dprintk("%s: read %Zd bytes\n", bd->name, count);
bsg_set_block(bd, file);
bytes_read = 0;
ret = __bsg_read(buf, count, bd, NULL, &bytes_read);
*ppos = bytes_read;
if (!bytes_read || err_block_err(ret))
bytes_read = ret;
return bytes_read;
}
static int __bsg_write(struct bsg_device *bd, const char __user *buf,
size_t count, ssize_t *bytes_written,
fmode_t has_write_perm)
{
struct bsg_command *bc;
struct request *rq;
int ret, nr_commands;
if (count % sizeof(struct sg_io_v4))
return -EINVAL;
nr_commands = count / sizeof(struct sg_io_v4);
rq = NULL;
bc = NULL;
ret = 0;
while (nr_commands) {
struct request_queue *q = bd->queue;
bc = bsg_alloc_command(bd);
if (IS_ERR(bc)) {
ret = PTR_ERR(bc);
bc = NULL;
break;
}
if (copy_from_user(&bc->hdr, buf, sizeof(bc->hdr))) {
ret = -EFAULT;
break;
}
/*
* get a request, fill in the blanks, and add to request queue
*/
rq = bsg_map_hdr(bd, &bc->hdr, has_write_perm, bc->sense);
if (IS_ERR(rq)) {
ret = PTR_ERR(rq);
rq = NULL;
break;
}
bsg_add_command(bd, q, bc, rq);
bc = NULL;
rq = NULL;
nr_commands--;
buf += sizeof(struct sg_io_v4);
*bytes_written += sizeof(struct sg_io_v4);
}
if (bc)
bsg_free_command(bc);
return ret;
}
static ssize_t
bsg_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
{
struct bsg_device *bd = file->private_data;
ssize_t bytes_written;
int ret;
dprintk("%s: write %Zd bytes\n", bd->name, count);
bsg_set_block(bd, file);
bytes_written = 0;
ret = __bsg_write(bd, buf, count, &bytes_written,
file->f_mode & FMODE_WRITE);
*ppos = bytes_written;
/*
* return bytes written on non-fatal errors
*/
if (!bytes_written || err_block_err(ret))
bytes_written = ret;
dprintk("%s: returning %Zd\n", bd->name, bytes_written);
return bytes_written;
}
static struct bsg_device *bsg_alloc_device(void)
{
struct bsg_device *bd;
bd = kzalloc(sizeof(struct bsg_device), GFP_KERNEL);
if (unlikely(!bd))
return NULL;
spin_lock_init(&bd->lock);
bd->max_queue = BSG_DEFAULT_CMDS;
INIT_LIST_HEAD(&bd->busy_list);
INIT_LIST_HEAD(&bd->done_list);
INIT_HLIST_NODE(&bd->dev_list);
init_waitqueue_head(&bd->wq_free);
init_waitqueue_head(&bd->wq_done);
return bd;
}
static void bsg_kref_release_function(struct kref *kref)
{
struct bsg_class_device *bcd =
container_of(kref, struct bsg_class_device, ref);
struct device *parent = bcd->parent;
if (bcd->release)
bcd->release(bcd->parent);
put_device(parent);
}
static int bsg_put_device(struct bsg_device *bd)
{
int ret = 0, do_free;
struct request_queue *q = bd->queue;
mutex_lock(&bsg_mutex);
do_free = atomic_dec_and_test(&bd->ref_count);
if (!do_free) {
mutex_unlock(&bsg_mutex);
goto out;
}
hlist_del(&bd->dev_list);
mutex_unlock(&bsg_mutex);
dprintk("%s: tearing down\n", bd->name);
/*
* close can always block
*/
set_bit(BSG_F_BLOCK, &bd->flags);
/*
* correct error detection baddies here again. it's the responsibility
* of the app to properly reap commands before close() if it wants
* fool-proof error detection
*/
ret = bsg_complete_all_commands(bd);
kfree(bd);
out:
kref_put(&q->bsg_dev.ref, bsg_kref_release_function);
if (do_free)
blk_put_queue(q);
return ret;
}
static struct bsg_device *bsg_add_device(struct inode *inode,
struct request_queue *rq,
struct file *file)
{
struct bsg_device *bd;
#ifdef BSG_DEBUG
unsigned char buf[32];
#endif
if (!blk_get_queue(rq))
return ERR_PTR(-ENXIO);
bd = bsg_alloc_device();
if (!bd) {
blk_put_queue(rq);
return ERR_PTR(-ENOMEM);
}
bd->queue = rq;
bsg_set_block(bd, file);
atomic_set(&bd->ref_count, 1);
mutex_lock(&bsg_mutex);
hlist_add_head(&bd->dev_list, bsg_dev_idx_hash(iminor(inode)));
strncpy(bd->name, dev_name(rq->bsg_dev.class_dev), sizeof(bd->name) - 1);
dprintk("bound to <%s>, max queue %d\n",
format_dev_t(buf, inode->i_rdev), bd->max_queue);
mutex_unlock(&bsg_mutex);
return bd;
}
static struct bsg_device *__bsg_get_device(int minor, struct request_queue *q)
{
struct bsg_device *bd;
mutex_lock(&bsg_mutex);
hlist_for_each_entry(bd, bsg_dev_idx_hash(minor), dev_list) {
if (bd->queue == q) {
atomic_inc(&bd->ref_count);
goto found;
}
}
bd = NULL;
found:
mutex_unlock(&bsg_mutex);
return bd;
}
static struct bsg_device *bsg_get_device(struct inode *inode, struct file *file)
{
struct bsg_device *bd;
struct bsg_class_device *bcd;
/*
* find the class device
*/
mutex_lock(&bsg_mutex);
bcd = idr_find(&bsg_minor_idr, iminor(inode));
if (bcd)
kref_get(&bcd->ref);
mutex_unlock(&bsg_mutex);
if (!bcd)
return ERR_PTR(-ENODEV);
bd = __bsg_get_device(iminor(inode), bcd->queue);
if (bd)
return bd;
bd = bsg_add_device(inode, bcd->queue, file);
if (IS_ERR(bd))
kref_put(&bcd->ref, bsg_kref_release_function);
return bd;
}
static int bsg_open(struct inode *inode, struct file *file)
{
struct bsg_device *bd;
bd = bsg_get_device(inode, file);
if (IS_ERR(bd))
return PTR_ERR(bd);
file->private_data = bd;
return 0;
}
static int bsg_release(struct inode *inode, struct file *file)
{
struct bsg_device *bd = file->private_data;
file->private_data = NULL;
return bsg_put_device(bd);
}
static unsigned int bsg_poll(struct file *file, poll_table *wait)
{
struct bsg_device *bd = file->private_data;
unsigned int mask = 0;
poll_wait(file, &bd->wq_done, wait);
poll_wait(file, &bd->wq_free, wait);
spin_lock_irq(&bd->lock);
if (!list_empty(&bd->done_list))
mask |= POLLIN | POLLRDNORM;
if (bd->queued_cmds < bd->max_queue)
mask |= POLLOUT;
spin_unlock_irq(&bd->lock);
return mask;
}
static long bsg_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct bsg_device *bd = file->private_data;
int __user *uarg = (int __user *) arg;
int ret;
switch (cmd) {
/*
* our own ioctls
*/
case SG_GET_COMMAND_Q:
return put_user(bd->max_queue, uarg);
case SG_SET_COMMAND_Q: {
int queue;
if (get_user(queue, uarg))
return -EFAULT;
if (queue < 1)
return -EINVAL;
spin_lock_irq(&bd->lock);
bd->max_queue = queue;
spin_unlock_irq(&bd->lock);
return 0;
}
/*
* SCSI/sg ioctls
*/
case SG_GET_VERSION_NUM:
case SCSI_IOCTL_GET_IDLUN:
case SCSI_IOCTL_GET_BUS_NUMBER:
case SG_SET_TIMEOUT:
case SG_GET_TIMEOUT:
case SG_GET_RESERVED_SIZE:
case SG_SET_RESERVED_SIZE:
case SG_EMULATED_HOST:
case SCSI_IOCTL_SEND_COMMAND: {
void __user *uarg = (void __user *) arg;
return scsi_cmd_ioctl(bd->queue, NULL, file->f_mode, cmd, uarg);
}
case SG_IO: {
struct request *rq;
struct bio *bio, *bidi_bio = NULL;
struct sg_io_v4 hdr;
int at_head;
u8 sense[SCSI_SENSE_BUFFERSIZE];
if (copy_from_user(&hdr, uarg, sizeof(hdr)))
return -EFAULT;
rq = bsg_map_hdr(bd, &hdr, file->f_mode & FMODE_WRITE, sense);
if (IS_ERR(rq))
return PTR_ERR(rq);
bio = rq->bio;
if (rq->next_rq)
bidi_bio = rq->next_rq->bio;
at_head = (0 == (hdr.flags & BSG_FLAG_Q_AT_TAIL));
blk_execute_rq(bd->queue, NULL, rq, at_head);
ret = blk_complete_sgv4_hdr_rq(rq, &hdr, bio, bidi_bio);
if (copy_to_user(uarg, &hdr, sizeof(hdr)))
return -EFAULT;
return ret;
}
/*
* block device ioctls
*/
default:
#if 0
return ioctl_by_bdev(bd->bdev, cmd, arg);
#else
return -ENOTTY;
#endif
}
}
static const struct file_operations bsg_fops = {
.read = bsg_read,
.write = bsg_write,
.poll = bsg_poll,
.open = bsg_open,
.release = bsg_release,
.unlocked_ioctl = bsg_ioctl,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
void bsg_unregister_queue(struct request_queue *q)
{
struct bsg_class_device *bcd = &q->bsg_dev;
if (!bcd->class_dev)
return;
mutex_lock(&bsg_mutex);
idr_remove(&bsg_minor_idr, bcd->minor);
if (q->kobj.sd)
sysfs_remove_link(&q->kobj, "bsg");
device_unregister(bcd->class_dev);
bcd->class_dev = NULL;
kref_put(&bcd->ref, bsg_kref_release_function);
mutex_unlock(&bsg_mutex);
}
EXPORT_SYMBOL_GPL(bsg_unregister_queue);
int bsg_register_queue(struct request_queue *q, struct device *parent,
const char *name, void (*release)(struct device *))
{
struct bsg_class_device *bcd;
dev_t dev;
int ret;
struct device *class_dev = NULL;
const char *devname;
if (name)
devname = name;
else
devname = dev_name(parent);
/*
* we need a proper transport to send commands, not a stacked device
*/
if (!queue_is_rq_based(q))
return 0;
bcd = &q->bsg_dev;
memset(bcd, 0, sizeof(*bcd));
mutex_lock(&bsg_mutex);
ret = idr_alloc(&bsg_minor_idr, bcd, 0, BSG_MAX_DEVS, GFP_KERNEL);
if (ret < 0) {
if (ret == -ENOSPC) {
printk(KERN_ERR "bsg: too many bsg devices\n");
ret = -EINVAL;
}
goto unlock;
}
bcd->minor = ret;
bcd->queue = q;
bcd->parent = get_device(parent);
bcd->release = release;
kref_init(&bcd->ref);
dev = MKDEV(bsg_major, bcd->minor);
class_dev = device_create(bsg_class, parent, dev, NULL, "%s", devname);
if (IS_ERR(class_dev)) {
ret = PTR_ERR(class_dev);
goto put_dev;
}
bcd->class_dev = class_dev;
if (q->kobj.sd) {
ret = sysfs_create_link(&q->kobj, &bcd->class_dev->kobj, "bsg");
if (ret)
goto unregister_class_dev;
}
mutex_unlock(&bsg_mutex);
return 0;
unregister_class_dev:
device_unregister(class_dev);
put_dev:
put_device(parent);
idr_remove(&bsg_minor_idr, bcd->minor);
unlock:
mutex_unlock(&bsg_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(bsg_register_queue);
static struct cdev bsg_cdev;
static char *bsg_devnode(struct device *dev, umode_t *mode)
{
return kasprintf(GFP_KERNEL, "bsg/%s", dev_name(dev));
}
static int __init bsg_init(void)
{
int ret, i;
dev_t devid;
bsg_cmd_cachep = kmem_cache_create("bsg_cmd",
sizeof(struct bsg_command), 0, 0, NULL);
if (!bsg_cmd_cachep) {
printk(KERN_ERR "bsg: failed creating slab cache\n");
return -ENOMEM;
}
for (i = 0; i < BSG_LIST_ARRAY_SIZE; i++)
INIT_HLIST_HEAD(&bsg_device_list[i]);
bsg_class = class_create(THIS_MODULE, "bsg");
if (IS_ERR(bsg_class)) {
ret = PTR_ERR(bsg_class);
goto destroy_kmemcache;
}
bsg_class->devnode = bsg_devnode;
ret = alloc_chrdev_region(&devid, 0, BSG_MAX_DEVS, "bsg");
if (ret)
goto destroy_bsg_class;
bsg_major = MAJOR(devid);
cdev_init(&bsg_cdev, &bsg_fops);
ret = cdev_add(&bsg_cdev, MKDEV(bsg_major, 0), BSG_MAX_DEVS);
if (ret)
goto unregister_chrdev;
printk(KERN_INFO BSG_DESCRIPTION " version " BSG_VERSION
" loaded (major %d)\n", bsg_major);
return 0;
unregister_chrdev:
unregister_chrdev_region(MKDEV(bsg_major, 0), BSG_MAX_DEVS);
destroy_bsg_class:
class_destroy(bsg_class);
destroy_kmemcache:
kmem_cache_destroy(bsg_cmd_cachep);
return ret;
}
MODULE_AUTHOR("Jens Axboe");
MODULE_DESCRIPTION(BSG_DESCRIPTION);
MODULE_LICENSE("GPL");
device_initcall(bsg_init);
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_4797_0 |
crossvul-cpp_data_bad_2993_0 | /*
* This is a module which is used for setting the MSS option in TCP packets.
*
* Copyright (C) 2000 Marc Boucher <marc@mbsi.ca>
* Copyright (C) 2007 Patrick McHardy <kaber@trash.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/gfp.h>
#include <linux/ipv6.h>
#include <linux/tcp.h>
#include <net/dst.h>
#include <net/flow.h>
#include <net/ipv6.h>
#include <net/route.h>
#include <net/tcp.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include <linux/netfilter_ipv6/ip6_tables.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter/xt_tcpudp.h>
#include <linux/netfilter/xt_TCPMSS.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Marc Boucher <marc@mbsi.ca>");
MODULE_DESCRIPTION("Xtables: TCP Maximum Segment Size (MSS) adjustment");
MODULE_ALIAS("ipt_TCPMSS");
MODULE_ALIAS("ip6t_TCPMSS");
static inline unsigned int
optlen(const u_int8_t *opt, unsigned int offset)
{
/* Beware zero-length options: make finite progress */
if (opt[offset] <= TCPOPT_NOP || opt[offset+1] == 0)
return 1;
else
return opt[offset+1];
}
static u_int32_t tcpmss_reverse_mtu(struct net *net,
const struct sk_buff *skb,
unsigned int family)
{
struct flowi fl;
const struct nf_afinfo *ai;
struct rtable *rt = NULL;
u_int32_t mtu = ~0U;
if (family == PF_INET) {
struct flowi4 *fl4 = &fl.u.ip4;
memset(fl4, 0, sizeof(*fl4));
fl4->daddr = ip_hdr(skb)->saddr;
} else {
struct flowi6 *fl6 = &fl.u.ip6;
memset(fl6, 0, sizeof(*fl6));
fl6->daddr = ipv6_hdr(skb)->saddr;
}
rcu_read_lock();
ai = nf_get_afinfo(family);
if (ai != NULL)
ai->route(net, (struct dst_entry **)&rt, &fl, false);
rcu_read_unlock();
if (rt != NULL) {
mtu = dst_mtu(&rt->dst);
dst_release(&rt->dst);
}
return mtu;
}
static int
tcpmss_mangle_packet(struct sk_buff *skb,
const struct xt_action_param *par,
unsigned int family,
unsigned int tcphoff,
unsigned int minlen)
{
const struct xt_tcpmss_info *info = par->targinfo;
struct tcphdr *tcph;
int len, tcp_hdrlen;
unsigned int i;
__be16 oldval;
u16 newmss;
u8 *opt;
/* This is a fragment, no TCP header is available */
if (par->fragoff != 0)
return 0;
if (!skb_make_writable(skb, skb->len))
return -1;
len = skb->len - tcphoff;
if (len < (int)sizeof(struct tcphdr))
return -1;
tcph = (struct tcphdr *)(skb_network_header(skb) + tcphoff);
tcp_hdrlen = tcph->doff * 4;
if (len < tcp_hdrlen)
return -1;
if (info->mss == XT_TCPMSS_CLAMP_PMTU) {
struct net *net = xt_net(par);
unsigned int in_mtu = tcpmss_reverse_mtu(net, skb, family);
unsigned int min_mtu = min(dst_mtu(skb_dst(skb)), in_mtu);
if (min_mtu <= minlen) {
net_err_ratelimited("unknown or invalid path-MTU (%u)\n",
min_mtu);
return -1;
}
newmss = min_mtu - minlen;
} else
newmss = info->mss;
opt = (u_int8_t *)tcph;
for (i = sizeof(struct tcphdr); i <= tcp_hdrlen - TCPOLEN_MSS; i += optlen(opt, i)) {
if (opt[i] == TCPOPT_MSS && opt[i+1] == TCPOLEN_MSS) {
u_int16_t oldmss;
oldmss = (opt[i+2] << 8) | opt[i+3];
/* Never increase MSS, even when setting it, as
* doing so results in problems for hosts that rely
* on MSS being set correctly.
*/
if (oldmss <= newmss)
return 0;
opt[i+2] = (newmss & 0xff00) >> 8;
opt[i+3] = newmss & 0x00ff;
inet_proto_csum_replace2(&tcph->check, skb,
htons(oldmss), htons(newmss),
false);
return 0;
}
}
/* There is data after the header so the option can't be added
* without moving it, and doing so may make the SYN packet
* itself too large. Accept the packet unmodified instead.
*/
if (len > tcp_hdrlen)
return 0;
/*
* MSS Option not found ?! add it..
*/
if (skb_tailroom(skb) < TCPOLEN_MSS) {
if (pskb_expand_head(skb, 0,
TCPOLEN_MSS - skb_tailroom(skb),
GFP_ATOMIC))
return -1;
tcph = (struct tcphdr *)(skb_network_header(skb) + tcphoff);
}
skb_put(skb, TCPOLEN_MSS);
/*
* IPv4: RFC 1122 states "If an MSS option is not received at
* connection setup, TCP MUST assume a default send MSS of 536".
* IPv6: RFC 2460 states IPv6 has a minimum MTU of 1280 and a minimum
* length IPv6 header of 60, ergo the default MSS value is 1220
* Since no MSS was provided, we must use the default values
*/
if (xt_family(par) == NFPROTO_IPV4)
newmss = min(newmss, (u16)536);
else
newmss = min(newmss, (u16)1220);
opt = (u_int8_t *)tcph + sizeof(struct tcphdr);
memmove(opt + TCPOLEN_MSS, opt, len - sizeof(struct tcphdr));
inet_proto_csum_replace2(&tcph->check, skb,
htons(len), htons(len + TCPOLEN_MSS), true);
opt[0] = TCPOPT_MSS;
opt[1] = TCPOLEN_MSS;
opt[2] = (newmss & 0xff00) >> 8;
opt[3] = newmss & 0x00ff;
inet_proto_csum_replace4(&tcph->check, skb, 0, *((__be32 *)opt), false);
oldval = ((__be16 *)tcph)[6];
tcph->doff += TCPOLEN_MSS/4;
inet_proto_csum_replace2(&tcph->check, skb,
oldval, ((__be16 *)tcph)[6], false);
return TCPOLEN_MSS;
}
static unsigned int
tcpmss_tg4(struct sk_buff *skb, const struct xt_action_param *par)
{
struct iphdr *iph = ip_hdr(skb);
__be16 newlen;
int ret;
ret = tcpmss_mangle_packet(skb, par,
PF_INET,
iph->ihl * 4,
sizeof(*iph) + sizeof(struct tcphdr));
if (ret < 0)
return NF_DROP;
if (ret > 0) {
iph = ip_hdr(skb);
newlen = htons(ntohs(iph->tot_len) + ret);
csum_replace2(&iph->check, iph->tot_len, newlen);
iph->tot_len = newlen;
}
return XT_CONTINUE;
}
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
static unsigned int
tcpmss_tg6(struct sk_buff *skb, const struct xt_action_param *par)
{
struct ipv6hdr *ipv6h = ipv6_hdr(skb);
u8 nexthdr;
__be16 frag_off, oldlen, newlen;
int tcphoff;
int ret;
nexthdr = ipv6h->nexthdr;
tcphoff = ipv6_skip_exthdr(skb, sizeof(*ipv6h), &nexthdr, &frag_off);
if (tcphoff < 0)
return NF_DROP;
ret = tcpmss_mangle_packet(skb, par,
PF_INET6,
tcphoff,
sizeof(*ipv6h) + sizeof(struct tcphdr));
if (ret < 0)
return NF_DROP;
if (ret > 0) {
ipv6h = ipv6_hdr(skb);
oldlen = ipv6h->payload_len;
newlen = htons(ntohs(oldlen) + ret);
if (skb->ip_summed == CHECKSUM_COMPLETE)
skb->csum = csum_add(csum_sub(skb->csum, oldlen),
newlen);
ipv6h->payload_len = newlen;
}
return XT_CONTINUE;
}
#endif
/* Must specify -p tcp --syn */
static inline bool find_syn_match(const struct xt_entry_match *m)
{
const struct xt_tcp *tcpinfo = (const struct xt_tcp *)m->data;
if (strcmp(m->u.kernel.match->name, "tcp") == 0 &&
tcpinfo->flg_cmp & TCPHDR_SYN &&
!(tcpinfo->invflags & XT_TCP_INV_FLAGS))
return true;
return false;
}
static int tcpmss_tg4_check(const struct xt_tgchk_param *par)
{
const struct xt_tcpmss_info *info = par->targinfo;
const struct ipt_entry *e = par->entryinfo;
const struct xt_entry_match *ematch;
if (info->mss == XT_TCPMSS_CLAMP_PMTU &&
(par->hook_mask & ~((1 << NF_INET_FORWARD) |
(1 << NF_INET_LOCAL_OUT) |
(1 << NF_INET_POST_ROUTING))) != 0) {
pr_info("path-MTU clamping only supported in "
"FORWARD, OUTPUT and POSTROUTING hooks\n");
return -EINVAL;
}
if (par->nft_compat)
return 0;
xt_ematch_foreach(ematch, e)
if (find_syn_match(ematch))
return 0;
pr_info("Only works on TCP SYN packets\n");
return -EINVAL;
}
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
static int tcpmss_tg6_check(const struct xt_tgchk_param *par)
{
const struct xt_tcpmss_info *info = par->targinfo;
const struct ip6t_entry *e = par->entryinfo;
const struct xt_entry_match *ematch;
if (info->mss == XT_TCPMSS_CLAMP_PMTU &&
(par->hook_mask & ~((1 << NF_INET_FORWARD) |
(1 << NF_INET_LOCAL_OUT) |
(1 << NF_INET_POST_ROUTING))) != 0) {
pr_info("path-MTU clamping only supported in "
"FORWARD, OUTPUT and POSTROUTING hooks\n");
return -EINVAL;
}
if (par->nft_compat)
return 0;
xt_ematch_foreach(ematch, e)
if (find_syn_match(ematch))
return 0;
pr_info("Only works on TCP SYN packets\n");
return -EINVAL;
}
#endif
static struct xt_target tcpmss_tg_reg[] __read_mostly = {
{
.family = NFPROTO_IPV4,
.name = "TCPMSS",
.checkentry = tcpmss_tg4_check,
.target = tcpmss_tg4,
.targetsize = sizeof(struct xt_tcpmss_info),
.proto = IPPROTO_TCP,
.me = THIS_MODULE,
},
#if IS_ENABLED(CONFIG_IP6_NF_IPTABLES)
{
.family = NFPROTO_IPV6,
.name = "TCPMSS",
.checkentry = tcpmss_tg6_check,
.target = tcpmss_tg6,
.targetsize = sizeof(struct xt_tcpmss_info),
.proto = IPPROTO_TCP,
.me = THIS_MODULE,
},
#endif
};
static int __init tcpmss_tg_init(void)
{
return xt_register_targets(tcpmss_tg_reg, ARRAY_SIZE(tcpmss_tg_reg));
}
static void __exit tcpmss_tg_exit(void)
{
xt_unregister_targets(tcpmss_tg_reg, ARRAY_SIZE(tcpmss_tg_reg));
}
module_init(tcpmss_tg_init);
module_exit(tcpmss_tg_exit);
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_2993_0 |
crossvul-cpp_data_bad_1006_0 | 404: Not Found | ./CrossVul/dataset_final_sorted/CWE-416/c/bad_1006_0 |
crossvul-cpp_data_bad_4230_0 | /*
** $Id: ldo.c $
** Stack and Call structure of Lua
** See Copyright Notice in lua.h
*/
#define ldo_c
#define LUA_CORE
#include "lprefix.h"
#include <setjmp.h>
#include <stdlib.h>
#include <string.h>
#include "lua.h"
#include "lapi.h"
#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lgc.h"
#include "lmem.h"
#include "lobject.h"
#include "lopcodes.h"
#include "lparser.h"
#include "lstate.h"
#include "lstring.h"
#include "ltable.h"
#include "ltm.h"
#include "lundump.h"
#include "lvm.h"
#include "lzio.h"
#define errorstatus(s) ((s) > LUA_YIELD)
/*
** {======================================================
** Error-recovery functions
** =======================================================
*/
/*
** LUAI_THROW/LUAI_TRY define how Lua does exception handling. By
** default, Lua handles errors with exceptions when compiling as
** C++ code, with _longjmp/_setjmp when asked to use them, and with
** longjmp/setjmp otherwise.
*/
#if !defined(LUAI_THROW) /* { */
#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP) /* { */
/* C++ exceptions */
#define LUAI_THROW(L,c) throw(c)
#define LUAI_TRY(L,c,a) \
try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; }
#define luai_jmpbuf int /* dummy variable */
#elif defined(LUA_USE_POSIX) /* }{ */
/* in POSIX, try _longjmp/_setjmp (more efficient) */
#define LUAI_THROW(L,c) _longjmp((c)->b, 1)
#define LUAI_TRY(L,c,a) if (_setjmp((c)->b) == 0) { a }
#define luai_jmpbuf jmp_buf
#else /* }{ */
/* ISO C handling with long jumps */
#define LUAI_THROW(L,c) longjmp((c)->b, 1)
#define LUAI_TRY(L,c,a) if (setjmp((c)->b) == 0) { a }
#define luai_jmpbuf jmp_buf
#endif /* } */
#endif /* } */
/* chain list of long jump buffers */
struct lua_longjmp {
struct lua_longjmp *previous;
luai_jmpbuf b;
volatile int status; /* error code */
};
void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) {
switch (errcode) {
case LUA_ERRMEM: { /* memory error? */
setsvalue2s(L, oldtop, G(L)->memerrmsg); /* reuse preregistered msg. */
break;
}
case LUA_ERRERR: {
setsvalue2s(L, oldtop, luaS_newliteral(L, "error in error handling"));
break;
}
case CLOSEPROTECT: {
setnilvalue(s2v(oldtop)); /* no error message */
break;
}
default: {
setobjs2s(L, oldtop, L->top - 1); /* error message on current top */
break;
}
}
L->top = oldtop + 1;
}
l_noret luaD_throw (lua_State *L, int errcode) {
if (L->errorJmp) { /* thread has an error handler? */
L->errorJmp->status = errcode; /* set status */
LUAI_THROW(L, L->errorJmp); /* jump to it */
}
else { /* thread has no error handler */
global_State *g = G(L);
errcode = luaF_close(L, L->stack, errcode); /* close all upvalues */
L->status = cast_byte(errcode); /* mark it as dead */
if (g->mainthread->errorJmp) { /* main thread has a handler? */
setobjs2s(L, g->mainthread->top++, L->top - 1); /* copy error obj. */
luaD_throw(g->mainthread, errcode); /* re-throw in main thread */
}
else { /* no handler at all; abort */
if (g->panic) { /* panic function? */
luaD_seterrorobj(L, errcode, L->top); /* assume EXTRA_STACK */
if (L->ci->top < L->top)
L->ci->top = L->top; /* pushing msg. can break this invariant */
lua_unlock(L);
g->panic(L); /* call panic function (last chance to jump out) */
}
abort();
}
}
}
int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
global_State *g = G(L);
l_uint32 oldnCcalls = g->Cstacklimit - (L->nCcalls + L->nci);
struct lua_longjmp lj;
lj.status = LUA_OK;
lj.previous = L->errorJmp; /* chain new error handler */
L->errorJmp = &lj;
LUAI_TRY(L, &lj,
(*f)(L, ud);
);
L->errorJmp = lj.previous; /* restore old error handler */
L->nCcalls = g->Cstacklimit - oldnCcalls - L->nci;
return lj.status;
}
/* }====================================================== */
/*
** {==================================================================
** Stack reallocation
** ===================================================================
*/
static void correctstack (lua_State *L, StkId oldstack, StkId newstack) {
CallInfo *ci;
UpVal *up;
if (oldstack == newstack)
return; /* stack address did not change */
L->top = (L->top - oldstack) + newstack;
for (up = L->openupval; up != NULL; up = up->u.open.next)
up->v = s2v((uplevel(up) - oldstack) + newstack);
for (ci = L->ci; ci != NULL; ci = ci->previous) {
ci->top = (ci->top - oldstack) + newstack;
ci->func = (ci->func - oldstack) + newstack;
if (isLua(ci))
ci->u.l.trap = 1; /* signal to update 'trap' in 'luaV_execute' */
}
}
/* some space for error handling */
#define ERRORSTACKSIZE (LUAI_MAXSTACK + 200)
int luaD_reallocstack (lua_State *L, int newsize, int raiseerror) {
int lim = L->stacksize;
StkId newstack = luaM_reallocvector(L, L->stack, lim, newsize, StackValue);
lua_assert(newsize <= LUAI_MAXSTACK || newsize == ERRORSTACKSIZE);
lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK);
if (unlikely(newstack == NULL)) { /* reallocation failed? */
if (raiseerror)
luaM_error(L);
else return 0; /* do not raise an error */
}
for (; lim < newsize; lim++)
setnilvalue(s2v(newstack + lim)); /* erase new segment */
correctstack(L, L->stack, newstack);
L->stack = newstack;
L->stacksize = newsize;
L->stack_last = L->stack + newsize - EXTRA_STACK;
return 1;
}
/*
** Try to grow the stack by at least 'n' elements. when 'raiseerror'
** is true, raises any error; otherwise, return 0 in case of errors.
*/
int luaD_growstack (lua_State *L, int n, int raiseerror) {
int size = L->stacksize;
int newsize = 2 * size; /* tentative new size */
if (unlikely(size > LUAI_MAXSTACK)) { /* need more space after extra size? */
if (raiseerror)
luaD_throw(L, LUA_ERRERR); /* error inside message handler */
else return 0;
}
else {
int needed = cast_int(L->top - L->stack) + n + EXTRA_STACK;
if (newsize > LUAI_MAXSTACK) /* cannot cross the limit */
newsize = LUAI_MAXSTACK;
if (newsize < needed) /* but must respect what was asked for */
newsize = needed;
if (unlikely(newsize > LUAI_MAXSTACK)) { /* stack overflow? */
/* add extra size to be able to handle the error message */
luaD_reallocstack(L, ERRORSTACKSIZE, raiseerror);
if (raiseerror)
luaG_runerror(L, "stack overflow");
else return 0;
}
} /* else no errors */
return luaD_reallocstack(L, newsize, raiseerror);
}
static int stackinuse (lua_State *L) {
CallInfo *ci;
StkId lim = L->top;
for (ci = L->ci; ci != NULL; ci = ci->previous) {
if (lim < ci->top) lim = ci->top;
}
lua_assert(lim <= L->stack_last);
return cast_int(lim - L->stack) + 1; /* part of stack in use */
}
void luaD_shrinkstack (lua_State *L) {
int inuse = stackinuse(L);
int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;
if (goodsize > LUAI_MAXSTACK)
goodsize = LUAI_MAXSTACK; /* respect stack limit */
/* if thread is currently not handling a stack overflow and its
good size is smaller than current size, shrink its stack */
if (inuse <= (LUAI_MAXSTACK - EXTRA_STACK) &&
goodsize < L->stacksize)
luaD_reallocstack(L, goodsize, 0); /* ok if that fails */
else /* don't change stack */
condmovestack(L,{},{}); /* (change only for debugging) */
luaE_shrinkCI(L); /* shrink CI list */
}
void luaD_inctop (lua_State *L) {
luaD_checkstack(L, 1);
L->top++;
}
/* }================================================================== */
/*
** Call a hook for the given event. Make sure there is a hook to be
** called. (Both 'L->hook' and 'L->hookmask', which trigger this
** function, can be changed asynchronously by signals.)
*/
void luaD_hook (lua_State *L, int event, int line,
int ftransfer, int ntransfer) {
lua_Hook hook = L->hook;
if (hook && L->allowhook) { /* make sure there is a hook */
int mask = CIST_HOOKED;
CallInfo *ci = L->ci;
ptrdiff_t top = savestack(L, L->top);
ptrdiff_t ci_top = savestack(L, ci->top);
lua_Debug ar;
ar.event = event;
ar.currentline = line;
ar.i_ci = ci;
if (ntransfer != 0) {
mask |= CIST_TRAN; /* 'ci' has transfer information */
ci->u2.transferinfo.ftransfer = ftransfer;
ci->u2.transferinfo.ntransfer = ntransfer;
}
luaD_checkstack(L, LUA_MINSTACK); /* ensure minimum stack size */
if (L->top + LUA_MINSTACK > ci->top)
ci->top = L->top + LUA_MINSTACK;
L->allowhook = 0; /* cannot call hooks inside a hook */
ci->callstatus |= mask;
lua_unlock(L);
(*hook)(L, &ar);
lua_lock(L);
lua_assert(!L->allowhook);
L->allowhook = 1;
ci->top = restorestack(L, ci_top);
L->top = restorestack(L, top);
ci->callstatus &= ~mask;
}
}
/*
** Executes a call hook for Lua functions. This function is called
** whenever 'hookmask' is not zero, so it checks whether call hooks are
** active.
*/
void luaD_hookcall (lua_State *L, CallInfo *ci) {
int hook = (ci->callstatus & CIST_TAIL) ? LUA_HOOKTAILCALL : LUA_HOOKCALL;
Proto *p;
if (!(L->hookmask & LUA_MASKCALL)) /* some other hook? */
return; /* don't call hook */
p = clLvalue(s2v(ci->func))->p;
L->top = ci->top; /* prepare top */
ci->u.l.savedpc++; /* hooks assume 'pc' is already incremented */
luaD_hook(L, hook, -1, 1, p->numparams);
ci->u.l.savedpc--; /* correct 'pc' */
}
static StkId rethook (lua_State *L, CallInfo *ci, StkId firstres, int nres) {
ptrdiff_t oldtop = savestack(L, L->top); /* hook may change top */
int delta = 0;
if (isLuacode(ci)) {
Proto *p = clLvalue(s2v(ci->func))->p;
if (p->is_vararg)
delta = ci->u.l.nextraargs + p->numparams + 1;
if (L->top < ci->top)
L->top = ci->top; /* correct top to run hook */
}
if (L->hookmask & LUA_MASKRET) { /* is return hook on? */
int ftransfer;
ci->func += delta; /* if vararg, back to virtual 'func' */
ftransfer = cast(unsigned short, firstres - ci->func);
luaD_hook(L, LUA_HOOKRET, -1, ftransfer, nres); /* call it */
ci->func -= delta;
}
if (isLua(ci->previous))
L->oldpc = ci->previous->u.l.savedpc; /* update 'oldpc' */
return restorestack(L, oldtop);
}
/*
** Check whether 'func' has a '__call' metafield. If so, put it in the
** stack, below original 'func', so that 'luaD_call' can call it. Raise
** an error if there is no '__call' metafield.
*/
void luaD_tryfuncTM (lua_State *L, StkId func) {
const TValue *tm = luaT_gettmbyobj(L, s2v(func), TM_CALL);
StkId p;
if (unlikely(ttisnil(tm)))
luaG_typeerror(L, s2v(func), "call"); /* nothing to call */
for (p = L->top; p > func; p--) /* open space for metamethod */
setobjs2s(L, p, p-1);
L->top++; /* stack space pre-allocated by the caller */
setobj2s(L, func, tm); /* metamethod is the new function to be called */
}
/*
** Given 'nres' results at 'firstResult', move 'wanted' of them to 'res'.
** Handle most typical cases (zero results for commands, one result for
** expressions, multiple results for tail calls/single parameters)
** separated.
*/
static void moveresults (lua_State *L, StkId res, int nres, int wanted) {
StkId firstresult;
int i;
switch (wanted) { /* handle typical cases separately */
case 0: /* no values needed */
L->top = res;
return;
case 1: /* one value needed */
if (nres == 0) /* no results? */
setnilvalue(s2v(res)); /* adjust with nil */
else
setobjs2s(L, res, L->top - nres); /* move it to proper place */
L->top = res + 1;
return;
case LUA_MULTRET:
wanted = nres; /* we want all results */
break;
default: /* multiple results (or to-be-closed variables) */
if (hastocloseCfunc(wanted)) { /* to-be-closed variables? */
ptrdiff_t savedres = savestack(L, res);
luaF_close(L, res, LUA_OK); /* may change the stack */
res = restorestack(L, savedres);
wanted = codeNresults(wanted); /* correct value */
if (wanted == LUA_MULTRET)
wanted = nres;
}
break;
}
firstresult = L->top - nres; /* index of first result */
/* move all results to correct place */
for (i = 0; i < nres && i < wanted; i++)
setobjs2s(L, res + i, firstresult + i);
for (; i < wanted; i++) /* complete wanted number of results */
setnilvalue(s2v(res + i));
L->top = res + wanted; /* top points after the last result */
}
/*
** Finishes a function call: calls hook if necessary, removes CallInfo,
** moves current number of results to proper place.
*/
void luaD_poscall (lua_State *L, CallInfo *ci, int nres) {
if (L->hookmask)
L->top = rethook(L, ci, L->top - nres, nres);
L->ci = ci->previous; /* back to caller */
/* move results to proper place */
moveresults(L, ci->func, nres, ci->nresults);
}
#define next_ci(L) (L->ci->next ? L->ci->next : luaE_extendCI(L))
/*
** Prepare a function for a tail call, building its call info on top
** of the current call info. 'narg1' is the number of arguments plus 1
** (so that it includes the function itself).
*/
void luaD_pretailcall (lua_State *L, CallInfo *ci, StkId func, int narg1) {
Proto *p = clLvalue(s2v(func))->p;
int fsize = p->maxstacksize; /* frame size */
int nfixparams = p->numparams;
int i;
for (i = 0; i < narg1; i++) /* move down function and arguments */
setobjs2s(L, ci->func + i, func + i);
checkstackGC(L, fsize);
func = ci->func; /* moved-down function */
for (; narg1 <= nfixparams; narg1++)
setnilvalue(s2v(func + narg1)); /* complete missing arguments */
ci->top = func + 1 + fsize; /* top for new function */
lua_assert(ci->top <= L->stack_last);
ci->u.l.savedpc = p->code; /* starting point */
ci->callstatus |= CIST_TAIL;
L->top = func + narg1; /* set top */
}
/*
** Call a function (C or Lua). The function to be called is at *func.
** The arguments are on the stack, right after the function.
** When returns, all the results are on the stack, starting at the original
** function position.
*/
void luaD_call (lua_State *L, StkId func, int nresults) {
lua_CFunction f;
retry:
switch (ttypetag(s2v(func))) {
case LUA_VCCL: /* C closure */
f = clCvalue(s2v(func))->f;
goto Cfunc;
case LUA_VLCF: /* light C function */
f = fvalue(s2v(func));
Cfunc: {
int n; /* number of returns */
CallInfo *ci = next_ci(L);
checkstackp(L, LUA_MINSTACK, func); /* ensure minimum stack size */
ci->nresults = nresults;
ci->callstatus = CIST_C;
ci->top = L->top + LUA_MINSTACK;
ci->func = func;
L->ci = ci;
lua_assert(ci->top <= L->stack_last);
if (L->hookmask & LUA_MASKCALL) {
int narg = cast_int(L->top - func) - 1;
luaD_hook(L, LUA_HOOKCALL, -1, 1, narg);
}
lua_unlock(L);
n = (*f)(L); /* do the actual call */
lua_lock(L);
api_checknelems(L, n);
luaD_poscall(L, ci, n);
break;
}
case LUA_VLCL: { /* Lua function */
CallInfo *ci = next_ci(L);
Proto *p = clLvalue(s2v(func))->p;
int narg = cast_int(L->top - func) - 1; /* number of real arguments */
int nfixparams = p->numparams;
int fsize = p->maxstacksize; /* frame size */
checkstackp(L, fsize, func);
ci->nresults = nresults;
ci->u.l.savedpc = p->code; /* starting point */
ci->callstatus = 0;
ci->top = func + 1 + fsize;
ci->func = func;
L->ci = ci;
for (; narg < nfixparams; narg++)
setnilvalue(s2v(L->top++)); /* complete missing arguments */
lua_assert(ci->top <= L->stack_last);
luaV_execute(L, ci); /* run the function */
break;
}
default: { /* not a function */
checkstackp(L, 1, func); /* space for metamethod */
luaD_tryfuncTM(L, func); /* try to get '__call' metamethod */
goto retry; /* try again with metamethod */
}
}
}
/*
** Similar to 'luaD_call', but does not allow yields during the call.
** If there is a stack overflow, freeing all CI structures will
** force the subsequent call to invoke 'luaE_extendCI', which then
** will raise any errors.
*/
void luaD_callnoyield (lua_State *L, StkId func, int nResults) {
incXCcalls(L);
if (getCcalls(L) <= CSTACKERR) /* possible stack overflow? */
luaE_freeCI(L);
luaD_call(L, func, nResults);
decXCcalls(L);
}
/*
** Completes the execution of an interrupted C function, calling its
** continuation function.
*/
static void finishCcall (lua_State *L, int status) {
CallInfo *ci = L->ci;
int n;
/* must have a continuation and must be able to call it */
lua_assert(ci->u.c.k != NULL && yieldable(L));
/* error status can only happen in a protected call */
lua_assert((ci->callstatus & CIST_YPCALL) || status == LUA_YIELD);
if (ci->callstatus & CIST_YPCALL) { /* was inside a pcall? */
ci->callstatus &= ~CIST_YPCALL; /* continuation is also inside it */
L->errfunc = ci->u.c.old_errfunc; /* with the same error function */
}
/* finish 'lua_callk'/'lua_pcall'; CIST_YPCALL and 'errfunc' already
handled */
adjustresults(L, ci->nresults);
lua_unlock(L);
n = (*ci->u.c.k)(L, status, ci->u.c.ctx); /* call continuation function */
lua_lock(L);
api_checknelems(L, n);
luaD_poscall(L, ci, n); /* finish 'luaD_call' */
}
/*
** Executes "full continuation" (everything in the stack) of a
** previously interrupted coroutine until the stack is empty (or another
** interruption long-jumps out of the loop). If the coroutine is
** recovering from an error, 'ud' points to the error status, which must
** be passed to the first continuation function (otherwise the default
** status is LUA_YIELD).
*/
static void unroll (lua_State *L, void *ud) {
CallInfo *ci;
if (ud != NULL) /* error status? */
finishCcall(L, *(int *)ud); /* finish 'lua_pcallk' callee */
while ((ci = L->ci) != &L->base_ci) { /* something in the stack */
if (!isLua(ci)) /* C function? */
finishCcall(L, LUA_YIELD); /* complete its execution */
else { /* Lua function */
luaV_finishOp(L); /* finish interrupted instruction */
luaV_execute(L, ci); /* execute down to higher C 'boundary' */
}
}
}
/*
** Try to find a suspended protected call (a "recover point") for the
** given thread.
*/
static CallInfo *findpcall (lua_State *L) {
CallInfo *ci;
for (ci = L->ci; ci != NULL; ci = ci->previous) { /* search for a pcall */
if (ci->callstatus & CIST_YPCALL)
return ci;
}
return NULL; /* no pending pcall */
}
/*
** Recovers from an error in a coroutine. Finds a recover point (if
** there is one) and completes the execution of the interrupted
** 'luaD_pcall'. If there is no recover point, returns zero.
*/
static int recover (lua_State *L, int status) {
StkId oldtop;
CallInfo *ci = findpcall(L);
if (ci == NULL) return 0; /* no recovery point */
/* "finish" luaD_pcall */
oldtop = restorestack(L, ci->u2.funcidx);
luaF_close(L, oldtop, status); /* may change the stack */
oldtop = restorestack(L, ci->u2.funcidx);
luaD_seterrorobj(L, status, oldtop);
L->ci = ci;
L->allowhook = getoah(ci->callstatus); /* restore original 'allowhook' */
luaD_shrinkstack(L);
L->errfunc = ci->u.c.old_errfunc;
return 1; /* continue running the coroutine */
}
/*
** Signal an error in the call to 'lua_resume', not in the execution
** of the coroutine itself. (Such errors should not be handled by any
** coroutine error handler and should not kill the coroutine.)
*/
static int resume_error (lua_State *L, const char *msg, int narg) {
L->top -= narg; /* remove args from the stack */
setsvalue2s(L, L->top, luaS_new(L, msg)); /* push error message */
api_incr_top(L);
lua_unlock(L);
return LUA_ERRRUN;
}
/*
** Do the work for 'lua_resume' in protected mode. Most of the work
** depends on the status of the coroutine: initial state, suspended
** inside a hook, or regularly suspended (optionally with a continuation
** function), plus erroneous cases: non-suspended coroutine or dead
** coroutine.
*/
static void resume (lua_State *L, void *ud) {
int n = *(cast(int*, ud)); /* number of arguments */
StkId firstArg = L->top - n; /* first argument */
CallInfo *ci = L->ci;
if (L->status == LUA_OK) { /* starting a coroutine? */
luaD_call(L, firstArg - 1, LUA_MULTRET);
}
else { /* resuming from previous yield */
lua_assert(L->status == LUA_YIELD);
L->status = LUA_OK; /* mark that it is running (again) */
if (isLua(ci)) /* yielded inside a hook? */
luaV_execute(L, ci); /* just continue running Lua code */
else { /* 'common' yield */
if (ci->u.c.k != NULL) { /* does it have a continuation function? */
lua_unlock(L);
n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
lua_lock(L);
api_checknelems(L, n);
}
luaD_poscall(L, ci, n); /* finish 'luaD_call' */
}
unroll(L, NULL); /* run continuation */
}
}
LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs,
int *nresults) {
int status;
lua_lock(L);
if (L->status == LUA_OK) { /* may be starting a coroutine */
if (L->ci != &L->base_ci) /* not in base level? */
return resume_error(L, "cannot resume non-suspended coroutine", nargs);
else if (L->top - (L->ci->func + 1) == nargs) /* no function? */
return resume_error(L, "cannot resume dead coroutine", nargs);
}
else if (L->status != LUA_YIELD) /* ended with errors? */
return resume_error(L, "cannot resume dead coroutine", nargs);
if (from == NULL)
L->nCcalls = CSTACKTHREAD;
else /* correct 'nCcalls' for this thread */
L->nCcalls = getCcalls(from) + from->nci - L->nci - CSTACKCF;
if (L->nCcalls <= CSTACKERR)
return resume_error(L, "C stack overflow", nargs);
luai_userstateresume(L, nargs);
api_checknelems(L, (L->status == LUA_OK) ? nargs + 1 : nargs);
status = luaD_rawrunprotected(L, resume, &nargs);
/* continue running after recoverable errors */
while (errorstatus(status) && recover(L, status)) {
/* unroll continuation */
status = luaD_rawrunprotected(L, unroll, &status);
}
if (likely(!errorstatus(status)))
lua_assert(status == L->status); /* normal end or yield */
else { /* unrecoverable error */
L->status = cast_byte(status); /* mark thread as 'dead' */
luaD_seterrorobj(L, status, L->top); /* push error message */
L->ci->top = L->top;
}
*nresults = (status == LUA_YIELD) ? L->ci->u2.nyield
: cast_int(L->top - (L->ci->func + 1));
lua_unlock(L);
return status;
}
LUA_API int lua_isyieldable (lua_State *L) {
return yieldable(L);
}
LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
lua_KFunction k) {
CallInfo *ci = L->ci;
luai_userstateyield(L, nresults);
lua_lock(L);
api_checknelems(L, nresults);
if (unlikely(!yieldable(L))) {
if (L != G(L)->mainthread)
luaG_runerror(L, "attempt to yield across a C-call boundary");
else
luaG_runerror(L, "attempt to yield from outside a coroutine");
}
L->status = LUA_YIELD;
if (isLua(ci)) { /* inside a hook? */
lua_assert(!isLuacode(ci));
api_check(L, k == NULL, "hooks cannot continue after yielding");
ci->u2.nyield = 0; /* no results */
}
else {
if ((ci->u.c.k = k) != NULL) /* is there a continuation? */
ci->u.c.ctx = ctx; /* save context */
ci->u2.nyield = nresults; /* save number of results */
luaD_throw(L, LUA_YIELD);
}
lua_assert(ci->callstatus & CIST_HOOKED); /* must be inside a hook */
lua_unlock(L);
return 0; /* return to 'luaD_hook' */
}
/*
** Call the C function 'func' in protected mode, restoring basic
** thread information ('allowhook', etc.) and in particular
** its stack level in case of errors.
*/
int luaD_pcall (lua_State *L, Pfunc func, void *u,
ptrdiff_t old_top, ptrdiff_t ef) {
int status;
CallInfo *old_ci = L->ci;
lu_byte old_allowhooks = L->allowhook;
ptrdiff_t old_errfunc = L->errfunc;
L->errfunc = ef;
status = luaD_rawrunprotected(L, func, u);
if (unlikely(status != LUA_OK)) { /* an error occurred? */
StkId oldtop = restorestack(L, old_top);
L->ci = old_ci;
L->allowhook = old_allowhooks;
status = luaF_close(L, oldtop, status);
oldtop = restorestack(L, old_top); /* previous call may change stack */
luaD_seterrorobj(L, status, oldtop);
luaD_shrinkstack(L);
}
L->errfunc = old_errfunc;
return status;
}
/*
** Execute a protected parser.
*/
struct SParser { /* data to 'f_parser' */
ZIO *z;
Mbuffer buff; /* dynamic structure used by the scanner */
Dyndata dyd; /* dynamic structures used by the parser */
const char *mode;
const char *name;
};
static void checkmode (lua_State *L, const char *mode, const char *x) {
if (mode && strchr(mode, x[0]) == NULL) {
luaO_pushfstring(L,
"attempt to load a %s chunk (mode is '%s')", x, mode);
luaD_throw(L, LUA_ERRSYNTAX);
}
}
static void f_parser (lua_State *L, void *ud) {
LClosure *cl;
struct SParser *p = cast(struct SParser *, ud);
int c = zgetc(p->z); /* read first character */
if (c == LUA_SIGNATURE[0]) {
checkmode(L, p->mode, "binary");
cl = luaU_undump(L, p->z, p->name);
}
else {
checkmode(L, p->mode, "text");
cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
}
lua_assert(cl->nupvalues == cl->p->sizeupvalues);
luaF_initupvals(L, cl);
}
int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
const char *mode) {
struct SParser p;
int status;
incnny(L); /* cannot yield during parsing */
p.z = z; p.name = name; p.mode = mode;
p.dyd.actvar.arr = NULL; p.dyd.actvar.size = 0;
p.dyd.gt.arr = NULL; p.dyd.gt.size = 0;
p.dyd.label.arr = NULL; p.dyd.label.size = 0;
luaZ_initbuffer(L, &p.buff);
status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
luaZ_freebuffer(L, &p.buff);
luaM_freearray(L, p.dyd.actvar.arr, p.dyd.actvar.size);
luaM_freearray(L, p.dyd.gt.arr, p.dyd.gt.size);
luaM_freearray(L, p.dyd.label.arr, p.dyd.label.size);
decnny(L);
return status;
}
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_4230_0 |
crossvul-cpp_data_bad_1390_0 | /* libcomps - C alternative to yum.comps library
* Copyright (C) 2013 Jindrich Luza
*
* 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
* 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 Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA
*/
#include "comps_mradix.h"
#include <stdio.h>
void comps_mrtree_data_destroy(COMPS_MRTreeData * rtd) {
free(rtd->key);
comps_hslist_destroy(&rtd->data);
comps_hslist_destroy(&rtd->subnodes);
free(rtd);
}
inline void comps_mrtree_data_destroy_v(void * rtd) {
comps_mrtree_data_destroy((COMPS_MRTreeData*)rtd);
}
COMPS_MRTreeData * comps_mrtree_data_create_n(COMPS_MRTree * tree, char * key,
size_t keylen, void * data) {
COMPS_MRTreeData * rtd;
if ((rtd = malloc(sizeof(*rtd))) == NULL)
return NULL;
if ((rtd->key = malloc(sizeof(char) * (keylen+1))) == NULL) {
free(rtd);
return NULL;
}
memcpy(rtd->key, key, sizeof(char)*keylen);
rtd->key[keylen] = 0;
rtd->is_leaf = 1;
rtd->data = comps_hslist_create();
comps_hslist_init(rtd->data, NULL, tree->data_cloner,
tree->data_destructor);
if (data)
comps_hslist_append(rtd->data, data, 0);
rtd->subnodes = comps_hslist_create();
comps_hslist_init(rtd->subnodes, NULL,
NULL,
&comps_mrtree_data_destroy_v);
return rtd;
}
COMPS_MRTreeData * comps_mrtree_data_create(COMPS_MRTree * tree,
char * key, void * data) {
return comps_mrtree_data_create_n(tree, key, strlen(key), data);
}
COMPS_MRTree * comps_mrtree_create(void* (*data_constructor)(void*),
void* (*data_cloner)(void*),
void (*data_destructor)(void*)) {
COMPS_MRTree *ret;
if ((ret = malloc(sizeof(COMPS_MRTree))) == NULL)
return NULL;
ret->subnodes = comps_hslist_create();
comps_hslist_init(ret->subnodes, NULL, NULL, &comps_mrtree_data_destroy_v);
if (ret->subnodes == NULL) {
free(ret);
return NULL;
}
ret->data_constructor = data_constructor;
ret->data_cloner = data_cloner;
ret->data_destructor = data_destructor;
return ret;
}
void comps_mrtree_destroy(COMPS_MRTree * rt) {
comps_hslist_destroy(&(rt->subnodes));
free(rt);
}
void comps_mrtree_print(COMPS_HSList * hl, unsigned deep) {
COMPS_HSListItem * it;
for (it = hl->first; it != NULL; it=it->next) {
printf("%d %s\n",deep, (((COMPS_MRTreeData*)it->data)->key));
comps_mrtree_print(((COMPS_MRTreeData*)it->data)->subnodes, deep+1);
}
}
void comps_mrtree_values_walk(COMPS_MRTree * rt, void* udata,
void (*walk_f)(void*, void*)) {
COMPS_HSList *tmplist, *tmp_subnodes;
COMPS_HSListItem *it, *it2;
tmplist = comps_hslist_create();
comps_hslist_init(tmplist, NULL, NULL, NULL);
comps_hslist_append(tmplist, rt->subnodes, 0);
while (tmplist->first != NULL) {
it = tmplist->first;
comps_hslist_remove(tmplist, tmplist->first);
tmp_subnodes = (COMPS_HSList*)it->data;
free(it);
for (it = tmp_subnodes->first; it != NULL; it=it->next) {
if (((COMPS_MRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist,
((COMPS_MRTreeData*)it->data)->subnodes, 0);
}
for (it2 = (COMPS_HSListItem*)((COMPS_MRTreeData*)it->data)->data->first;
it2 != NULL; it2 = it2->next) {
walk_f(udata, it2->data);
}
}
}
comps_hslist_destroy(&tmplist);
}
COMPS_MRTree * comps_mrtree_clone(COMPS_MRTree * rt) {
COMPS_HSList * to_clone, *tmplist, *new_subnodes;
COMPS_MRTree * ret;
COMPS_HSListItem *it, *it2;
COMPS_MRTreeData *rtdata;
COMPS_HSList *new_data_list;
to_clone = comps_hslist_create();
comps_hslist_init(to_clone, NULL, NULL, NULL);
ret = comps_mrtree_create(rt->data_constructor, rt->data_cloner,
rt->data_destructor);
for (it = rt->subnodes->first; it != NULL; it = it->next) {
rtdata = comps_mrtree_data_create(rt,
((COMPS_MRTreeData*)it->data)->key, NULL);
new_data_list = comps_hslist_clone(((COMPS_MRTreeData*)it->data)->data);
comps_hslist_destroy(&rtdata->data);
comps_hslist_destroy(&rtdata->subnodes);
rtdata->subnodes = ((COMPS_MRTreeData*)it->data)->subnodes;
rtdata->data = new_data_list;
comps_hslist_append(ret->subnodes, rtdata, 0);
comps_hslist_append(to_clone, rtdata, 0);
}
while (to_clone->first) {
it2 = to_clone->first;
tmplist = ((COMPS_MRTreeData*)it2->data)->subnodes;
comps_hslist_remove(to_clone, to_clone->first);
new_subnodes = comps_hslist_create();
comps_hslist_init(new_subnodes, NULL, NULL, &comps_mrtree_data_destroy_v);
for (it = tmplist->first; it != NULL; it = it->next) {
rtdata = comps_mrtree_data_create(rt,
((COMPS_MRTreeData*)it->data)->key, NULL);
new_data_list = comps_hslist_clone(((COMPS_MRTreeData*)it->data)->data);
comps_hslist_destroy(&rtdata->subnodes);
comps_hslist_destroy(&rtdata->data);
rtdata->subnodes = ((COMPS_MRTreeData*)it->data)->subnodes;
rtdata->data = new_data_list;
comps_hslist_append(new_subnodes, rtdata, 0);
comps_hslist_append(to_clone, rtdata, 0);
}
((COMPS_MRTreeData*)it2->data)->subnodes = new_subnodes;
free(it2);
}
comps_hslist_destroy(&to_clone);
return ret;
}
void comps_mrtree_unite(COMPS_MRTree *rt1, COMPS_MRTree *rt2) {
COMPS_HSList *tmplist, *tmp_subnodes;
COMPS_HSListItem *it, *it2;
struct Pair {
COMPS_HSList * subnodes;
char * key;
char added;
} *pair, *parent_pair;
pair = malloc(sizeof(struct Pair));
pair->subnodes = rt2->subnodes;
pair->key = NULL;
tmplist = comps_hslist_create();
comps_hslist_init(tmplist, NULL, NULL, &free);
comps_hslist_append(tmplist, pair, 0);
while (tmplist->first != NULL) {
it = tmplist->first;
comps_hslist_remove(tmplist, tmplist->first);
tmp_subnodes = ((struct Pair*)it->data)->subnodes;
parent_pair = (struct Pair*) it->data;
free(it);
pair->added = 0;
for (it = tmp_subnodes->first; it != NULL; it=it->next) {
pair = malloc(sizeof(struct Pair));
pair->subnodes = ((COMPS_MRTreeData*)it->data)->subnodes;
if (parent_pair->key != NULL) {
pair->key =
malloc(sizeof(char)
* (strlen(((COMPS_MRTreeData*)it->data)->key)
+ strlen(parent_pair->key) + 1));
memcpy(pair->key, parent_pair->key,
sizeof(char) * strlen(parent_pair->key));
memcpy(pair->key+strlen(parent_pair->key),
((COMPS_MRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_MRTreeData*)it->data)->key)+1));
} else {
pair->key = malloc(sizeof(char)*
(strlen(((COMPS_MRTreeData*)it->data)->key) +
1));
memcpy(pair->key, ((COMPS_MRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_MRTreeData*)it->data)->key)+1));
}
/* current node has data */
if (((COMPS_MRTreeData*)it->data)->data->first != NULL) {
for (it2 = ((COMPS_MRTreeData*)it->data)->data->first;
it2 != NULL; it2 = it2->next) {
comps_mrtree_set(rt1, pair->key, it2->data);
}
if (((COMPS_MRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair->key);
free(pair);
}
/* current node hasn't data */
} else {
if (((COMPS_MRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair->key);
free(pair);
}
}
}
free(parent_pair->key);
free(parent_pair);
}
comps_hslist_destroy(&tmplist);
}
COMPS_HSList* comps_mrtree_keys(COMPS_MRTree * rt) {
COMPS_HSList *tmplist, *tmp_subnodes, *ret;
COMPS_HSListItem *it;
struct Pair {
COMPS_HSList * subnodes;
char * key;
char added;
} *pair, *parent_pair;
pair = malloc(sizeof(struct Pair));
pair->subnodes = rt->subnodes;
pair->key = NULL;
pair->added = 0;
tmplist = comps_hslist_create();
comps_hslist_init(tmplist, NULL, NULL, &free);
ret = comps_hslist_create();
comps_hslist_init(ret, NULL, NULL, &free);
comps_hslist_append(tmplist, pair, 0);
while (tmplist->first != NULL) {
it = tmplist->first;
comps_hslist_remove(tmplist, tmplist->first);
tmp_subnodes = ((struct Pair*)it->data)->subnodes;
parent_pair = (struct Pair*) it->data;
free(it);
for (it = tmp_subnodes->first; it != NULL; it=it->next) {
pair = malloc(sizeof(struct Pair));
pair->subnodes = ((COMPS_MRTreeData*)it->data)->subnodes;
pair->added = 0;
if (parent_pair->key != NULL) {
pair->key =
malloc(sizeof(char)
* (strlen(((COMPS_MRTreeData*)it->data)->key)
+ strlen(parent_pair->key) + 1));
memcpy(pair->key, parent_pair->key,
sizeof(char) * strlen(parent_pair->key));
memcpy(pair->key+strlen(parent_pair->key),
((COMPS_MRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_MRTreeData*)it->data)->key)+1));
} else {
pair->key = malloc(sizeof(char)*
(strlen(((COMPS_MRTreeData*)it->data)->key) +
1));
memcpy(pair->key, ((COMPS_MRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_MRTreeData*)it->data)->key)+1));
}
/* current node has data */
if (((COMPS_MRTreeData*)it->data)->data->first != NULL) {
//printf("data not null for |%s|\n", pair->key);
comps_hslist_append(ret, pair->key, 0);
pair->added = 1;
if (((COMPS_MRTreeData*)it->data)->subnodes->first != NULL) {
// printf("subnodes found\b");
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair);
}
/* current node hasn't data */
} else {
if (((COMPS_MRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair->key);
free(pair);
}
}
}
if (parent_pair->added == 0)
free(parent_pair->key);
free(parent_pair);
}
comps_hslist_destroy(&tmplist);
return ret;
}
void __comps_mrtree_set(COMPS_MRTree * rt, char * key, size_t len, void * data)
{
static COMPS_HSListItem *it;
COMPS_HSList *subnodes;
COMPS_MRTreeData *rtd;
static COMPS_MRTreeData *rtdata;
size_t _len, offset=0;
unsigned x, found = 0;
void *ndata;
char ended;//, tmpch;
if (rt->subnodes == NULL)
return;
if (rt->data_constructor)
ndata = rt->data_constructor(data);
else
ndata = data;
subnodes = rt->subnodes;
while (offset != len)
{
found = 0;
for (it = subnodes->first; it != NULL; it=it->next) {
if (((COMPS_MRTreeData*)it->data)->key[0] == key[offset]) {
found = 1;
break;
}
}
if (!found) { // not found in subnodes; create new subnode
rtd = comps_mrtree_data_create(rt, key+offset, ndata);
comps_hslist_append(subnodes, rtd, 0);
return;
} else {
rtdata = (COMPS_MRTreeData*)it->data;
ended = 0;
for (x=1; ;x++) {
if (rtdata->key[x] == 0) ended += 1;
if (x == len - offset) ended += 2;
if (ended != 0) break;
if (key[offset+x] != rtdata->key[x]) break;
}
if (ended == 3) { //keys equals; append new data
comps_hslist_append(rtdata->data, ndata, 0);
return;
} else if (ended == 2) { //global key ends first; make global leaf
comps_hslist_remove(subnodes, it);
it->next = NULL;
rtd = comps_mrtree_data_create(rt, key+offset, ndata);
comps_hslist_append(subnodes, rtd, 0);
((COMPS_MRTreeData*)subnodes->last->data)->subnodes->last = it;
((COMPS_MRTreeData*)subnodes->last->data)->subnodes->first = it;
_len = strlen(key + offset);
memmove(rtdata->key,rtdata->key+_len, strlen(rtdata->key) - _len);
rtdata->key[strlen(rtdata->key) - _len] = 0;
rtdata->key = realloc(rtdata->key,
sizeof(char)* (strlen(rtdata->key)+1));
return;
} else if (ended == 1) { //local key ends first; go deeper
subnodes = rtdata->subnodes;
offset += x;
} else { /* keys differ */
void *tmpdata = rtdata->data;
COMPS_HSList *tmpnodes = rtdata->subnodes;
int cmpret = strcmp(key+offset+x, rtdata->key+x);
rtdata->subnodes = comps_hslist_create();
comps_hslist_init(rtdata->subnodes, NULL, NULL,
&comps_mrtree_data_destroy_v);
rtdata->data = NULL;
if (cmpret > 0) {
rtd = comps_mrtree_data_create(rt, rtdata->key+x, tmpdata);
comps_hslist_destroy(&rtd->subnodes);
rtd->subnodes = tmpnodes;
comps_hslist_append(rtdata->subnodes, rtd, 0);
rtd = comps_mrtree_data_create(rt, key+offset+x, ndata);
comps_hslist_append(rtdata->subnodes, rtd, 0);
} else {
rtd = comps_mrtree_data_create(rt, key+offset+x, ndata);
comps_hslist_append(rtdata->subnodes, rtd, 0);
rtd = comps_mrtree_data_create(rt, rtdata->key+x, tmpdata);
comps_hslist_destroy(&rtd->subnodes);
rtd->subnodes = tmpnodes;
comps_hslist_append(rtdata->subnodes, rtd, 0);
}
rtdata->key = realloc(rtdata->key, sizeof(char)*(x+1));
rtdata->key[x] = 0;
return;
}
}
}
}
void comps_mrtree_set(COMPS_MRTree * rt, char * key, void * data)
{
__comps_mrtree_set(rt, key, strlen(key), data);
}
void comps_mrtree_set_n(COMPS_MRTree * rt, char * key, size_t len, void * data)
{
__comps_mrtree_set(rt, key, len, data);
}
COMPS_HSList * comps_mrtree_get(COMPS_MRTree * rt, const char * key) {
COMPS_HSList * subnodes;
COMPS_HSListItem * it = NULL;
COMPS_MRTreeData * rtdata;
unsigned int offset, len, x;
char found, ended;
len = strlen(key);
offset = 0;
subnodes = rt->subnodes;
while (offset != len) {
found = 0;
for (it = subnodes->first; it != NULL; it=it->next) {
if (((COMPS_MRTreeData*)it->data)->key[0] == key[offset]) {
found = 1;
break;
}
}
if (!found)
return NULL;
rtdata = (COMPS_MRTreeData*)it->data;
for (x=1; ;x++) {
ended=0;
if (rtdata->key[x] == 0) ended += 1;
if (x == len - offset) ended += 2;
if (ended != 0) break;
if (key[offset+x] != rtdata->key[x]) break;
}
if (ended == 3) return rtdata->data;
else if (ended == 1) offset+=x;
else return NULL;
subnodes = ((COMPS_MRTreeData*)it->data)->subnodes;
}
if (it)
return ((COMPS_MRTreeData*)it->data)->data;
else return NULL;
}
COMPS_HSList ** comps_mrtree_getp(COMPS_MRTree * rt, const char * key) {
COMPS_HSList * subnodes;
COMPS_HSListItem * it = NULL;
COMPS_MRTreeData * rtdata;
unsigned int offset, len, x;
char found, ended;
len = strlen(key);
offset = 0;
subnodes = rt->subnodes;
while (offset != len) {
found = 0;
for (it = subnodes->first; it != NULL; it=it->next) {
if (((COMPS_MRTreeData*)it->data)->key[0] == key[offset]) {
found = 1;
break;
}
}
if (!found)
return NULL;
rtdata = (COMPS_MRTreeData*)it->data;
for (x=1; ;x++) {
ended=0;
if (rtdata->key[x] == 0) ended += 1;
if (x == len - offset) ended += 2;
if (ended != 0) break;
if (key[offset+x] != rtdata->key[x]) break;
}
if (ended == 3) return &rtdata->data;
else if (ended == 1) offset+=x;
else return NULL;
subnodes = ((COMPS_MRTreeData*)it->data)->subnodes;
}
if (it)
return &((COMPS_MRTreeData*)it->data)->data;
else return NULL;
}
void comps_mrtree_unset(COMPS_MRTree * rt, const char * key) {
COMPS_HSList * subnodes;
COMPS_HSListItem * it;
COMPS_MRTreeData * rtdata;
unsigned int offset, len, x;
char found, ended;
COMPS_HSList * path;
struct Relation {
COMPS_HSList * parent_nodes;
COMPS_HSListItem * child_it;
} *relation;
path = comps_hslist_create();
comps_hslist_init(path, NULL, NULL, &free);
len = strlen(key);
offset = 0;
subnodes = rt->subnodes;
while (offset != len) {
found = 0;
for (it = subnodes->first; it != NULL; it=it->next) {
if (((COMPS_MRTreeData*)it->data)->key[0] == key[offset]) {
found = 1;
break;
}
}
if (!found) {
comps_hslist_destroy(&path);
return;
}
rtdata = (COMPS_MRTreeData*)it->data;
for (x=1; ;x++) {
ended=0;
if (rtdata->key[x] == 0) ended += 1;
if (x == len - offset) ended += 2;
if (ended != 0) break;
if (key[offset+x] != rtdata->key[x]) break;
}
if (ended == 3) {
/* remove node from tree only if there's no descendant*/
if (rtdata->subnodes->last == NULL) {
printf("removing all\n");
comps_hslist_remove(subnodes, it);
comps_mrtree_data_destroy(rtdata);
free(it);
}
else {
printf("removing data only\n");
comps_hslist_clear(rtdata->data);
rtdata->is_leaf = 0;
}
if (path->last == NULL) {
comps_hslist_destroy(&path);
return;
}
rtdata = (COMPS_MRTreeData*)
((struct Relation*)path->last->data)->child_it->data;
/*remove all predecessor of deleted node (recursive) with no childs*/
while (rtdata->subnodes->last == NULL) {
printf("removing '%s'\n", rtdata->key);
comps_mrtree_data_destroy(rtdata);
comps_hslist_remove(
((struct Relation*)path->last->data)->parent_nodes,
((struct Relation*)path->last->data)->child_it);
free(((struct Relation*)path->last->data)->child_it);
it = path->last;
comps_hslist_remove(path, path->last);
free(it);
rtdata = (COMPS_MRTreeData*)
((struct Relation*)path->last->data)->child_it->data;
}
comps_hslist_destroy(&path);
return;
}
else if (ended == 1) offset+=x;
else {
comps_hslist_destroy(&path);
return;
}
if ((relation = malloc(sizeof(struct Relation))) == NULL) {
comps_hslist_destroy(&path);
return;
}
subnodes = ((COMPS_MRTreeData*)it->data)->subnodes;
relation->parent_nodes = subnodes;
relation->child_it = it;
comps_hslist_append(path, (void*)relation, 0);
}
comps_hslist_destroy(&path);
return;
}
void comps_mrtree_clear(COMPS_MRTree * rt) {
COMPS_HSListItem *it, *oldit;
if (rt == NULL) return;
if (rt->subnodes == NULL) return;
oldit = rt->subnodes->first;
it = (oldit)?oldit->next:NULL;
for (;it != NULL; it=it->next) {
if (rt->subnodes->data_destructor != NULL)
rt->subnodes->data_destructor(oldit->data);
free(oldit);
oldit = it;
}
if (oldit) {
if (rt->subnodes->data_destructor != NULL)
rt->subnodes->data_destructor(oldit->data);
free(oldit);
}
}
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_1390_0 |
crossvul-cpp_data_good_5021_3 | /*
* PF_INET6 socket protocol family
* Linux INET6 implementation
*
* Authors:
* Pedro Roque <roque@di.fc.ul.pt>
*
* Adapted from linux/net/ipv4/af_inet.c
*
* Fixes:
* piggy, Karl Knutson : Socket protocol table
* Hideaki YOSHIFUJI : sin6_scope_id support
* Arnaldo Melo : check proc_net_create return, cleanups
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#define pr_fmt(fmt) "IPv6: " fmt
#include <linux/module.h>
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/proc_fs.h>
#include <linux/stat.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/icmpv6.h>
#include <linux/netfilter_ipv6.h>
#include <net/ip.h>
#include <net/ipv6.h>
#include <net/udp.h>
#include <net/udplite.h>
#include <net/tcp.h>
#include <net/ping.h>
#include <net/protocol.h>
#include <net/inet_common.h>
#include <net/route.h>
#include <net/transp_v6.h>
#include <net/ip6_route.h>
#include <net/addrconf.h>
#include <net/ndisc.h>
#ifdef CONFIG_IPV6_TUNNEL
#include <net/ip6_tunnel.h>
#endif
#include <asm/uaccess.h>
#include <linux/mroute6.h>
MODULE_AUTHOR("Cast of dozens");
MODULE_DESCRIPTION("IPv6 protocol stack for Linux");
MODULE_LICENSE("GPL");
/* The inetsw6 table contains everything that inet6_create needs to
* build a new socket.
*/
static struct list_head inetsw6[SOCK_MAX];
static DEFINE_SPINLOCK(inetsw6_lock);
struct ipv6_params ipv6_defaults = {
.disable_ipv6 = 0,
.autoconf = 1,
};
static int disable_ipv6_mod;
module_param_named(disable, disable_ipv6_mod, int, 0444);
MODULE_PARM_DESC(disable, "Disable IPv6 module such that it is non-functional");
module_param_named(disable_ipv6, ipv6_defaults.disable_ipv6, int, 0444);
MODULE_PARM_DESC(disable_ipv6, "Disable IPv6 on all interfaces");
module_param_named(autoconf, ipv6_defaults.autoconf, int, 0444);
MODULE_PARM_DESC(autoconf, "Enable IPv6 address autoconfiguration on all interfaces");
static __inline__ struct ipv6_pinfo *inet6_sk_generic(struct sock *sk)
{
const int offset = sk->sk_prot->obj_size - sizeof(struct ipv6_pinfo);
return (struct ipv6_pinfo *)(((u8 *)sk) + offset);
}
static int inet6_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct inet_sock *inet;
struct ipv6_pinfo *np;
struct sock *sk;
struct inet_protosw *answer;
struct proto *answer_prot;
unsigned char answer_flags;
int try_loading_module = 0;
int err;
/* Look for the requested type/protocol pair. */
lookup_protocol:
err = -ESOCKTNOSUPPORT;
rcu_read_lock();
list_for_each_entry_rcu(answer, &inetsw6[sock->type], list) {
err = 0;
/* Check the non-wild match. */
if (protocol == answer->protocol) {
if (protocol != IPPROTO_IP)
break;
} else {
/* Check for the two wild cases. */
if (IPPROTO_IP == protocol) {
protocol = answer->protocol;
break;
}
if (IPPROTO_IP == answer->protocol)
break;
}
err = -EPROTONOSUPPORT;
}
if (err) {
if (try_loading_module < 2) {
rcu_read_unlock();
/*
* Be more specific, e.g. net-pf-10-proto-132-type-1
* (net-pf-PF_INET6-proto-IPPROTO_SCTP-type-SOCK_STREAM)
*/
if (++try_loading_module == 1)
request_module("net-pf-%d-proto-%d-type-%d",
PF_INET6, protocol, sock->type);
/*
* Fall back to generic, e.g. net-pf-10-proto-132
* (net-pf-PF_INET6-proto-IPPROTO_SCTP)
*/
else
request_module("net-pf-%d-proto-%d",
PF_INET6, protocol);
goto lookup_protocol;
} else
goto out_rcu_unlock;
}
err = -EPERM;
if (sock->type == SOCK_RAW && !kern &&
!ns_capable(net->user_ns, CAP_NET_RAW))
goto out_rcu_unlock;
sock->ops = answer->ops;
answer_prot = answer->prot;
answer_flags = answer->flags;
rcu_read_unlock();
WARN_ON(!answer_prot->slab);
err = -ENOBUFS;
sk = sk_alloc(net, PF_INET6, GFP_KERNEL, answer_prot, kern);
if (!sk)
goto out;
sock_init_data(sock, sk);
err = 0;
if (INET_PROTOSW_REUSE & answer_flags)
sk->sk_reuse = SK_CAN_REUSE;
inet = inet_sk(sk);
inet->is_icsk = (INET_PROTOSW_ICSK & answer_flags) != 0;
if (SOCK_RAW == sock->type) {
inet->inet_num = protocol;
if (IPPROTO_RAW == protocol)
inet->hdrincl = 1;
}
sk->sk_destruct = inet_sock_destruct;
sk->sk_family = PF_INET6;
sk->sk_protocol = protocol;
sk->sk_backlog_rcv = answer->prot->backlog_rcv;
inet_sk(sk)->pinet6 = np = inet6_sk_generic(sk);
np->hop_limit = -1;
np->mcast_hops = IPV6_DEFAULT_MCASTHOPS;
np->mc_loop = 1;
np->pmtudisc = IPV6_PMTUDISC_WANT;
np->autoflowlabel = ip6_default_np_autolabel(sock_net(sk));
sk->sk_ipv6only = net->ipv6.sysctl.bindv6only;
/* Init the ipv4 part of the socket since we can have sockets
* using v6 API for ipv4.
*/
inet->uc_ttl = -1;
inet->mc_loop = 1;
inet->mc_ttl = 1;
inet->mc_index = 0;
inet->mc_list = NULL;
inet->rcv_tos = 0;
if (net->ipv4.sysctl_ip_no_pmtu_disc)
inet->pmtudisc = IP_PMTUDISC_DONT;
else
inet->pmtudisc = IP_PMTUDISC_WANT;
/*
* Increment only the relevant sk_prot->socks debug field, this changes
* the previous behaviour of incrementing both the equivalent to
* answer->prot->socks (inet6_sock_nr) and inet_sock_nr.
*
* This allows better debug granularity as we'll know exactly how many
* UDPv6, TCPv6, etc socks were allocated, not the sum of all IPv6
* transport protocol socks. -acme
*/
sk_refcnt_debug_inc(sk);
if (inet->inet_num) {
/* It assumes that any protocol which allows
* the user to assign a number at socket
* creation time automatically shares.
*/
inet->inet_sport = htons(inet->inet_num);
sk->sk_prot->hash(sk);
}
if (sk->sk_prot->init) {
err = sk->sk_prot->init(sk);
if (err) {
sk_common_release(sk);
goto out;
}
}
out:
return err;
out_rcu_unlock:
rcu_read_unlock();
goto out;
}
/* bind for INET6 API */
int inet6_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sockaddr_in6 *addr = (struct sockaddr_in6 *)uaddr;
struct sock *sk = sock->sk;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct net *net = sock_net(sk);
__be32 v4addr = 0;
unsigned short snum;
int addr_type = 0;
int err = 0;
/* If the socket has its own bind function then use it. */
if (sk->sk_prot->bind)
return sk->sk_prot->bind(sk, uaddr, addr_len);
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (addr->sin6_family != AF_INET6)
return -EAFNOSUPPORT;
addr_type = ipv6_addr_type(&addr->sin6_addr);
if ((addr_type & IPV6_ADDR_MULTICAST) && sock->type == SOCK_STREAM)
return -EINVAL;
snum = ntohs(addr->sin6_port);
if (snum && snum < PROT_SOCK && !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE))
return -EACCES;
lock_sock(sk);
/* Check these errors (active socket, double bind). */
if (sk->sk_state != TCP_CLOSE || inet->inet_num) {
err = -EINVAL;
goto out;
}
/* Check if the address belongs to the host. */
if (addr_type == IPV6_ADDR_MAPPED) {
int chk_addr_ret;
/* Binding to v4-mapped address on a v6-only socket
* makes no sense
*/
if (sk->sk_ipv6only) {
err = -EINVAL;
goto out;
}
/* Reproduce AF_INET checks to make the bindings consistent */
v4addr = addr->sin6_addr.s6_addr32[3];
chk_addr_ret = inet_addr_type(net, v4addr);
if (!net->ipv4.sysctl_ip_nonlocal_bind &&
!(inet->freebind || inet->transparent) &&
v4addr != htonl(INADDR_ANY) &&
chk_addr_ret != RTN_LOCAL &&
chk_addr_ret != RTN_MULTICAST &&
chk_addr_ret != RTN_BROADCAST) {
err = -EADDRNOTAVAIL;
goto out;
}
} else {
if (addr_type != IPV6_ADDR_ANY) {
struct net_device *dev = NULL;
rcu_read_lock();
if (__ipv6_addr_needs_scope_id(addr_type)) {
if (addr_len >= sizeof(struct sockaddr_in6) &&
addr->sin6_scope_id) {
/* Override any existing binding, if another one
* is supplied by user.
*/
sk->sk_bound_dev_if = addr->sin6_scope_id;
}
/* Binding to link-local address requires an interface */
if (!sk->sk_bound_dev_if) {
err = -EINVAL;
goto out_unlock;
}
dev = dev_get_by_index_rcu(net, sk->sk_bound_dev_if);
if (!dev) {
err = -ENODEV;
goto out_unlock;
}
}
/* ipv4 addr of the socket is invalid. Only the
* unspecified and mapped address have a v4 equivalent.
*/
v4addr = LOOPBACK4_IPV6;
if (!(addr_type & IPV6_ADDR_MULTICAST)) {
if (!net->ipv6.sysctl.ip_nonlocal_bind &&
!(inet->freebind || inet->transparent) &&
!ipv6_chk_addr(net, &addr->sin6_addr,
dev, 0)) {
err = -EADDRNOTAVAIL;
goto out_unlock;
}
}
rcu_read_unlock();
}
}
inet->inet_rcv_saddr = v4addr;
inet->inet_saddr = v4addr;
sk->sk_v6_rcv_saddr = addr->sin6_addr;
if (!(addr_type & IPV6_ADDR_MULTICAST))
np->saddr = addr->sin6_addr;
/* Make sure we are allowed to bind here. */
if ((snum || !inet->bind_address_no_port) &&
sk->sk_prot->get_port(sk, snum)) {
inet_reset_saddr(sk);
err = -EADDRINUSE;
goto out;
}
if (addr_type != IPV6_ADDR_ANY) {
sk->sk_userlocks |= SOCK_BINDADDR_LOCK;
if (addr_type != IPV6_ADDR_MAPPED)
sk->sk_ipv6only = 1;
}
if (snum)
sk->sk_userlocks |= SOCK_BINDPORT_LOCK;
inet->inet_sport = htons(inet->inet_num);
inet->inet_dport = 0;
inet->inet_daddr = 0;
out:
release_sock(sk);
return err;
out_unlock:
rcu_read_unlock();
goto out;
}
EXPORT_SYMBOL(inet6_bind);
int inet6_release(struct socket *sock)
{
struct sock *sk = sock->sk;
if (!sk)
return -EINVAL;
/* Free mc lists */
ipv6_sock_mc_close(sk);
/* Free ac lists */
ipv6_sock_ac_close(sk);
return inet_release(sock);
}
EXPORT_SYMBOL(inet6_release);
void inet6_destroy_sock(struct sock *sk)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct sk_buff *skb;
struct ipv6_txoptions *opt;
/* Release rx options */
skb = xchg(&np->pktoptions, NULL);
if (skb)
kfree_skb(skb);
skb = xchg(&np->rxpmtu, NULL);
if (skb)
kfree_skb(skb);
/* Free flowlabels */
fl6_free_socklist(sk);
/* Free tx options */
opt = xchg((__force struct ipv6_txoptions **)&np->opt, NULL);
if (opt) {
atomic_sub(opt->tot_len, &sk->sk_omem_alloc);
txopt_put(opt);
}
}
EXPORT_SYMBOL_GPL(inet6_destroy_sock);
/*
* This does both peername and sockname.
*/
int inet6_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct sockaddr_in6 *sin = (struct sockaddr_in6 *)uaddr;
struct sock *sk = sock->sk;
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
sin->sin6_family = AF_INET6;
sin->sin6_flowinfo = 0;
sin->sin6_scope_id = 0;
if (peer) {
if (!inet->inet_dport)
return -ENOTCONN;
if (((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_SYN_SENT)) &&
peer == 1)
return -ENOTCONN;
sin->sin6_port = inet->inet_dport;
sin->sin6_addr = sk->sk_v6_daddr;
if (np->sndflow)
sin->sin6_flowinfo = np->flow_label;
} else {
if (ipv6_addr_any(&sk->sk_v6_rcv_saddr))
sin->sin6_addr = np->saddr;
else
sin->sin6_addr = sk->sk_v6_rcv_saddr;
sin->sin6_port = inet->inet_sport;
}
sin->sin6_scope_id = ipv6_iface_scope_id(&sin->sin6_addr,
sk->sk_bound_dev_if);
*uaddr_len = sizeof(*sin);
return 0;
}
EXPORT_SYMBOL(inet6_getname);
int inet6_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
switch (cmd) {
case SIOCGSTAMP:
return sock_get_timestamp(sk, (struct timeval __user *)arg);
case SIOCGSTAMPNS:
return sock_get_timestampns(sk, (struct timespec __user *)arg);
case SIOCADDRT:
case SIOCDELRT:
return ipv6_route_ioctl(net, cmd, (void __user *)arg);
case SIOCSIFADDR:
return addrconf_add_ifaddr(net, (void __user *) arg);
case SIOCDIFADDR:
return addrconf_del_ifaddr(net, (void __user *) arg);
case SIOCSIFDSTADDR:
return addrconf_set_dstaddr(net, (void __user *) arg);
default:
if (!sk->sk_prot->ioctl)
return -ENOIOCTLCMD;
return sk->sk_prot->ioctl(sk, cmd, arg);
}
/*NOTREACHED*/
return 0;
}
EXPORT_SYMBOL(inet6_ioctl);
const struct proto_ops inet6_stream_ops = {
.family = PF_INET6,
.owner = THIS_MODULE,
.release = inet6_release,
.bind = inet6_bind,
.connect = inet_stream_connect, /* ok */
.socketpair = sock_no_socketpair, /* a do nothing */
.accept = inet_accept, /* ok */
.getname = inet6_getname,
.poll = tcp_poll, /* ok */
.ioctl = inet6_ioctl, /* must change */
.listen = inet_listen, /* ok */
.shutdown = inet_shutdown, /* ok */
.setsockopt = sock_common_setsockopt, /* ok */
.getsockopt = sock_common_getsockopt, /* ok */
.sendmsg = inet_sendmsg, /* ok */
.recvmsg = inet_recvmsg, /* ok */
.mmap = sock_no_mmap,
.sendpage = inet_sendpage,
.splice_read = tcp_splice_read,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_sock_common_setsockopt,
.compat_getsockopt = compat_sock_common_getsockopt,
#endif
};
const struct proto_ops inet6_dgram_ops = {
.family = PF_INET6,
.owner = THIS_MODULE,
.release = inet6_release,
.bind = inet6_bind,
.connect = inet_dgram_connect, /* ok */
.socketpair = sock_no_socketpair, /* a do nothing */
.accept = sock_no_accept, /* a do nothing */
.getname = inet6_getname,
.poll = udp_poll, /* ok */
.ioctl = inet6_ioctl, /* must change */
.listen = sock_no_listen, /* ok */
.shutdown = inet_shutdown, /* ok */
.setsockopt = sock_common_setsockopt, /* ok */
.getsockopt = sock_common_getsockopt, /* ok */
.sendmsg = inet_sendmsg, /* ok */
.recvmsg = inet_recvmsg, /* ok */
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_sock_common_setsockopt,
.compat_getsockopt = compat_sock_common_getsockopt,
#endif
};
static const struct net_proto_family inet6_family_ops = {
.family = PF_INET6,
.create = inet6_create,
.owner = THIS_MODULE,
};
int inet6_register_protosw(struct inet_protosw *p)
{
struct list_head *lh;
struct inet_protosw *answer;
struct list_head *last_perm;
int protocol = p->protocol;
int ret;
spin_lock_bh(&inetsw6_lock);
ret = -EINVAL;
if (p->type >= SOCK_MAX)
goto out_illegal;
/* If we are trying to override a permanent protocol, bail. */
answer = NULL;
ret = -EPERM;
last_perm = &inetsw6[p->type];
list_for_each(lh, &inetsw6[p->type]) {
answer = list_entry(lh, struct inet_protosw, list);
/* Check only the non-wild match. */
if (INET_PROTOSW_PERMANENT & answer->flags) {
if (protocol == answer->protocol)
break;
last_perm = lh;
}
answer = NULL;
}
if (answer)
goto out_permanent;
/* Add the new entry after the last permanent entry if any, so that
* the new entry does not override a permanent entry when matched with
* a wild-card protocol. But it is allowed to override any existing
* non-permanent entry. This means that when we remove this entry, the
* system automatically returns to the old behavior.
*/
list_add_rcu(&p->list, last_perm);
ret = 0;
out:
spin_unlock_bh(&inetsw6_lock);
return ret;
out_permanent:
pr_err("Attempt to override permanent protocol %d\n", protocol);
goto out;
out_illegal:
pr_err("Ignoring attempt to register invalid socket type %d\n",
p->type);
goto out;
}
EXPORT_SYMBOL(inet6_register_protosw);
void
inet6_unregister_protosw(struct inet_protosw *p)
{
if (INET_PROTOSW_PERMANENT & p->flags) {
pr_err("Attempt to unregister permanent protocol %d\n",
p->protocol);
} else {
spin_lock_bh(&inetsw6_lock);
list_del_rcu(&p->list);
spin_unlock_bh(&inetsw6_lock);
synchronize_net();
}
}
EXPORT_SYMBOL(inet6_unregister_protosw);
int inet6_sk_rebuild_header(struct sock *sk)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct dst_entry *dst;
dst = __sk_dst_check(sk, np->dst_cookie);
if (!dst) {
struct inet_sock *inet = inet_sk(sk);
struct in6_addr *final_p, final;
struct flowi6 fl6;
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_proto = sk->sk_protocol;
fl6.daddr = sk->sk_v6_daddr;
fl6.saddr = np->saddr;
fl6.flowlabel = np->flow_label;
fl6.flowi6_oif = sk->sk_bound_dev_if;
fl6.flowi6_mark = sk->sk_mark;
fl6.fl6_dport = inet->inet_dport;
fl6.fl6_sport = inet->inet_sport;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
rcu_read_lock();
final_p = fl6_update_dst(&fl6, rcu_dereference(np->opt),
&final);
rcu_read_unlock();
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
sk->sk_route_caps = 0;
sk->sk_err_soft = -PTR_ERR(dst);
return PTR_ERR(dst);
}
__ip6_dst_store(sk, dst, NULL, NULL);
}
return 0;
}
EXPORT_SYMBOL_GPL(inet6_sk_rebuild_header);
bool ipv6_opt_accepted(const struct sock *sk, const struct sk_buff *skb,
const struct inet6_skb_parm *opt)
{
const struct ipv6_pinfo *np = inet6_sk(sk);
if (np->rxopt.all) {
if (((opt->flags & IP6SKB_HOPBYHOP) &&
(np->rxopt.bits.hopopts || np->rxopt.bits.ohopopts)) ||
(ip6_flowinfo((struct ipv6hdr *) skb_network_header(skb)) &&
np->rxopt.bits.rxflow) ||
(opt->srcrt && (np->rxopt.bits.srcrt ||
np->rxopt.bits.osrcrt)) ||
((opt->dst1 || opt->dst0) &&
(np->rxopt.bits.dstopts || np->rxopt.bits.odstopts)))
return true;
}
return false;
}
EXPORT_SYMBOL_GPL(ipv6_opt_accepted);
static struct packet_type ipv6_packet_type __read_mostly = {
.type = cpu_to_be16(ETH_P_IPV6),
.func = ipv6_rcv,
};
static int __init ipv6_packet_init(void)
{
dev_add_pack(&ipv6_packet_type);
return 0;
}
static void ipv6_packet_cleanup(void)
{
dev_remove_pack(&ipv6_packet_type);
}
static int __net_init ipv6_init_mibs(struct net *net)
{
int i;
net->mib.udp_stats_in6 = alloc_percpu(struct udp_mib);
if (!net->mib.udp_stats_in6)
return -ENOMEM;
net->mib.udplite_stats_in6 = alloc_percpu(struct udp_mib);
if (!net->mib.udplite_stats_in6)
goto err_udplite_mib;
net->mib.ipv6_statistics = alloc_percpu(struct ipstats_mib);
if (!net->mib.ipv6_statistics)
goto err_ip_mib;
for_each_possible_cpu(i) {
struct ipstats_mib *af_inet6_stats;
af_inet6_stats = per_cpu_ptr(net->mib.ipv6_statistics, i);
u64_stats_init(&af_inet6_stats->syncp);
}
net->mib.icmpv6_statistics = alloc_percpu(struct icmpv6_mib);
if (!net->mib.icmpv6_statistics)
goto err_icmp_mib;
net->mib.icmpv6msg_statistics = kzalloc(sizeof(struct icmpv6msg_mib),
GFP_KERNEL);
if (!net->mib.icmpv6msg_statistics)
goto err_icmpmsg_mib;
return 0;
err_icmpmsg_mib:
free_percpu(net->mib.icmpv6_statistics);
err_icmp_mib:
free_percpu(net->mib.ipv6_statistics);
err_ip_mib:
free_percpu(net->mib.udplite_stats_in6);
err_udplite_mib:
free_percpu(net->mib.udp_stats_in6);
return -ENOMEM;
}
static void ipv6_cleanup_mibs(struct net *net)
{
free_percpu(net->mib.udp_stats_in6);
free_percpu(net->mib.udplite_stats_in6);
free_percpu(net->mib.ipv6_statistics);
free_percpu(net->mib.icmpv6_statistics);
kfree(net->mib.icmpv6msg_statistics);
}
static int __net_init inet6_net_init(struct net *net)
{
int err = 0;
net->ipv6.sysctl.bindv6only = 0;
net->ipv6.sysctl.icmpv6_time = 1*HZ;
net->ipv6.sysctl.flowlabel_consistency = 1;
net->ipv6.sysctl.auto_flowlabels = IP6_DEFAULT_AUTO_FLOW_LABELS;
net->ipv6.sysctl.idgen_retries = 3;
net->ipv6.sysctl.idgen_delay = 1 * HZ;
net->ipv6.sysctl.flowlabel_state_ranges = 0;
atomic_set(&net->ipv6.fib6_sernum, 1);
err = ipv6_init_mibs(net);
if (err)
return err;
#ifdef CONFIG_PROC_FS
err = udp6_proc_init(net);
if (err)
goto out;
err = tcp6_proc_init(net);
if (err)
goto proc_tcp6_fail;
err = ac6_proc_init(net);
if (err)
goto proc_ac6_fail;
#endif
return err;
#ifdef CONFIG_PROC_FS
proc_ac6_fail:
tcp6_proc_exit(net);
proc_tcp6_fail:
udp6_proc_exit(net);
out:
ipv6_cleanup_mibs(net);
return err;
#endif
}
static void __net_exit inet6_net_exit(struct net *net)
{
#ifdef CONFIG_PROC_FS
udp6_proc_exit(net);
tcp6_proc_exit(net);
ac6_proc_exit(net);
#endif
ipv6_cleanup_mibs(net);
}
static struct pernet_operations inet6_net_ops = {
.init = inet6_net_init,
.exit = inet6_net_exit,
};
static const struct ipv6_stub ipv6_stub_impl = {
.ipv6_sock_mc_join = ipv6_sock_mc_join,
.ipv6_sock_mc_drop = ipv6_sock_mc_drop,
.ipv6_dst_lookup = ip6_dst_lookup,
.udpv6_encap_enable = udpv6_encap_enable,
.ndisc_send_na = ndisc_send_na,
.nd_tbl = &nd_tbl,
};
static int __init inet6_init(void)
{
struct list_head *r;
int err = 0;
sock_skb_cb_check_size(sizeof(struct inet6_skb_parm));
/* Register the socket-side information for inet6_create. */
for (r = &inetsw6[0]; r < &inetsw6[SOCK_MAX]; ++r)
INIT_LIST_HEAD(r);
if (disable_ipv6_mod) {
pr_info("Loaded, but administratively disabled, reboot required to enable\n");
goto out;
}
err = proto_register(&tcpv6_prot, 1);
if (err)
goto out;
err = proto_register(&udpv6_prot, 1);
if (err)
goto out_unregister_tcp_proto;
err = proto_register(&udplitev6_prot, 1);
if (err)
goto out_unregister_udp_proto;
err = proto_register(&rawv6_prot, 1);
if (err)
goto out_unregister_udplite_proto;
err = proto_register(&pingv6_prot, 1);
if (err)
goto out_unregister_ping_proto;
/* We MUST register RAW sockets before we create the ICMP6,
* IGMP6, or NDISC control sockets.
*/
err = rawv6_init();
if (err)
goto out_unregister_raw_proto;
/* Register the family here so that the init calls below will
* be able to create sockets. (?? is this dangerous ??)
*/
err = sock_register(&inet6_family_ops);
if (err)
goto out_sock_register_fail;
/*
* ipngwg API draft makes clear that the correct semantics
* for TCP and UDP is to consider one TCP and UDP instance
* in a host available by both INET and INET6 APIs and
* able to communicate via both network protocols.
*/
err = register_pernet_subsys(&inet6_net_ops);
if (err)
goto register_pernet_fail;
err = icmpv6_init();
if (err)
goto icmp_fail;
err = ip6_mr_init();
if (err)
goto ipmr_fail;
err = ndisc_init();
if (err)
goto ndisc_fail;
err = igmp6_init();
if (err)
goto igmp_fail;
ipv6_stub = &ipv6_stub_impl;
err = ipv6_netfilter_init();
if (err)
goto netfilter_fail;
/* Create /proc/foo6 entries. */
#ifdef CONFIG_PROC_FS
err = -ENOMEM;
if (raw6_proc_init())
goto proc_raw6_fail;
if (udplite6_proc_init())
goto proc_udplite6_fail;
if (ipv6_misc_proc_init())
goto proc_misc6_fail;
if (if6_proc_init())
goto proc_if6_fail;
#endif
err = ip6_route_init();
if (err)
goto ip6_route_fail;
err = ndisc_late_init();
if (err)
goto ndisc_late_fail;
err = ip6_flowlabel_init();
if (err)
goto ip6_flowlabel_fail;
err = addrconf_init();
if (err)
goto addrconf_fail;
/* Init v6 extension headers. */
err = ipv6_exthdrs_init();
if (err)
goto ipv6_exthdrs_fail;
err = ipv6_frag_init();
if (err)
goto ipv6_frag_fail;
/* Init v6 transport protocols. */
err = udpv6_init();
if (err)
goto udpv6_fail;
err = udplitev6_init();
if (err)
goto udplitev6_fail;
err = tcpv6_init();
if (err)
goto tcpv6_fail;
err = ipv6_packet_init();
if (err)
goto ipv6_packet_fail;
err = pingv6_init();
if (err)
goto pingv6_fail;
#ifdef CONFIG_SYSCTL
err = ipv6_sysctl_register();
if (err)
goto sysctl_fail;
#endif
out:
return err;
#ifdef CONFIG_SYSCTL
sysctl_fail:
pingv6_exit();
#endif
pingv6_fail:
ipv6_packet_cleanup();
ipv6_packet_fail:
tcpv6_exit();
tcpv6_fail:
udplitev6_exit();
udplitev6_fail:
udpv6_exit();
udpv6_fail:
ipv6_frag_exit();
ipv6_frag_fail:
ipv6_exthdrs_exit();
ipv6_exthdrs_fail:
addrconf_cleanup();
addrconf_fail:
ip6_flowlabel_cleanup();
ip6_flowlabel_fail:
ndisc_late_cleanup();
ndisc_late_fail:
ip6_route_cleanup();
ip6_route_fail:
#ifdef CONFIG_PROC_FS
if6_proc_exit();
proc_if6_fail:
ipv6_misc_proc_exit();
proc_misc6_fail:
udplite6_proc_exit();
proc_udplite6_fail:
raw6_proc_exit();
proc_raw6_fail:
#endif
ipv6_netfilter_fini();
netfilter_fail:
igmp6_cleanup();
igmp_fail:
ndisc_cleanup();
ndisc_fail:
ip6_mr_cleanup();
ipmr_fail:
icmpv6_cleanup();
icmp_fail:
unregister_pernet_subsys(&inet6_net_ops);
register_pernet_fail:
sock_unregister(PF_INET6);
rtnl_unregister_all(PF_INET6);
out_sock_register_fail:
rawv6_exit();
out_unregister_ping_proto:
proto_unregister(&pingv6_prot);
out_unregister_raw_proto:
proto_unregister(&rawv6_prot);
out_unregister_udplite_proto:
proto_unregister(&udplitev6_prot);
out_unregister_udp_proto:
proto_unregister(&udpv6_prot);
out_unregister_tcp_proto:
proto_unregister(&tcpv6_prot);
goto out;
}
module_init(inet6_init);
MODULE_ALIAS_NETPROTO(PF_INET6);
| ./CrossVul/dataset_final_sorted/CWE-416/c/good_5021_3 |
crossvul-cpp_data_bad_3175_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.
*
* PACKET - implements raw packet sockets.
*
* Authors: Ross Biro
* Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
* Alan Cox, <gw4pts@gw4pts.ampr.org>
*
* Fixes:
* Alan Cox : verify_area() now used correctly
* Alan Cox : new skbuff lists, look ma no backlogs!
* Alan Cox : tidied skbuff lists.
* Alan Cox : Now uses generic datagram routines I
* added. Also fixed the peek/read crash
* from all old Linux datagram code.
* Alan Cox : Uses the improved datagram code.
* Alan Cox : Added NULL's for socket options.
* Alan Cox : Re-commented the code.
* Alan Cox : Use new kernel side addressing
* Rob Janssen : Correct MTU usage.
* Dave Platt : Counter leaks caused by incorrect
* interrupt locking and some slightly
* dubious gcc output. Can you read
* compiler: it said _VOLATILE_
* Richard Kooijman : Timestamp fixes.
* Alan Cox : New buffers. Use sk->mac.raw.
* Alan Cox : sendmsg/recvmsg support.
* Alan Cox : Protocol setting support
* Alexey Kuznetsov : Untied from IPv4 stack.
* Cyrus Durgin : Fixed kerneld for kmod.
* Michal Ostrowski : Module initialization cleanup.
* Ulises Alonso : Frame number limit removal and
* packet_set_ring memory leak.
* Eric Biederman : Allow for > 8 byte hardware addresses.
* The convention is that longer addresses
* will simply extend the hardware address
* byte arrays at the end of sockaddr_ll
* and packet_mreq.
* Johann Baudy : Added TX RING.
* Chetan Loke : Implemented TPACKET_V3 block abstraction
* layer.
* Copyright (C) 2011, <lokec@ccs.neu.edu>
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
*/
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/capability.h>
#include <linux/fcntl.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/if_packet.h>
#include <linux/wireless.h>
#include <linux/kernel.h>
#include <linux/kmod.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <net/net_namespace.h>
#include <net/ip.h>
#include <net/protocol.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <linux/uaccess.h>
#include <asm/ioctls.h>
#include <asm/page.h>
#include <asm/cacheflush.h>
#include <asm/io.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/poll.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <linux/if_vlan.h>
#include <linux/virtio_net.h>
#include <linux/errqueue.h>
#include <linux/net_tstamp.h>
#include <linux/percpu.h>
#ifdef CONFIG_INET
#include <net/inet_common.h>
#endif
#include <linux/bpf.h>
#include <net/compat.h>
#include "internal.h"
/*
Assumptions:
- if device has no dev->hard_header routine, it adds and removes ll header
inside itself. In this case ll header is invisible outside of device,
but higher levels still should reserve dev->hard_header_len.
Some devices are enough clever to reallocate skb, when header
will not fit to reserved space (tunnel), another ones are silly
(PPP).
- packet socket receives packets with pulled ll header,
so that SOCK_RAW should push it back.
On receive:
-----------
Incoming, dev->hard_header!=NULL
mac_header -> ll header
data -> data
Outgoing, dev->hard_header!=NULL
mac_header -> ll header
data -> ll header
Incoming, dev->hard_header==NULL
mac_header -> UNKNOWN position. It is very likely, that it points to ll
header. PPP makes it, that is wrong, because introduce
assymetry between rx and tx paths.
data -> data
Outgoing, dev->hard_header==NULL
mac_header -> data. ll header is still not built!
data -> data
Resume
If dev->hard_header==NULL we are unlikely to restore sensible ll header.
On transmit:
------------
dev->hard_header != NULL
mac_header -> ll header
data -> ll header
dev->hard_header == NULL (ll header is added by device, we cannot control it)
mac_header -> data
data -> data
We should set nh.raw on output to correct posistion,
packet classifier depends on it.
*/
/* Private packet socket structures. */
/* identical to struct packet_mreq except it has
* a longer address field.
*/
struct packet_mreq_max {
int mr_ifindex;
unsigned short mr_type;
unsigned short mr_alen;
unsigned char mr_address[MAX_ADDR_LEN];
};
union tpacket_uhdr {
struct tpacket_hdr *h1;
struct tpacket2_hdr *h2;
struct tpacket3_hdr *h3;
void *raw;
};
static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
int closing, int tx_ring);
#define V3_ALIGNMENT (8)
#define BLK_HDR_LEN (ALIGN(sizeof(struct tpacket_block_desc), V3_ALIGNMENT))
#define BLK_PLUS_PRIV(sz_of_priv) \
(BLK_HDR_LEN + ALIGN((sz_of_priv), V3_ALIGNMENT))
#define PGV_FROM_VMALLOC 1
#define BLOCK_STATUS(x) ((x)->hdr.bh1.block_status)
#define BLOCK_NUM_PKTS(x) ((x)->hdr.bh1.num_pkts)
#define BLOCK_O2FP(x) ((x)->hdr.bh1.offset_to_first_pkt)
#define BLOCK_LEN(x) ((x)->hdr.bh1.blk_len)
#define BLOCK_SNUM(x) ((x)->hdr.bh1.seq_num)
#define BLOCK_O2PRIV(x) ((x)->offset_to_priv)
#define BLOCK_PRIV(x) ((void *)((char *)(x) + BLOCK_O2PRIV(x)))
struct packet_sock;
static int tpacket_snd(struct packet_sock *po, struct msghdr *msg);
static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev);
static void *packet_previous_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status);
static void packet_increment_head(struct packet_ring_buffer *buff);
static int prb_curr_blk_in_use(struct tpacket_kbdq_core *,
struct tpacket_block_desc *);
static void *prb_dispatch_next_block(struct tpacket_kbdq_core *,
struct packet_sock *);
static void prb_retire_current_block(struct tpacket_kbdq_core *,
struct packet_sock *, unsigned int status);
static int prb_queue_frozen(struct tpacket_kbdq_core *);
static void prb_open_block(struct tpacket_kbdq_core *,
struct tpacket_block_desc *);
static void prb_retire_rx_blk_timer_expired(unsigned long);
static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *);
static void prb_init_blk_timer(struct packet_sock *,
struct tpacket_kbdq_core *,
void (*func) (unsigned long));
static void prb_fill_rxhash(struct tpacket_kbdq_core *, struct tpacket3_hdr *);
static void prb_clear_rxhash(struct tpacket_kbdq_core *,
struct tpacket3_hdr *);
static void prb_fill_vlan_info(struct tpacket_kbdq_core *,
struct tpacket3_hdr *);
static void packet_flush_mclist(struct sock *sk);
struct packet_skb_cb {
union {
struct sockaddr_pkt pkt;
union {
/* Trick: alias skb original length with
* ll.sll_family and ll.protocol in order
* to save room.
*/
unsigned int origlen;
struct sockaddr_ll ll;
};
} sa;
};
#define vio_le() virtio_legacy_is_little_endian()
#define PACKET_SKB_CB(__skb) ((struct packet_skb_cb *)((__skb)->cb))
#define GET_PBDQC_FROM_RB(x) ((struct tpacket_kbdq_core *)(&(x)->prb_bdqc))
#define GET_PBLOCK_DESC(x, bid) \
((struct tpacket_block_desc *)((x)->pkbdq[(bid)].buffer))
#define GET_CURR_PBLOCK_DESC_FROM_CORE(x) \
((struct tpacket_block_desc *)((x)->pkbdq[(x)->kactive_blk_num].buffer))
#define GET_NEXT_PRB_BLK_NUM(x) \
(((x)->kactive_blk_num < ((x)->knum_blocks-1)) ? \
((x)->kactive_blk_num+1) : 0)
static void __fanout_unlink(struct sock *sk, struct packet_sock *po);
static void __fanout_link(struct sock *sk, struct packet_sock *po);
static int packet_direct_xmit(struct sk_buff *skb)
{
struct net_device *dev = skb->dev;
struct sk_buff *orig_skb = skb;
struct netdev_queue *txq;
int ret = NETDEV_TX_BUSY;
if (unlikely(!netif_running(dev) ||
!netif_carrier_ok(dev)))
goto drop;
skb = validate_xmit_skb_list(skb, dev);
if (skb != orig_skb)
goto drop;
txq = skb_get_tx_queue(dev, skb);
local_bh_disable();
HARD_TX_LOCK(dev, txq, smp_processor_id());
if (!netif_xmit_frozen_or_drv_stopped(txq))
ret = netdev_start_xmit(skb, dev, txq, false);
HARD_TX_UNLOCK(dev, txq);
local_bh_enable();
if (!dev_xmit_complete(ret))
kfree_skb(skb);
return ret;
drop:
atomic_long_inc(&dev->tx_dropped);
kfree_skb_list(skb);
return NET_XMIT_DROP;
}
static struct net_device *packet_cached_dev_get(struct packet_sock *po)
{
struct net_device *dev;
rcu_read_lock();
dev = rcu_dereference(po->cached_dev);
if (likely(dev))
dev_hold(dev);
rcu_read_unlock();
return dev;
}
static void packet_cached_dev_assign(struct packet_sock *po,
struct net_device *dev)
{
rcu_assign_pointer(po->cached_dev, dev);
}
static void packet_cached_dev_reset(struct packet_sock *po)
{
RCU_INIT_POINTER(po->cached_dev, NULL);
}
static bool packet_use_direct_xmit(const struct packet_sock *po)
{
return po->xmit == packet_direct_xmit;
}
static u16 __packet_pick_tx_queue(struct net_device *dev, struct sk_buff *skb)
{
return (u16) raw_smp_processor_id() % dev->real_num_tx_queues;
}
static void packet_pick_tx_queue(struct net_device *dev, struct sk_buff *skb)
{
const struct net_device_ops *ops = dev->netdev_ops;
u16 queue_index;
if (ops->ndo_select_queue) {
queue_index = ops->ndo_select_queue(dev, skb, NULL,
__packet_pick_tx_queue);
queue_index = netdev_cap_txqueue(dev, queue_index);
} else {
queue_index = __packet_pick_tx_queue(dev, skb);
}
skb_set_queue_mapping(skb, queue_index);
}
/* register_prot_hook must be invoked with the po->bind_lock held,
* or from a context in which asynchronous accesses to the packet
* socket is not possible (packet_create()).
*/
static void register_prot_hook(struct sock *sk)
{
struct packet_sock *po = pkt_sk(sk);
if (!po->running) {
if (po->fanout)
__fanout_link(sk, po);
else
dev_add_pack(&po->prot_hook);
sock_hold(sk);
po->running = 1;
}
}
/* {,__}unregister_prot_hook() must be invoked with the po->bind_lock
* held. If the sync parameter is true, we will temporarily drop
* the po->bind_lock and do a synchronize_net to make sure no
* asynchronous packet processing paths still refer to the elements
* of po->prot_hook. If the sync parameter is false, it is the
* callers responsibility to take care of this.
*/
static void __unregister_prot_hook(struct sock *sk, bool sync)
{
struct packet_sock *po = pkt_sk(sk);
po->running = 0;
if (po->fanout)
__fanout_unlink(sk, po);
else
__dev_remove_pack(&po->prot_hook);
__sock_put(sk);
if (sync) {
spin_unlock(&po->bind_lock);
synchronize_net();
spin_lock(&po->bind_lock);
}
}
static void unregister_prot_hook(struct sock *sk, bool sync)
{
struct packet_sock *po = pkt_sk(sk);
if (po->running)
__unregister_prot_hook(sk, sync);
}
static inline struct page * __pure pgv_to_page(void *addr)
{
if (is_vmalloc_addr(addr))
return vmalloc_to_page(addr);
return virt_to_page(addr);
}
static void __packet_set_status(struct packet_sock *po, void *frame, int status)
{
union tpacket_uhdr h;
h.raw = frame;
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_status = status;
flush_dcache_page(pgv_to_page(&h.h1->tp_status));
break;
case TPACKET_V2:
h.h2->tp_status = status;
flush_dcache_page(pgv_to_page(&h.h2->tp_status));
break;
case TPACKET_V3:
default:
WARN(1, "TPACKET version not supported.\n");
BUG();
}
smp_wmb();
}
static int __packet_get_status(struct packet_sock *po, void *frame)
{
union tpacket_uhdr h;
smp_rmb();
h.raw = frame;
switch (po->tp_version) {
case TPACKET_V1:
flush_dcache_page(pgv_to_page(&h.h1->tp_status));
return h.h1->tp_status;
case TPACKET_V2:
flush_dcache_page(pgv_to_page(&h.h2->tp_status));
return h.h2->tp_status;
case TPACKET_V3:
default:
WARN(1, "TPACKET version not supported.\n");
BUG();
return 0;
}
}
static __u32 tpacket_get_timestamp(struct sk_buff *skb, struct timespec *ts,
unsigned int flags)
{
struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
if (shhwtstamps &&
(flags & SOF_TIMESTAMPING_RAW_HARDWARE) &&
ktime_to_timespec_cond(shhwtstamps->hwtstamp, ts))
return TP_STATUS_TS_RAW_HARDWARE;
if (ktime_to_timespec_cond(skb->tstamp, ts))
return TP_STATUS_TS_SOFTWARE;
return 0;
}
static __u32 __packet_set_timestamp(struct packet_sock *po, void *frame,
struct sk_buff *skb)
{
union tpacket_uhdr h;
struct timespec ts;
__u32 ts_status;
if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
return 0;
h.raw = frame;
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_sec = ts.tv_sec;
h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
break;
case TPACKET_V2:
h.h2->tp_sec = ts.tv_sec;
h.h2->tp_nsec = ts.tv_nsec;
break;
case TPACKET_V3:
default:
WARN(1, "TPACKET version not supported.\n");
BUG();
}
/* one flush is safe, as both fields always lie on the same cacheline */
flush_dcache_page(pgv_to_page(&h.h1->tp_sec));
smp_wmb();
return ts_status;
}
static void *packet_lookup_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
unsigned int position,
int status)
{
unsigned int pg_vec_pos, frame_offset;
union tpacket_uhdr h;
pg_vec_pos = position / rb->frames_per_block;
frame_offset = position % rb->frames_per_block;
h.raw = rb->pg_vec[pg_vec_pos].buffer +
(frame_offset * rb->frame_size);
if (status != __packet_get_status(po, h.raw))
return NULL;
return h.raw;
}
static void *packet_current_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
return packet_lookup_frame(po, rb, rb->head, status);
}
static void prb_del_retire_blk_timer(struct tpacket_kbdq_core *pkc)
{
del_timer_sync(&pkc->retire_blk_timer);
}
static void prb_shutdown_retire_blk_timer(struct packet_sock *po,
struct sk_buff_head *rb_queue)
{
struct tpacket_kbdq_core *pkc;
pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
spin_lock_bh(&rb_queue->lock);
pkc->delete_blk_timer = 1;
spin_unlock_bh(&rb_queue->lock);
prb_del_retire_blk_timer(pkc);
}
static void prb_init_blk_timer(struct packet_sock *po,
struct tpacket_kbdq_core *pkc,
void (*func) (unsigned long))
{
init_timer(&pkc->retire_blk_timer);
pkc->retire_blk_timer.data = (long)po;
pkc->retire_blk_timer.function = func;
pkc->retire_blk_timer.expires = jiffies;
}
static void prb_setup_retire_blk_timer(struct packet_sock *po)
{
struct tpacket_kbdq_core *pkc;
pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
prb_init_blk_timer(po, pkc, prb_retire_rx_blk_timer_expired);
}
static int prb_calc_retire_blk_tmo(struct packet_sock *po,
int blk_size_in_bytes)
{
struct net_device *dev;
unsigned int mbits = 0, msec = 0, div = 0, tmo = 0;
struct ethtool_link_ksettings ecmd;
int err;
rtnl_lock();
dev = __dev_get_by_index(sock_net(&po->sk), po->ifindex);
if (unlikely(!dev)) {
rtnl_unlock();
return DEFAULT_PRB_RETIRE_TOV;
}
err = __ethtool_get_link_ksettings(dev, &ecmd);
rtnl_unlock();
if (!err) {
/*
* If the link speed is so slow you don't really
* need to worry about perf anyways
*/
if (ecmd.base.speed < SPEED_1000 ||
ecmd.base.speed == SPEED_UNKNOWN) {
return DEFAULT_PRB_RETIRE_TOV;
} else {
msec = 1;
div = ecmd.base.speed / 1000;
}
}
mbits = (blk_size_in_bytes * 8) / (1024 * 1024);
if (div)
mbits /= div;
tmo = mbits * msec;
if (div)
return tmo+1;
return tmo;
}
static void prb_init_ft_ops(struct tpacket_kbdq_core *p1,
union tpacket_req_u *req_u)
{
p1->feature_req_word = req_u->req3.tp_feature_req_word;
}
static void init_prb_bdqc(struct packet_sock *po,
struct packet_ring_buffer *rb,
struct pgv *pg_vec,
union tpacket_req_u *req_u)
{
struct tpacket_kbdq_core *p1 = GET_PBDQC_FROM_RB(rb);
struct tpacket_block_desc *pbd;
memset(p1, 0x0, sizeof(*p1));
p1->knxt_seq_num = 1;
p1->pkbdq = pg_vec;
pbd = (struct tpacket_block_desc *)pg_vec[0].buffer;
p1->pkblk_start = pg_vec[0].buffer;
p1->kblk_size = req_u->req3.tp_block_size;
p1->knum_blocks = req_u->req3.tp_block_nr;
p1->hdrlen = po->tp_hdrlen;
p1->version = po->tp_version;
p1->last_kactive_blk_num = 0;
po->stats.stats3.tp_freeze_q_cnt = 0;
if (req_u->req3.tp_retire_blk_tov)
p1->retire_blk_tov = req_u->req3.tp_retire_blk_tov;
else
p1->retire_blk_tov = prb_calc_retire_blk_tmo(po,
req_u->req3.tp_block_size);
p1->tov_in_jiffies = msecs_to_jiffies(p1->retire_blk_tov);
p1->blk_sizeof_priv = req_u->req3.tp_sizeof_priv;
p1->max_frame_len = p1->kblk_size - BLK_PLUS_PRIV(p1->blk_sizeof_priv);
prb_init_ft_ops(p1, req_u);
prb_setup_retire_blk_timer(po);
prb_open_block(p1, pbd);
}
/* Do NOT update the last_blk_num first.
* Assumes sk_buff_head lock is held.
*/
static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *pkc)
{
mod_timer(&pkc->retire_blk_timer,
jiffies + pkc->tov_in_jiffies);
pkc->last_kactive_blk_num = pkc->kactive_blk_num;
}
/*
* Timer logic:
* 1) We refresh the timer only when we open a block.
* By doing this we don't waste cycles refreshing the timer
* on packet-by-packet basis.
*
* With a 1MB block-size, on a 1Gbps line, it will take
* i) ~8 ms to fill a block + ii) memcpy etc.
* In this cut we are not accounting for the memcpy time.
*
* So, if the user sets the 'tmo' to 10ms then the timer
* will never fire while the block is still getting filled
* (which is what we want). However, the user could choose
* to close a block early and that's fine.
*
* But when the timer does fire, we check whether or not to refresh it.
* Since the tmo granularity is in msecs, it is not too expensive
* to refresh the timer, lets say every '8' msecs.
* Either the user can set the 'tmo' or we can derive it based on
* a) line-speed and b) block-size.
* prb_calc_retire_blk_tmo() calculates the tmo.
*
*/
static void prb_retire_rx_blk_timer_expired(unsigned long data)
{
struct packet_sock *po = (struct packet_sock *)data;
struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
unsigned int frozen;
struct tpacket_block_desc *pbd;
spin_lock(&po->sk.sk_receive_queue.lock);
frozen = prb_queue_frozen(pkc);
pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
if (unlikely(pkc->delete_blk_timer))
goto out;
/* We only need to plug the race when the block is partially filled.
* tpacket_rcv:
* lock(); increment BLOCK_NUM_PKTS; unlock()
* copy_bits() is in progress ...
* timer fires on other cpu:
* we can't retire the current block because copy_bits
* is in progress.
*
*/
if (BLOCK_NUM_PKTS(pbd)) {
while (atomic_read(&pkc->blk_fill_in_prog)) {
/* Waiting for skb_copy_bits to finish... */
cpu_relax();
}
}
if (pkc->last_kactive_blk_num == pkc->kactive_blk_num) {
if (!frozen) {
if (!BLOCK_NUM_PKTS(pbd)) {
/* An empty block. Just refresh the timer. */
goto refresh_timer;
}
prb_retire_current_block(pkc, po, TP_STATUS_BLK_TMO);
if (!prb_dispatch_next_block(pkc, po))
goto refresh_timer;
else
goto out;
} else {
/* Case 1. Queue was frozen because user-space was
* lagging behind.
*/
if (prb_curr_blk_in_use(pkc, pbd)) {
/*
* Ok, user-space is still behind.
* So just refresh the timer.
*/
goto refresh_timer;
} else {
/* Case 2. queue was frozen,user-space caught up,
* now the link went idle && the timer fired.
* We don't have a block to close.So we open this
* block and restart the timer.
* opening a block thaws the queue,restarts timer
* Thawing/timer-refresh is a side effect.
*/
prb_open_block(pkc, pbd);
goto out;
}
}
}
refresh_timer:
_prb_refresh_rx_retire_blk_timer(pkc);
out:
spin_unlock(&po->sk.sk_receive_queue.lock);
}
static void prb_flush_block(struct tpacket_kbdq_core *pkc1,
struct tpacket_block_desc *pbd1, __u32 status)
{
/* Flush everything minus the block header */
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
u8 *start, *end;
start = (u8 *)pbd1;
/* Skip the block header(we know header WILL fit in 4K) */
start += PAGE_SIZE;
end = (u8 *)PAGE_ALIGN((unsigned long)pkc1->pkblk_end);
for (; start < end; start += PAGE_SIZE)
flush_dcache_page(pgv_to_page(start));
smp_wmb();
#endif
/* Now update the block status. */
BLOCK_STATUS(pbd1) = status;
/* Flush the block header */
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
start = (u8 *)pbd1;
flush_dcache_page(pgv_to_page(start));
smp_wmb();
#endif
}
/*
* Side effect:
*
* 1) flush the block
* 2) Increment active_blk_num
*
* Note:We DONT refresh the timer on purpose.
* Because almost always the next block will be opened.
*/
static void prb_close_block(struct tpacket_kbdq_core *pkc1,
struct tpacket_block_desc *pbd1,
struct packet_sock *po, unsigned int stat)
{
__u32 status = TP_STATUS_USER | stat;
struct tpacket3_hdr *last_pkt;
struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
struct sock *sk = &po->sk;
if (po->stats.stats3.tp_drops)
status |= TP_STATUS_LOSING;
last_pkt = (struct tpacket3_hdr *)pkc1->prev;
last_pkt->tp_next_offset = 0;
/* Get the ts of the last pkt */
if (BLOCK_NUM_PKTS(pbd1)) {
h1->ts_last_pkt.ts_sec = last_pkt->tp_sec;
h1->ts_last_pkt.ts_nsec = last_pkt->tp_nsec;
} else {
/* Ok, we tmo'd - so get the current time.
*
* It shouldn't really happen as we don't close empty
* blocks. See prb_retire_rx_blk_timer_expired().
*/
struct timespec ts;
getnstimeofday(&ts);
h1->ts_last_pkt.ts_sec = ts.tv_sec;
h1->ts_last_pkt.ts_nsec = ts.tv_nsec;
}
smp_wmb();
/* Flush the block */
prb_flush_block(pkc1, pbd1, status);
sk->sk_data_ready(sk);
pkc1->kactive_blk_num = GET_NEXT_PRB_BLK_NUM(pkc1);
}
static void prb_thaw_queue(struct tpacket_kbdq_core *pkc)
{
pkc->reset_pending_on_curr_blk = 0;
}
/*
* Side effect of opening a block:
*
* 1) prb_queue is thawed.
* 2) retire_blk_timer is refreshed.
*
*/
static void prb_open_block(struct tpacket_kbdq_core *pkc1,
struct tpacket_block_desc *pbd1)
{
struct timespec ts;
struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
smp_rmb();
/* We could have just memset this but we will lose the
* flexibility of making the priv area sticky
*/
BLOCK_SNUM(pbd1) = pkc1->knxt_seq_num++;
BLOCK_NUM_PKTS(pbd1) = 0;
BLOCK_LEN(pbd1) = BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
getnstimeofday(&ts);
h1->ts_first_pkt.ts_sec = ts.tv_sec;
h1->ts_first_pkt.ts_nsec = ts.tv_nsec;
pkc1->pkblk_start = (char *)pbd1;
pkc1->nxt_offset = pkc1->pkblk_start + BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
BLOCK_O2FP(pbd1) = (__u32)BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
BLOCK_O2PRIV(pbd1) = BLK_HDR_LEN;
pbd1->version = pkc1->version;
pkc1->prev = pkc1->nxt_offset;
pkc1->pkblk_end = pkc1->pkblk_start + pkc1->kblk_size;
prb_thaw_queue(pkc1);
_prb_refresh_rx_retire_blk_timer(pkc1);
smp_wmb();
}
/*
* Queue freeze logic:
* 1) Assume tp_block_nr = 8 blocks.
* 2) At time 't0', user opens Rx ring.
* 3) Some time past 't0', kernel starts filling blocks starting from 0 .. 7
* 4) user-space is either sleeping or processing block '0'.
* 5) tpacket_rcv is currently filling block '7', since there is no space left,
* it will close block-7,loop around and try to fill block '0'.
* call-flow:
* __packet_lookup_frame_in_block
* prb_retire_current_block()
* prb_dispatch_next_block()
* |->(BLOCK_STATUS == USER) evaluates to true
* 5.1) Since block-0 is currently in-use, we just freeze the queue.
* 6) Now there are two cases:
* 6.1) Link goes idle right after the queue is frozen.
* But remember, the last open_block() refreshed the timer.
* When this timer expires,it will refresh itself so that we can
* re-open block-0 in near future.
* 6.2) Link is busy and keeps on receiving packets. This is a simple
* case and __packet_lookup_frame_in_block will check if block-0
* is free and can now be re-used.
*/
static void prb_freeze_queue(struct tpacket_kbdq_core *pkc,
struct packet_sock *po)
{
pkc->reset_pending_on_curr_blk = 1;
po->stats.stats3.tp_freeze_q_cnt++;
}
#define TOTAL_PKT_LEN_INCL_ALIGN(length) (ALIGN((length), V3_ALIGNMENT))
/*
* If the next block is free then we will dispatch it
* and return a good offset.
* Else, we will freeze the queue.
* So, caller must check the return value.
*/
static void *prb_dispatch_next_block(struct tpacket_kbdq_core *pkc,
struct packet_sock *po)
{
struct tpacket_block_desc *pbd;
smp_rmb();
/* 1. Get current block num */
pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
/* 2. If this block is currently in_use then freeze the queue */
if (TP_STATUS_USER & BLOCK_STATUS(pbd)) {
prb_freeze_queue(pkc, po);
return NULL;
}
/*
* 3.
* open this block and return the offset where the first packet
* needs to get stored.
*/
prb_open_block(pkc, pbd);
return (void *)pkc->nxt_offset;
}
static void prb_retire_current_block(struct tpacket_kbdq_core *pkc,
struct packet_sock *po, unsigned int status)
{
struct tpacket_block_desc *pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
/* retire/close the current block */
if (likely(TP_STATUS_KERNEL == BLOCK_STATUS(pbd))) {
/*
* Plug the case where copy_bits() is in progress on
* cpu-0 and tpacket_rcv() got invoked on cpu-1, didn't
* have space to copy the pkt in the current block and
* called prb_retire_current_block()
*
* We don't need to worry about the TMO case because
* the timer-handler already handled this case.
*/
if (!(status & TP_STATUS_BLK_TMO)) {
while (atomic_read(&pkc->blk_fill_in_prog)) {
/* Waiting for skb_copy_bits to finish... */
cpu_relax();
}
}
prb_close_block(pkc, pbd, po, status);
return;
}
}
static int prb_curr_blk_in_use(struct tpacket_kbdq_core *pkc,
struct tpacket_block_desc *pbd)
{
return TP_STATUS_USER & BLOCK_STATUS(pbd);
}
static int prb_queue_frozen(struct tpacket_kbdq_core *pkc)
{
return pkc->reset_pending_on_curr_blk;
}
static void prb_clear_blk_fill_status(struct packet_ring_buffer *rb)
{
struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
atomic_dec(&pkc->blk_fill_in_prog);
}
static void prb_fill_rxhash(struct tpacket_kbdq_core *pkc,
struct tpacket3_hdr *ppd)
{
ppd->hv1.tp_rxhash = skb_get_hash(pkc->skb);
}
static void prb_clear_rxhash(struct tpacket_kbdq_core *pkc,
struct tpacket3_hdr *ppd)
{
ppd->hv1.tp_rxhash = 0;
}
static void prb_fill_vlan_info(struct tpacket_kbdq_core *pkc,
struct tpacket3_hdr *ppd)
{
if (skb_vlan_tag_present(pkc->skb)) {
ppd->hv1.tp_vlan_tci = skb_vlan_tag_get(pkc->skb);
ppd->hv1.tp_vlan_tpid = ntohs(pkc->skb->vlan_proto);
ppd->tp_status = TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
} else {
ppd->hv1.tp_vlan_tci = 0;
ppd->hv1.tp_vlan_tpid = 0;
ppd->tp_status = TP_STATUS_AVAILABLE;
}
}
static void prb_run_all_ft_ops(struct tpacket_kbdq_core *pkc,
struct tpacket3_hdr *ppd)
{
ppd->hv1.tp_padding = 0;
prb_fill_vlan_info(pkc, ppd);
if (pkc->feature_req_word & TP_FT_REQ_FILL_RXHASH)
prb_fill_rxhash(pkc, ppd);
else
prb_clear_rxhash(pkc, ppd);
}
static void prb_fill_curr_block(char *curr,
struct tpacket_kbdq_core *pkc,
struct tpacket_block_desc *pbd,
unsigned int len)
{
struct tpacket3_hdr *ppd;
ppd = (struct tpacket3_hdr *)curr;
ppd->tp_next_offset = TOTAL_PKT_LEN_INCL_ALIGN(len);
pkc->prev = curr;
pkc->nxt_offset += TOTAL_PKT_LEN_INCL_ALIGN(len);
BLOCK_LEN(pbd) += TOTAL_PKT_LEN_INCL_ALIGN(len);
BLOCK_NUM_PKTS(pbd) += 1;
atomic_inc(&pkc->blk_fill_in_prog);
prb_run_all_ft_ops(pkc, ppd);
}
/* Assumes caller has the sk->rx_queue.lock */
static void *__packet_lookup_frame_in_block(struct packet_sock *po,
struct sk_buff *skb,
int status,
unsigned int len
)
{
struct tpacket_kbdq_core *pkc;
struct tpacket_block_desc *pbd;
char *curr, *end;
pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
/* Queue is frozen when user space is lagging behind */
if (prb_queue_frozen(pkc)) {
/*
* Check if that last block which caused the queue to freeze,
* is still in_use by user-space.
*/
if (prb_curr_blk_in_use(pkc, pbd)) {
/* Can't record this packet */
return NULL;
} else {
/*
* Ok, the block was released by user-space.
* Now let's open that block.
* opening a block also thaws the queue.
* Thawing is a side effect.
*/
prb_open_block(pkc, pbd);
}
}
smp_mb();
curr = pkc->nxt_offset;
pkc->skb = skb;
end = (char *)pbd + pkc->kblk_size;
/* first try the current block */
if (curr+TOTAL_PKT_LEN_INCL_ALIGN(len) < end) {
prb_fill_curr_block(curr, pkc, pbd, len);
return (void *)curr;
}
/* Ok, close the current block */
prb_retire_current_block(pkc, po, 0);
/* Now, try to dispatch the next block */
curr = (char *)prb_dispatch_next_block(pkc, po);
if (curr) {
pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
prb_fill_curr_block(curr, pkc, pbd, len);
return (void *)curr;
}
/*
* No free blocks are available.user_space hasn't caught up yet.
* Queue was just frozen and now this packet will get dropped.
*/
return NULL;
}
static void *packet_current_rx_frame(struct packet_sock *po,
struct sk_buff *skb,
int status, unsigned int len)
{
char *curr = NULL;
switch (po->tp_version) {
case TPACKET_V1:
case TPACKET_V2:
curr = packet_lookup_frame(po, &po->rx_ring,
po->rx_ring.head, status);
return curr;
case TPACKET_V3:
return __packet_lookup_frame_in_block(po, skb, status, len);
default:
WARN(1, "TPACKET version not supported\n");
BUG();
return NULL;
}
}
static void *prb_lookup_block(struct packet_sock *po,
struct packet_ring_buffer *rb,
unsigned int idx,
int status)
{
struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
struct tpacket_block_desc *pbd = GET_PBLOCK_DESC(pkc, idx);
if (status != BLOCK_STATUS(pbd))
return NULL;
return pbd;
}
static int prb_previous_blk_num(struct packet_ring_buffer *rb)
{
unsigned int prev;
if (rb->prb_bdqc.kactive_blk_num)
prev = rb->prb_bdqc.kactive_blk_num-1;
else
prev = rb->prb_bdqc.knum_blocks-1;
return prev;
}
/* Assumes caller has held the rx_queue.lock */
static void *__prb_previous_block(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
unsigned int previous = prb_previous_blk_num(rb);
return prb_lookup_block(po, rb, previous, status);
}
static void *packet_previous_rx_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
if (po->tp_version <= TPACKET_V2)
return packet_previous_frame(po, rb, status);
return __prb_previous_block(po, rb, status);
}
static void packet_increment_rx_head(struct packet_sock *po,
struct packet_ring_buffer *rb)
{
switch (po->tp_version) {
case TPACKET_V1:
case TPACKET_V2:
return packet_increment_head(rb);
case TPACKET_V3:
default:
WARN(1, "TPACKET version not supported.\n");
BUG();
return;
}
}
static void *packet_previous_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
unsigned int previous = rb->head ? rb->head - 1 : rb->frame_max;
return packet_lookup_frame(po, rb, previous, status);
}
static void packet_increment_head(struct packet_ring_buffer *buff)
{
buff->head = buff->head != buff->frame_max ? buff->head+1 : 0;
}
static void packet_inc_pending(struct packet_ring_buffer *rb)
{
this_cpu_inc(*rb->pending_refcnt);
}
static void packet_dec_pending(struct packet_ring_buffer *rb)
{
this_cpu_dec(*rb->pending_refcnt);
}
static unsigned int packet_read_pending(const struct packet_ring_buffer *rb)
{
unsigned int refcnt = 0;
int cpu;
/* We don't use pending refcount in rx_ring. */
if (rb->pending_refcnt == NULL)
return 0;
for_each_possible_cpu(cpu)
refcnt += *per_cpu_ptr(rb->pending_refcnt, cpu);
return refcnt;
}
static int packet_alloc_pending(struct packet_sock *po)
{
po->rx_ring.pending_refcnt = NULL;
po->tx_ring.pending_refcnt = alloc_percpu(unsigned int);
if (unlikely(po->tx_ring.pending_refcnt == NULL))
return -ENOBUFS;
return 0;
}
static void packet_free_pending(struct packet_sock *po)
{
free_percpu(po->tx_ring.pending_refcnt);
}
#define ROOM_POW_OFF 2
#define ROOM_NONE 0x0
#define ROOM_LOW 0x1
#define ROOM_NORMAL 0x2
static bool __tpacket_has_room(struct packet_sock *po, int pow_off)
{
int idx, len;
len = po->rx_ring.frame_max + 1;
idx = po->rx_ring.head;
if (pow_off)
idx += len >> pow_off;
if (idx >= len)
idx -= len;
return packet_lookup_frame(po, &po->rx_ring, idx, TP_STATUS_KERNEL);
}
static bool __tpacket_v3_has_room(struct packet_sock *po, int pow_off)
{
int idx, len;
len = po->rx_ring.prb_bdqc.knum_blocks;
idx = po->rx_ring.prb_bdqc.kactive_blk_num;
if (pow_off)
idx += len >> pow_off;
if (idx >= len)
idx -= len;
return prb_lookup_block(po, &po->rx_ring, idx, TP_STATUS_KERNEL);
}
static int __packet_rcv_has_room(struct packet_sock *po, struct sk_buff *skb)
{
struct sock *sk = &po->sk;
int ret = ROOM_NONE;
if (po->prot_hook.func != tpacket_rcv) {
int avail = sk->sk_rcvbuf - atomic_read(&sk->sk_rmem_alloc)
- (skb ? skb->truesize : 0);
if (avail > (sk->sk_rcvbuf >> ROOM_POW_OFF))
return ROOM_NORMAL;
else if (avail > 0)
return ROOM_LOW;
else
return ROOM_NONE;
}
if (po->tp_version == TPACKET_V3) {
if (__tpacket_v3_has_room(po, ROOM_POW_OFF))
ret = ROOM_NORMAL;
else if (__tpacket_v3_has_room(po, 0))
ret = ROOM_LOW;
} else {
if (__tpacket_has_room(po, ROOM_POW_OFF))
ret = ROOM_NORMAL;
else if (__tpacket_has_room(po, 0))
ret = ROOM_LOW;
}
return ret;
}
static int packet_rcv_has_room(struct packet_sock *po, struct sk_buff *skb)
{
int ret;
bool has_room;
spin_lock_bh(&po->sk.sk_receive_queue.lock);
ret = __packet_rcv_has_room(po, skb);
has_room = ret == ROOM_NORMAL;
if (po->pressure == has_room)
po->pressure = !has_room;
spin_unlock_bh(&po->sk.sk_receive_queue.lock);
return ret;
}
static void packet_sock_destruct(struct sock *sk)
{
skb_queue_purge(&sk->sk_error_queue);
WARN_ON(atomic_read(&sk->sk_rmem_alloc));
WARN_ON(atomic_read(&sk->sk_wmem_alloc));
if (!sock_flag(sk, SOCK_DEAD)) {
pr_err("Attempt to release alive packet socket: %p\n", sk);
return;
}
sk_refcnt_debug_dec(sk);
}
static bool fanout_flow_is_huge(struct packet_sock *po, struct sk_buff *skb)
{
u32 rxhash;
int i, count = 0;
rxhash = skb_get_hash(skb);
for (i = 0; i < ROLLOVER_HLEN; i++)
if (po->rollover->history[i] == rxhash)
count++;
po->rollover->history[prandom_u32() % ROLLOVER_HLEN] = rxhash;
return count > (ROLLOVER_HLEN >> 1);
}
static unsigned int fanout_demux_hash(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
return reciprocal_scale(__skb_get_hash_symmetric(skb), num);
}
static unsigned int fanout_demux_lb(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
unsigned int val = atomic_inc_return(&f->rr_cur);
return val % num;
}
static unsigned int fanout_demux_cpu(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
return smp_processor_id() % num;
}
static unsigned int fanout_demux_rnd(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
return prandom_u32_max(num);
}
static unsigned int fanout_demux_rollover(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int idx, bool try_self,
unsigned int num)
{
struct packet_sock *po, *po_next, *po_skip = NULL;
unsigned int i, j, room = ROOM_NONE;
po = pkt_sk(f->arr[idx]);
if (try_self) {
room = packet_rcv_has_room(po, skb);
if (room == ROOM_NORMAL ||
(room == ROOM_LOW && !fanout_flow_is_huge(po, skb)))
return idx;
po_skip = po;
}
i = j = min_t(int, po->rollover->sock, num - 1);
do {
po_next = pkt_sk(f->arr[i]);
if (po_next != po_skip && !po_next->pressure &&
packet_rcv_has_room(po_next, skb) == ROOM_NORMAL) {
if (i != j)
po->rollover->sock = i;
atomic_long_inc(&po->rollover->num);
if (room == ROOM_LOW)
atomic_long_inc(&po->rollover->num_huge);
return i;
}
if (++i == num)
i = 0;
} while (i != j);
atomic_long_inc(&po->rollover->num_failed);
return idx;
}
static unsigned int fanout_demux_qm(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
return skb_get_queue_mapping(skb) % num;
}
static unsigned int fanout_demux_bpf(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
struct bpf_prog *prog;
unsigned int ret = 0;
rcu_read_lock();
prog = rcu_dereference(f->bpf_prog);
if (prog)
ret = bpf_prog_run_clear_cb(prog, skb) % num;
rcu_read_unlock();
return ret;
}
static bool fanout_has_flag(struct packet_fanout *f, u16 flag)
{
return f->flags & (flag >> 8);
}
static int packet_rcv_fanout(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct packet_fanout *f = pt->af_packet_priv;
unsigned int num = READ_ONCE(f->num_members);
struct net *net = read_pnet(&f->net);
struct packet_sock *po;
unsigned int idx;
if (!net_eq(dev_net(dev), net) || !num) {
kfree_skb(skb);
return 0;
}
if (fanout_has_flag(f, PACKET_FANOUT_FLAG_DEFRAG)) {
skb = ip_check_defrag(net, skb, IP_DEFRAG_AF_PACKET);
if (!skb)
return 0;
}
switch (f->type) {
case PACKET_FANOUT_HASH:
default:
idx = fanout_demux_hash(f, skb, num);
break;
case PACKET_FANOUT_LB:
idx = fanout_demux_lb(f, skb, num);
break;
case PACKET_FANOUT_CPU:
idx = fanout_demux_cpu(f, skb, num);
break;
case PACKET_FANOUT_RND:
idx = fanout_demux_rnd(f, skb, num);
break;
case PACKET_FANOUT_QM:
idx = fanout_demux_qm(f, skb, num);
break;
case PACKET_FANOUT_ROLLOVER:
idx = fanout_demux_rollover(f, skb, 0, false, num);
break;
case PACKET_FANOUT_CBPF:
case PACKET_FANOUT_EBPF:
idx = fanout_demux_bpf(f, skb, num);
break;
}
if (fanout_has_flag(f, PACKET_FANOUT_FLAG_ROLLOVER))
idx = fanout_demux_rollover(f, skb, idx, true, num);
po = pkt_sk(f->arr[idx]);
return po->prot_hook.func(skb, dev, &po->prot_hook, orig_dev);
}
DEFINE_MUTEX(fanout_mutex);
EXPORT_SYMBOL_GPL(fanout_mutex);
static LIST_HEAD(fanout_list);
static void __fanout_link(struct sock *sk, struct packet_sock *po)
{
struct packet_fanout *f = po->fanout;
spin_lock(&f->lock);
f->arr[f->num_members] = sk;
smp_wmb();
f->num_members++;
spin_unlock(&f->lock);
}
static void __fanout_unlink(struct sock *sk, struct packet_sock *po)
{
struct packet_fanout *f = po->fanout;
int i;
spin_lock(&f->lock);
for (i = 0; i < f->num_members; i++) {
if (f->arr[i] == sk)
break;
}
BUG_ON(i >= f->num_members);
f->arr[i] = f->arr[f->num_members - 1];
f->num_members--;
spin_unlock(&f->lock);
}
static bool match_fanout_group(struct packet_type *ptype, struct sock *sk)
{
if (sk->sk_family != PF_PACKET)
return false;
return ptype->af_packet_priv == pkt_sk(sk)->fanout;
}
static void fanout_init_data(struct packet_fanout *f)
{
switch (f->type) {
case PACKET_FANOUT_LB:
atomic_set(&f->rr_cur, 0);
break;
case PACKET_FANOUT_CBPF:
case PACKET_FANOUT_EBPF:
RCU_INIT_POINTER(f->bpf_prog, NULL);
break;
}
}
static void __fanout_set_data_bpf(struct packet_fanout *f, struct bpf_prog *new)
{
struct bpf_prog *old;
spin_lock(&f->lock);
old = rcu_dereference_protected(f->bpf_prog, lockdep_is_held(&f->lock));
rcu_assign_pointer(f->bpf_prog, new);
spin_unlock(&f->lock);
if (old) {
synchronize_net();
bpf_prog_destroy(old);
}
}
static int fanout_set_data_cbpf(struct packet_sock *po, char __user *data,
unsigned int len)
{
struct bpf_prog *new;
struct sock_fprog fprog;
int ret;
if (sock_flag(&po->sk, SOCK_FILTER_LOCKED))
return -EPERM;
if (len != sizeof(fprog))
return -EINVAL;
if (copy_from_user(&fprog, data, len))
return -EFAULT;
ret = bpf_prog_create_from_user(&new, &fprog, NULL, false);
if (ret)
return ret;
__fanout_set_data_bpf(po->fanout, new);
return 0;
}
static int fanout_set_data_ebpf(struct packet_sock *po, char __user *data,
unsigned int len)
{
struct bpf_prog *new;
u32 fd;
if (sock_flag(&po->sk, SOCK_FILTER_LOCKED))
return -EPERM;
if (len != sizeof(fd))
return -EINVAL;
if (copy_from_user(&fd, data, len))
return -EFAULT;
new = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
if (IS_ERR(new))
return PTR_ERR(new);
__fanout_set_data_bpf(po->fanout, new);
return 0;
}
static int fanout_set_data(struct packet_sock *po, char __user *data,
unsigned int len)
{
switch (po->fanout->type) {
case PACKET_FANOUT_CBPF:
return fanout_set_data_cbpf(po, data, len);
case PACKET_FANOUT_EBPF:
return fanout_set_data_ebpf(po, data, len);
default:
return -EINVAL;
};
}
static void fanout_release_data(struct packet_fanout *f)
{
switch (f->type) {
case PACKET_FANOUT_CBPF:
case PACKET_FANOUT_EBPF:
__fanout_set_data_bpf(f, NULL);
};
}
static int fanout_add(struct sock *sk, u16 id, u16 type_flags)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_fanout *f, *match;
u8 type = type_flags & 0xff;
u8 flags = type_flags >> 8;
int err;
switch (type) {
case PACKET_FANOUT_ROLLOVER:
if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
return -EINVAL;
case PACKET_FANOUT_HASH:
case PACKET_FANOUT_LB:
case PACKET_FANOUT_CPU:
case PACKET_FANOUT_RND:
case PACKET_FANOUT_QM:
case PACKET_FANOUT_CBPF:
case PACKET_FANOUT_EBPF:
break;
default:
return -EINVAL;
}
if (!po->running)
return -EINVAL;
if (po->fanout)
return -EALREADY;
if (type == PACKET_FANOUT_ROLLOVER ||
(type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) {
po->rollover = kzalloc(sizeof(*po->rollover), GFP_KERNEL);
if (!po->rollover)
return -ENOMEM;
atomic_long_set(&po->rollover->num, 0);
atomic_long_set(&po->rollover->num_huge, 0);
atomic_long_set(&po->rollover->num_failed, 0);
}
mutex_lock(&fanout_mutex);
match = NULL;
list_for_each_entry(f, &fanout_list, list) {
if (f->id == id &&
read_pnet(&f->net) == sock_net(sk)) {
match = f;
break;
}
}
err = -EINVAL;
if (match && match->flags != flags)
goto out;
if (!match) {
err = -ENOMEM;
match = kzalloc(sizeof(*match), GFP_KERNEL);
if (!match)
goto out;
write_pnet(&match->net, sock_net(sk));
match->id = id;
match->type = type;
match->flags = flags;
INIT_LIST_HEAD(&match->list);
spin_lock_init(&match->lock);
atomic_set(&match->sk_ref, 0);
fanout_init_data(match);
match->prot_hook.type = po->prot_hook.type;
match->prot_hook.dev = po->prot_hook.dev;
match->prot_hook.func = packet_rcv_fanout;
match->prot_hook.af_packet_priv = match;
match->prot_hook.id_match = match_fanout_group;
dev_add_pack(&match->prot_hook);
list_add(&match->list, &fanout_list);
}
err = -EINVAL;
if (match->type == type &&
match->prot_hook.type == po->prot_hook.type &&
match->prot_hook.dev == po->prot_hook.dev) {
err = -ENOSPC;
if (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) {
__dev_remove_pack(&po->prot_hook);
po->fanout = match;
atomic_inc(&match->sk_ref);
__fanout_link(sk, po);
err = 0;
}
}
out:
mutex_unlock(&fanout_mutex);
if (err) {
kfree(po->rollover);
po->rollover = NULL;
}
return err;
}
static void fanout_release(struct sock *sk)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_fanout *f;
f = po->fanout;
if (!f)
return;
mutex_lock(&fanout_mutex);
po->fanout = NULL;
if (atomic_dec_and_test(&f->sk_ref)) {
list_del(&f->list);
dev_remove_pack(&f->prot_hook);
fanout_release_data(f);
kfree(f);
}
mutex_unlock(&fanout_mutex);
if (po->rollover)
kfree_rcu(po->rollover, rcu);
}
static bool packet_extra_vlan_len_allowed(const struct net_device *dev,
struct sk_buff *skb)
{
/* Earlier code assumed this would be a VLAN pkt, double-check
* this now that we have the actual packet in hand. We can only
* do this check on Ethernet devices.
*/
if (unlikely(dev->type != ARPHRD_ETHER))
return false;
skb_reset_mac_header(skb);
return likely(eth_hdr(skb)->h_proto == htons(ETH_P_8021Q));
}
static const struct proto_ops packet_ops;
static const struct proto_ops packet_ops_spkt;
static int packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct sockaddr_pkt *spkt;
/*
* When we registered the protocol we saved the socket in the data
* field for just this event.
*/
sk = pt->af_packet_priv;
/*
* Yank back the headers [hope the device set this
* right or kerboom...]
*
* Incoming packets have ll header pulled,
* push it back.
*
* For outgoing ones skb->data == skb_mac_header(skb)
* so that this procedure is noop.
*/
if (skb->pkt_type == PACKET_LOOPBACK)
goto out;
if (!net_eq(dev_net(dev), sock_net(sk)))
goto out;
skb = skb_share_check(skb, GFP_ATOMIC);
if (skb == NULL)
goto oom;
/* drop any routing info */
skb_dst_drop(skb);
/* drop conntrack reference */
nf_reset(skb);
spkt = &PACKET_SKB_CB(skb)->sa.pkt;
skb_push(skb, skb->data - skb_mac_header(skb));
/*
* The SOCK_PACKET socket receives _all_ frames.
*/
spkt->spkt_family = dev->type;
strlcpy(spkt->spkt_device, dev->name, sizeof(spkt->spkt_device));
spkt->spkt_protocol = skb->protocol;
/*
* Charge the memory to the socket. This is done specifically
* to prevent sockets using all the memory up.
*/
if (sock_queue_rcv_skb(sk, skb) == 0)
return 0;
out:
kfree_skb(skb);
oom:
return 0;
}
/*
* Output a raw packet to a device layer. This bypasses all the other
* protocol layers and you must therefore supply it with a complete frame
*/
static int packet_sendmsg_spkt(struct socket *sock, struct msghdr *msg,
size_t len)
{
struct sock *sk = sock->sk;
DECLARE_SOCKADDR(struct sockaddr_pkt *, saddr, msg->msg_name);
struct sk_buff *skb = NULL;
struct net_device *dev;
struct sockcm_cookie sockc;
__be16 proto = 0;
int err;
int extra_len = 0;
/*
* Get and verify the address.
*/
if (saddr) {
if (msg->msg_namelen < sizeof(struct sockaddr))
return -EINVAL;
if (msg->msg_namelen == sizeof(struct sockaddr_pkt))
proto = saddr->spkt_protocol;
} else
return -ENOTCONN; /* SOCK_PACKET must be sent giving an address */
/*
* Find the device first to size check it
*/
saddr->spkt_device[sizeof(saddr->spkt_device) - 1] = 0;
retry:
rcu_read_lock();
dev = dev_get_by_name_rcu(sock_net(sk), saddr->spkt_device);
err = -ENODEV;
if (dev == NULL)
goto out_unlock;
err = -ENETDOWN;
if (!(dev->flags & IFF_UP))
goto out_unlock;
/*
* You may not queue a frame bigger than the mtu. This is the lowest level
* raw protocol and you must do your own fragmentation at this level.
*/
if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
if (!netif_supports_nofcs(dev)) {
err = -EPROTONOSUPPORT;
goto out_unlock;
}
extra_len = 4; /* We're doing our own CRC */
}
err = -EMSGSIZE;
if (len > dev->mtu + dev->hard_header_len + VLAN_HLEN + extra_len)
goto out_unlock;
if (!skb) {
size_t reserved = LL_RESERVED_SPACE(dev);
int tlen = dev->needed_tailroom;
unsigned int hhlen = dev->header_ops ? dev->hard_header_len : 0;
rcu_read_unlock();
skb = sock_wmalloc(sk, len + reserved + tlen, 0, GFP_KERNEL);
if (skb == NULL)
return -ENOBUFS;
/* FIXME: Save some space for broken drivers that write a hard
* header at transmission time by themselves. PPP is the notable
* one here. This should really be fixed at the driver level.
*/
skb_reserve(skb, reserved);
skb_reset_network_header(skb);
/* Try to align data part correctly */
if (hhlen) {
skb->data -= hhlen;
skb->tail -= hhlen;
if (len < hhlen)
skb_reset_network_header(skb);
}
err = memcpy_from_msg(skb_put(skb, len), msg, len);
if (err)
goto out_free;
goto retry;
}
if (!dev_validate_header(dev, skb->data, len)) {
err = -EINVAL;
goto out_unlock;
}
if (len > (dev->mtu + dev->hard_header_len + extra_len) &&
!packet_extra_vlan_len_allowed(dev, skb)) {
err = -EMSGSIZE;
goto out_unlock;
}
sockc.tsflags = sk->sk_tsflags;
if (msg->msg_controllen) {
err = sock_cmsg_send(sk, msg, &sockc);
if (unlikely(err))
goto out_unlock;
}
skb->protocol = proto;
skb->dev = dev;
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
sock_tx_timestamp(sk, sockc.tsflags, &skb_shinfo(skb)->tx_flags);
if (unlikely(extra_len == 4))
skb->no_fcs = 1;
skb_probe_transport_header(skb, 0);
dev_queue_xmit(skb);
rcu_read_unlock();
return len;
out_unlock:
rcu_read_unlock();
out_free:
kfree_skb(skb);
return err;
}
static unsigned int run_filter(struct sk_buff *skb,
const struct sock *sk,
unsigned int res)
{
struct sk_filter *filter;
rcu_read_lock();
filter = rcu_dereference(sk->sk_filter);
if (filter != NULL)
res = bpf_prog_run_clear_cb(filter->prog, skb);
rcu_read_unlock();
return res;
}
static int packet_rcv_vnet(struct msghdr *msg, const struct sk_buff *skb,
size_t *len)
{
struct virtio_net_hdr vnet_hdr;
if (*len < sizeof(vnet_hdr))
return -EINVAL;
*len -= sizeof(vnet_hdr);
if (virtio_net_hdr_from_skb(skb, &vnet_hdr, vio_le(), true))
return -EINVAL;
return memcpy_to_msg(msg, (void *)&vnet_hdr, sizeof(vnet_hdr));
}
/*
* This function makes lazy skb cloning in hope that most of packets
* are discarded by BPF.
*
* Note tricky part: we DO mangle shared skb! skb->data, skb->len
* and skb->cb are mangled. It works because (and until) packets
* falling here are owned by current CPU. Output packets are cloned
* by dev_queue_xmit_nit(), input packets are processed by net_bh
* sequencially, so that if we return skb to original state on exit,
* we will not harm anyone.
*/
static int packet_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct sockaddr_ll *sll;
struct packet_sock *po;
u8 *skb_head = skb->data;
int skb_len = skb->len;
unsigned int snaplen, res;
bool is_drop_n_account = false;
if (skb->pkt_type == PACKET_LOOPBACK)
goto drop;
sk = pt->af_packet_priv;
po = pkt_sk(sk);
if (!net_eq(dev_net(dev), sock_net(sk)))
goto drop;
skb->dev = dev;
if (dev->header_ops) {
/* The device has an explicit notion of ll header,
* exported to higher levels.
*
* Otherwise, the device hides details of its frame
* structure, so that corresponding packet head is
* never delivered to user.
*/
if (sk->sk_type != SOCK_DGRAM)
skb_push(skb, skb->data - skb_mac_header(skb));
else if (skb->pkt_type == PACKET_OUTGOING) {
/* Special case: outgoing packets have ll header at head */
skb_pull(skb, skb_network_offset(skb));
}
}
snaplen = skb->len;
res = run_filter(skb, sk, snaplen);
if (!res)
goto drop_n_restore;
if (snaplen > res)
snaplen = res;
if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
goto drop_n_acct;
if (skb_shared(skb)) {
struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
if (nskb == NULL)
goto drop_n_acct;
if (skb_head != skb->data) {
skb->data = skb_head;
skb->len = skb_len;
}
consume_skb(skb);
skb = nskb;
}
sock_skb_cb_check_size(sizeof(*PACKET_SKB_CB(skb)) + MAX_ADDR_LEN - 8);
sll = &PACKET_SKB_CB(skb)->sa.ll;
sll->sll_hatype = dev->type;
sll->sll_pkttype = skb->pkt_type;
if (unlikely(po->origdev))
sll->sll_ifindex = orig_dev->ifindex;
else
sll->sll_ifindex = dev->ifindex;
sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
/* sll->sll_family and sll->sll_protocol are set in packet_recvmsg().
* Use their space for storing the original skb length.
*/
PACKET_SKB_CB(skb)->sa.origlen = skb->len;
if (pskb_trim(skb, snaplen))
goto drop_n_acct;
skb_set_owner_r(skb, sk);
skb->dev = NULL;
skb_dst_drop(skb);
/* drop conntrack reference */
nf_reset(skb);
spin_lock(&sk->sk_receive_queue.lock);
po->stats.stats1.tp_packets++;
sock_skb_set_dropcount(sk, skb);
__skb_queue_tail(&sk->sk_receive_queue, skb);
spin_unlock(&sk->sk_receive_queue.lock);
sk->sk_data_ready(sk);
return 0;
drop_n_acct:
is_drop_n_account = true;
spin_lock(&sk->sk_receive_queue.lock);
po->stats.stats1.tp_drops++;
atomic_inc(&sk->sk_drops);
spin_unlock(&sk->sk_receive_queue.lock);
drop_n_restore:
if (skb_head != skb->data && skb_shared(skb)) {
skb->data = skb_head;
skb->len = skb_len;
}
drop:
if (!is_drop_n_account)
consume_skb(skb);
else
kfree_skb(skb);
return 0;
}
static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct packet_sock *po;
struct sockaddr_ll *sll;
union tpacket_uhdr h;
u8 *skb_head = skb->data;
int skb_len = skb->len;
unsigned int snaplen, res;
unsigned long status = TP_STATUS_USER;
unsigned short macoff, netoff, hdrlen;
struct sk_buff *copy_skb = NULL;
struct timespec ts;
__u32 ts_status;
bool is_drop_n_account = false;
/* struct tpacket{2,3}_hdr is aligned to a multiple of TPACKET_ALIGNMENT.
* We may add members to them until current aligned size without forcing
* userspace to call getsockopt(..., PACKET_HDRLEN, ...).
*/
BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h2)) != 32);
BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h3)) != 48);
if (skb->pkt_type == PACKET_LOOPBACK)
goto drop;
sk = pt->af_packet_priv;
po = pkt_sk(sk);
if (!net_eq(dev_net(dev), sock_net(sk)))
goto drop;
if (dev->header_ops) {
if (sk->sk_type != SOCK_DGRAM)
skb_push(skb, skb->data - skb_mac_header(skb));
else if (skb->pkt_type == PACKET_OUTGOING) {
/* Special case: outgoing packets have ll header at head */
skb_pull(skb, skb_network_offset(skb));
}
}
snaplen = skb->len;
res = run_filter(skb, sk, snaplen);
if (!res)
goto drop_n_restore;
if (skb->ip_summed == CHECKSUM_PARTIAL)
status |= TP_STATUS_CSUMNOTREADY;
else if (skb->pkt_type != PACKET_OUTGOING &&
(skb->ip_summed == CHECKSUM_COMPLETE ||
skb_csum_unnecessary(skb)))
status |= TP_STATUS_CSUM_VALID;
if (snaplen > res)
snaplen = res;
if (sk->sk_type == SOCK_DGRAM) {
macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
po->tp_reserve;
} else {
unsigned int maclen = skb_network_offset(skb);
netoff = TPACKET_ALIGN(po->tp_hdrlen +
(maclen < 16 ? 16 : maclen)) +
po->tp_reserve;
if (po->has_vnet_hdr)
netoff += sizeof(struct virtio_net_hdr);
macoff = netoff - maclen;
}
if (po->tp_version <= TPACKET_V2) {
if (macoff + snaplen > po->rx_ring.frame_size) {
if (po->copy_thresh &&
atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {
if (skb_shared(skb)) {
copy_skb = skb_clone(skb, GFP_ATOMIC);
} else {
copy_skb = skb_get(skb);
skb_head = skb->data;
}
if (copy_skb)
skb_set_owner_r(copy_skb, sk);
}
snaplen = po->rx_ring.frame_size - macoff;
if ((int)snaplen < 0)
snaplen = 0;
}
} else if (unlikely(macoff + snaplen >
GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) {
u32 nval;
nval = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len - macoff;
pr_err_once("tpacket_rcv: packet too big, clamped from %u to %u. macoff=%u\n",
snaplen, nval, macoff);
snaplen = nval;
if (unlikely((int)snaplen < 0)) {
snaplen = 0;
macoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len;
}
}
spin_lock(&sk->sk_receive_queue.lock);
h.raw = packet_current_rx_frame(po, skb,
TP_STATUS_KERNEL, (macoff+snaplen));
if (!h.raw)
goto drop_n_account;
if (po->tp_version <= TPACKET_V2) {
packet_increment_rx_head(po, &po->rx_ring);
/*
* LOSING will be reported till you read the stats,
* because it's COR - Clear On Read.
* Anyways, moving it for V1/V2 only as V3 doesn't need this
* at packet level.
*/
if (po->stats.stats1.tp_drops)
status |= TP_STATUS_LOSING;
}
po->stats.stats1.tp_packets++;
if (copy_skb) {
status |= TP_STATUS_COPY;
__skb_queue_tail(&sk->sk_receive_queue, copy_skb);
}
spin_unlock(&sk->sk_receive_queue.lock);
if (po->has_vnet_hdr) {
if (virtio_net_hdr_from_skb(skb, h.raw + macoff -
sizeof(struct virtio_net_hdr),
vio_le(), true)) {
spin_lock(&sk->sk_receive_queue.lock);
goto drop_n_account;
}
}
skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
getnstimeofday(&ts);
status |= ts_status;
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_len = skb->len;
h.h1->tp_snaplen = snaplen;
h.h1->tp_mac = macoff;
h.h1->tp_net = netoff;
h.h1->tp_sec = ts.tv_sec;
h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
hdrlen = sizeof(*h.h1);
break;
case TPACKET_V2:
h.h2->tp_len = skb->len;
h.h2->tp_snaplen = snaplen;
h.h2->tp_mac = macoff;
h.h2->tp_net = netoff;
h.h2->tp_sec = ts.tv_sec;
h.h2->tp_nsec = ts.tv_nsec;
if (skb_vlan_tag_present(skb)) {
h.h2->tp_vlan_tci = skb_vlan_tag_get(skb);
h.h2->tp_vlan_tpid = ntohs(skb->vlan_proto);
status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
} else {
h.h2->tp_vlan_tci = 0;
h.h2->tp_vlan_tpid = 0;
}
memset(h.h2->tp_padding, 0, sizeof(h.h2->tp_padding));
hdrlen = sizeof(*h.h2);
break;
case TPACKET_V3:
/* tp_nxt_offset,vlan are already populated above.
* So DONT clear those fields here
*/
h.h3->tp_status |= status;
h.h3->tp_len = skb->len;
h.h3->tp_snaplen = snaplen;
h.h3->tp_mac = macoff;
h.h3->tp_net = netoff;
h.h3->tp_sec = ts.tv_sec;
h.h3->tp_nsec = ts.tv_nsec;
memset(h.h3->tp_padding, 0, sizeof(h.h3->tp_padding));
hdrlen = sizeof(*h.h3);
break;
default:
BUG();
}
sll = h.raw + TPACKET_ALIGN(hdrlen);
sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
sll->sll_family = AF_PACKET;
sll->sll_hatype = dev->type;
sll->sll_protocol = skb->protocol;
sll->sll_pkttype = skb->pkt_type;
if (unlikely(po->origdev))
sll->sll_ifindex = orig_dev->ifindex;
else
sll->sll_ifindex = dev->ifindex;
smp_mb();
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
if (po->tp_version <= TPACKET_V2) {
u8 *start, *end;
end = (u8 *) PAGE_ALIGN((unsigned long) h.raw +
macoff + snaplen);
for (start = h.raw; start < end; start += PAGE_SIZE)
flush_dcache_page(pgv_to_page(start));
}
smp_wmb();
#endif
if (po->tp_version <= TPACKET_V2) {
__packet_set_status(po, h.raw, status);
sk->sk_data_ready(sk);
} else {
prb_clear_blk_fill_status(&po->rx_ring);
}
drop_n_restore:
if (skb_head != skb->data && skb_shared(skb)) {
skb->data = skb_head;
skb->len = skb_len;
}
drop:
if (!is_drop_n_account)
consume_skb(skb);
else
kfree_skb(skb);
return 0;
drop_n_account:
is_drop_n_account = true;
po->stats.stats1.tp_drops++;
spin_unlock(&sk->sk_receive_queue.lock);
sk->sk_data_ready(sk);
kfree_skb(copy_skb);
goto drop_n_restore;
}
static void tpacket_destruct_skb(struct sk_buff *skb)
{
struct packet_sock *po = pkt_sk(skb->sk);
if (likely(po->tx_ring.pg_vec)) {
void *ph;
__u32 ts;
ph = skb_shinfo(skb)->destructor_arg;
packet_dec_pending(&po->tx_ring);
ts = __packet_set_timestamp(po, ph, skb);
__packet_set_status(po, ph, TP_STATUS_AVAILABLE | ts);
}
sock_wfree(skb);
}
static void tpacket_set_protocol(const struct net_device *dev,
struct sk_buff *skb)
{
if (dev->type == ARPHRD_ETHER) {
skb_reset_mac_header(skb);
skb->protocol = eth_hdr(skb)->h_proto;
}
}
static int __packet_snd_vnet_parse(struct virtio_net_hdr *vnet_hdr, size_t len)
{
if ((vnet_hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
(__virtio16_to_cpu(vio_le(), vnet_hdr->csum_start) +
__virtio16_to_cpu(vio_le(), vnet_hdr->csum_offset) + 2 >
__virtio16_to_cpu(vio_le(), vnet_hdr->hdr_len)))
vnet_hdr->hdr_len = __cpu_to_virtio16(vio_le(),
__virtio16_to_cpu(vio_le(), vnet_hdr->csum_start) +
__virtio16_to_cpu(vio_le(), vnet_hdr->csum_offset) + 2);
if (__virtio16_to_cpu(vio_le(), vnet_hdr->hdr_len) > len)
return -EINVAL;
return 0;
}
static int packet_snd_vnet_parse(struct msghdr *msg, size_t *len,
struct virtio_net_hdr *vnet_hdr)
{
if (*len < sizeof(*vnet_hdr))
return -EINVAL;
*len -= sizeof(*vnet_hdr);
if (!copy_from_iter_full(vnet_hdr, sizeof(*vnet_hdr), &msg->msg_iter))
return -EFAULT;
return __packet_snd_vnet_parse(vnet_hdr, *len);
}
static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
void *frame, struct net_device *dev, void *data, int tp_len,
__be16 proto, unsigned char *addr, int hlen, int copylen,
const struct sockcm_cookie *sockc)
{
union tpacket_uhdr ph;
int to_write, offset, len, nr_frags, len_max;
struct socket *sock = po->sk.sk_socket;
struct page *page;
int err;
ph.raw = frame;
skb->protocol = proto;
skb->dev = dev;
skb->priority = po->sk.sk_priority;
skb->mark = po->sk.sk_mark;
sock_tx_timestamp(&po->sk, sockc->tsflags, &skb_shinfo(skb)->tx_flags);
skb_shinfo(skb)->destructor_arg = ph.raw;
skb_reserve(skb, hlen);
skb_reset_network_header(skb);
to_write = tp_len;
if (sock->type == SOCK_DGRAM) {
err = dev_hard_header(skb, dev, ntohs(proto), addr,
NULL, tp_len);
if (unlikely(err < 0))
return -EINVAL;
} else if (copylen) {
int hdrlen = min_t(int, copylen, tp_len);
skb_push(skb, dev->hard_header_len);
skb_put(skb, copylen - dev->hard_header_len);
err = skb_store_bits(skb, 0, data, hdrlen);
if (unlikely(err))
return err;
if (!dev_validate_header(dev, skb->data, hdrlen))
return -EINVAL;
if (!skb->protocol)
tpacket_set_protocol(dev, skb);
data += hdrlen;
to_write -= hdrlen;
}
offset = offset_in_page(data);
len_max = PAGE_SIZE - offset;
len = ((to_write > len_max) ? len_max : to_write);
skb->data_len = to_write;
skb->len += to_write;
skb->truesize += to_write;
atomic_add(to_write, &po->sk.sk_wmem_alloc);
while (likely(to_write)) {
nr_frags = skb_shinfo(skb)->nr_frags;
if (unlikely(nr_frags >= MAX_SKB_FRAGS)) {
pr_err("Packet exceed the number of skb frags(%lu)\n",
MAX_SKB_FRAGS);
return -EFAULT;
}
page = pgv_to_page(data);
data += len;
flush_dcache_page(page);
get_page(page);
skb_fill_page_desc(skb, nr_frags, page, offset, len);
to_write -= len;
offset = 0;
len_max = PAGE_SIZE;
len = ((to_write > len_max) ? len_max : to_write);
}
skb_probe_transport_header(skb, 0);
return tp_len;
}
static int tpacket_parse_header(struct packet_sock *po, void *frame,
int size_max, void **data)
{
union tpacket_uhdr ph;
int tp_len, off;
ph.raw = frame;
switch (po->tp_version) {
case TPACKET_V2:
tp_len = ph.h2->tp_len;
break;
default:
tp_len = ph.h1->tp_len;
break;
}
if (unlikely(tp_len > size_max)) {
pr_err("packet size is too long (%d > %d)\n", tp_len, size_max);
return -EMSGSIZE;
}
if (unlikely(po->tp_tx_has_off)) {
int off_min, off_max;
off_min = po->tp_hdrlen - sizeof(struct sockaddr_ll);
off_max = po->tx_ring.frame_size - tp_len;
if (po->sk.sk_type == SOCK_DGRAM) {
switch (po->tp_version) {
case TPACKET_V2:
off = ph.h2->tp_net;
break;
default:
off = ph.h1->tp_net;
break;
}
} else {
switch (po->tp_version) {
case TPACKET_V2:
off = ph.h2->tp_mac;
break;
default:
off = ph.h1->tp_mac;
break;
}
}
if (unlikely((off < off_min) || (off_max < off)))
return -EINVAL;
} else {
off = po->tp_hdrlen - sizeof(struct sockaddr_ll);
}
*data = frame + off;
return tp_len;
}
static int tpacket_snd(struct packet_sock *po, struct msghdr *msg)
{
struct sk_buff *skb;
struct net_device *dev;
struct virtio_net_hdr *vnet_hdr = NULL;
struct sockcm_cookie sockc;
__be16 proto;
int err, reserve = 0;
void *ph;
DECLARE_SOCKADDR(struct sockaddr_ll *, saddr, msg->msg_name);
bool need_wait = !(msg->msg_flags & MSG_DONTWAIT);
int tp_len, size_max;
unsigned char *addr;
void *data;
int len_sum = 0;
int status = TP_STATUS_AVAILABLE;
int hlen, tlen, copylen = 0;
mutex_lock(&po->pg_vec_lock);
if (likely(saddr == NULL)) {
dev = packet_cached_dev_get(po);
proto = po->num;
addr = NULL;
} else {
err = -EINVAL;
if (msg->msg_namelen < sizeof(struct sockaddr_ll))
goto out;
if (msg->msg_namelen < (saddr->sll_halen
+ offsetof(struct sockaddr_ll,
sll_addr)))
goto out;
proto = saddr->sll_protocol;
addr = saddr->sll_addr;
dev = dev_get_by_index(sock_net(&po->sk), saddr->sll_ifindex);
}
sockc.tsflags = po->sk.sk_tsflags;
if (msg->msg_controllen) {
err = sock_cmsg_send(&po->sk, msg, &sockc);
if (unlikely(err))
goto out;
}
err = -ENXIO;
if (unlikely(dev == NULL))
goto out;
err = -ENETDOWN;
if (unlikely(!(dev->flags & IFF_UP)))
goto out_put;
if (po->sk.sk_socket->type == SOCK_RAW)
reserve = dev->hard_header_len;
size_max = po->tx_ring.frame_size
- (po->tp_hdrlen - sizeof(struct sockaddr_ll));
if ((size_max > dev->mtu + reserve + VLAN_HLEN) && !po->has_vnet_hdr)
size_max = dev->mtu + reserve + VLAN_HLEN;
do {
ph = packet_current_frame(po, &po->tx_ring,
TP_STATUS_SEND_REQUEST);
if (unlikely(ph == NULL)) {
if (need_wait && need_resched())
schedule();
continue;
}
skb = NULL;
tp_len = tpacket_parse_header(po, ph, size_max, &data);
if (tp_len < 0)
goto tpacket_error;
status = TP_STATUS_SEND_REQUEST;
hlen = LL_RESERVED_SPACE(dev);
tlen = dev->needed_tailroom;
if (po->has_vnet_hdr) {
vnet_hdr = data;
data += sizeof(*vnet_hdr);
tp_len -= sizeof(*vnet_hdr);
if (tp_len < 0 ||
__packet_snd_vnet_parse(vnet_hdr, tp_len)) {
tp_len = -EINVAL;
goto tpacket_error;
}
copylen = __virtio16_to_cpu(vio_le(),
vnet_hdr->hdr_len);
}
copylen = max_t(int, copylen, dev->hard_header_len);
skb = sock_alloc_send_skb(&po->sk,
hlen + tlen + sizeof(struct sockaddr_ll) +
(copylen - dev->hard_header_len),
!need_wait, &err);
if (unlikely(skb == NULL)) {
/* we assume the socket was initially writeable ... */
if (likely(len_sum > 0))
err = len_sum;
goto out_status;
}
tp_len = tpacket_fill_skb(po, skb, ph, dev, data, tp_len, proto,
addr, hlen, copylen, &sockc);
if (likely(tp_len >= 0) &&
tp_len > dev->mtu + reserve &&
!po->has_vnet_hdr &&
!packet_extra_vlan_len_allowed(dev, skb))
tp_len = -EMSGSIZE;
if (unlikely(tp_len < 0)) {
tpacket_error:
if (po->tp_loss) {
__packet_set_status(po, ph,
TP_STATUS_AVAILABLE);
packet_increment_head(&po->tx_ring);
kfree_skb(skb);
continue;
} else {
status = TP_STATUS_WRONG_FORMAT;
err = tp_len;
goto out_status;
}
}
if (po->has_vnet_hdr && virtio_net_hdr_to_skb(skb, vnet_hdr,
vio_le())) {
tp_len = -EINVAL;
goto tpacket_error;
}
packet_pick_tx_queue(dev, skb);
skb->destructor = tpacket_destruct_skb;
__packet_set_status(po, ph, TP_STATUS_SENDING);
packet_inc_pending(&po->tx_ring);
status = TP_STATUS_SEND_REQUEST;
err = po->xmit(skb);
if (unlikely(err > 0)) {
err = net_xmit_errno(err);
if (err && __packet_get_status(po, ph) ==
TP_STATUS_AVAILABLE) {
/* skb was destructed already */
skb = NULL;
goto out_status;
}
/*
* skb was dropped but not destructed yet;
* let's treat it like congestion or err < 0
*/
err = 0;
}
packet_increment_head(&po->tx_ring);
len_sum += tp_len;
} while (likely((ph != NULL) ||
/* Note: packet_read_pending() might be slow if we have
* to call it as it's per_cpu variable, but in fast-path
* we already short-circuit the loop with the first
* condition, and luckily don't have to go that path
* anyway.
*/
(need_wait && packet_read_pending(&po->tx_ring))));
err = len_sum;
goto out_put;
out_status:
__packet_set_status(po, ph, status);
kfree_skb(skb);
out_put:
dev_put(dev);
out:
mutex_unlock(&po->pg_vec_lock);
return err;
}
static struct sk_buff *packet_alloc_skb(struct sock *sk, size_t prepad,
size_t reserve, size_t len,
size_t linear, int noblock,
int *err)
{
struct sk_buff *skb;
/* Under a page? Don't bother with paged skb. */
if (prepad + len < PAGE_SIZE || !linear)
linear = len;
skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
err, 0);
if (!skb)
return NULL;
skb_reserve(skb, reserve);
skb_put(skb, linear);
skb->data_len = len - linear;
skb->len += len - linear;
return skb;
}
static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
DECLARE_SOCKADDR(struct sockaddr_ll *, saddr, msg->msg_name);
struct sk_buff *skb;
struct net_device *dev;
__be16 proto;
unsigned char *addr;
int err, reserve = 0;
struct sockcm_cookie sockc;
struct virtio_net_hdr vnet_hdr = { 0 };
int offset = 0;
struct packet_sock *po = pkt_sk(sk);
int hlen, tlen, linear;
int extra_len = 0;
/*
* Get and verify the address.
*/
if (likely(saddr == NULL)) {
dev = packet_cached_dev_get(po);
proto = po->num;
addr = NULL;
} else {
err = -EINVAL;
if (msg->msg_namelen < sizeof(struct sockaddr_ll))
goto out;
if (msg->msg_namelen < (saddr->sll_halen + offsetof(struct sockaddr_ll, sll_addr)))
goto out;
proto = saddr->sll_protocol;
addr = saddr->sll_addr;
dev = dev_get_by_index(sock_net(sk), saddr->sll_ifindex);
}
err = -ENXIO;
if (unlikely(dev == NULL))
goto out_unlock;
err = -ENETDOWN;
if (unlikely(!(dev->flags & IFF_UP)))
goto out_unlock;
sockc.tsflags = sk->sk_tsflags;
sockc.mark = sk->sk_mark;
if (msg->msg_controllen) {
err = sock_cmsg_send(sk, msg, &sockc);
if (unlikely(err))
goto out_unlock;
}
if (sock->type == SOCK_RAW)
reserve = dev->hard_header_len;
if (po->has_vnet_hdr) {
err = packet_snd_vnet_parse(msg, &len, &vnet_hdr);
if (err)
goto out_unlock;
}
if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
if (!netif_supports_nofcs(dev)) {
err = -EPROTONOSUPPORT;
goto out_unlock;
}
extra_len = 4; /* We're doing our own CRC */
}
err = -EMSGSIZE;
if (!vnet_hdr.gso_type &&
(len > dev->mtu + reserve + VLAN_HLEN + extra_len))
goto out_unlock;
err = -ENOBUFS;
hlen = LL_RESERVED_SPACE(dev);
tlen = dev->needed_tailroom;
linear = __virtio16_to_cpu(vio_le(), vnet_hdr.hdr_len);
linear = max(linear, min_t(int, len, dev->hard_header_len));
skb = packet_alloc_skb(sk, hlen + tlen, hlen, len, linear,
msg->msg_flags & MSG_DONTWAIT, &err);
if (skb == NULL)
goto out_unlock;
skb_set_network_header(skb, reserve);
err = -EINVAL;
if (sock->type == SOCK_DGRAM) {
offset = dev_hard_header(skb, dev, ntohs(proto), addr, NULL, len);
if (unlikely(offset < 0))
goto out_free;
}
/* Returns -EFAULT on error */
err = skb_copy_datagram_from_iter(skb, offset, &msg->msg_iter, len);
if (err)
goto out_free;
if (sock->type == SOCK_RAW &&
!dev_validate_header(dev, skb->data, len)) {
err = -EINVAL;
goto out_free;
}
sock_tx_timestamp(sk, sockc.tsflags, &skb_shinfo(skb)->tx_flags);
if (!vnet_hdr.gso_type && (len > dev->mtu + reserve + extra_len) &&
!packet_extra_vlan_len_allowed(dev, skb)) {
err = -EMSGSIZE;
goto out_free;
}
skb->protocol = proto;
skb->dev = dev;
skb->priority = sk->sk_priority;
skb->mark = sockc.mark;
packet_pick_tx_queue(dev, skb);
if (po->has_vnet_hdr) {
err = virtio_net_hdr_to_skb(skb, &vnet_hdr, vio_le());
if (err)
goto out_free;
len += sizeof(vnet_hdr);
}
skb_probe_transport_header(skb, reserve);
if (unlikely(extra_len == 4))
skb->no_fcs = 1;
err = po->xmit(skb);
if (err > 0 && (err = net_xmit_errno(err)) != 0)
goto out_unlock;
dev_put(dev);
return len;
out_free:
kfree_skb(skb);
out_unlock:
if (dev)
dev_put(dev);
out:
return err;
}
static int packet_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
if (po->tx_ring.pg_vec)
return tpacket_snd(po, msg);
else
return packet_snd(sock, msg, len);
}
/*
* Close a PACKET socket. This is fairly simple. We immediately go
* to 'closed' state and remove our protocol entry in the device list.
*/
static int packet_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct packet_sock *po;
struct net *net;
union tpacket_req_u req_u;
if (!sk)
return 0;
net = sock_net(sk);
po = pkt_sk(sk);
mutex_lock(&net->packet.sklist_lock);
sk_del_node_init_rcu(sk);
mutex_unlock(&net->packet.sklist_lock);
preempt_disable();
sock_prot_inuse_add(net, sk->sk_prot, -1);
preempt_enable();
spin_lock(&po->bind_lock);
unregister_prot_hook(sk, false);
packet_cached_dev_reset(po);
if (po->prot_hook.dev) {
dev_put(po->prot_hook.dev);
po->prot_hook.dev = NULL;
}
spin_unlock(&po->bind_lock);
packet_flush_mclist(sk);
if (po->rx_ring.pg_vec) {
memset(&req_u, 0, sizeof(req_u));
packet_set_ring(sk, &req_u, 1, 0);
}
if (po->tx_ring.pg_vec) {
memset(&req_u, 0, sizeof(req_u));
packet_set_ring(sk, &req_u, 1, 1);
}
fanout_release(sk);
synchronize_net();
/*
* Now the socket is dead. No more input will appear.
*/
sock_orphan(sk);
sock->sk = NULL;
/* Purge queues */
skb_queue_purge(&sk->sk_receive_queue);
packet_free_pending(po);
sk_refcnt_debug_release(sk);
sock_put(sk);
return 0;
}
/*
* Attach a packet hook.
*/
static int packet_do_bind(struct sock *sk, const char *name, int ifindex,
__be16 proto)
{
struct packet_sock *po = pkt_sk(sk);
struct net_device *dev_curr;
__be16 proto_curr;
bool need_rehook;
struct net_device *dev = NULL;
int ret = 0;
bool unlisted = false;
if (po->fanout)
return -EINVAL;
lock_sock(sk);
spin_lock(&po->bind_lock);
rcu_read_lock();
if (name) {
dev = dev_get_by_name_rcu(sock_net(sk), name);
if (!dev) {
ret = -ENODEV;
goto out_unlock;
}
} else if (ifindex) {
dev = dev_get_by_index_rcu(sock_net(sk), ifindex);
if (!dev) {
ret = -ENODEV;
goto out_unlock;
}
}
if (dev)
dev_hold(dev);
proto_curr = po->prot_hook.type;
dev_curr = po->prot_hook.dev;
need_rehook = proto_curr != proto || dev_curr != dev;
if (need_rehook) {
if (po->running) {
rcu_read_unlock();
__unregister_prot_hook(sk, true);
rcu_read_lock();
dev_curr = po->prot_hook.dev;
if (dev)
unlisted = !dev_get_by_index_rcu(sock_net(sk),
dev->ifindex);
}
po->num = proto;
po->prot_hook.type = proto;
if (unlikely(unlisted)) {
dev_put(dev);
po->prot_hook.dev = NULL;
po->ifindex = -1;
packet_cached_dev_reset(po);
} else {
po->prot_hook.dev = dev;
po->ifindex = dev ? dev->ifindex : 0;
packet_cached_dev_assign(po, dev);
}
}
if (dev_curr)
dev_put(dev_curr);
if (proto == 0 || !need_rehook)
goto out_unlock;
if (!unlisted && (!dev || (dev->flags & IFF_UP))) {
register_prot_hook(sk);
} else {
sk->sk_err = ENETDOWN;
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_error_report(sk);
}
out_unlock:
rcu_read_unlock();
spin_unlock(&po->bind_lock);
release_sock(sk);
return ret;
}
/*
* Bind a packet socket to a device
*/
static int packet_bind_spkt(struct socket *sock, struct sockaddr *uaddr,
int addr_len)
{
struct sock *sk = sock->sk;
char name[15];
/*
* Check legality
*/
if (addr_len != sizeof(struct sockaddr))
return -EINVAL;
strlcpy(name, uaddr->sa_data, sizeof(name));
return packet_do_bind(sk, name, 0, pkt_sk(sk)->num);
}
static int packet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sockaddr_ll *sll = (struct sockaddr_ll *)uaddr;
struct sock *sk = sock->sk;
/*
* Check legality
*/
if (addr_len < sizeof(struct sockaddr_ll))
return -EINVAL;
if (sll->sll_family != AF_PACKET)
return -EINVAL;
return packet_do_bind(sk, NULL, sll->sll_ifindex,
sll->sll_protocol ? : pkt_sk(sk)->num);
}
static struct proto packet_proto = {
.name = "PACKET",
.owner = THIS_MODULE,
.obj_size = sizeof(struct packet_sock),
};
/*
* Create a packet of type SOCK_PACKET.
*/
static int packet_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
struct packet_sock *po;
__be16 proto = (__force __be16)protocol; /* weird, but documented */
int err;
if (!ns_capable(net->user_ns, CAP_NET_RAW))
return -EPERM;
if (sock->type != SOCK_DGRAM && sock->type != SOCK_RAW &&
sock->type != SOCK_PACKET)
return -ESOCKTNOSUPPORT;
sock->state = SS_UNCONNECTED;
err = -ENOBUFS;
sk = sk_alloc(net, PF_PACKET, GFP_KERNEL, &packet_proto, kern);
if (sk == NULL)
goto out;
sock->ops = &packet_ops;
if (sock->type == SOCK_PACKET)
sock->ops = &packet_ops_spkt;
sock_init_data(sock, sk);
po = pkt_sk(sk);
sk->sk_family = PF_PACKET;
po->num = proto;
po->xmit = dev_queue_xmit;
err = packet_alloc_pending(po);
if (err)
goto out2;
packet_cached_dev_reset(po);
sk->sk_destruct = packet_sock_destruct;
sk_refcnt_debug_inc(sk);
/*
* Attach a protocol block
*/
spin_lock_init(&po->bind_lock);
mutex_init(&po->pg_vec_lock);
po->rollover = NULL;
po->prot_hook.func = packet_rcv;
if (sock->type == SOCK_PACKET)
po->prot_hook.func = packet_rcv_spkt;
po->prot_hook.af_packet_priv = sk;
if (proto) {
po->prot_hook.type = proto;
register_prot_hook(sk);
}
mutex_lock(&net->packet.sklist_lock);
sk_add_node_rcu(sk, &net->packet.sklist);
mutex_unlock(&net->packet.sklist_lock);
preempt_disable();
sock_prot_inuse_add(net, &packet_proto, 1);
preempt_enable();
return 0;
out2:
sk_free(sk);
out:
return err;
}
/*
* Pull a packet from our receive queue and hand it to the user.
* If necessary we block.
*/
static int packet_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
int flags)
{
struct sock *sk = sock->sk;
struct sk_buff *skb;
int copied, err;
int vnet_hdr_len = 0;
unsigned int origlen = 0;
err = -EINVAL;
if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))
goto out;
#if 0
/* What error should we return now? EUNATTACH? */
if (pkt_sk(sk)->ifindex < 0)
return -ENODEV;
#endif
if (flags & MSG_ERRQUEUE) {
err = sock_recv_errqueue(sk, msg, len,
SOL_PACKET, PACKET_TX_TIMESTAMP);
goto out;
}
/*
* Call the generic datagram receiver. This handles all sorts
* of horrible races and re-entrancy so we can forget about it
* in the protocol layers.
*
* Now it will return ENETDOWN, if device have just gone down,
* but then it will block.
*/
skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
/*
* An error occurred so return it. Because skb_recv_datagram()
* handles the blocking we don't see and worry about blocking
* retries.
*/
if (skb == NULL)
goto out;
if (pkt_sk(sk)->pressure)
packet_rcv_has_room(pkt_sk(sk), NULL);
if (pkt_sk(sk)->has_vnet_hdr) {
err = packet_rcv_vnet(msg, skb, &len);
if (err)
goto out_free;
vnet_hdr_len = sizeof(struct virtio_net_hdr);
}
/* You lose any data beyond the buffer you gave. If it worries
* a user program they can ask the device for its MTU
* anyway.
*/
copied = skb->len;
if (copied > len) {
copied = len;
msg->msg_flags |= MSG_TRUNC;
}
err = skb_copy_datagram_msg(skb, 0, msg, copied);
if (err)
goto out_free;
if (sock->type != SOCK_PACKET) {
struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
/* Original length was stored in sockaddr_ll fields */
origlen = PACKET_SKB_CB(skb)->sa.origlen;
sll->sll_family = AF_PACKET;
sll->sll_protocol = skb->protocol;
}
sock_recv_ts_and_drops(msg, sk, skb);
if (msg->msg_name) {
/* If the address length field is there to be filled
* in, we fill it in now.
*/
if (sock->type == SOCK_PACKET) {
__sockaddr_check_size(sizeof(struct sockaddr_pkt));
msg->msg_namelen = sizeof(struct sockaddr_pkt);
} else {
struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
msg->msg_namelen = sll->sll_halen +
offsetof(struct sockaddr_ll, sll_addr);
}
memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa,
msg->msg_namelen);
}
if (pkt_sk(sk)->auxdata) {
struct tpacket_auxdata aux;
aux.tp_status = TP_STATUS_USER;
if (skb->ip_summed == CHECKSUM_PARTIAL)
aux.tp_status |= TP_STATUS_CSUMNOTREADY;
else if (skb->pkt_type != PACKET_OUTGOING &&
(skb->ip_summed == CHECKSUM_COMPLETE ||
skb_csum_unnecessary(skb)))
aux.tp_status |= TP_STATUS_CSUM_VALID;
aux.tp_len = origlen;
aux.tp_snaplen = skb->len;
aux.tp_mac = 0;
aux.tp_net = skb_network_offset(skb);
if (skb_vlan_tag_present(skb)) {
aux.tp_vlan_tci = skb_vlan_tag_get(skb);
aux.tp_vlan_tpid = ntohs(skb->vlan_proto);
aux.tp_status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
} else {
aux.tp_vlan_tci = 0;
aux.tp_vlan_tpid = 0;
}
put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);
}
/*
* Free or return the buffer as appropriate. Again this
* hides all the races and re-entrancy issues from us.
*/
err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);
out_free:
skb_free_datagram(sk, skb);
out:
return err;
}
static int packet_getname_spkt(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct net_device *dev;
struct sock *sk = sock->sk;
if (peer)
return -EOPNOTSUPP;
uaddr->sa_family = AF_PACKET;
memset(uaddr->sa_data, 0, sizeof(uaddr->sa_data));
rcu_read_lock();
dev = dev_get_by_index_rcu(sock_net(sk), pkt_sk(sk)->ifindex);
if (dev)
strlcpy(uaddr->sa_data, dev->name, sizeof(uaddr->sa_data));
rcu_read_unlock();
*uaddr_len = sizeof(*uaddr);
return 0;
}
static int packet_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct net_device *dev;
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_ll *, sll, uaddr);
if (peer)
return -EOPNOTSUPP;
sll->sll_family = AF_PACKET;
sll->sll_ifindex = po->ifindex;
sll->sll_protocol = po->num;
sll->sll_pkttype = 0;
rcu_read_lock();
dev = dev_get_by_index_rcu(sock_net(sk), po->ifindex);
if (dev) {
sll->sll_hatype = dev->type;
sll->sll_halen = dev->addr_len;
memcpy(sll->sll_addr, dev->dev_addr, dev->addr_len);
} else {
sll->sll_hatype = 0; /* Bad: we have no ARPHRD_UNSPEC */
sll->sll_halen = 0;
}
rcu_read_unlock();
*uaddr_len = offsetof(struct sockaddr_ll, sll_addr) + sll->sll_halen;
return 0;
}
static int packet_dev_mc(struct net_device *dev, struct packet_mclist *i,
int what)
{
switch (i->type) {
case PACKET_MR_MULTICAST:
if (i->alen != dev->addr_len)
return -EINVAL;
if (what > 0)
return dev_mc_add(dev, i->addr);
else
return dev_mc_del(dev, i->addr);
break;
case PACKET_MR_PROMISC:
return dev_set_promiscuity(dev, what);
case PACKET_MR_ALLMULTI:
return dev_set_allmulti(dev, what);
case PACKET_MR_UNICAST:
if (i->alen != dev->addr_len)
return -EINVAL;
if (what > 0)
return dev_uc_add(dev, i->addr);
else
return dev_uc_del(dev, i->addr);
break;
default:
break;
}
return 0;
}
static void packet_dev_mclist_delete(struct net_device *dev,
struct packet_mclist **mlp)
{
struct packet_mclist *ml;
while ((ml = *mlp) != NULL) {
if (ml->ifindex == dev->ifindex) {
packet_dev_mc(dev, ml, -1);
*mlp = ml->next;
kfree(ml);
} else
mlp = &ml->next;
}
}
static int packet_mc_add(struct sock *sk, struct packet_mreq_max *mreq)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_mclist *ml, *i;
struct net_device *dev;
int err;
rtnl_lock();
err = -ENODEV;
dev = __dev_get_by_index(sock_net(sk), mreq->mr_ifindex);
if (!dev)
goto done;
err = -EINVAL;
if (mreq->mr_alen > dev->addr_len)
goto done;
err = -ENOBUFS;
i = kmalloc(sizeof(*i), GFP_KERNEL);
if (i == NULL)
goto done;
err = 0;
for (ml = po->mclist; ml; ml = ml->next) {
if (ml->ifindex == mreq->mr_ifindex &&
ml->type == mreq->mr_type &&
ml->alen == mreq->mr_alen &&
memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
ml->count++;
/* Free the new element ... */
kfree(i);
goto done;
}
}
i->type = mreq->mr_type;
i->ifindex = mreq->mr_ifindex;
i->alen = mreq->mr_alen;
memcpy(i->addr, mreq->mr_address, i->alen);
memset(i->addr + i->alen, 0, sizeof(i->addr) - i->alen);
i->count = 1;
i->next = po->mclist;
po->mclist = i;
err = packet_dev_mc(dev, i, 1);
if (err) {
po->mclist = i->next;
kfree(i);
}
done:
rtnl_unlock();
return err;
}
static int packet_mc_drop(struct sock *sk, struct packet_mreq_max *mreq)
{
struct packet_mclist *ml, **mlp;
rtnl_lock();
for (mlp = &pkt_sk(sk)->mclist; (ml = *mlp) != NULL; mlp = &ml->next) {
if (ml->ifindex == mreq->mr_ifindex &&
ml->type == mreq->mr_type &&
ml->alen == mreq->mr_alen &&
memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
if (--ml->count == 0) {
struct net_device *dev;
*mlp = ml->next;
dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
if (dev)
packet_dev_mc(dev, ml, -1);
kfree(ml);
}
break;
}
}
rtnl_unlock();
return 0;
}
static void packet_flush_mclist(struct sock *sk)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_mclist *ml;
if (!po->mclist)
return;
rtnl_lock();
while ((ml = po->mclist) != NULL) {
struct net_device *dev;
po->mclist = ml->next;
dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
if (dev != NULL)
packet_dev_mc(dev, ml, -1);
kfree(ml);
}
rtnl_unlock();
}
static int
packet_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
int ret;
if (level != SOL_PACKET)
return -ENOPROTOOPT;
switch (optname) {
case PACKET_ADD_MEMBERSHIP:
case PACKET_DROP_MEMBERSHIP:
{
struct packet_mreq_max mreq;
int len = optlen;
memset(&mreq, 0, sizeof(mreq));
if (len < sizeof(struct packet_mreq))
return -EINVAL;
if (len > sizeof(mreq))
len = sizeof(mreq);
if (copy_from_user(&mreq, optval, len))
return -EFAULT;
if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address)))
return -EINVAL;
if (optname == PACKET_ADD_MEMBERSHIP)
ret = packet_mc_add(sk, &mreq);
else
ret = packet_mc_drop(sk, &mreq);
return ret;
}
case PACKET_RX_RING:
case PACKET_TX_RING:
{
union tpacket_req_u req_u;
int len;
switch (po->tp_version) {
case TPACKET_V1:
case TPACKET_V2:
len = sizeof(req_u.req);
break;
case TPACKET_V3:
default:
len = sizeof(req_u.req3);
break;
}
if (optlen < len)
return -EINVAL;
if (copy_from_user(&req_u.req, optval, len))
return -EFAULT;
return packet_set_ring(sk, &req_u, 0,
optname == PACKET_TX_RING);
}
case PACKET_COPY_THRESH:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
pkt_sk(sk)->copy_thresh = val;
return 0;
}
case PACKET_VERSION:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
switch (val) {
case TPACKET_V1:
case TPACKET_V2:
case TPACKET_V3:
break;
default:
return -EINVAL;
}
lock_sock(sk);
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
ret = -EBUSY;
} else {
po->tp_version = val;
ret = 0;
}
release_sock(sk);
return ret;
}
case PACKET_RESERVE:
{
unsigned int val;
if (optlen != sizeof(val))
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->tp_reserve = val;
return 0;
}
case PACKET_LOSS:
{
unsigned int val;
if (optlen != sizeof(val))
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->tp_loss = !!val;
return 0;
}
case PACKET_AUXDATA:
{
int val;
if (optlen < sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->auxdata = !!val;
return 0;
}
case PACKET_ORIGDEV:
{
int val;
if (optlen < sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->origdev = !!val;
return 0;
}
case PACKET_VNET_HDR:
{
int val;
if (sock->type != SOCK_RAW)
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (optlen < sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->has_vnet_hdr = !!val;
return 0;
}
case PACKET_TIMESTAMP:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->tp_tstamp = val;
return 0;
}
case PACKET_FANOUT:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
return fanout_add(sk, val & 0xffff, val >> 16);
}
case PACKET_FANOUT_DATA:
{
if (!po->fanout)
return -EINVAL;
return fanout_set_data(po, optval, optlen);
}
case PACKET_TX_HAS_OFF:
{
unsigned int val;
if (optlen != sizeof(val))
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->tp_tx_has_off = !!val;
return 0;
}
case PACKET_QDISC_BYPASS:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->xmit = val ? packet_direct_xmit : dev_queue_xmit;
return 0;
}
default:
return -ENOPROTOOPT;
}
}
static int packet_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
int len;
int val, lv = sizeof(val);
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
void *data = &val;
union tpacket_stats_u st;
struct tpacket_rollover_stats rstats;
if (level != SOL_PACKET)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
switch (optname) {
case PACKET_STATISTICS:
spin_lock_bh(&sk->sk_receive_queue.lock);
memcpy(&st, &po->stats, sizeof(st));
memset(&po->stats, 0, sizeof(po->stats));
spin_unlock_bh(&sk->sk_receive_queue.lock);
if (po->tp_version == TPACKET_V3) {
lv = sizeof(struct tpacket_stats_v3);
st.stats3.tp_packets += st.stats3.tp_drops;
data = &st.stats3;
} else {
lv = sizeof(struct tpacket_stats);
st.stats1.tp_packets += st.stats1.tp_drops;
data = &st.stats1;
}
break;
case PACKET_AUXDATA:
val = po->auxdata;
break;
case PACKET_ORIGDEV:
val = po->origdev;
break;
case PACKET_VNET_HDR:
val = po->has_vnet_hdr;
break;
case PACKET_VERSION:
val = po->tp_version;
break;
case PACKET_HDRLEN:
if (len > sizeof(int))
len = sizeof(int);
if (copy_from_user(&val, optval, len))
return -EFAULT;
switch (val) {
case TPACKET_V1:
val = sizeof(struct tpacket_hdr);
break;
case TPACKET_V2:
val = sizeof(struct tpacket2_hdr);
break;
case TPACKET_V3:
val = sizeof(struct tpacket3_hdr);
break;
default:
return -EINVAL;
}
break;
case PACKET_RESERVE:
val = po->tp_reserve;
break;
case PACKET_LOSS:
val = po->tp_loss;
break;
case PACKET_TIMESTAMP:
val = po->tp_tstamp;
break;
case PACKET_FANOUT:
val = (po->fanout ?
((u32)po->fanout->id |
((u32)po->fanout->type << 16) |
((u32)po->fanout->flags << 24)) :
0);
break;
case PACKET_ROLLOVER_STATS:
if (!po->rollover)
return -EINVAL;
rstats.tp_all = atomic_long_read(&po->rollover->num);
rstats.tp_huge = atomic_long_read(&po->rollover->num_huge);
rstats.tp_failed = atomic_long_read(&po->rollover->num_failed);
data = &rstats;
lv = sizeof(rstats);
break;
case PACKET_TX_HAS_OFF:
val = po->tp_tx_has_off;
break;
case PACKET_QDISC_BYPASS:
val = packet_use_direct_xmit(po);
break;
default:
return -ENOPROTOOPT;
}
if (len > lv)
len = lv;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, data, len))
return -EFAULT;
return 0;
}
#ifdef CONFIG_COMPAT
static int compat_packet_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct packet_sock *po = pkt_sk(sock->sk);
if (level != SOL_PACKET)
return -ENOPROTOOPT;
if (optname == PACKET_FANOUT_DATA &&
po->fanout && po->fanout->type == PACKET_FANOUT_CBPF) {
optval = (char __user *)get_compat_bpf_fprog(optval);
if (!optval)
return -EFAULT;
optlen = sizeof(struct sock_fprog);
}
return packet_setsockopt(sock, level, optname, optval, optlen);
}
#endif
static int packet_notifier(struct notifier_block *this,
unsigned long msg, void *ptr)
{
struct sock *sk;
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
struct net *net = dev_net(dev);
rcu_read_lock();
sk_for_each_rcu(sk, &net->packet.sklist) {
struct packet_sock *po = pkt_sk(sk);
switch (msg) {
case NETDEV_UNREGISTER:
if (po->mclist)
packet_dev_mclist_delete(dev, &po->mclist);
/* fallthrough */
case NETDEV_DOWN:
if (dev->ifindex == po->ifindex) {
spin_lock(&po->bind_lock);
if (po->running) {
__unregister_prot_hook(sk, false);
sk->sk_err = ENETDOWN;
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_error_report(sk);
}
if (msg == NETDEV_UNREGISTER) {
packet_cached_dev_reset(po);
fanout_release(sk);
po->ifindex = -1;
if (po->prot_hook.dev)
dev_put(po->prot_hook.dev);
po->prot_hook.dev = NULL;
}
spin_unlock(&po->bind_lock);
}
break;
case NETDEV_UP:
if (dev->ifindex == po->ifindex) {
spin_lock(&po->bind_lock);
if (po->num)
register_prot_hook(sk);
spin_unlock(&po->bind_lock);
}
break;
}
}
rcu_read_unlock();
return NOTIFY_DONE;
}
static int packet_ioctl(struct socket *sock, unsigned int cmd,
unsigned long arg)
{
struct sock *sk = sock->sk;
switch (cmd) {
case SIOCOUTQ:
{
int amount = sk_wmem_alloc_get(sk);
return put_user(amount, (int __user *)arg);
}
case SIOCINQ:
{
struct sk_buff *skb;
int amount = 0;
spin_lock_bh(&sk->sk_receive_queue.lock);
skb = skb_peek(&sk->sk_receive_queue);
if (skb)
amount = skb->len;
spin_unlock_bh(&sk->sk_receive_queue.lock);
return put_user(amount, (int __user *)arg);
}
case SIOCGSTAMP:
return sock_get_timestamp(sk, (struct timeval __user *)arg);
case SIOCGSTAMPNS:
return sock_get_timestampns(sk, (struct timespec __user *)arg);
#ifdef CONFIG_INET
case SIOCADDRT:
case SIOCDELRT:
case SIOCDARP:
case SIOCGARP:
case SIOCSARP:
case SIOCGIFADDR:
case SIOCSIFADDR:
case SIOCGIFBRDADDR:
case SIOCSIFBRDADDR:
case SIOCGIFNETMASK:
case SIOCSIFNETMASK:
case SIOCGIFDSTADDR:
case SIOCSIFDSTADDR:
case SIOCSIFFLAGS:
return inet_dgram_ops.ioctl(sock, cmd, arg);
#endif
default:
return -ENOIOCTLCMD;
}
return 0;
}
static unsigned int packet_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
unsigned int mask = datagram_poll(file, sock, wait);
spin_lock_bh(&sk->sk_receive_queue.lock);
if (po->rx_ring.pg_vec) {
if (!packet_previous_rx_frame(po, &po->rx_ring,
TP_STATUS_KERNEL))
mask |= POLLIN | POLLRDNORM;
}
if (po->pressure && __packet_rcv_has_room(po, NULL) == ROOM_NORMAL)
po->pressure = 0;
spin_unlock_bh(&sk->sk_receive_queue.lock);
spin_lock_bh(&sk->sk_write_queue.lock);
if (po->tx_ring.pg_vec) {
if (packet_current_frame(po, &po->tx_ring, TP_STATUS_AVAILABLE))
mask |= POLLOUT | POLLWRNORM;
}
spin_unlock_bh(&sk->sk_write_queue.lock);
return mask;
}
/* Dirty? Well, I still did not learn better way to account
* for user mmaps.
*/
static void packet_mm_open(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
struct socket *sock = file->private_data;
struct sock *sk = sock->sk;
if (sk)
atomic_inc(&pkt_sk(sk)->mapped);
}
static void packet_mm_close(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
struct socket *sock = file->private_data;
struct sock *sk = sock->sk;
if (sk)
atomic_dec(&pkt_sk(sk)->mapped);
}
static const struct vm_operations_struct packet_mmap_ops = {
.open = packet_mm_open,
.close = packet_mm_close,
};
static void free_pg_vec(struct pgv *pg_vec, unsigned int order,
unsigned int len)
{
int i;
for (i = 0; i < len; i++) {
if (likely(pg_vec[i].buffer)) {
if (is_vmalloc_addr(pg_vec[i].buffer))
vfree(pg_vec[i].buffer);
else
free_pages((unsigned long)pg_vec[i].buffer,
order);
pg_vec[i].buffer = NULL;
}
}
kfree(pg_vec);
}
static char *alloc_one_pg_vec_page(unsigned long order)
{
char *buffer;
gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
__GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
buffer = (char *) __get_free_pages(gfp_flags, order);
if (buffer)
return buffer;
/* __get_free_pages failed, fall back to vmalloc */
buffer = vzalloc((1 << order) * PAGE_SIZE);
if (buffer)
return buffer;
/* vmalloc failed, lets dig into swap here */
gfp_flags &= ~__GFP_NORETRY;
buffer = (char *) __get_free_pages(gfp_flags, order);
if (buffer)
return buffer;
/* complete and utter failure */
return NULL;
}
static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
{
unsigned int block_nr = req->tp_block_nr;
struct pgv *pg_vec;
int i;
pg_vec = kcalloc(block_nr, sizeof(struct pgv), GFP_KERNEL);
if (unlikely(!pg_vec))
goto out;
for (i = 0; i < block_nr; i++) {
pg_vec[i].buffer = alloc_one_pg_vec_page(order);
if (unlikely(!pg_vec[i].buffer))
goto out_free_pgvec;
}
out:
return pg_vec;
out_free_pgvec:
free_pg_vec(pg_vec, order, block_nr);
pg_vec = NULL;
goto out;
}
static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
int closing, int tx_ring)
{
struct pgv *pg_vec = NULL;
struct packet_sock *po = pkt_sk(sk);
int was_running, order = 0;
struct packet_ring_buffer *rb;
struct sk_buff_head *rb_queue;
__be16 num;
int err = -EINVAL;
/* Added to avoid minimal code churn */
struct tpacket_req *req = &req_u->req;
lock_sock(sk);
/* Opening a Tx-ring is NOT supported in TPACKET_V3 */
if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) {
net_warn_ratelimited("Tx-ring is not supported.\n");
goto out;
}
rb = tx_ring ? &po->tx_ring : &po->rx_ring;
rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
err = -EBUSY;
if (!closing) {
if (atomic_read(&po->mapped))
goto out;
if (packet_read_pending(rb))
goto out;
}
if (req->tp_block_nr) {
/* Sanity tests and some calculations */
err = -EBUSY;
if (unlikely(rb->pg_vec))
goto out;
switch (po->tp_version) {
case TPACKET_V1:
po->tp_hdrlen = TPACKET_HDRLEN;
break;
case TPACKET_V2:
po->tp_hdrlen = TPACKET2_HDRLEN;
break;
case TPACKET_V3:
po->tp_hdrlen = TPACKET3_HDRLEN;
break;
}
err = -EINVAL;
if (unlikely((int)req->tp_block_size <= 0))
goto out;
if (unlikely(!PAGE_ALIGNED(req->tp_block_size)))
goto out;
if (po->tp_version >= TPACKET_V3 &&
(int)(req->tp_block_size -
BLK_PLUS_PRIV(req_u->req3.tp_sizeof_priv)) <= 0)
goto out;
if (unlikely(req->tp_frame_size < po->tp_hdrlen +
po->tp_reserve))
goto out;
if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1)))
goto out;
rb->frames_per_block = req->tp_block_size / req->tp_frame_size;
if (unlikely(rb->frames_per_block == 0))
goto out;
if (unlikely((rb->frames_per_block * req->tp_block_nr) !=
req->tp_frame_nr))
goto out;
err = -ENOMEM;
order = get_order(req->tp_block_size);
pg_vec = alloc_pg_vec(req, order);
if (unlikely(!pg_vec))
goto out;
switch (po->tp_version) {
case TPACKET_V3:
/* Transmit path is not supported. We checked
* it above but just being paranoid
*/
if (!tx_ring)
init_prb_bdqc(po, rb, pg_vec, req_u);
break;
default:
break;
}
}
/* Done */
else {
err = -EINVAL;
if (unlikely(req->tp_frame_nr))
goto out;
}
/* Detach socket from network */
spin_lock(&po->bind_lock);
was_running = po->running;
num = po->num;
if (was_running) {
po->num = 0;
__unregister_prot_hook(sk, false);
}
spin_unlock(&po->bind_lock);
synchronize_net();
err = -EBUSY;
mutex_lock(&po->pg_vec_lock);
if (closing || atomic_read(&po->mapped) == 0) {
err = 0;
spin_lock_bh(&rb_queue->lock);
swap(rb->pg_vec, pg_vec);
rb->frame_max = (req->tp_frame_nr - 1);
rb->head = 0;
rb->frame_size = req->tp_frame_size;
spin_unlock_bh(&rb_queue->lock);
swap(rb->pg_vec_order, order);
swap(rb->pg_vec_len, req->tp_block_nr);
rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE;
po->prot_hook.func = (po->rx_ring.pg_vec) ?
tpacket_rcv : packet_rcv;
skb_queue_purge(rb_queue);
if (atomic_read(&po->mapped))
pr_err("packet_mmap: vma is busy: %d\n",
atomic_read(&po->mapped));
}
mutex_unlock(&po->pg_vec_lock);
spin_lock(&po->bind_lock);
if (was_running) {
po->num = num;
register_prot_hook(sk);
}
spin_unlock(&po->bind_lock);
if (closing && (po->tp_version > TPACKET_V2)) {
/* Because we don't support block-based V3 on tx-ring */
if (!tx_ring)
prb_shutdown_retire_blk_timer(po, rb_queue);
}
if (pg_vec)
free_pg_vec(pg_vec, order, req->tp_block_nr);
out:
release_sock(sk);
return err;
}
static int packet_mmap(struct file *file, struct socket *sock,
struct vm_area_struct *vma)
{
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
unsigned long size, expected_size;
struct packet_ring_buffer *rb;
unsigned long start;
int err = -EINVAL;
int i;
if (vma->vm_pgoff)
return -EINVAL;
mutex_lock(&po->pg_vec_lock);
expected_size = 0;
for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
if (rb->pg_vec) {
expected_size += rb->pg_vec_len
* rb->pg_vec_pages
* PAGE_SIZE;
}
}
if (expected_size == 0)
goto out;
size = vma->vm_end - vma->vm_start;
if (size != expected_size)
goto out;
start = vma->vm_start;
for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
if (rb->pg_vec == NULL)
continue;
for (i = 0; i < rb->pg_vec_len; i++) {
struct page *page;
void *kaddr = rb->pg_vec[i].buffer;
int pg_num;
for (pg_num = 0; pg_num < rb->pg_vec_pages; pg_num++) {
page = pgv_to_page(kaddr);
err = vm_insert_page(vma, start, page);
if (unlikely(err))
goto out;
start += PAGE_SIZE;
kaddr += PAGE_SIZE;
}
}
}
atomic_inc(&po->mapped);
vma->vm_ops = &packet_mmap_ops;
err = 0;
out:
mutex_unlock(&po->pg_vec_lock);
return err;
}
static const struct proto_ops packet_ops_spkt = {
.family = PF_PACKET,
.owner = THIS_MODULE,
.release = packet_release,
.bind = packet_bind_spkt,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = packet_getname_spkt,
.poll = datagram_poll,
.ioctl = packet_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = packet_sendmsg_spkt,
.recvmsg = packet_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static const struct proto_ops packet_ops = {
.family = PF_PACKET,
.owner = THIS_MODULE,
.release = packet_release,
.bind = packet_bind,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = packet_getname,
.poll = packet_poll,
.ioctl = packet_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = packet_setsockopt,
.getsockopt = packet_getsockopt,
#ifdef CONFIG_COMPAT
.compat_setsockopt = compat_packet_setsockopt,
#endif
.sendmsg = packet_sendmsg,
.recvmsg = packet_recvmsg,
.mmap = packet_mmap,
.sendpage = sock_no_sendpage,
};
static const struct net_proto_family packet_family_ops = {
.family = PF_PACKET,
.create = packet_create,
.owner = THIS_MODULE,
};
static struct notifier_block packet_netdev_notifier = {
.notifier_call = packet_notifier,
};
#ifdef CONFIG_PROC_FS
static void *packet_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(RCU)
{
struct net *net = seq_file_net(seq);
rcu_read_lock();
return seq_hlist_start_head_rcu(&net->packet.sklist, *pos);
}
static void *packet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct net *net = seq_file_net(seq);
return seq_hlist_next_rcu(v, &net->packet.sklist, pos);
}
static void packet_seq_stop(struct seq_file *seq, void *v)
__releases(RCU)
{
rcu_read_unlock();
}
static int packet_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq, "sk RefCnt Type Proto Iface R Rmem User Inode\n");
else {
struct sock *s = sk_entry(v);
const struct packet_sock *po = pkt_sk(s);
seq_printf(seq,
"%pK %-6d %-4d %04x %-5d %1d %-6u %-6u %-6lu\n",
s,
atomic_read(&s->sk_refcnt),
s->sk_type,
ntohs(po->num),
po->ifindex,
po->running,
atomic_read(&s->sk_rmem_alloc),
from_kuid_munged(seq_user_ns(seq), sock_i_uid(s)),
sock_i_ino(s));
}
return 0;
}
static const struct seq_operations packet_seq_ops = {
.start = packet_seq_start,
.next = packet_seq_next,
.stop = packet_seq_stop,
.show = packet_seq_show,
};
static int packet_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &packet_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations packet_seq_fops = {
.owner = THIS_MODULE,
.open = packet_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
static int __net_init packet_net_init(struct net *net)
{
mutex_init(&net->packet.sklist_lock);
INIT_HLIST_HEAD(&net->packet.sklist);
if (!proc_create("packet", 0, net->proc_net, &packet_seq_fops))
return -ENOMEM;
return 0;
}
static void __net_exit packet_net_exit(struct net *net)
{
remove_proc_entry("packet", net->proc_net);
}
static struct pernet_operations packet_net_ops = {
.init = packet_net_init,
.exit = packet_net_exit,
};
static void __exit packet_exit(void)
{
unregister_netdevice_notifier(&packet_netdev_notifier);
unregister_pernet_subsys(&packet_net_ops);
sock_unregister(PF_PACKET);
proto_unregister(&packet_proto);
}
static int __init packet_init(void)
{
int rc = proto_register(&packet_proto, 0);
if (rc != 0)
goto out;
sock_register(&packet_family_ops);
register_pernet_subsys(&packet_net_ops);
register_netdevice_notifier(&packet_netdev_notifier);
out:
return rc;
}
module_init(packet_init);
module_exit(packet_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_PACKET);
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_3175_0 |
crossvul-cpp_data_good_84_0 | /*
** vm.c - virtual machine for mruby
**
** See Copyright Notice in mruby.h
*/
#include <stddef.h>
#include <stdarg.h>
#include <math.h>
#include <mruby.h>
#include <mruby/array.h>
#include <mruby/class.h>
#include <mruby/hash.h>
#include <mruby/irep.h>
#include <mruby/numeric.h>
#include <mruby/proc.h>
#include <mruby/range.h>
#include <mruby/string.h>
#include <mruby/variable.h>
#include <mruby/error.h>
#include <mruby/opcode.h>
#include "value_array.h"
#include <mruby/throw.h>
#ifdef MRB_DISABLE_STDIO
#if defined(__cplusplus)
extern "C" {
#endif
void abort(void);
#if defined(__cplusplus)
} /* extern "C" { */
#endif
#endif
#define STACK_INIT_SIZE 128
#define CALLINFO_INIT_SIZE 32
#ifndef ENSURE_STACK_INIT_SIZE
#define ENSURE_STACK_INIT_SIZE 16
#endif
#ifndef RESCUE_STACK_INIT_SIZE
#define RESCUE_STACK_INIT_SIZE 16
#endif
/* Define amount of linear stack growth. */
#ifndef MRB_STACK_GROWTH
#define MRB_STACK_GROWTH 128
#endif
/* Maximum mrb_funcall() depth. Should be set lower on memory constrained systems. */
#ifndef MRB_FUNCALL_DEPTH_MAX
#define MRB_FUNCALL_DEPTH_MAX 512
#endif
/* Maximum depth of ecall() recursion. */
#ifndef MRB_ECALL_DEPTH_MAX
#define MRB_ECALL_DEPTH_MAX 32
#endif
/* Maximum stack depth. Should be set lower on memory constrained systems.
The value below allows about 60000 recursive calls in the simplest case. */
#ifndef MRB_STACK_MAX
#define MRB_STACK_MAX (0x40000 - MRB_STACK_GROWTH)
#endif
#ifdef VM_DEBUG
# define DEBUG(x) (x)
#else
# define DEBUG(x)
#endif
#ifndef MRB_GC_FIXED_ARENA
static void
mrb_gc_arena_shrink(mrb_state *mrb, int idx)
{
mrb_gc *gc = &mrb->gc;
int capa = gc->arena_capa;
if (idx < capa / 4) {
capa >>= 2;
if (capa < MRB_GC_ARENA_SIZE) {
capa = MRB_GC_ARENA_SIZE;
}
if (capa != gc->arena_capa) {
gc->arena = (struct RBasic**)mrb_realloc(mrb, gc->arena, sizeof(struct RBasic*)*capa);
gc->arena_capa = capa;
}
}
}
#else
#define mrb_gc_arena_shrink(mrb,idx)
#endif
#define CALL_MAXARGS 127
void mrb_method_missing(mrb_state *mrb, mrb_sym name, mrb_value self, mrb_value args);
static inline void
stack_clear(mrb_value *from, size_t count)
{
#ifndef MRB_NAN_BOXING
const mrb_value mrb_value_zero = { { 0 } };
while (count-- > 0) {
*from++ = mrb_value_zero;
}
#else
while (count-- > 0) {
SET_NIL_VALUE(*from);
from++;
}
#endif
}
static inline void
stack_copy(mrb_value *dst, const mrb_value *src, size_t size)
{
while (size-- > 0) {
*dst++ = *src++;
}
}
static void
stack_init(mrb_state *mrb)
{
struct mrb_context *c = mrb->c;
/* mrb_assert(mrb->stack == NULL); */
c->stbase = (mrb_value *)mrb_calloc(mrb, STACK_INIT_SIZE, sizeof(mrb_value));
c->stend = c->stbase + STACK_INIT_SIZE;
c->stack = c->stbase;
/* mrb_assert(ci == NULL); */
c->cibase = (mrb_callinfo *)mrb_calloc(mrb, CALLINFO_INIT_SIZE, sizeof(mrb_callinfo));
c->ciend = c->cibase + CALLINFO_INIT_SIZE;
c->ci = c->cibase;
c->ci->target_class = mrb->object_class;
c->ci->stackent = c->stack;
}
static inline void
envadjust(mrb_state *mrb, mrb_value *oldbase, mrb_value *newbase, size_t size)
{
mrb_callinfo *ci = mrb->c->cibase;
if (newbase == oldbase) return;
while (ci <= mrb->c->ci) {
struct REnv *e = ci->env;
mrb_value *st;
if (e && MRB_ENV_STACK_SHARED_P(e) &&
(st = e->stack) && oldbase <= st && st < oldbase+size) {
ptrdiff_t off = e->stack - oldbase;
e->stack = newbase + off;
}
if (ci->proc && MRB_PROC_ENV_P(ci->proc) && ci->env != MRB_PROC_ENV(ci->proc)) {
e = MRB_PROC_ENV(ci->proc);
if (e && MRB_ENV_STACK_SHARED_P(e) &&
(st = e->stack) && oldbase <= st && st < oldbase+size) {
ptrdiff_t off = e->stack - oldbase;
e->stack = newbase + off;
}
}
ci->stackent = newbase + (ci->stackent - oldbase);
ci++;
}
}
/** def rec ; $deep =+ 1 ; if $deep > 1000 ; return 0 ; end ; rec ; end */
static void
stack_extend_alloc(mrb_state *mrb, int room)
{
mrb_value *oldbase = mrb->c->stbase;
mrb_value *newstack;
size_t oldsize = mrb->c->stend - mrb->c->stbase;
size_t size = oldsize;
size_t off = mrb->c->stack - mrb->c->stbase;
if (off > size) size = off;
#ifdef MRB_STACK_EXTEND_DOUBLING
if (room <= size)
size *= 2;
else
size += room;
#else
/* Use linear stack growth.
It is slightly slower than doubling the stack space,
but it saves memory on small devices. */
if (room <= MRB_STACK_GROWTH)
size += MRB_STACK_GROWTH;
else
size += room;
#endif
newstack = (mrb_value *)mrb_realloc(mrb, mrb->c->stbase, sizeof(mrb_value) * size);
if (newstack == NULL) {
mrb_exc_raise(mrb, mrb_obj_value(mrb->stack_err));
}
stack_clear(&(newstack[oldsize]), size - oldsize);
envadjust(mrb, oldbase, newstack, size);
mrb->c->stbase = newstack;
mrb->c->stack = mrb->c->stbase + off;
mrb->c->stend = mrb->c->stbase + size;
/* Raise an exception if the new stack size will be too large,
to prevent infinite recursion. However, do this only after resizing the stack, so mrb_raise has stack space to work with. */
if (size > MRB_STACK_MAX) {
mrb_exc_raise(mrb, mrb_obj_value(mrb->stack_err));
}
}
static inline void
stack_extend(mrb_state *mrb, int room)
{
if (mrb->c->stack + room >= mrb->c->stend) {
stack_extend_alloc(mrb, room);
}
}
static inline struct REnv*
uvenv(mrb_state *mrb, int up)
{
struct RProc *proc = mrb->c->ci->proc;
struct REnv *e;
while (up--) {
proc = proc->upper;
if (!proc) return NULL;
}
e = MRB_PROC_ENV(proc);
if (e) return e; /* proc has enclosed env */
else {
mrb_callinfo *ci = mrb->c->ci;
mrb_callinfo *cb = mrb->c->cibase;
while (cb <= ci) {
if (ci->proc == proc) {
return ci->env;
}
ci--;
}
}
return NULL;
}
static inline struct RProc*
top_proc(mrb_state *mrb, struct RProc *proc)
{
while (proc->upper) {
if (MRB_PROC_SCOPE_P(proc) || MRB_PROC_STRICT_P(proc))
return proc;
proc = proc->upper;
}
return proc;
}
#define CI_ACC_SKIP -1
#define CI_ACC_DIRECT -2
#define CI_ACC_RESUMED -3
static inline mrb_callinfo*
cipush(mrb_state *mrb)
{
struct mrb_context *c = mrb->c;
static const mrb_callinfo ci_zero = { 0 };
mrb_callinfo *ci = c->ci;
int ridx = ci->ridx;
if (ci + 1 == c->ciend) {
ptrdiff_t size = ci - c->cibase;
c->cibase = (mrb_callinfo *)mrb_realloc(mrb, c->cibase, sizeof(mrb_callinfo)*size*2);
c->ci = c->cibase + size;
c->ciend = c->cibase + size * 2;
}
ci = ++c->ci;
*ci = ci_zero;
ci->epos = mrb->c->eidx;
ci->ridx = ridx;
return ci;
}
void
mrb_env_unshare(mrb_state *mrb, struct REnv *e)
{
if (e == NULL) return;
else {
size_t len = (size_t)MRB_ENV_STACK_LEN(e);
mrb_value *p;
if (!MRB_ENV_STACK_SHARED_P(e)) return;
if (e->cxt != mrb->c) return;
p = (mrb_value *)mrb_malloc(mrb, sizeof(mrb_value)*len);
if (len > 0) {
stack_copy(p, e->stack, len);
}
e->stack = p;
MRB_ENV_UNSHARE_STACK(e);
mrb_write_barrier(mrb, (struct RBasic *)e);
}
}
static inline void
cipop(mrb_state *mrb)
{
struct mrb_context *c = mrb->c;
struct REnv *env = c->ci->env;
c->ci--;
if (env) mrb_env_unshare(mrb, env);
}
void mrb_exc_set(mrb_state *mrb, mrb_value exc);
static void
ecall(mrb_state *mrb)
{
struct RProc *p;
struct mrb_context *c = mrb->c;
mrb_callinfo *ci = c->ci;
struct RObject *exc;
struct REnv *env;
ptrdiff_t cioff;
int ai = mrb_gc_arena_save(mrb);
int i = --c->eidx;
int nregs;
if (i<0) return;
if (ci - c->cibase > MRB_ECALL_DEPTH_MAX) {
mrb_exc_raise(mrb, mrb_obj_value(mrb->stack_err));
}
p = c->ensure[i];
if (!p) return;
mrb_assert(!MRB_PROC_CFUNC_P(p));
c->ensure[i] = NULL;
nregs = p->upper->body.irep->nregs;
if (ci->proc && !MRB_PROC_CFUNC_P(ci->proc) &&
ci->proc->body.irep->nregs > nregs) {
nregs = ci->proc->body.irep->nregs;
}
cioff = ci - c->cibase;
ci = cipush(mrb);
ci->stackent = mrb->c->stack;
ci->mid = ci[-1].mid;
ci->acc = CI_ACC_SKIP;
ci->argc = 0;
ci->proc = p;
ci->nregs = p->body.irep->nregs;
ci->target_class = MRB_PROC_TARGET_CLASS(p);
env = MRB_PROC_ENV(p);
mrb_assert(env);
c->stack += nregs;
exc = mrb->exc; mrb->exc = 0;
if (exc) {
mrb_gc_protect(mrb, mrb_obj_value(exc));
}
mrb_run(mrb, p, env->stack[0]);
mrb->c = c;
c->ci = c->cibase + cioff;
if (!mrb->exc) mrb->exc = exc;
mrb_gc_arena_restore(mrb, ai);
}
#ifndef MRB_FUNCALL_ARGC_MAX
#define MRB_FUNCALL_ARGC_MAX 16
#endif
MRB_API mrb_value
mrb_funcall(mrb_state *mrb, mrb_value self, const char *name, mrb_int argc, ...)
{
mrb_value argv[MRB_FUNCALL_ARGC_MAX];
va_list ap;
mrb_int i;
mrb_sym mid = mrb_intern_cstr(mrb, name);
if (argc > MRB_FUNCALL_ARGC_MAX) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "Too long arguments. (limit=" MRB_STRINGIZE(MRB_FUNCALL_ARGC_MAX) ")");
}
va_start(ap, argc);
for (i = 0; i < argc; i++) {
argv[i] = va_arg(ap, mrb_value);
}
va_end(ap);
return mrb_funcall_argv(mrb, self, mid, argc, argv);
}
MRB_API mrb_value
mrb_funcall_with_block(mrb_state *mrb, mrb_value self, mrb_sym mid, mrb_int argc, const mrb_value *argv, mrb_value blk)
{
mrb_value val;
if (!mrb->jmp) {
struct mrb_jmpbuf c_jmp;
ptrdiff_t nth_ci = mrb->c->ci - mrb->c->cibase;
MRB_TRY(&c_jmp) {
mrb->jmp = &c_jmp;
/* recursive call */
val = mrb_funcall_with_block(mrb, self, mid, argc, argv, blk);
mrb->jmp = 0;
}
MRB_CATCH(&c_jmp) { /* error */
while (nth_ci < (mrb->c->ci - mrb->c->cibase)) {
mrb->c->stack = mrb->c->ci->stackent;
cipop(mrb);
}
mrb->jmp = 0;
val = mrb_obj_value(mrb->exc);
}
MRB_END_EXC(&c_jmp);
mrb->jmp = 0;
}
else {
mrb_method_t m;
struct RClass *c;
mrb_callinfo *ci;
int n;
ptrdiff_t voff = -1;
if (!mrb->c->stack) {
stack_init(mrb);
}
n = mrb->c->ci->nregs;
if (argc < 0) {
mrb_raisef(mrb, E_ARGUMENT_ERROR, "negative argc for funcall (%S)", mrb_fixnum_value(argc));
}
c = mrb_class(mrb, self);
m = mrb_method_search_vm(mrb, &c, mid);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_sym missing = mrb_intern_lit(mrb, "method_missing");
mrb_value args = mrb_ary_new_from_values(mrb, argc, argv);
m = mrb_method_search_vm(mrb, &c, missing);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_method_missing(mrb, mid, self, args);
}
mrb_ary_unshift(mrb, args, mrb_symbol_value(mid));
stack_extend(mrb, n+2);
mrb->c->stack[n+1] = args;
argc = -1;
}
if (mrb->c->ci - mrb->c->cibase > MRB_FUNCALL_DEPTH_MAX) {
mrb_exc_raise(mrb, mrb_obj_value(mrb->stack_err));
}
ci = cipush(mrb);
ci->mid = mid;
ci->stackent = mrb->c->stack;
ci->argc = (int)argc;
ci->target_class = c;
mrb->c->stack = mrb->c->stack + n;
if (mrb->c->stbase <= argv && argv < mrb->c->stend) {
voff = argv - mrb->c->stbase;
}
if (MRB_METHOD_CFUNC_P(m)) {
ci->nregs = (int)(argc + 2);
stack_extend(mrb, ci->nregs);
}
else if (argc >= CALL_MAXARGS) {
mrb_value args = mrb_ary_new_from_values(mrb, argc, argv);
stack_extend(mrb, ci->nregs+2);
mrb->c->stack[1] = args;
ci->argc = -1;
argc = 1;
}
else {
struct RProc *p = MRB_METHOD_PROC(m);
ci->proc = p;
if (argc < 0) argc = 1;
ci->nregs = (int)(p->body.irep->nregs + argc);
stack_extend(mrb, ci->nregs);
}
if (voff >= 0) {
argv = mrb->c->stbase + voff;
}
mrb->c->stack[0] = self;
if (ci->argc > 0) {
stack_copy(mrb->c->stack+1, argv, argc);
}
mrb->c->stack[argc+1] = blk;
if (MRB_METHOD_CFUNC_P(m)) {
int ai = mrb_gc_arena_save(mrb);
ci->acc = CI_ACC_DIRECT;
if (MRB_METHOD_PROC_P(m)) {
ci->proc = MRB_METHOD_PROC(m);
}
val = MRB_METHOD_CFUNC(m)(mrb, self);
mrb->c->stack = mrb->c->ci->stackent;
cipop(mrb);
mrb_gc_arena_restore(mrb, ai);
}
else {
ci->acc = CI_ACC_SKIP;
val = mrb_run(mrb, MRB_METHOD_PROC(m), self);
}
}
mrb_gc_protect(mrb, val);
return val;
}
MRB_API mrb_value
mrb_funcall_argv(mrb_state *mrb, mrb_value self, mrb_sym mid, mrb_int argc, const mrb_value *argv)
{
return mrb_funcall_with_block(mrb, self, mid, argc, argv, mrb_nil_value());
}
mrb_value
mrb_exec_irep(mrb_state *mrb, mrb_value self, struct RProc *p)
{
mrb_callinfo *ci = mrb->c->ci;
int keep;
mrb->c->stack[0] = self;
ci->proc = p;
if (MRB_PROC_CFUNC_P(p)) {
return MRB_PROC_CFUNC(p)(mrb, self);
}
ci->nregs = p->body.irep->nregs;
if (ci->argc < 0) keep = 3;
else keep = ci->argc + 2;
if (ci->nregs < keep) {
stack_extend(mrb, keep);
}
else {
stack_extend(mrb, ci->nregs);
stack_clear(mrb->c->stack+keep, ci->nregs-keep);
}
ci = cipush(mrb);
ci->nregs = 0;
ci->target_class = 0;
ci->pc = p->body.irep->iseq;
ci->stackent = mrb->c->stack;
ci->acc = 0;
return self;
}
/* 15.3.1.3.4 */
/* 15.3.1.3.44 */
/*
* call-seq:
* obj.send(symbol [, args...]) -> obj
* obj.__send__(symbol [, args...]) -> obj
*
* Invokes the method identified by _symbol_, passing it any
* arguments specified. You can use <code>__send__</code> if the name
* +send+ clashes with an existing method in _obj_.
*
* class Klass
* def hello(*args)
* "Hello " + args.join(' ')
* end
* end
* k = Klass.new
* k.send :hello, "gentle", "readers" #=> "Hello gentle readers"
*/
MRB_API mrb_value
mrb_f_send(mrb_state *mrb, mrb_value self)
{
mrb_sym name;
mrb_value block, *argv, *regs;
mrb_int argc, i, len;
mrb_method_t m;
struct RClass *c;
mrb_callinfo *ci;
mrb_get_args(mrb, "n*&", &name, &argv, &argc, &block);
ci = mrb->c->ci;
if (ci->acc < 0) {
funcall:
return mrb_funcall_with_block(mrb, self, name, argc, argv, block);
}
c = mrb_class(mrb, self);
m = mrb_method_search_vm(mrb, &c, name);
if (MRB_METHOD_UNDEF_P(m)) { /* call method_mising */
goto funcall;
}
ci->mid = name;
ci->target_class = c;
regs = mrb->c->stack+1;
/* remove first symbol from arguments */
if (ci->argc >= 0) {
for (i=0,len=ci->argc; i<len; i++) {
regs[i] = regs[i+1];
}
ci->argc--;
}
else { /* variable length arguments */
mrb_ary_shift(mrb, regs[0]);
}
if (MRB_METHOD_CFUNC_P(m)) {
if (MRB_METHOD_PROC_P(m)) {
ci->proc = MRB_METHOD_PROC(m);
}
return MRB_METHOD_CFUNC(m)(mrb, self);
}
return mrb_exec_irep(mrb, self, MRB_METHOD_PROC(m));
}
static mrb_value
eval_under(mrb_state *mrb, mrb_value self, mrb_value blk, struct RClass *c)
{
struct RProc *p;
mrb_callinfo *ci;
if (mrb_nil_p(blk)) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "no block given");
}
ci = mrb->c->ci;
if (ci->acc == CI_ACC_DIRECT) {
ci->target_class = c;
return mrb_yield_cont(mrb, blk, self, 1, &self);
}
ci->target_class = c;
p = mrb_proc_ptr(blk);
ci->proc = p;
ci->argc = 1;
ci->mid = ci[-1].mid;
if (MRB_PROC_CFUNC_P(p)) {
stack_extend(mrb, 3);
mrb->c->stack[0] = self;
mrb->c->stack[1] = self;
mrb->c->stack[2] = mrb_nil_value();
return MRB_PROC_CFUNC(p)(mrb, self);
}
ci->nregs = p->body.irep->nregs;
stack_extend(mrb, (ci->nregs < 3) ? 3 : ci->nregs);
mrb->c->stack[0] = self;
mrb->c->stack[1] = self;
mrb->c->stack[2] = mrb_nil_value();
ci = cipush(mrb);
ci->nregs = 0;
ci->target_class = 0;
ci->pc = p->body.irep->iseq;
ci->stackent = mrb->c->stack;
ci->acc = 0;
return self;
}
/* 15.2.2.4.35 */
/*
* call-seq:
* mod.class_eval {| | block } -> obj
* mod.module_eval {| | block } -> obj
*
* Evaluates block in the context of _mod_. This can
* be used to add methods to a class. <code>module_eval</code> returns
* the result of evaluating its argument.
*/
mrb_value
mrb_mod_module_eval(mrb_state *mrb, mrb_value mod)
{
mrb_value a, b;
if (mrb_get_args(mrb, "|S&", &a, &b) == 1) {
mrb_raise(mrb, E_NOTIMP_ERROR, "module_eval/class_eval with string not implemented");
}
return eval_under(mrb, mod, b, mrb_class_ptr(mod));
}
/* 15.3.1.3.18 */
/*
* call-seq:
* obj.instance_eval {| | block } -> obj
*
* Evaluates the given block,within the context of the receiver (_obj_).
* In order to set the context, the variable +self+ is set to _obj_ while
* the code is executing, giving the code access to _obj_'s
* instance variables. In the version of <code>instance_eval</code>
* that takes a +String+, the optional second and third
* parameters supply a filename and starting line number that are used
* when reporting compilation errors.
*
* class KlassWithSecret
* def initialize
* @secret = 99
* end
* end
* k = KlassWithSecret.new
* k.instance_eval { @secret } #=> 99
*/
mrb_value
mrb_obj_instance_eval(mrb_state *mrb, mrb_value self)
{
mrb_value a, b;
mrb_value cv;
struct RClass *c;
if (mrb_get_args(mrb, "|S&", &a, &b) == 1) {
mrb_raise(mrb, E_NOTIMP_ERROR, "instance_eval with string not implemented");
}
switch (mrb_type(self)) {
case MRB_TT_SYMBOL:
case MRB_TT_FIXNUM:
#ifndef MRB_WITHOUT_FLOAT
case MRB_TT_FLOAT:
#endif
c = 0;
break;
default:
cv = mrb_singleton_class(mrb, self);
c = mrb_class_ptr(cv);
break;
}
return eval_under(mrb, self, b, c);
}
MRB_API mrb_value
mrb_yield_with_class(mrb_state *mrb, mrb_value b, mrb_int argc, const mrb_value *argv, mrb_value self, struct RClass *c)
{
struct RProc *p;
mrb_sym mid = mrb->c->ci->mid;
mrb_callinfo *ci;
int n = mrb->c->ci->nregs;
mrb_value val;
if (mrb_nil_p(b)) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "no block given");
}
if (mrb->c->ci - mrb->c->cibase > MRB_FUNCALL_DEPTH_MAX) {
mrb_exc_raise(mrb, mrb_obj_value(mrb->stack_err));
}
p = mrb_proc_ptr(b);
ci = cipush(mrb);
ci->mid = mid;
ci->proc = p;
ci->stackent = mrb->c->stack;
ci->argc = (int)argc;
ci->target_class = c;
ci->acc = CI_ACC_SKIP;
mrb->c->stack = mrb->c->stack + n;
ci->nregs = MRB_PROC_CFUNC_P(p) ? (int)(argc+2) : p->body.irep->nregs;
stack_extend(mrb, ci->nregs);
mrb->c->stack[0] = self;
if (argc > 0) {
stack_copy(mrb->c->stack+1, argv, argc);
}
mrb->c->stack[argc+1] = mrb_nil_value();
if (MRB_PROC_CFUNC_P(p)) {
val = MRB_PROC_CFUNC(p)(mrb, self);
mrb->c->stack = mrb->c->ci->stackent;
cipop(mrb);
}
else {
val = mrb_run(mrb, p, self);
}
return val;
}
MRB_API mrb_value
mrb_yield_argv(mrb_state *mrb, mrb_value b, mrb_int argc, const mrb_value *argv)
{
struct RProc *p = mrb_proc_ptr(b);
return mrb_yield_with_class(mrb, b, argc, argv, MRB_PROC_ENV(p)->stack[0], MRB_PROC_TARGET_CLASS(p));
}
MRB_API mrb_value
mrb_yield(mrb_state *mrb, mrb_value b, mrb_value arg)
{
struct RProc *p = mrb_proc_ptr(b);
return mrb_yield_with_class(mrb, b, 1, &arg, MRB_PROC_ENV(p)->stack[0], MRB_PROC_TARGET_CLASS(p));
}
mrb_value
mrb_yield_cont(mrb_state *mrb, mrb_value b, mrb_value self, mrb_int argc, const mrb_value *argv)
{
struct RProc *p;
mrb_callinfo *ci;
if (mrb_nil_p(b)) {
mrb_raise(mrb, E_ARGUMENT_ERROR, "no block given");
}
if (mrb_type(b) != MRB_TT_PROC) {
mrb_raise(mrb, E_TYPE_ERROR, "not a block");
}
p = mrb_proc_ptr(b);
ci = mrb->c->ci;
stack_extend(mrb, 3);
mrb->c->stack[1] = mrb_ary_new_from_values(mrb, argc, argv);
mrb->c->stack[2] = mrb_nil_value();
ci->argc = -1;
return mrb_exec_irep(mrb, self, p);
}
mrb_value
mrb_mod_s_nesting(mrb_state *mrb, mrb_value mod)
{
struct RProc *proc;
mrb_value ary;
struct RClass *c = NULL;
mrb_get_args(mrb, "");
ary = mrb_ary_new(mrb);
proc = mrb->c->ci[-1].proc; /* callee proc */
mrb_assert(!MRB_PROC_CFUNC_P(proc));
while (proc) {
if (MRB_PROC_SCOPE_P(proc)) {
struct RClass *c2 = MRB_PROC_TARGET_CLASS(proc);
if (c2 != c) {
c = c2;
mrb_ary_push(mrb, ary, mrb_obj_value(c));
}
}
proc = proc->upper;
}
return ary;
}
static struct RBreak*
break_new(mrb_state *mrb, struct RProc *p, mrb_value val)
{
struct RBreak *brk;
brk = (struct RBreak*)mrb_obj_alloc(mrb, MRB_TT_BREAK, NULL);
brk->proc = p;
brk->val = val;
return brk;
}
typedef enum {
LOCALJUMP_ERROR_RETURN = 0,
LOCALJUMP_ERROR_BREAK = 1,
LOCALJUMP_ERROR_YIELD = 2
} localjump_error_kind;
static void
localjump_error(mrb_state *mrb, localjump_error_kind kind)
{
char kind_str[3][7] = { "return", "break", "yield" };
char kind_str_len[] = { 6, 5, 5 };
static const char lead[] = "unexpected ";
mrb_value msg;
mrb_value exc;
msg = mrb_str_new_capa(mrb, sizeof(lead) + 7);
mrb_str_cat(mrb, msg, lead, sizeof(lead) - 1);
mrb_str_cat(mrb, msg, kind_str[kind], kind_str_len[kind]);
exc = mrb_exc_new_str(mrb, E_LOCALJUMP_ERROR, msg);
mrb_exc_set(mrb, exc);
}
static void
argnum_error(mrb_state *mrb, mrb_int num)
{
mrb_value exc;
mrb_value str;
mrb_int argc = mrb->c->ci->argc;
if (argc < 0) {
mrb_value args = mrb->c->stack[1];
if (mrb_array_p(args)) {
argc = RARRAY_LEN(args);
}
}
if (mrb->c->ci->mid) {
str = mrb_format(mrb, "'%S': wrong number of arguments (%S for %S)",
mrb_sym2str(mrb, mrb->c->ci->mid),
mrb_fixnum_value(argc), mrb_fixnum_value(num));
}
else {
str = mrb_format(mrb, "wrong number of arguments (%S for %S)",
mrb_fixnum_value(argc), mrb_fixnum_value(num));
}
exc = mrb_exc_new_str(mrb, E_ARGUMENT_ERROR, str);
mrb_exc_set(mrb, exc);
}
#define ERR_PC_SET(mrb, pc) mrb->c->ci->err = pc;
#define ERR_PC_CLR(mrb) mrb->c->ci->err = 0;
#ifdef MRB_ENABLE_DEBUG_HOOK
#define CODE_FETCH_HOOK(mrb, irep, pc, regs) if ((mrb)->code_fetch_hook) (mrb)->code_fetch_hook((mrb), (irep), (pc), (regs));
#else
#define CODE_FETCH_HOOK(mrb, irep, pc, regs)
#endif
#ifdef MRB_BYTECODE_DECODE_OPTION
#define BYTECODE_DECODER(x) ((mrb)->bytecode_decoder)?(mrb)->bytecode_decoder((mrb), (x)):(x)
#else
#define BYTECODE_DECODER(x) (x)
#endif
#if defined __GNUC__ || defined __clang__ || defined __INTEL_COMPILER
#define DIRECT_THREADED
#endif
#ifndef DIRECT_THREADED
#define INIT_DISPATCH for (;;) { i = BYTECODE_DECODER(*pc); CODE_FETCH_HOOK(mrb, irep, pc, regs); switch (GET_OPCODE(i)) {
#define CASE(op) case op:
#define NEXT pc++; break
#define JUMP break
#define END_DISPATCH }}
#else
#define INIT_DISPATCH JUMP; return mrb_nil_value();
#define CASE(op) L_ ## op:
#define NEXT i=BYTECODE_DECODER(*++pc); CODE_FETCH_HOOK(mrb, irep, pc, regs); goto *optable[GET_OPCODE(i)]
#define JUMP i=BYTECODE_DECODER(*pc); CODE_FETCH_HOOK(mrb, irep, pc, regs); goto *optable[GET_OPCODE(i)]
#define END_DISPATCH
#endif
MRB_API mrb_value
mrb_vm_run(mrb_state *mrb, struct RProc *proc, mrb_value self, unsigned int stack_keep)
{
mrb_irep *irep = proc->body.irep;
mrb_value result;
struct mrb_context *c = mrb->c;
ptrdiff_t cioff = c->ci - c->cibase;
unsigned int nregs = irep->nregs;
if (!c->stack) {
stack_init(mrb);
}
if (stack_keep > nregs)
nregs = stack_keep;
stack_extend(mrb, nregs);
stack_clear(c->stack + stack_keep, nregs - stack_keep);
c->stack[0] = self;
result = mrb_vm_exec(mrb, proc, irep->iseq);
if (c->ci - c->cibase > cioff) {
c->ci = c->cibase + cioff;
}
if (mrb->c != c) {
if (mrb->c->fib) {
mrb_write_barrier(mrb, (struct RBasic*)mrb->c->fib);
}
mrb->c = c;
}
return result;
}
MRB_API mrb_value
mrb_vm_exec(mrb_state *mrb, struct RProc *proc, mrb_code *pc)
{
/* mrb_assert(mrb_proc_cfunc_p(proc)) */
mrb_irep *irep = proc->body.irep;
mrb_value *pool = irep->pool;
mrb_sym *syms = irep->syms;
mrb_code i;
int ai = mrb_gc_arena_save(mrb);
struct mrb_jmpbuf *prev_jmp = mrb->jmp;
struct mrb_jmpbuf c_jmp;
#ifdef DIRECT_THREADED
static void *optable[] = {
&&L_OP_NOP, &&L_OP_MOVE,
&&L_OP_LOADL, &&L_OP_LOADI, &&L_OP_LOADSYM, &&L_OP_LOADNIL,
&&L_OP_LOADSELF, &&L_OP_LOADT, &&L_OP_LOADF,
&&L_OP_GETGLOBAL, &&L_OP_SETGLOBAL, &&L_OP_GETSPECIAL, &&L_OP_SETSPECIAL,
&&L_OP_GETIV, &&L_OP_SETIV, &&L_OP_GETCV, &&L_OP_SETCV,
&&L_OP_GETCONST, &&L_OP_SETCONST, &&L_OP_GETMCNST, &&L_OP_SETMCNST,
&&L_OP_GETUPVAR, &&L_OP_SETUPVAR,
&&L_OP_JMP, &&L_OP_JMPIF, &&L_OP_JMPNOT,
&&L_OP_ONERR, &&L_OP_RESCUE, &&L_OP_POPERR, &&L_OP_RAISE, &&L_OP_EPUSH, &&L_OP_EPOP,
&&L_OP_SEND, &&L_OP_SENDB, &&L_OP_FSEND,
&&L_OP_CALL, &&L_OP_SUPER, &&L_OP_ARGARY, &&L_OP_ENTER,
&&L_OP_KARG, &&L_OP_KDICT, &&L_OP_RETURN, &&L_OP_TAILCALL, &&L_OP_BLKPUSH,
&&L_OP_ADD, &&L_OP_ADDI, &&L_OP_SUB, &&L_OP_SUBI, &&L_OP_MUL, &&L_OP_DIV,
&&L_OP_EQ, &&L_OP_LT, &&L_OP_LE, &&L_OP_GT, &&L_OP_GE,
&&L_OP_ARRAY, &&L_OP_ARYCAT, &&L_OP_ARYPUSH, &&L_OP_AREF, &&L_OP_ASET, &&L_OP_APOST,
&&L_OP_STRING, &&L_OP_STRCAT, &&L_OP_HASH,
&&L_OP_LAMBDA, &&L_OP_RANGE, &&L_OP_OCLASS,
&&L_OP_CLASS, &&L_OP_MODULE, &&L_OP_EXEC,
&&L_OP_METHOD, &&L_OP_SCLASS, &&L_OP_TCLASS,
&&L_OP_DEBUG, &&L_OP_STOP, &&L_OP_ERR,
};
#endif
mrb_bool exc_catched = FALSE;
RETRY_TRY_BLOCK:
MRB_TRY(&c_jmp) {
if (exc_catched) {
exc_catched = FALSE;
if (mrb->exc && mrb->exc->tt == MRB_TT_BREAK)
goto L_BREAK;
goto L_RAISE;
}
mrb->jmp = &c_jmp;
mrb->c->ci->proc = proc;
mrb->c->ci->nregs = irep->nregs;
#define regs (mrb->c->stack)
INIT_DISPATCH {
CASE(OP_NOP) {
/* do nothing */
NEXT;
}
CASE(OP_MOVE) {
/* A B R(A) := R(B) */
int a = GETARG_A(i);
int b = GETARG_B(i);
regs[a] = regs[b];
NEXT;
}
CASE(OP_LOADL) {
/* A Bx R(A) := Pool(Bx) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
#ifdef MRB_WORD_BOXING
mrb_value val = pool[bx];
#ifndef MRB_WITHOUT_FLOAT
if (mrb_float_p(val)) {
val = mrb_float_value(mrb, mrb_float(val));
}
#endif
regs[a] = val;
#else
regs[a] = pool[bx];
#endif
NEXT;
}
CASE(OP_LOADI) {
/* A sBx R(A) := sBx */
int a = GETARG_A(i);
mrb_int bx = GETARG_sBx(i);
SET_INT_VALUE(regs[a], bx);
NEXT;
}
CASE(OP_LOADSYM) {
/* A Bx R(A) := Syms(Bx) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
SET_SYM_VALUE(regs[a], syms[bx]);
NEXT;
}
CASE(OP_LOADSELF) {
/* A R(A) := self */
int a = GETARG_A(i);
regs[a] = regs[0];
NEXT;
}
CASE(OP_LOADT) {
/* A R(A) := true */
int a = GETARG_A(i);
SET_TRUE_VALUE(regs[a]);
NEXT;
}
CASE(OP_LOADF) {
/* A R(A) := false */
int a = GETARG_A(i);
SET_FALSE_VALUE(regs[a]);
NEXT;
}
CASE(OP_GETGLOBAL) {
/* A Bx R(A) := getglobal(Syms(Bx)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_value val = mrb_gv_get(mrb, syms[bx]);
regs[a] = val;
NEXT;
}
CASE(OP_SETGLOBAL) {
/* A Bx setglobal(Syms(Bx), R(A)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_gv_set(mrb, syms[bx], regs[a]);
NEXT;
}
CASE(OP_GETSPECIAL) {
/* A Bx R(A) := Special[Bx] */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_value val = mrb_vm_special_get(mrb, bx);
regs[a] = val;
NEXT;
}
CASE(OP_SETSPECIAL) {
/* A Bx Special[Bx] := R(A) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_vm_special_set(mrb, bx, regs[a]);
NEXT;
}
CASE(OP_GETIV) {
/* A Bx R(A) := ivget(Bx) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_value val = mrb_vm_iv_get(mrb, syms[bx]);
regs[a] = val;
NEXT;
}
CASE(OP_SETIV) {
/* A Bx ivset(Syms(Bx),R(A)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_vm_iv_set(mrb, syms[bx], regs[a]);
NEXT;
}
CASE(OP_GETCV) {
/* A Bx R(A) := cvget(Syms(Bx)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_value val;
ERR_PC_SET(mrb, pc);
val = mrb_vm_cv_get(mrb, syms[bx]);
ERR_PC_CLR(mrb);
regs[a] = val;
NEXT;
}
CASE(OP_SETCV) {
/* A Bx cvset(Syms(Bx),R(A)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_vm_cv_set(mrb, syms[bx], regs[a]);
NEXT;
}
CASE(OP_GETCONST) {
/* A Bx R(A) := constget(Syms(Bx)) */
mrb_value val;
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_sym sym = syms[bx];
ERR_PC_SET(mrb, pc);
val = mrb_vm_const_get(mrb, sym);
ERR_PC_CLR(mrb);
regs[a] = val;
NEXT;
}
CASE(OP_SETCONST) {
/* A Bx constset(Syms(Bx),R(A)) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_vm_const_set(mrb, syms[bx], regs[a]);
NEXT;
}
CASE(OP_GETMCNST) {
/* A Bx R(A) := R(A)::Syms(Bx) */
mrb_value val;
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
ERR_PC_SET(mrb, pc);
val = mrb_const_get(mrb, regs[a], syms[bx]);
ERR_PC_CLR(mrb);
regs[a] = val;
NEXT;
}
CASE(OP_SETMCNST) {
/* A Bx R(A+1)::Syms(Bx) := R(A) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_const_set(mrb, regs[a+1], syms[bx], regs[a]);
NEXT;
}
CASE(OP_GETUPVAR) {
/* A B C R(A) := uvget(B,C) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
mrb_value *regs_a = regs + a;
struct REnv *e = uvenv(mrb, c);
if (e && b < MRB_ENV_STACK_LEN(e)) {
*regs_a = e->stack[b];
}
else {
*regs_a = mrb_nil_value();
}
NEXT;
}
CASE(OP_SETUPVAR) {
/* A B C uvset(B,C,R(A)) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
struct REnv *e = uvenv(mrb, c);
if (e) {
mrb_value *regs_a = regs + a;
if (b < MRB_ENV_STACK_LEN(e)) {
e->stack[b] = *regs_a;
mrb_write_barrier(mrb, (struct RBasic*)e);
}
}
NEXT;
}
CASE(OP_JMP) {
/* sBx pc+=sBx */
int sbx = GETARG_sBx(i);
pc += sbx;
JUMP;
}
CASE(OP_JMPIF) {
/* A sBx if R(A) pc+=sBx */
int a = GETARG_A(i);
int sbx = GETARG_sBx(i);
if (mrb_test(regs[a])) {
pc += sbx;
JUMP;
}
NEXT;
}
CASE(OP_JMPNOT) {
/* A sBx if !R(A) pc+=sBx */
int a = GETARG_A(i);
int sbx = GETARG_sBx(i);
if (!mrb_test(regs[a])) {
pc += sbx;
JUMP;
}
NEXT;
}
CASE(OP_ONERR) {
/* sBx pc+=sBx on exception */
int sbx = GETARG_sBx(i);
if (mrb->c->rsize <= mrb->c->ci->ridx) {
if (mrb->c->rsize == 0) mrb->c->rsize = RESCUE_STACK_INIT_SIZE;
else mrb->c->rsize *= 2;
mrb->c->rescue = (mrb_code **)mrb_realloc(mrb, mrb->c->rescue, sizeof(mrb_code*) * mrb->c->rsize);
}
mrb->c->rescue[mrb->c->ci->ridx++] = pc + sbx;
NEXT;
}
CASE(OP_RESCUE) {
/* A B R(A) := exc; clear(exc); R(B) := matched (bool) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
mrb_value exc;
if (c == 0) {
exc = mrb_obj_value(mrb->exc);
mrb->exc = 0;
}
else { /* continued; exc taken from R(A) */
exc = regs[a];
}
if (b != 0) {
mrb_value e = regs[b];
struct RClass *ec;
switch (mrb_type(e)) {
case MRB_TT_CLASS:
case MRB_TT_MODULE:
break;
default:
{
mrb_value exc;
exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR,
"class or module required for rescue clause");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
}
ec = mrb_class_ptr(e);
regs[b] = mrb_bool_value(mrb_obj_is_kind_of(mrb, exc, ec));
}
if (a != 0 && c == 0) {
regs[a] = exc;
}
NEXT;
}
CASE(OP_POPERR) {
/* A A.times{rescue_pop()} */
int a = GETARG_A(i);
mrb->c->ci->ridx -= a;
NEXT;
}
CASE(OP_RAISE) {
/* A raise(R(A)) */
int a = GETARG_A(i);
mrb_exc_set(mrb, regs[a]);
goto L_RAISE;
}
CASE(OP_EPUSH) {
/* Bx ensure_push(SEQ[Bx]) */
int bx = GETARG_Bx(i);
struct RProc *p;
p = mrb_closure_new(mrb, irep->reps[bx]);
/* push ensure_stack */
if (mrb->c->esize <= mrb->c->eidx+1) {
if (mrb->c->esize == 0) mrb->c->esize = ENSURE_STACK_INIT_SIZE;
else mrb->c->esize *= 2;
mrb->c->ensure = (struct RProc **)mrb_realloc(mrb, mrb->c->ensure, sizeof(struct RProc*) * mrb->c->esize);
}
mrb->c->ensure[mrb->c->eidx++] = p;
mrb->c->ensure[mrb->c->eidx] = NULL;
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_EPOP) {
/* A A.times{ensure_pop().call} */
int a = GETARG_A(i);
mrb_callinfo *ci = mrb->c->ci;
int n, epos = ci->epos;
mrb_value self = regs[0];
struct RClass *target_class = ci->target_class;
if (mrb->c->eidx <= epos) {
NEXT;
}
if (a > mrb->c->eidx - epos)
a = mrb->c->eidx - epos;
pc = pc + 1;
for (n=0; n<a; n++) {
proc = mrb->c->ensure[epos+n];
mrb->c->ensure[epos+n] = NULL;
if (proc == NULL) continue;
irep = proc->body.irep;
ci = cipush(mrb);
ci->mid = ci[-1].mid;
ci->argc = 0;
ci->proc = proc;
ci->stackent = mrb->c->stack;
ci->nregs = irep->nregs;
ci->target_class = target_class;
ci->pc = pc;
ci->acc = ci[-1].nregs;
mrb->c->stack += ci->acc;
stack_extend(mrb, ci->nregs);
regs[0] = self;
pc = irep->iseq;
}
pool = irep->pool;
syms = irep->syms;
mrb->c->eidx = epos;
JUMP;
}
CASE(OP_LOADNIL) {
/* A R(A) := nil */
int a = GETARG_A(i);
SET_NIL_VALUE(regs[a]);
NEXT;
}
CASE(OP_SENDB) {
/* A B C R(A) := call(R(A),Syms(B),R(A+1),...,R(A+C),&R(A+C+1))*/
/* fall through */
};
L_SEND:
CASE(OP_SEND) {
/* A B C R(A) := call(R(A),Syms(B),R(A+1),...,R(A+C)) */
int a = GETARG_A(i);
int n = GETARG_C(i);
int argc = (n == CALL_MAXARGS) ? -1 : n;
int bidx = (argc < 0) ? a+2 : a+n+1;
mrb_method_t m;
struct RClass *c;
mrb_callinfo *ci = mrb->c->ci;
mrb_value recv, blk;
mrb_sym mid = syms[GETARG_B(i)];
mrb_assert(bidx < ci->nregs);
recv = regs[a];
if (GET_OPCODE(i) != OP_SENDB) {
SET_NIL_VALUE(regs[bidx]);
blk = regs[bidx];
}
else {
blk = regs[bidx];
if (!mrb_nil_p(blk) && mrb_type(blk) != MRB_TT_PROC) {
blk = mrb_convert_type(mrb, blk, MRB_TT_PROC, "Proc", "to_proc");
/* The stack might have been reallocated during mrb_convert_type(),
see #3622 */
regs[bidx] = blk;
}
}
c = mrb_class(mrb, recv);
m = mrb_method_search_vm(mrb, &c, mid);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_sym missing = mrb_intern_lit(mrb, "method_missing");
m = mrb_method_search_vm(mrb, &c, missing);
if (MRB_METHOD_UNDEF_P(m) || (missing == mrb->c->ci->mid && mrb_obj_eq(mrb, regs[0], recv))) {
mrb_value args = (argc < 0) ? regs[a+1] : mrb_ary_new_from_values(mrb, n, regs+a+1);
ERR_PC_SET(mrb, pc);
mrb_method_missing(mrb, mid, recv, args);
}
if (argc >= 0) {
if (a+2 >= irep->nregs) {
stack_extend(mrb, a+3);
}
regs[a+1] = mrb_ary_new_from_values(mrb, n, regs+a+1);
regs[a+2] = blk;
argc = -1;
}
mrb_ary_unshift(mrb, regs[a+1], mrb_symbol_value(mid));
mid = missing;
}
/* push callinfo */
ci = cipush(mrb);
ci->mid = mid;
ci->stackent = mrb->c->stack;
ci->target_class = c;
ci->argc = argc;
ci->pc = pc + 1;
ci->acc = a;
/* prepare stack */
mrb->c->stack += a;
if (MRB_METHOD_CFUNC_P(m)) {
ci->nregs = (argc < 0) ? 3 : n+2;
if (MRB_METHOD_PROC_P(m)) {
struct RProc *p = MRB_METHOD_PROC(m);
ci->proc = p;
recv = p->body.func(mrb, recv);
}
else {
recv = MRB_METHOD_FUNC(m)(mrb, recv);
}
mrb_gc_arena_restore(mrb, ai);
mrb_gc_arena_shrink(mrb, ai);
if (mrb->exc) goto L_RAISE;
ci = mrb->c->ci;
if (GET_OPCODE(i) == OP_SENDB) {
if (mrb_type(blk) == MRB_TT_PROC) {
struct RProc *p = mrb_proc_ptr(blk);
if (p && !MRB_PROC_STRICT_P(p) && MRB_PROC_ENV(p) == ci[-1].env) {
p->flags |= MRB_PROC_ORPHAN;
}
}
}
if (!ci->target_class) { /* return from context modifying method (resume/yield) */
if (ci->acc == CI_ACC_RESUMED) {
mrb->jmp = prev_jmp;
return recv;
}
else {
mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));
proc = ci[-1].proc;
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
}
}
mrb->c->stack[0] = recv;
/* pop stackpos */
mrb->c->stack = ci->stackent;
pc = ci->pc;
cipop(mrb);
JUMP;
}
else {
/* setup environment for calling method */
proc = ci->proc = MRB_METHOD_PROC(m);
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
ci->nregs = irep->nregs;
stack_extend(mrb, (argc < 0 && ci->nregs < 3) ? 3 : ci->nregs);
pc = irep->iseq;
JUMP;
}
}
CASE(OP_FSEND) {
/* A B C R(A) := fcall(R(A),Syms(B),R(A+1),... ,R(A+C-1)) */
/* not implemented yet */
NEXT;
}
CASE(OP_CALL) {
/* A R(A) := self.call(frame.argc, frame.argv) */
mrb_callinfo *ci;
mrb_value recv = mrb->c->stack[0];
struct RProc *m = mrb_proc_ptr(recv);
/* replace callinfo */
ci = mrb->c->ci;
ci->target_class = MRB_PROC_TARGET_CLASS(m);
ci->proc = m;
if (MRB_PROC_ENV_P(m)) {
mrb_sym mid;
struct REnv *e = MRB_PROC_ENV(m);
mid = e->mid;
if (mid) ci->mid = mid;
if (!e->stack) {
e->stack = mrb->c->stack;
}
}
/* prepare stack */
if (MRB_PROC_CFUNC_P(m)) {
recv = MRB_PROC_CFUNC(m)(mrb, recv);
mrb_gc_arena_restore(mrb, ai);
mrb_gc_arena_shrink(mrb, ai);
if (mrb->exc) goto L_RAISE;
/* pop stackpos */
ci = mrb->c->ci;
mrb->c->stack = ci->stackent;
regs[ci->acc] = recv;
pc = ci->pc;
cipop(mrb);
irep = mrb->c->ci->proc->body.irep;
pool = irep->pool;
syms = irep->syms;
JUMP;
}
else {
/* setup environment for calling method */
proc = m;
irep = m->body.irep;
if (!irep) {
mrb->c->stack[0] = mrb_nil_value();
goto L_RETURN;
}
pool = irep->pool;
syms = irep->syms;
ci->nregs = irep->nregs;
stack_extend(mrb, ci->nregs);
if (ci->argc < 0) {
if (irep->nregs > 3) {
stack_clear(regs+3, irep->nregs-3);
}
}
else if (ci->argc+2 < irep->nregs) {
stack_clear(regs+ci->argc+2, irep->nregs-ci->argc-2);
}
if (MRB_PROC_ENV_P(m)) {
regs[0] = MRB_PROC_ENV(m)->stack[0];
}
pc = irep->iseq;
JUMP;
}
}
CASE(OP_SUPER) {
/* A C R(A) := super(R(A+1),... ,R(A+C+1)) */
int a = GETARG_A(i);
int n = GETARG_C(i);
int argc = (n == CALL_MAXARGS) ? -1 : n;
int bidx = (argc < 0) ? a+2 : a+n+1;
mrb_method_t m;
struct RClass *c;
mrb_callinfo *ci = mrb->c->ci;
mrb_value recv, blk;
mrb_sym mid = ci->mid;
struct RClass* target_class = MRB_PROC_TARGET_CLASS(ci->proc);
mrb_assert(bidx < ci->nregs);
if (mid == 0 || !target_class) {
mrb_value exc = mrb_exc_new_str_lit(mrb, E_NOMETHOD_ERROR, "super called outside of method");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
if (target_class->tt == MRB_TT_MODULE) {
target_class = ci->target_class;
if (target_class->tt != MRB_TT_ICLASS) {
mrb_value exc = mrb_exc_new_str_lit(mrb, E_RUNTIME_ERROR, "superclass info lost [mruby limitations]");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
}
recv = regs[0];
if (!mrb_obj_is_kind_of(mrb, recv, target_class)) {
mrb_value exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR,
"self has wrong type to call super in this context");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
blk = regs[bidx];
if (!mrb_nil_p(blk) && mrb_type(blk) != MRB_TT_PROC) {
blk = mrb_convert_type(mrb, blk, MRB_TT_PROC, "Proc", "to_proc");
/* The stack or ci stack might have been reallocated during
mrb_convert_type(), see #3622 and #3784 */
regs[bidx] = blk;
ci = mrb->c->ci;
}
c = target_class->super;
m = mrb_method_search_vm(mrb, &c, mid);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_sym missing = mrb_intern_lit(mrb, "method_missing");
if (mid != missing) {
c = mrb_class(mrb, recv);
}
m = mrb_method_search_vm(mrb, &c, missing);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_value args = (argc < 0) ? regs[a+1] : mrb_ary_new_from_values(mrb, n, regs+a+1);
ERR_PC_SET(mrb, pc);
mrb_method_missing(mrb, mid, recv, args);
}
mid = missing;
if (argc >= 0) {
if (a+2 >= ci->nregs) {
stack_extend(mrb, a+3);
}
regs[a+1] = mrb_ary_new_from_values(mrb, n, regs+a+1);
regs[a+2] = blk;
argc = -1;
}
mrb_ary_unshift(mrb, regs[a+1], mrb_symbol_value(ci->mid));
}
/* push callinfo */
ci = cipush(mrb);
ci->mid = mid;
ci->stackent = mrb->c->stack;
ci->target_class = c;
ci->pc = pc + 1;
ci->argc = argc;
/* prepare stack */
mrb->c->stack += a;
mrb->c->stack[0] = recv;
if (MRB_METHOD_CFUNC_P(m)) {
mrb_value v;
ci->nregs = (argc < 0) ? 3 : n+2;
if (MRB_METHOD_PROC_P(m)) {
ci->proc = MRB_METHOD_PROC(m);
}
v = MRB_METHOD_CFUNC(m)(mrb, recv);
mrb_gc_arena_restore(mrb, ai);
if (mrb->exc) goto L_RAISE;
ci = mrb->c->ci;
if (!ci->target_class) { /* return from context modifying method (resume/yield) */
if (ci->acc == CI_ACC_RESUMED) {
mrb->jmp = prev_jmp;
return v;
}
else {
mrb_assert(!MRB_PROC_CFUNC_P(ci[-1].proc));
proc = ci[-1].proc;
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
}
}
mrb->c->stack[0] = v;
/* pop stackpos */
mrb->c->stack = ci->stackent;
pc = ci->pc;
cipop(mrb);
JUMP;
}
else {
/* fill callinfo */
ci->acc = a;
/* setup environment for calling method */
proc = ci->proc = MRB_METHOD_PROC(m);
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
ci->nregs = irep->nregs;
stack_extend(mrb, (argc < 0 && ci->nregs < 3) ? 3 : ci->nregs);
pc = irep->iseq;
JUMP;
}
}
CASE(OP_ARGARY) {
/* A Bx R(A) := argument array (16=6:1:5:4) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
int m1 = (bx>>10)&0x3f;
int r = (bx>>9)&0x1;
int m2 = (bx>>4)&0x1f;
int lv = (bx>>0)&0xf;
mrb_value *stack;
if (mrb->c->ci->mid == 0 || mrb->c->ci->target_class == NULL) {
mrb_value exc;
L_NOSUPER:
exc = mrb_exc_new_str_lit(mrb, E_NOMETHOD_ERROR, "super called outside of method");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
if (lv == 0) stack = regs + 1;
else {
struct REnv *e = uvenv(mrb, lv-1);
if (!e) goto L_NOSUPER;
if (MRB_ENV_STACK_LEN(e) <= m1+r+m2+1)
goto L_NOSUPER;
stack = e->stack + 1;
}
if (r == 0) {
regs[a] = mrb_ary_new_from_values(mrb, m1+m2, stack);
}
else {
mrb_value *pp = NULL;
struct RArray *rest;
int len = 0;
if (mrb_array_p(stack[m1])) {
struct RArray *ary = mrb_ary_ptr(stack[m1]);
pp = ARY_PTR(ary);
len = (int)ARY_LEN(ary);
}
regs[a] = mrb_ary_new_capa(mrb, m1+len+m2);
rest = mrb_ary_ptr(regs[a]);
if (m1 > 0) {
stack_copy(ARY_PTR(rest), stack, m1);
}
if (len > 0) {
stack_copy(ARY_PTR(rest)+m1, pp, len);
}
if (m2 > 0) {
stack_copy(ARY_PTR(rest)+m1+len, stack+m1+1, m2);
}
ARY_SET_LEN(rest, m1+len+m2);
}
regs[a+1] = stack[m1+r+m2];
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_ENTER) {
/* Ax arg setup according to flags (23=5:5:1:5:5:1:1) */
/* number of optional arguments times OP_JMP should follow */
mrb_aspec ax = GETARG_Ax(i);
int m1 = MRB_ASPEC_REQ(ax);
int o = MRB_ASPEC_OPT(ax);
int r = MRB_ASPEC_REST(ax);
int m2 = MRB_ASPEC_POST(ax);
/* unused
int k = MRB_ASPEC_KEY(ax);
int kd = MRB_ASPEC_KDICT(ax);
int b = MRB_ASPEC_BLOCK(ax);
*/
int argc = mrb->c->ci->argc;
mrb_value *argv = regs+1;
mrb_value *argv0 = argv;
int len = m1 + o + r + m2;
mrb_value *blk = &argv[argc < 0 ? 1 : argc];
if (argc < 0) {
struct RArray *ary = mrb_ary_ptr(regs[1]);
argv = ARY_PTR(ary);
argc = (int)ARY_LEN(ary);
mrb_gc_protect(mrb, regs[1]);
}
if (mrb->c->ci->proc && MRB_PROC_STRICT_P(mrb->c->ci->proc)) {
if (argc >= 0) {
if (argc < m1 + m2 || (r == 0 && argc > len)) {
argnum_error(mrb, m1+m2);
goto L_RAISE;
}
}
}
else if (len > 1 && argc == 1 && mrb_array_p(argv[0])) {
mrb_gc_protect(mrb, argv[0]);
argc = (int)RARRAY_LEN(argv[0]);
argv = RARRAY_PTR(argv[0]);
}
if (argc < len) {
int mlen = m2;
if (argc < m1+m2) {
if (m1 < argc)
mlen = argc - m1;
else
mlen = 0;
}
regs[len+1] = *blk; /* move block */
SET_NIL_VALUE(regs[argc+1]);
if (argv0 != argv) {
value_move(®s[1], argv, argc-mlen); /* m1 + o */
}
if (argc < m1) {
stack_clear(®s[argc+1], m1-argc);
}
if (mlen) {
value_move(®s[len-m2+1], &argv[argc-mlen], mlen);
}
if (mlen < m2) {
stack_clear(®s[len-m2+mlen+1], m2-mlen);
}
if (r) {
regs[m1+o+1] = mrb_ary_new_capa(mrb, 0);
}
if (o == 0 || argc < m1+m2) pc++;
else
pc += argc - m1 - m2 + 1;
}
else {
int rnum = 0;
if (argv0 != argv) {
regs[len+1] = *blk; /* move block */
value_move(®s[1], argv, m1+o);
}
if (r) {
rnum = argc-m1-o-m2;
regs[m1+o+1] = mrb_ary_new_from_values(mrb, rnum, argv+m1+o);
}
if (m2) {
if (argc-m2 > m1) {
value_move(®s[m1+o+r+1], &argv[m1+o+rnum], m2);
}
}
if (argv0 == argv) {
regs[len+1] = *blk; /* move block */
}
pc += o + 1;
}
mrb->c->ci->argc = len;
/* clear local (but non-argument) variables */
if (irep->nlocals-len-2 > 0) {
stack_clear(®s[len+2], irep->nlocals-len-2);
}
JUMP;
}
CASE(OP_KARG) {
/* A B C R(A) := kdict[Syms(B)]; if C kdict.rm(Syms(B)) */
/* if C == 2; raise unless kdict.empty? */
/* OP_JMP should follow to skip init code */
NEXT;
}
CASE(OP_KDICT) {
/* A C R(A) := kdict */
NEXT;
}
L_RETURN:
i = MKOP_AB(OP_RETURN, GETARG_A(i), OP_R_NORMAL);
/* fall through */
CASE(OP_RETURN) {
/* A B return R(A) (B=normal,in-block return/break) */
mrb_callinfo *ci;
#define ecall_adjust() do {\
ptrdiff_t cioff = ci - mrb->c->cibase;\
ecall(mrb);\
ci = mrb->c->cibase + cioff;\
} while (0)
ci = mrb->c->ci;
if (ci->mid) {
mrb_value blk;
if (ci->argc < 0) {
blk = regs[2];
}
else {
blk = regs[ci->argc+1];
}
if (mrb_type(blk) == MRB_TT_PROC) {
struct RProc *p = mrb_proc_ptr(blk);
if (!MRB_PROC_STRICT_P(p) &&
ci > mrb->c->cibase && MRB_PROC_ENV(p) == ci[-1].env) {
p->flags |= MRB_PROC_ORPHAN;
}
}
}
if (mrb->exc) {
mrb_callinfo *ci0;
L_RAISE:
ci0 = ci = mrb->c->ci;
if (ci == mrb->c->cibase) {
if (ci->ridx == 0) goto L_FTOP;
goto L_RESCUE;
}
while (ci[0].ridx == ci[-1].ridx) {
cipop(mrb);
mrb->c->stack = ci->stackent;
if (ci->acc == CI_ACC_SKIP && prev_jmp) {
mrb->jmp = prev_jmp;
MRB_THROW(prev_jmp);
}
ci = mrb->c->ci;
if (ci == mrb->c->cibase) {
if (ci->ridx == 0) {
L_FTOP: /* fiber top */
if (mrb->c == mrb->root_c) {
mrb->c->stack = mrb->c->stbase;
goto L_STOP;
}
else {
struct mrb_context *c = mrb->c;
while (c->eidx > ci->epos) {
ecall_adjust();
}
if (c->fib) {
mrb_write_barrier(mrb, (struct RBasic*)c->fib);
}
mrb->c->status = MRB_FIBER_TERMINATED;
mrb->c = c->prev;
c->prev = NULL;
goto L_RAISE;
}
}
break;
}
/* call ensure only when we skip this callinfo */
if (ci[0].ridx == ci[-1].ridx) {
while (mrb->c->eidx > ci->epos) {
ecall_adjust();
}
}
}
L_RESCUE:
if (ci->ridx == 0) goto L_STOP;
proc = ci->proc;
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
if (ci < ci0) {
mrb->c->stack = ci[1].stackent;
}
stack_extend(mrb, irep->nregs);
pc = mrb->c->rescue[--ci->ridx];
}
else {
int acc;
mrb_value v;
struct RProc *dst;
ci = mrb->c->ci;
v = regs[GETARG_A(i)];
mrb_gc_protect(mrb, v);
switch (GETARG_B(i)) {
case OP_R_RETURN:
/* Fall through to OP_R_NORMAL otherwise */
if (ci->acc >=0 && MRB_PROC_ENV_P(proc) && !MRB_PROC_STRICT_P(proc)) {
mrb_callinfo *cibase = mrb->c->cibase;
dst = top_proc(mrb, proc);
if (MRB_PROC_ENV_P(dst)) {
struct REnv *e = MRB_PROC_ENV(dst);
if (!MRB_ENV_STACK_SHARED_P(e) || e->cxt != mrb->c) {
localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
goto L_RAISE;
}
}
while (cibase <= ci && ci->proc != dst) {
if (ci->acc < 0) {
localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
goto L_RAISE;
}
ci--;
}
if (ci <= cibase) {
localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
goto L_RAISE;
}
break;
}
case OP_R_NORMAL:
NORMAL_RETURN:
if (ci == mrb->c->cibase) {
struct mrb_context *c;
if (!mrb->c->prev) { /* toplevel return */
localjump_error(mrb, LOCALJUMP_ERROR_RETURN);
goto L_RAISE;
}
if (mrb->c->prev->ci == mrb->c->prev->cibase) {
mrb_value exc = mrb_exc_new_str_lit(mrb, E_FIBER_ERROR, "double resume");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
while (mrb->c->eidx > 0) {
ecall(mrb);
}
/* automatic yield at the end */
c = mrb->c;
c->status = MRB_FIBER_TERMINATED;
mrb->c = c->prev;
c->prev = NULL;
mrb->c->status = MRB_FIBER_RUNNING;
ci = mrb->c->ci;
}
break;
case OP_R_BREAK:
if (MRB_PROC_STRICT_P(proc)) goto NORMAL_RETURN;
if (MRB_PROC_ORPHAN_P(proc)) {
mrb_value exc;
L_BREAK_ERROR:
exc = mrb_exc_new_str_lit(mrb, E_LOCALJUMP_ERROR,
"break from proc-closure");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
if (!MRB_PROC_ENV_P(proc) || !MRB_ENV_STACK_SHARED_P(MRB_PROC_ENV(proc))) {
goto L_BREAK_ERROR;
}
else {
struct REnv *e = MRB_PROC_ENV(proc);
if (e == mrb->c->cibase->env && proc != mrb->c->cibase->proc) {
goto L_BREAK_ERROR;
}
if (e->cxt != mrb->c) {
goto L_BREAK_ERROR;
}
}
while (mrb->c->eidx > mrb->c->ci->epos) {
ecall_adjust();
}
/* break from fiber block */
if (ci == mrb->c->cibase && ci->pc) {
struct mrb_context *c = mrb->c;
mrb->c = c->prev;
c->prev = NULL;
ci = mrb->c->ci;
}
if (ci->acc < 0) {
mrb_gc_arena_restore(mrb, ai);
mrb->c->vmexec = FALSE;
mrb->exc = (struct RObject*)break_new(mrb, proc, v);
mrb->jmp = prev_jmp;
MRB_THROW(prev_jmp);
}
if (FALSE) {
L_BREAK:
v = ((struct RBreak*)mrb->exc)->val;
proc = ((struct RBreak*)mrb->exc)->proc;
mrb->exc = NULL;
ci = mrb->c->ci;
}
mrb->c->stack = ci->stackent;
proc = proc->upper;
while (mrb->c->cibase < ci && ci[-1].proc != proc) {
if (ci[-1].acc == CI_ACC_SKIP) {
while (ci < mrb->c->ci) {
cipop(mrb);
}
goto L_BREAK_ERROR;
}
ci--;
}
if (ci == mrb->c->cibase) {
goto L_BREAK_ERROR;
}
break;
default:
/* cannot happen */
break;
}
while (ci < mrb->c->ci) {
cipop(mrb);
}
ci[0].ridx = ci[-1].ridx;
while (mrb->c->eidx > ci->epos) {
ecall_adjust();
}
if (mrb->c->vmexec && !ci->target_class) {
mrb_gc_arena_restore(mrb, ai);
mrb->c->vmexec = FALSE;
mrb->jmp = prev_jmp;
return v;
}
acc = ci->acc;
mrb->c->stack = ci->stackent;
cipop(mrb);
if (acc == CI_ACC_SKIP || acc == CI_ACC_DIRECT) {
mrb_gc_arena_restore(mrb, ai);
mrb->jmp = prev_jmp;
return v;
}
pc = ci->pc;
ci = mrb->c->ci;
DEBUG(fprintf(stderr, "from :%s\n", mrb_sym2name(mrb, ci->mid)));
proc = mrb->c->ci->proc;
irep = proc->body.irep;
pool = irep->pool;
syms = irep->syms;
regs[acc] = v;
mrb_gc_arena_restore(mrb, ai);
}
JUMP;
}
CASE(OP_TAILCALL) {
/* A B C return call(R(A),Syms(B),R(A+1),... ,R(A+C+1)) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int n = GETARG_C(i);
mrb_method_t m;
struct RClass *c;
mrb_callinfo *ci;
mrb_value recv;
mrb_sym mid = syms[b];
recv = regs[a];
c = mrb_class(mrb, recv);
m = mrb_method_search_vm(mrb, &c, mid);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_value sym = mrb_symbol_value(mid);
mrb_sym missing = mrb_intern_lit(mrb, "method_missing");
m = mrb_method_search_vm(mrb, &c, missing);
if (MRB_METHOD_UNDEF_P(m)) {
mrb_value args;
if (n == CALL_MAXARGS) {
args = regs[a+1];
}
else {
args = mrb_ary_new_from_values(mrb, n, regs+a+1);
}
ERR_PC_SET(mrb, pc);
mrb_method_missing(mrb, mid, recv, args);
}
mid = missing;
if (n == CALL_MAXARGS) {
mrb_ary_unshift(mrb, regs[a+1], sym);
}
else {
value_move(regs+a+2, regs+a+1, ++n);
regs[a+1] = sym;
}
}
/* replace callinfo */
ci = mrb->c->ci;
ci->mid = mid;
ci->target_class = c;
if (n == CALL_MAXARGS) {
ci->argc = -1;
}
else {
ci->argc = n;
}
/* move stack */
value_move(mrb->c->stack, ®s[a], ci->argc+1);
if (MRB_METHOD_CFUNC_P(m)) {
mrb_value v = MRB_METHOD_CFUNC(m)(mrb, recv);
mrb->c->stack[0] = v;
mrb_gc_arena_restore(mrb, ai);
goto L_RETURN;
}
else {
/* setup environment for calling method */
struct RProc *p = MRB_METHOD_PROC(m);
irep = p->body.irep;
pool = irep->pool;
syms = irep->syms;
if (ci->argc < 0) {
stack_extend(mrb, (irep->nregs < 3) ? 3 : irep->nregs);
}
else {
stack_extend(mrb, irep->nregs);
}
pc = irep->iseq;
}
JUMP;
}
CASE(OP_BLKPUSH) {
/* A Bx R(A) := block (16=6:1:5:4) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
int m1 = (bx>>10)&0x3f;
int r = (bx>>9)&0x1;
int m2 = (bx>>4)&0x1f;
int lv = (bx>>0)&0xf;
mrb_value *stack;
if (lv == 0) stack = regs + 1;
else {
struct REnv *e = uvenv(mrb, lv-1);
if (!e || (!MRB_ENV_STACK_SHARED_P(e) && e->mid == 0) ||
MRB_ENV_STACK_LEN(e) <= m1+r+m2+1) {
localjump_error(mrb, LOCALJUMP_ERROR_YIELD);
goto L_RAISE;
}
stack = e->stack + 1;
}
if (mrb_nil_p(stack[m1+r+m2])) {
localjump_error(mrb, LOCALJUMP_ERROR_YIELD);
goto L_RAISE;
}
regs[a] = stack[m1+r+m2];
NEXT;
}
#define TYPES2(a,b) ((((uint16_t)(a))<<8)|(((uint16_t)(b))&0xff))
#define OP_MATH_BODY(op,v1,v2) do {\
v1(regs[a]) = v1(regs[a]) op v2(regs[a+1]);\
} while(0)
CASE(OP_ADD) {
/* A B C R(A) := R(A)+R(A+1) (Syms[B]=:+,C=1)*/
int a = GETARG_A(i);
/* need to check if op is overridden */
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):
{
mrb_int x, y, z;
mrb_value *regs_a = regs + a;
x = mrb_fixnum(regs_a[0]);
y = mrb_fixnum(regs_a[1]);
if (mrb_int_add_overflow(x, y, &z)) {
#ifndef MRB_WITHOUT_FLOAT
SET_FLOAT_VALUE(mrb, regs_a[0], (mrb_float)x + (mrb_float)y);
break;
#endif
}
SET_INT_VALUE(regs[a], z);
}
break;
#ifndef MRB_WITHOUT_FLOAT
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):
{
mrb_int x = mrb_fixnum(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x + y);
}
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_int y = mrb_fixnum(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x + y);
}
#else
OP_MATH_BODY(+,mrb_float,mrb_fixnum);
#endif
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x + y);
}
#else
OP_MATH_BODY(+,mrb_float,mrb_float);
#endif
break;
#endif
case TYPES2(MRB_TT_STRING,MRB_TT_STRING):
regs[a] = mrb_str_plus(mrb, regs[a], regs[a+1]);
break;
default:
goto L_SEND;
}
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_SUB) {
/* A B C R(A) := R(A)-R(A+1) (Syms[B]=:-,C=1)*/
int a = GETARG_A(i);
/* need to check if op is overridden */
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):
{
mrb_int x, y, z;
x = mrb_fixnum(regs[a]);
y = mrb_fixnum(regs[a+1]);
if (mrb_int_sub_overflow(x, y, &z)) {
#ifndef MRB_WITHOUT_FLOAT
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x - (mrb_float)y);
break;
#endif
}
SET_INT_VALUE(regs[a], z);
}
break;
#ifndef MRB_WITHOUT_FLOAT
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):
{
mrb_int x = mrb_fixnum(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x - y);
}
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_int y = mrb_fixnum(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x - y);
}
#else
OP_MATH_BODY(-,mrb_float,mrb_fixnum);
#endif
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x - y);
}
#else
OP_MATH_BODY(-,mrb_float,mrb_float);
#endif
break;
#endif
default:
goto L_SEND;
}
NEXT;
}
CASE(OP_MUL) {
/* A B C R(A) := R(A)*R(A+1) (Syms[B]=:*,C=1)*/
int a = GETARG_A(i);
/* need to check if op is overridden */
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):
{
mrb_int x, y, z;
x = mrb_fixnum(regs[a]);
y = mrb_fixnum(regs[a+1]);
if (mrb_int_mul_overflow(x, y, &z)) {
#ifndef MRB_WITHOUT_FLOAT
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x * (mrb_float)y);
break;
#endif
}
SET_INT_VALUE(regs[a], z);
}
break;
#ifndef MRB_WITHOUT_FLOAT
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):
{
mrb_int x = mrb_fixnum(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x * y);
}
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_int y = mrb_fixnum(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x * y);
}
#else
OP_MATH_BODY(*,mrb_float,mrb_fixnum);
#endif
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
mrb_float y = mrb_float(regs[a+1]);
SET_FLOAT_VALUE(mrb, regs[a], x * y);
}
#else
OP_MATH_BODY(*,mrb_float,mrb_float);
#endif
break;
#endif
default:
goto L_SEND;
}
NEXT;
}
CASE(OP_DIV) {
/* A B C R(A) := R(A)/R(A+1) (Syms[B]=:/,C=1)*/
int a = GETARG_A(i);
#ifndef MRB_WITHOUT_FLOAT
double x, y, f;
#endif
/* need to check if op is overridden */
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):
#ifdef MRB_WITHOUT_FLOAT
{
mrb_int x = mrb_fixnum(regs[a]);
mrb_int y = mrb_fixnum(regs[a+1]);
SET_INT_VALUE(regs[a], y ? x / y : 0);
}
break;
#else
x = (mrb_float)mrb_fixnum(regs[a]);
y = (mrb_float)mrb_fixnum(regs[a+1]);
break;
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):
x = (mrb_float)mrb_fixnum(regs[a]);
y = mrb_float(regs[a+1]);
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):
x = mrb_float(regs[a]);
y = (mrb_float)mrb_fixnum(regs[a+1]);
break;
case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):
x = mrb_float(regs[a]);
y = mrb_float(regs[a+1]);
break;
#endif
default:
goto L_SEND;
}
#ifndef MRB_WITHOUT_FLOAT
if (y == 0) {
if (x > 0) f = INFINITY;
else if (x < 0) f = -INFINITY;
else /* if (x == 0) */ f = NAN;
}
else {
f = x / y;
}
SET_FLOAT_VALUE(mrb, regs[a], f);
#endif
NEXT;
}
CASE(OP_ADDI) {
/* A B C R(A) := R(A)+C (Syms[B]=:+)*/
int a = GETARG_A(i);
/* need to check if + is overridden */
switch (mrb_type(regs[a])) {
case MRB_TT_FIXNUM:
{
mrb_int x = mrb_fixnum(regs[a]);
mrb_int y = GETARG_C(i);
mrb_int z;
if (mrb_int_add_overflow(x, y, &z)) {
#ifndef MRB_WITHOUT_FLOAT
SET_FLOAT_VALUE(mrb, regs[a], (mrb_float)x + (mrb_float)y);
break;
#endif
}
SET_INT_VALUE(regs[a], z);
}
break;
#ifndef MRB_WITHOUT_FLOAT
case MRB_TT_FLOAT:
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
SET_FLOAT_VALUE(mrb, regs[a], x + GETARG_C(i));
}
#else
mrb_float(regs[a]) += GETARG_C(i);
#endif
break;
#endif
default:
SET_INT_VALUE(regs[a+1], GETARG_C(i));
i = MKOP_ABC(OP_SEND, a, GETARG_B(i), 1);
goto L_SEND;
}
NEXT;
}
CASE(OP_SUBI) {
/* A B C R(A) := R(A)-C (Syms[B]=:-)*/
int a = GETARG_A(i);
mrb_value *regs_a = regs + a;
/* need to check if + is overridden */
switch (mrb_type(regs_a[0])) {
case MRB_TT_FIXNUM:
{
mrb_int x = mrb_fixnum(regs_a[0]);
mrb_int y = GETARG_C(i);
mrb_int z;
if (mrb_int_sub_overflow(x, y, &z)) {
#ifndef MRB_WITHOUT_FLOAT
SET_FLOAT_VALUE(mrb, regs_a[0], (mrb_float)x - (mrb_float)y);
break;
#endif
}
SET_INT_VALUE(regs_a[0], z);
}
break;
#ifndef MRB_WITHOUT_FLOAT
case MRB_TT_FLOAT:
#ifdef MRB_WORD_BOXING
{
mrb_float x = mrb_float(regs[a]);
SET_FLOAT_VALUE(mrb, regs[a], x - GETARG_C(i));
}
#else
mrb_float(regs_a[0]) -= GETARG_C(i);
#endif
break;
#endif
default:
SET_INT_VALUE(regs_a[1], GETARG_C(i));
i = MKOP_ABC(OP_SEND, a, GETARG_B(i), 1);
goto L_SEND;
}
NEXT;
}
#define OP_CMP_BODY(op,v1,v2) (v1(regs[a]) op v2(regs[a+1]))
#ifdef MRB_WITHOUT_FLOAT
#define OP_CMP(op) do {\
int result;\
/* need to check if - is overridden */\
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\
result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\
break;\
default:\
goto L_SEND;\
}\
if (result) {\
SET_TRUE_VALUE(regs[a]);\
}\
else {\
SET_FALSE_VALUE(regs[a]);\
}\
} while(0)
#else
#define OP_CMP(op) do {\
int result;\
/* need to check if - is overridden */\
switch (TYPES2(mrb_type(regs[a]),mrb_type(regs[a+1]))) {\
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FIXNUM):\
result = OP_CMP_BODY(op,mrb_fixnum,mrb_fixnum);\
break;\
case TYPES2(MRB_TT_FIXNUM,MRB_TT_FLOAT):\
result = OP_CMP_BODY(op,mrb_fixnum,mrb_float);\
break;\
case TYPES2(MRB_TT_FLOAT,MRB_TT_FIXNUM):\
result = OP_CMP_BODY(op,mrb_float,mrb_fixnum);\
break;\
case TYPES2(MRB_TT_FLOAT,MRB_TT_FLOAT):\
result = OP_CMP_BODY(op,mrb_float,mrb_float);\
break;\
default:\
goto L_SEND;\
}\
if (result) {\
SET_TRUE_VALUE(regs[a]);\
}\
else {\
SET_FALSE_VALUE(regs[a]);\
}\
} while(0)
#endif
CASE(OP_EQ) {
/* A B C R(A) := R(A)==R(A+1) (Syms[B]=:==,C=1)*/
int a = GETARG_A(i);
if (mrb_obj_eq(mrb, regs[a], regs[a+1])) {
SET_TRUE_VALUE(regs[a]);
}
else {
OP_CMP(==);
}
NEXT;
}
CASE(OP_LT) {
/* A B C R(A) := R(A)<R(A+1) (Syms[B]=:<,C=1)*/
int a = GETARG_A(i);
OP_CMP(<);
NEXT;
}
CASE(OP_LE) {
/* A B C R(A) := R(A)<=R(A+1) (Syms[B]=:<=,C=1)*/
int a = GETARG_A(i);
OP_CMP(<=);
NEXT;
}
CASE(OP_GT) {
/* A B C R(A) := R(A)>R(A+1) (Syms[B]=:>,C=1)*/
int a = GETARG_A(i);
OP_CMP(>);
NEXT;
}
CASE(OP_GE) {
/* A B C R(A) := R(A)>=R(A+1) (Syms[B]=:>=,C=1)*/
int a = GETARG_A(i);
OP_CMP(>=);
NEXT;
}
CASE(OP_ARRAY) {
/* A B C R(A) := ary_new(R(B),R(B+1)..R(B+C)) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
mrb_value v = mrb_ary_new_from_values(mrb, c, ®s[b]);
regs[a] = v;
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_ARYCAT) {
/* A B mrb_ary_concat(R(A),R(B)) */
int a = GETARG_A(i);
int b = GETARG_B(i);
mrb_value splat = mrb_ary_splat(mrb, regs[b]);
mrb_ary_concat(mrb, regs[a], splat);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_ARYPUSH) {
/* A B R(A).push(R(B)) */
int a = GETARG_A(i);
int b = GETARG_B(i);
mrb_ary_push(mrb, regs[a], regs[b]);
NEXT;
}
CASE(OP_AREF) {
/* A B C R(A) := R(B)[C] */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
mrb_value v = regs[b];
if (!mrb_array_p(v)) {
if (c == 0) {
regs[a] = v;
}
else {
SET_NIL_VALUE(regs[a]);
}
}
else {
v = mrb_ary_ref(mrb, v, c);
regs[a] = v;
}
NEXT;
}
CASE(OP_ASET) {
/* A B C R(B)[C] := R(A) */
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
mrb_ary_set(mrb, regs[b], c, regs[a]);
NEXT;
}
CASE(OP_APOST) {
/* A B C *R(A),R(A+1)..R(A+C) := R(A) */
int a = GETARG_A(i);
mrb_value v = regs[a];
int pre = GETARG_B(i);
int post = GETARG_C(i);
struct RArray *ary;
int len, idx;
if (!mrb_array_p(v)) {
v = mrb_ary_new_from_values(mrb, 1, ®s[a]);
}
ary = mrb_ary_ptr(v);
len = (int)ARY_LEN(ary);
if (len > pre + post) {
v = mrb_ary_new_from_values(mrb, len - pre - post, ARY_PTR(ary)+pre);
regs[a++] = v;
while (post--) {
regs[a++] = ARY_PTR(ary)[len-post-1];
}
}
else {
v = mrb_ary_new_capa(mrb, 0);
regs[a++] = v;
for (idx=0; idx+pre<len; idx++) {
regs[a+idx] = ARY_PTR(ary)[pre+idx];
}
while (idx < post) {
SET_NIL_VALUE(regs[a+idx]);
idx++;
}
}
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_STRING) {
/* A Bx R(A) := str_new(Lit(Bx)) */
mrb_int a = GETARG_A(i);
mrb_int bx = GETARG_Bx(i);
mrb_value str = mrb_str_dup(mrb, pool[bx]);
regs[a] = str;
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_STRCAT) {
/* A B R(A).concat(R(B)) */
mrb_int a = GETARG_A(i);
mrb_int b = GETARG_B(i);
mrb_str_concat(mrb, regs[a], regs[b]);
NEXT;
}
CASE(OP_HASH) {
/* A B C R(A) := hash_new(R(B),R(B+1)..R(B+C)) */
int b = GETARG_B(i);
int c = GETARG_C(i);
int lim = b+c*2;
mrb_value hash = mrb_hash_new_capa(mrb, c);
while (b < lim) {
mrb_hash_set(mrb, hash, regs[b], regs[b+1]);
b+=2;
}
regs[GETARG_A(i)] = hash;
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_LAMBDA) {
/* A b c R(A) := lambda(SEQ[b],c) (b:c = 14:2) */
struct RProc *p;
int a = GETARG_A(i);
int b = GETARG_b(i);
int c = GETARG_c(i);
mrb_irep *nirep = irep->reps[b];
if (c & OP_L_CAPTURE) {
p = mrb_closure_new(mrb, nirep);
}
else {
p = mrb_proc_new(mrb, nirep);
p->flags |= MRB_PROC_SCOPE;
}
if (c & OP_L_STRICT) p->flags |= MRB_PROC_STRICT;
regs[a] = mrb_obj_value(p);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_OCLASS) {
/* A R(A) := ::Object */
regs[GETARG_A(i)] = mrb_obj_value(mrb->object_class);
NEXT;
}
CASE(OP_CLASS) {
/* A B R(A) := newclass(R(A),Syms(B),R(A+1)) */
struct RClass *c = 0, *baseclass;
int a = GETARG_A(i);
mrb_value base, super;
mrb_sym id = syms[GETARG_B(i)];
base = regs[a];
super = regs[a+1];
if (mrb_nil_p(base)) {
baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);
base = mrb_obj_value(baseclass);
}
c = mrb_vm_define_class(mrb, base, super, id);
regs[a] = mrb_obj_value(c);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_MODULE) {
/* A B R(A) := newmodule(R(A),Syms(B)) */
struct RClass *c = 0, *baseclass;
int a = GETARG_A(i);
mrb_value base;
mrb_sym id = syms[GETARG_B(i)];
base = regs[a];
if (mrb_nil_p(base)) {
baseclass = MRB_PROC_TARGET_CLASS(mrb->c->ci->proc);
base = mrb_obj_value(baseclass);
}
c = mrb_vm_define_module(mrb, base, id);
regs[a] = mrb_obj_value(c);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_EXEC) {
/* A Bx R(A) := blockexec(R(A),SEQ[Bx]) */
int a = GETARG_A(i);
int bx = GETARG_Bx(i);
mrb_callinfo *ci;
mrb_value recv = regs[a];
struct RProc *p;
mrb_irep *nirep = irep->reps[bx];
/* prepare closure */
p = mrb_proc_new(mrb, nirep);
p->c = NULL;
mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)proc);
MRB_PROC_SET_TARGET_CLASS(p, mrb_class_ptr(recv));
p->flags |= MRB_PROC_SCOPE;
/* prepare call stack */
ci = cipush(mrb);
ci->pc = pc + 1;
ci->acc = a;
ci->mid = 0;
ci->stackent = mrb->c->stack;
ci->argc = 0;
ci->target_class = mrb_class_ptr(recv);
/* prepare stack */
mrb->c->stack += a;
/* setup block to call */
ci->proc = p;
irep = p->body.irep;
pool = irep->pool;
syms = irep->syms;
ci->nregs = irep->nregs;
stack_extend(mrb, ci->nregs);
stack_clear(regs+1, ci->nregs-1);
pc = irep->iseq;
JUMP;
}
CASE(OP_METHOD) {
/* A B R(A).newmethod(Syms(B),R(A+1)) */
int a = GETARG_A(i);
struct RClass *c = mrb_class_ptr(regs[a]);
struct RProc *p = mrb_proc_ptr(regs[a+1]);
mrb_method_t m;
MRB_METHOD_FROM_PROC(m, p);
mrb_define_method_raw(mrb, c, syms[GETARG_B(i)], m);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_SCLASS) {
/* A B R(A) := R(B).singleton_class */
int a = GETARG_A(i);
int b = GETARG_B(i);
regs[a] = mrb_singleton_class(mrb, regs[b]);
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_TCLASS) {
/* A R(A) := target_class */
if (!mrb->c->ci->target_class) {
mrb_value exc = mrb_exc_new_str_lit(mrb, E_TYPE_ERROR, "no target class or module");
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
regs[GETARG_A(i)] = mrb_obj_value(mrb->c->ci->target_class);
NEXT;
}
CASE(OP_RANGE) {
/* A B C R(A) := range_new(R(B),R(B+1),C) */
int b = GETARG_B(i);
mrb_value val = mrb_range_new(mrb, regs[b], regs[b+1], GETARG_C(i));
regs[GETARG_A(i)] = val;
mrb_gc_arena_restore(mrb, ai);
NEXT;
}
CASE(OP_DEBUG) {
/* A B C debug print R(A),R(B),R(C) */
#ifdef MRB_ENABLE_DEBUG_HOOK
mrb->debug_op_hook(mrb, irep, pc, regs);
#else
#ifndef MRB_DISABLE_STDIO
printf("OP_DEBUG %d %d %d\n", GETARG_A(i), GETARG_B(i), GETARG_C(i));
#else
abort();
#endif
#endif
NEXT;
}
CASE(OP_STOP) {
/* stop VM */
L_STOP:
while (mrb->c->eidx > 0) {
ecall(mrb);
}
ERR_PC_CLR(mrb);
mrb->jmp = prev_jmp;
if (mrb->exc) {
return mrb_obj_value(mrb->exc);
}
return regs[irep->nlocals];
}
CASE(OP_ERR) {
/* Bx raise RuntimeError with message Lit(Bx) */
mrb_value msg = mrb_str_dup(mrb, pool[GETARG_Bx(i)]);
mrb_value exc;
if (GETARG_A(i) == 0) {
exc = mrb_exc_new_str(mrb, E_RUNTIME_ERROR, msg);
}
else {
exc = mrb_exc_new_str(mrb, E_LOCALJUMP_ERROR, msg);
}
ERR_PC_SET(mrb, pc);
mrb_exc_set(mrb, exc);
goto L_RAISE;
}
}
END_DISPATCH;
#undef regs
}
MRB_CATCH(&c_jmp) {
exc_catched = TRUE;
goto RETRY_TRY_BLOCK;
}
MRB_END_EXC(&c_jmp);
}
MRB_API mrb_value
mrb_run(mrb_state *mrb, struct RProc *proc, mrb_value self)
{
if (mrb->c->ci->argc < 0) {
return mrb_vm_run(mrb, proc, self, 3); /* receiver, args and block) */
}
else {
return mrb_vm_run(mrb, proc, self, mrb->c->ci->argc + 2); /* argc + 2 (receiver and block) */
}
}
MRB_API mrb_value
mrb_top_run(mrb_state *mrb, struct RProc *proc, mrb_value self, unsigned int stack_keep)
{
mrb_callinfo *ci;
mrb_value v;
if (!mrb->c->cibase) {
return mrb_vm_run(mrb, proc, self, stack_keep);
}
if (mrb->c->ci == mrb->c->cibase) {
return mrb_vm_run(mrb, proc, self, stack_keep);
}
ci = cipush(mrb);
ci->mid = 0;
ci->nregs = 1; /* protect the receiver */
ci->acc = CI_ACC_SKIP;
ci->target_class = mrb->object_class;
v = mrb_vm_run(mrb, proc, self, stack_keep);
cipop(mrb);
return v;
}
#if defined(MRB_ENABLE_CXX_EXCEPTION) && defined(__cplusplus)
# if !defined(MRB_ENABLE_CXX_ABI)
} /* end of extern "C" */
# endif
mrb_int mrb_jmpbuf::jmpbuf_id = 0;
# if !defined(MRB_ENABLE_CXX_ABI)
extern "C" {
# endif
#endif
| ./CrossVul/dataset_final_sorted/CWE-416/c/good_84_0 |
crossvul-cpp_data_good_2905_0 | /*
* USB Serial Console driver
*
* Copyright (C) 2001 - 2002 Greg Kroah-Hartman (greg@kroah.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation.
*
* Thanks to Randy Dunlap for the original version of this code.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/console.h>
#include <linux/serial.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
struct usbcons_info {
int magic;
int break_flag;
struct usb_serial_port *port;
};
static struct usbcons_info usbcons_info;
static struct console usbcons;
/*
* ------------------------------------------------------------
* USB Serial console driver
*
* Much of the code here is copied from drivers/char/serial.c
* and implements a phony serial console in the same way that
* serial.c does so that in case some software queries it,
* it will get the same results.
*
* Things that are different from the way the serial port code
* does things, is that we call the lower level usb-serial
* driver code to initialize the device, and we set the initial
* console speeds based on the command line arguments.
* ------------------------------------------------------------
*/
static const struct tty_operations usb_console_fake_tty_ops = {
};
/*
* The parsing of the command line works exactly like the
* serial.c code, except that the specifier is "ttyUSB" instead
* of "ttyS".
*/
static int usb_console_setup(struct console *co, char *options)
{
struct usbcons_info *info = &usbcons_info;
int baud = 9600;
int bits = 8;
int parity = 'n';
int doflow = 0;
int cflag = CREAD | HUPCL | CLOCAL;
char *s;
struct usb_serial *serial;
struct usb_serial_port *port;
int retval;
struct tty_struct *tty = NULL;
struct ktermios dummy;
if (options) {
baud = simple_strtoul(options, NULL, 10);
s = options;
while (*s >= '0' && *s <= '9')
s++;
if (*s)
parity = *s++;
if (*s)
bits = *s++ - '0';
if (*s)
doflow = (*s++ == 'r');
}
/* Sane default */
if (baud == 0)
baud = 9600;
switch (bits) {
case 7:
cflag |= CS7;
break;
default:
case 8:
cflag |= CS8;
break;
}
switch (parity) {
case 'o': case 'O':
cflag |= PARODD;
break;
case 'e': case 'E':
cflag |= PARENB;
break;
}
co->cflag = cflag;
/*
* no need to check the index here: if the index is wrong, console
* code won't call us
*/
port = usb_serial_port_get_by_minor(co->index);
if (port == NULL) {
/* no device is connected yet, sorry :( */
pr_err("No USB device connected to ttyUSB%i\n", co->index);
return -ENODEV;
}
serial = port->serial;
retval = usb_autopm_get_interface(serial->interface);
if (retval)
goto error_get_interface;
tty_port_tty_set(&port->port, NULL);
info->port = port;
++port->port.count;
if (!tty_port_initialized(&port->port)) {
if (serial->type->set_termios) {
/*
* allocate a fake tty so the driver can initialize
* the termios structure, then later call set_termios to
* configure according to command line arguments
*/
tty = kzalloc(sizeof(*tty), GFP_KERNEL);
if (!tty) {
retval = -ENOMEM;
goto reset_open_count;
}
kref_init(&tty->kref);
tty->driver = usb_serial_tty_driver;
tty->index = co->index;
init_ldsem(&tty->ldisc_sem);
spin_lock_init(&tty->files_lock);
INIT_LIST_HEAD(&tty->tty_files);
kref_get(&tty->driver->kref);
__module_get(tty->driver->owner);
tty->ops = &usb_console_fake_tty_ops;
tty_init_termios(tty);
tty_port_tty_set(&port->port, tty);
}
/* only call the device specific open if this
* is the first time the port is opened */
retval = serial->type->open(NULL, port);
if (retval) {
dev_err(&port->dev, "could not open USB console port\n");
goto fail;
}
if (serial->type->set_termios) {
tty->termios.c_cflag = cflag;
tty_termios_encode_baud_rate(&tty->termios, baud, baud);
memset(&dummy, 0, sizeof(struct ktermios));
serial->type->set_termios(tty, port, &dummy);
tty_port_tty_set(&port->port, NULL);
tty_kref_put(tty);
}
tty_port_set_initialized(&port->port, 1);
}
/* Now that any required fake tty operations are completed restore
* the tty port count */
--port->port.count;
/* The console is special in terms of closing the device so
* indicate this port is now acting as a system console. */
port->port.console = 1;
mutex_unlock(&serial->disc_mutex);
return retval;
fail:
tty_port_tty_set(&port->port, NULL);
tty_kref_put(tty);
reset_open_count:
port->port.count = 0;
info->port = NULL;
usb_autopm_put_interface(serial->interface);
error_get_interface:
usb_serial_put(serial);
mutex_unlock(&serial->disc_mutex);
return retval;
}
static void usb_console_write(struct console *co,
const char *buf, unsigned count)
{
static struct usbcons_info *info = &usbcons_info;
struct usb_serial_port *port = info->port;
struct usb_serial *serial;
int retval = -ENODEV;
if (!port || port->serial->dev->state == USB_STATE_NOTATTACHED)
return;
serial = port->serial;
if (count == 0)
return;
dev_dbg(&port->dev, "%s - %d byte(s)\n", __func__, count);
if (!port->port.console) {
dev_dbg(&port->dev, "%s - port not opened\n", __func__);
return;
}
while (count) {
unsigned int i;
unsigned int lf;
/* search for LF so we can insert CR if necessary */
for (i = 0, lf = 0 ; i < count ; i++) {
if (*(buf + i) == 10) {
lf = 1;
i++;
break;
}
}
/* pass on to the driver specific version of this function if
it is available */
retval = serial->type->write(NULL, port, buf, i);
dev_dbg(&port->dev, "%s - write: %d\n", __func__, retval);
if (lf) {
/* append CR after LF */
unsigned char cr = 13;
retval = serial->type->write(NULL, port, &cr, 1);
dev_dbg(&port->dev, "%s - write cr: %d\n",
__func__, retval);
}
buf += i;
count -= i;
}
}
static struct tty_driver *usb_console_device(struct console *co, int *index)
{
struct tty_driver **p = (struct tty_driver **)co->data;
if (!*p)
return NULL;
*index = co->index;
return *p;
}
static struct console usbcons = {
.name = "ttyUSB",
.write = usb_console_write,
.device = usb_console_device,
.setup = usb_console_setup,
.flags = CON_PRINTBUFFER,
.index = -1,
.data = &usb_serial_tty_driver,
};
void usb_serial_console_disconnect(struct usb_serial *serial)
{
if (serial->port[0] && serial->port[0] == usbcons_info.port) {
usb_serial_console_exit();
usb_serial_put(serial);
}
}
void usb_serial_console_init(int minor)
{
if (minor == 0) {
/*
* Call register_console() if this is the first device plugged
* in. If we call it earlier, then the callback to
* console_setup() will fail, as there is not a device seen by
* the USB subsystem yet.
*/
/*
* Register console.
* NOTES:
* console_setup() is called (back) immediately (from
* register_console). console_write() is called immediately
* from register_console iff CON_PRINTBUFFER is set in flags.
*/
pr_debug("registering the USB serial console.\n");
register_console(&usbcons);
}
}
void usb_serial_console_exit(void)
{
if (usbcons_info.port) {
unregister_console(&usbcons);
usbcons_info.port->port.console = 0;
usbcons_info.port = NULL;
}
}
| ./CrossVul/dataset_final_sorted/CWE-416/c/good_2905_0 |
crossvul-cpp_data_good_1859_0 | /*
* Performance events core code:
*
* Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
* Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
* Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
* Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
*
* For licensing details see kernel-base/COPYING
*/
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/cpu.h>
#include <linux/smp.h>
#include <linux/idr.h>
#include <linux/file.h>
#include <linux/poll.h>
#include <linux/slab.h>
#include <linux/hash.h>
#include <linux/tick.h>
#include <linux/sysfs.h>
#include <linux/dcache.h>
#include <linux/percpu.h>
#include <linux/ptrace.h>
#include <linux/reboot.h>
#include <linux/vmstat.h>
#include <linux/device.h>
#include <linux/export.h>
#include <linux/vmalloc.h>
#include <linux/hardirq.h>
#include <linux/rculist.h>
#include <linux/uaccess.h>
#include <linux/syscalls.h>
#include <linux/anon_inodes.h>
#include <linux/kernel_stat.h>
#include <linux/cgroup.h>
#include <linux/perf_event.h>
#include <linux/trace_events.h>
#include <linux/hw_breakpoint.h>
#include <linux/mm_types.h>
#include <linux/module.h>
#include <linux/mman.h>
#include <linux/compat.h>
#include <linux/bpf.h>
#include <linux/filter.h>
#include "internal.h"
#include <asm/irq_regs.h>
static struct workqueue_struct *perf_wq;
typedef int (*remote_function_f)(void *);
struct remote_function_call {
struct task_struct *p;
remote_function_f func;
void *info;
int ret;
};
static void remote_function(void *data)
{
struct remote_function_call *tfc = data;
struct task_struct *p = tfc->p;
if (p) {
tfc->ret = -EAGAIN;
if (task_cpu(p) != smp_processor_id() || !task_curr(p))
return;
}
tfc->ret = tfc->func(tfc->info);
}
/**
* task_function_call - call a function on the cpu on which a task runs
* @p: the task to evaluate
* @func: the function to be called
* @info: the function call argument
*
* Calls the function @func when the task is currently running. This might
* be on the current CPU, which just calls the function directly
*
* returns: @func return value, or
* -ESRCH - when the process isn't running
* -EAGAIN - when the process moved away
*/
static int
task_function_call(struct task_struct *p, remote_function_f func, void *info)
{
struct remote_function_call data = {
.p = p,
.func = func,
.info = info,
.ret = -ESRCH, /* No such (running) process */
};
if (task_curr(p))
smp_call_function_single(task_cpu(p), remote_function, &data, 1);
return data.ret;
}
/**
* cpu_function_call - call a function on the cpu
* @func: the function to be called
* @info: the function call argument
*
* Calls the function @func on the remote cpu.
*
* returns: @func return value or -ENXIO when the cpu is offline
*/
static int cpu_function_call(int cpu, remote_function_f func, void *info)
{
struct remote_function_call data = {
.p = NULL,
.func = func,
.info = info,
.ret = -ENXIO, /* No such CPU */
};
smp_call_function_single(cpu, remote_function, &data, 1);
return data.ret;
}
#define EVENT_OWNER_KERNEL ((void *) -1)
static bool is_kernel_event(struct perf_event *event)
{
return event->owner == EVENT_OWNER_KERNEL;
}
#define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
PERF_FLAG_FD_OUTPUT |\
PERF_FLAG_PID_CGROUP |\
PERF_FLAG_FD_CLOEXEC)
/*
* branch priv levels that need permission checks
*/
#define PERF_SAMPLE_BRANCH_PERM_PLM \
(PERF_SAMPLE_BRANCH_KERNEL |\
PERF_SAMPLE_BRANCH_HV)
enum event_type_t {
EVENT_FLEXIBLE = 0x1,
EVENT_PINNED = 0x2,
EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
};
/*
* perf_sched_events : >0 events exist
* perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
*/
struct static_key_deferred perf_sched_events __read_mostly;
static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
static DEFINE_PER_CPU(int, perf_sched_cb_usages);
static atomic_t nr_mmap_events __read_mostly;
static atomic_t nr_comm_events __read_mostly;
static atomic_t nr_task_events __read_mostly;
static atomic_t nr_freq_events __read_mostly;
static atomic_t nr_switch_events __read_mostly;
static LIST_HEAD(pmus);
static DEFINE_MUTEX(pmus_lock);
static struct srcu_struct pmus_srcu;
/*
* perf event paranoia level:
* -1 - not paranoid at all
* 0 - disallow raw tracepoint access for unpriv
* 1 - disallow cpu events for unpriv
* 2 - disallow kernel profiling for unpriv
*/
int sysctl_perf_event_paranoid __read_mostly = 1;
/* Minimum for 512 kiB + 1 user control page */
int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
/*
* max perf event sample rate
*/
#define DEFAULT_MAX_SAMPLE_RATE 100000
#define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
#define DEFAULT_CPU_TIME_MAX_PERCENT 25
int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
static int perf_sample_allowed_ns __read_mostly =
DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
static void update_perf_cpu_limits(void)
{
u64 tmp = perf_sample_period_ns;
tmp *= sysctl_perf_cpu_time_max_percent;
do_div(tmp, 100);
ACCESS_ONCE(perf_sample_allowed_ns) = tmp;
}
static int perf_rotate_context(struct perf_cpu_context *cpuctx);
int perf_proc_update_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
if (ret || !write)
return ret;
max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
update_perf_cpu_limits();
return 0;
}
int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp,
loff_t *ppos)
{
int ret = proc_dointvec(table, write, buffer, lenp, ppos);
if (ret || !write)
return ret;
update_perf_cpu_limits();
return 0;
}
/*
* perf samples are done in some very critical code paths (NMIs).
* If they take too much CPU time, the system can lock up and not
* get any real work done. This will drop the sample rate when
* we detect that events are taking too long.
*/
#define NR_ACCUMULATED_SAMPLES 128
static DEFINE_PER_CPU(u64, running_sample_length);
static void perf_duration_warn(struct irq_work *w)
{
u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
u64 avg_local_sample_len;
u64 local_samples_len;
local_samples_len = __this_cpu_read(running_sample_length);
avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
printk_ratelimited(KERN_WARNING
"perf interrupt took too long (%lld > %lld), lowering "
"kernel.perf_event_max_sample_rate to %d\n",
avg_local_sample_len, allowed_ns >> 1,
sysctl_perf_event_sample_rate);
}
static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
void perf_sample_event_took(u64 sample_len_ns)
{
u64 allowed_ns = ACCESS_ONCE(perf_sample_allowed_ns);
u64 avg_local_sample_len;
u64 local_samples_len;
if (allowed_ns == 0)
return;
/* decay the counter by 1 average sample */
local_samples_len = __this_cpu_read(running_sample_length);
local_samples_len -= local_samples_len/NR_ACCUMULATED_SAMPLES;
local_samples_len += sample_len_ns;
__this_cpu_write(running_sample_length, local_samples_len);
/*
* note: this will be biased artifically low until we have
* seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
* from having to maintain a count.
*/
avg_local_sample_len = local_samples_len/NR_ACCUMULATED_SAMPLES;
if (avg_local_sample_len <= allowed_ns)
return;
if (max_samples_per_tick <= 1)
return;
max_samples_per_tick = DIV_ROUND_UP(max_samples_per_tick, 2);
sysctl_perf_event_sample_rate = max_samples_per_tick * HZ;
perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
update_perf_cpu_limits();
if (!irq_work_queue(&perf_duration_work)) {
early_printk("perf interrupt took too long (%lld > %lld), lowering "
"kernel.perf_event_max_sample_rate to %d\n",
avg_local_sample_len, allowed_ns >> 1,
sysctl_perf_event_sample_rate);
}
}
static atomic64_t perf_event_id;
static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
enum event_type_t event_type);
static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
enum event_type_t event_type,
struct task_struct *task);
static void update_context_time(struct perf_event_context *ctx);
static u64 perf_event_time(struct perf_event *event);
void __weak perf_event_print_debug(void) { }
extern __weak const char *perf_pmu_name(void)
{
return "pmu";
}
static inline u64 perf_clock(void)
{
return local_clock();
}
static inline u64 perf_event_clock(struct perf_event *event)
{
return event->clock();
}
static inline struct perf_cpu_context *
__get_cpu_context(struct perf_event_context *ctx)
{
return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
}
static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
struct perf_event_context *ctx)
{
raw_spin_lock(&cpuctx->ctx.lock);
if (ctx)
raw_spin_lock(&ctx->lock);
}
static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
struct perf_event_context *ctx)
{
if (ctx)
raw_spin_unlock(&ctx->lock);
raw_spin_unlock(&cpuctx->ctx.lock);
}
#ifdef CONFIG_CGROUP_PERF
static inline bool
perf_cgroup_match(struct perf_event *event)
{
struct perf_event_context *ctx = event->ctx;
struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
/* @event doesn't care about cgroup */
if (!event->cgrp)
return true;
/* wants specific cgroup scope but @cpuctx isn't associated with any */
if (!cpuctx->cgrp)
return false;
/*
* Cgroup scoping is recursive. An event enabled for a cgroup is
* also enabled for all its descendant cgroups. If @cpuctx's
* cgroup is a descendant of @event's (the test covers identity
* case), it's a match.
*/
return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
event->cgrp->css.cgroup);
}
static inline void perf_detach_cgroup(struct perf_event *event)
{
css_put(&event->cgrp->css);
event->cgrp = NULL;
}
static inline int is_cgroup_event(struct perf_event *event)
{
return event->cgrp != NULL;
}
static inline u64 perf_cgroup_event_time(struct perf_event *event)
{
struct perf_cgroup_info *t;
t = per_cpu_ptr(event->cgrp->info, event->cpu);
return t->time;
}
static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
{
struct perf_cgroup_info *info;
u64 now;
now = perf_clock();
info = this_cpu_ptr(cgrp->info);
info->time += now - info->timestamp;
info->timestamp = now;
}
static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
{
struct perf_cgroup *cgrp_out = cpuctx->cgrp;
if (cgrp_out)
__update_cgrp_time(cgrp_out);
}
static inline void update_cgrp_time_from_event(struct perf_event *event)
{
struct perf_cgroup *cgrp;
/*
* ensure we access cgroup data only when needed and
* when we know the cgroup is pinned (css_get)
*/
if (!is_cgroup_event(event))
return;
cgrp = perf_cgroup_from_task(current, event->ctx);
/*
* Do not update time when cgroup is not active
*/
if (cgrp == event->cgrp)
__update_cgrp_time(event->cgrp);
}
static inline void
perf_cgroup_set_timestamp(struct task_struct *task,
struct perf_event_context *ctx)
{
struct perf_cgroup *cgrp;
struct perf_cgroup_info *info;
/*
* ctx->lock held by caller
* ensure we do not access cgroup data
* unless we have the cgroup pinned (css_get)
*/
if (!task || !ctx->nr_cgroups)
return;
cgrp = perf_cgroup_from_task(task, ctx);
info = this_cpu_ptr(cgrp->info);
info->timestamp = ctx->timestamp;
}
#define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
#define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
/*
* reschedule events based on the cgroup constraint of task.
*
* mode SWOUT : schedule out everything
* mode SWIN : schedule in based on cgroup for next
*/
static void perf_cgroup_switch(struct task_struct *task, int mode)
{
struct perf_cpu_context *cpuctx;
struct pmu *pmu;
unsigned long flags;
/*
* disable interrupts to avoid geting nr_cgroup
* changes via __perf_event_disable(). Also
* avoids preemption.
*/
local_irq_save(flags);
/*
* we reschedule only in the presence of cgroup
* constrained events.
*/
list_for_each_entry_rcu(pmu, &pmus, entry) {
cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
if (cpuctx->unique_pmu != pmu)
continue; /* ensure we process each cpuctx once */
/*
* perf_cgroup_events says at least one
* context on this CPU has cgroup events.
*
* ctx->nr_cgroups reports the number of cgroup
* events for a context.
*/
if (cpuctx->ctx.nr_cgroups > 0) {
perf_ctx_lock(cpuctx, cpuctx->task_ctx);
perf_pmu_disable(cpuctx->ctx.pmu);
if (mode & PERF_CGROUP_SWOUT) {
cpu_ctx_sched_out(cpuctx, EVENT_ALL);
/*
* must not be done before ctxswout due
* to event_filter_match() in event_sched_out()
*/
cpuctx->cgrp = NULL;
}
if (mode & PERF_CGROUP_SWIN) {
WARN_ON_ONCE(cpuctx->cgrp);
/*
* set cgrp before ctxsw in to allow
* event_filter_match() to not have to pass
* task around
* we pass the cpuctx->ctx to perf_cgroup_from_task()
* because cgorup events are only per-cpu
*/
cpuctx->cgrp = perf_cgroup_from_task(task, &cpuctx->ctx);
cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
}
perf_pmu_enable(cpuctx->ctx.pmu);
perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
}
}
local_irq_restore(flags);
}
static inline void perf_cgroup_sched_out(struct task_struct *task,
struct task_struct *next)
{
struct perf_cgroup *cgrp1;
struct perf_cgroup *cgrp2 = NULL;
rcu_read_lock();
/*
* we come here when we know perf_cgroup_events > 0
* we do not need to pass the ctx here because we know
* we are holding the rcu lock
*/
cgrp1 = perf_cgroup_from_task(task, NULL);
/*
* next is NULL when called from perf_event_enable_on_exec()
* that will systematically cause a cgroup_switch()
*/
if (next)
cgrp2 = perf_cgroup_from_task(next, NULL);
/*
* only schedule out current cgroup events if we know
* that we are switching to a different cgroup. Otherwise,
* do no touch the cgroup events.
*/
if (cgrp1 != cgrp2)
perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
rcu_read_unlock();
}
static inline void perf_cgroup_sched_in(struct task_struct *prev,
struct task_struct *task)
{
struct perf_cgroup *cgrp1;
struct perf_cgroup *cgrp2 = NULL;
rcu_read_lock();
/*
* we come here when we know perf_cgroup_events > 0
* we do not need to pass the ctx here because we know
* we are holding the rcu lock
*/
cgrp1 = perf_cgroup_from_task(task, NULL);
/* prev can never be NULL */
cgrp2 = perf_cgroup_from_task(prev, NULL);
/*
* only need to schedule in cgroup events if we are changing
* cgroup during ctxsw. Cgroup events were not scheduled
* out of ctxsw out if that was not the case.
*/
if (cgrp1 != cgrp2)
perf_cgroup_switch(task, PERF_CGROUP_SWIN);
rcu_read_unlock();
}
static inline int perf_cgroup_connect(int fd, struct perf_event *event,
struct perf_event_attr *attr,
struct perf_event *group_leader)
{
struct perf_cgroup *cgrp;
struct cgroup_subsys_state *css;
struct fd f = fdget(fd);
int ret = 0;
if (!f.file)
return -EBADF;
css = css_tryget_online_from_dir(f.file->f_path.dentry,
&perf_event_cgrp_subsys);
if (IS_ERR(css)) {
ret = PTR_ERR(css);
goto out;
}
cgrp = container_of(css, struct perf_cgroup, css);
event->cgrp = cgrp;
/*
* all events in a group must monitor
* the same cgroup because a task belongs
* to only one perf cgroup at a time
*/
if (group_leader && group_leader->cgrp != cgrp) {
perf_detach_cgroup(event);
ret = -EINVAL;
}
out:
fdput(f);
return ret;
}
static inline void
perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
{
struct perf_cgroup_info *t;
t = per_cpu_ptr(event->cgrp->info, event->cpu);
event->shadow_ctx_time = now - t->timestamp;
}
static inline void
perf_cgroup_defer_enabled(struct perf_event *event)
{
/*
* when the current task's perf cgroup does not match
* the event's, we need to remember to call the
* perf_mark_enable() function the first time a task with
* a matching perf cgroup is scheduled in.
*/
if (is_cgroup_event(event) && !perf_cgroup_match(event))
event->cgrp_defer_enabled = 1;
}
static inline void
perf_cgroup_mark_enabled(struct perf_event *event,
struct perf_event_context *ctx)
{
struct perf_event *sub;
u64 tstamp = perf_event_time(event);
if (!event->cgrp_defer_enabled)
return;
event->cgrp_defer_enabled = 0;
event->tstamp_enabled = tstamp - event->total_time_enabled;
list_for_each_entry(sub, &event->sibling_list, group_entry) {
if (sub->state >= PERF_EVENT_STATE_INACTIVE) {
sub->tstamp_enabled = tstamp - sub->total_time_enabled;
sub->cgrp_defer_enabled = 0;
}
}
}
#else /* !CONFIG_CGROUP_PERF */
static inline bool
perf_cgroup_match(struct perf_event *event)
{
return true;
}
static inline void perf_detach_cgroup(struct perf_event *event)
{}
static inline int is_cgroup_event(struct perf_event *event)
{
return 0;
}
static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event)
{
return 0;
}
static inline void update_cgrp_time_from_event(struct perf_event *event)
{
}
static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
{
}
static inline void perf_cgroup_sched_out(struct task_struct *task,
struct task_struct *next)
{
}
static inline void perf_cgroup_sched_in(struct task_struct *prev,
struct task_struct *task)
{
}
static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
struct perf_event_attr *attr,
struct perf_event *group_leader)
{
return -EINVAL;
}
static inline void
perf_cgroup_set_timestamp(struct task_struct *task,
struct perf_event_context *ctx)
{
}
void
perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
{
}
static inline void
perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
{
}
static inline u64 perf_cgroup_event_time(struct perf_event *event)
{
return 0;
}
static inline void
perf_cgroup_defer_enabled(struct perf_event *event)
{
}
static inline void
perf_cgroup_mark_enabled(struct perf_event *event,
struct perf_event_context *ctx)
{
}
#endif
/*
* set default to be dependent on timer tick just
* like original code
*/
#define PERF_CPU_HRTIMER (1000 / HZ)
/*
* function must be called with interrupts disbled
*/
static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
{
struct perf_cpu_context *cpuctx;
int rotations = 0;
WARN_ON(!irqs_disabled());
cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
rotations = perf_rotate_context(cpuctx);
raw_spin_lock(&cpuctx->hrtimer_lock);
if (rotations)
hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
else
cpuctx->hrtimer_active = 0;
raw_spin_unlock(&cpuctx->hrtimer_lock);
return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
}
static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
{
struct hrtimer *timer = &cpuctx->hrtimer;
struct pmu *pmu = cpuctx->ctx.pmu;
u64 interval;
/* no multiplexing needed for SW PMU */
if (pmu->task_ctx_nr == perf_sw_context)
return;
/*
* check default is sane, if not set then force to
* default interval (1/tick)
*/
interval = pmu->hrtimer_interval_ms;
if (interval < 1)
interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
raw_spin_lock_init(&cpuctx->hrtimer_lock);
hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
timer->function = perf_mux_hrtimer_handler;
}
static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
{
struct hrtimer *timer = &cpuctx->hrtimer;
struct pmu *pmu = cpuctx->ctx.pmu;
unsigned long flags;
/* not for SW PMU */
if (pmu->task_ctx_nr == perf_sw_context)
return 0;
raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
if (!cpuctx->hrtimer_active) {
cpuctx->hrtimer_active = 1;
hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
}
raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
return 0;
}
void perf_pmu_disable(struct pmu *pmu)
{
int *count = this_cpu_ptr(pmu->pmu_disable_count);
if (!(*count)++)
pmu->pmu_disable(pmu);
}
void perf_pmu_enable(struct pmu *pmu)
{
int *count = this_cpu_ptr(pmu->pmu_disable_count);
if (!--(*count))
pmu->pmu_enable(pmu);
}
static DEFINE_PER_CPU(struct list_head, active_ctx_list);
/*
* perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
* perf_event_task_tick() are fully serialized because they're strictly cpu
* affine and perf_event_ctx{activate,deactivate} are called with IRQs
* disabled, while perf_event_task_tick is called from IRQ context.
*/
static void perf_event_ctx_activate(struct perf_event_context *ctx)
{
struct list_head *head = this_cpu_ptr(&active_ctx_list);
WARN_ON(!irqs_disabled());
WARN_ON(!list_empty(&ctx->active_ctx_list));
list_add(&ctx->active_ctx_list, head);
}
static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
{
WARN_ON(!irqs_disabled());
WARN_ON(list_empty(&ctx->active_ctx_list));
list_del_init(&ctx->active_ctx_list);
}
static void get_ctx(struct perf_event_context *ctx)
{
WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
}
static void free_ctx(struct rcu_head *head)
{
struct perf_event_context *ctx;
ctx = container_of(head, struct perf_event_context, rcu_head);
kfree(ctx->task_ctx_data);
kfree(ctx);
}
static void put_ctx(struct perf_event_context *ctx)
{
if (atomic_dec_and_test(&ctx->refcount)) {
if (ctx->parent_ctx)
put_ctx(ctx->parent_ctx);
if (ctx->task)
put_task_struct(ctx->task);
call_rcu(&ctx->rcu_head, free_ctx);
}
}
/*
* Because of perf_event::ctx migration in sys_perf_event_open::move_group and
* perf_pmu_migrate_context() we need some magic.
*
* Those places that change perf_event::ctx will hold both
* perf_event_ctx::mutex of the 'old' and 'new' ctx value.
*
* Lock ordering is by mutex address. There are two other sites where
* perf_event_context::mutex nests and those are:
*
* - perf_event_exit_task_context() [ child , 0 ]
* __perf_event_exit_task()
* sync_child_event()
* put_event() [ parent, 1 ]
*
* - perf_event_init_context() [ parent, 0 ]
* inherit_task_group()
* inherit_group()
* inherit_event()
* perf_event_alloc()
* perf_init_event()
* perf_try_init_event() [ child , 1 ]
*
* While it appears there is an obvious deadlock here -- the parent and child
* nesting levels are inverted between the two. This is in fact safe because
* life-time rules separate them. That is an exiting task cannot fork, and a
* spawning task cannot (yet) exit.
*
* But remember that that these are parent<->child context relations, and
* migration does not affect children, therefore these two orderings should not
* interact.
*
* The change in perf_event::ctx does not affect children (as claimed above)
* because the sys_perf_event_open() case will install a new event and break
* the ctx parent<->child relation, and perf_pmu_migrate_context() is only
* concerned with cpuctx and that doesn't have children.
*
* The places that change perf_event::ctx will issue:
*
* perf_remove_from_context();
* synchronize_rcu();
* perf_install_in_context();
*
* to affect the change. The remove_from_context() + synchronize_rcu() should
* quiesce the event, after which we can install it in the new location. This
* means that only external vectors (perf_fops, prctl) can perturb the event
* while in transit. Therefore all such accessors should also acquire
* perf_event_context::mutex to serialize against this.
*
* However; because event->ctx can change while we're waiting to acquire
* ctx->mutex we must be careful and use the below perf_event_ctx_lock()
* function.
*
* Lock order:
* task_struct::perf_event_mutex
* perf_event_context::mutex
* perf_event_context::lock
* perf_event::child_mutex;
* perf_event::mmap_mutex
* mmap_sem
*/
static struct perf_event_context *
perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
{
struct perf_event_context *ctx;
again:
rcu_read_lock();
ctx = ACCESS_ONCE(event->ctx);
if (!atomic_inc_not_zero(&ctx->refcount)) {
rcu_read_unlock();
goto again;
}
rcu_read_unlock();
mutex_lock_nested(&ctx->mutex, nesting);
if (event->ctx != ctx) {
mutex_unlock(&ctx->mutex);
put_ctx(ctx);
goto again;
}
return ctx;
}
static inline struct perf_event_context *
perf_event_ctx_lock(struct perf_event *event)
{
return perf_event_ctx_lock_nested(event, 0);
}
static void perf_event_ctx_unlock(struct perf_event *event,
struct perf_event_context *ctx)
{
mutex_unlock(&ctx->mutex);
put_ctx(ctx);
}
/*
* This must be done under the ctx->lock, such as to serialize against
* context_equiv(), therefore we cannot call put_ctx() since that might end up
* calling scheduler related locks and ctx->lock nests inside those.
*/
static __must_check struct perf_event_context *
unclone_ctx(struct perf_event_context *ctx)
{
struct perf_event_context *parent_ctx = ctx->parent_ctx;
lockdep_assert_held(&ctx->lock);
if (parent_ctx)
ctx->parent_ctx = NULL;
ctx->generation++;
return parent_ctx;
}
static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
{
/*
* only top level events have the pid namespace they were created in
*/
if (event->parent)
event = event->parent;
return task_tgid_nr_ns(p, event->ns);
}
static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
{
/*
* only top level events have the pid namespace they were created in
*/
if (event->parent)
event = event->parent;
return task_pid_nr_ns(p, event->ns);
}
/*
* If we inherit events we want to return the parent event id
* to userspace.
*/
static u64 primary_event_id(struct perf_event *event)
{
u64 id = event->id;
if (event->parent)
id = event->parent->id;
return id;
}
/*
* Get the perf_event_context for a task and lock it.
* This has to cope with with the fact that until it is locked,
* the context could get moved to another task.
*/
static struct perf_event_context *
perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
{
struct perf_event_context *ctx;
retry:
/*
* One of the few rules of preemptible RCU is that one cannot do
* rcu_read_unlock() while holding a scheduler (or nested) lock when
* part of the read side critical section was irqs-enabled -- see
* rcu_read_unlock_special().
*
* Since ctx->lock nests under rq->lock we must ensure the entire read
* side critical section has interrupts disabled.
*/
local_irq_save(*flags);
rcu_read_lock();
ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
if (ctx) {
/*
* If this context is a clone of another, it might
* get swapped for another underneath us by
* perf_event_task_sched_out, though the
* rcu_read_lock() protects us from any context
* getting freed. Lock the context and check if it
* got swapped before we could get the lock, and retry
* if so. If we locked the right context, then it
* can't get swapped on us any more.
*/
raw_spin_lock(&ctx->lock);
if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
raw_spin_unlock(&ctx->lock);
rcu_read_unlock();
local_irq_restore(*flags);
goto retry;
}
if (!atomic_inc_not_zero(&ctx->refcount)) {
raw_spin_unlock(&ctx->lock);
ctx = NULL;
}
}
rcu_read_unlock();
if (!ctx)
local_irq_restore(*flags);
return ctx;
}
/*
* Get the context for a task and increment its pin_count so it
* can't get swapped to another task. This also increments its
* reference count so that the context can't get freed.
*/
static struct perf_event_context *
perf_pin_task_context(struct task_struct *task, int ctxn)
{
struct perf_event_context *ctx;
unsigned long flags;
ctx = perf_lock_task_context(task, ctxn, &flags);
if (ctx) {
++ctx->pin_count;
raw_spin_unlock_irqrestore(&ctx->lock, flags);
}
return ctx;
}
static void perf_unpin_context(struct perf_event_context *ctx)
{
unsigned long flags;
raw_spin_lock_irqsave(&ctx->lock, flags);
--ctx->pin_count;
raw_spin_unlock_irqrestore(&ctx->lock, flags);
}
/*
* Update the record of the current time in a context.
*/
static void update_context_time(struct perf_event_context *ctx)
{
u64 now = perf_clock();
ctx->time += now - ctx->timestamp;
ctx->timestamp = now;
}
static u64 perf_event_time(struct perf_event *event)
{
struct perf_event_context *ctx = event->ctx;
if (is_cgroup_event(event))
return perf_cgroup_event_time(event);
return ctx ? ctx->time : 0;
}
/*
* Update the total_time_enabled and total_time_running fields for a event.
* The caller of this function needs to hold the ctx->lock.
*/
static void update_event_times(struct perf_event *event)
{
struct perf_event_context *ctx = event->ctx;
u64 run_end;
if (event->state < PERF_EVENT_STATE_INACTIVE ||
event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
return;
/*
* in cgroup mode, time_enabled represents
* the time the event was enabled AND active
* tasks were in the monitored cgroup. This is
* independent of the activity of the context as
* there may be a mix of cgroup and non-cgroup events.
*
* That is why we treat cgroup events differently
* here.
*/
if (is_cgroup_event(event))
run_end = perf_cgroup_event_time(event);
else if (ctx->is_active)
run_end = ctx->time;
else
run_end = event->tstamp_stopped;
event->total_time_enabled = run_end - event->tstamp_enabled;
if (event->state == PERF_EVENT_STATE_INACTIVE)
run_end = event->tstamp_stopped;
else
run_end = perf_event_time(event);
event->total_time_running = run_end - event->tstamp_running;
}
/*
* Update total_time_enabled and total_time_running for all events in a group.
*/
static void update_group_times(struct perf_event *leader)
{
struct perf_event *event;
update_event_times(leader);
list_for_each_entry(event, &leader->sibling_list, group_entry)
update_event_times(event);
}
static struct list_head *
ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
{
if (event->attr.pinned)
return &ctx->pinned_groups;
else
return &ctx->flexible_groups;
}
/*
* Add a event from the lists for its context.
* Must be called with ctx->mutex and ctx->lock held.
*/
static void
list_add_event(struct perf_event *event, struct perf_event_context *ctx)
{
WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
event->attach_state |= PERF_ATTACH_CONTEXT;
/*
* If we're a stand alone event or group leader, we go to the context
* list, group events are kept attached to the group so that
* perf_group_detach can, at all times, locate all siblings.
*/
if (event->group_leader == event) {
struct list_head *list;
if (is_software_event(event))
event->group_flags |= PERF_GROUP_SOFTWARE;
list = ctx_group_list(event, ctx);
list_add_tail(&event->group_entry, list);
}
if (is_cgroup_event(event))
ctx->nr_cgroups++;
list_add_rcu(&event->event_entry, &ctx->event_list);
ctx->nr_events++;
if (event->attr.inherit_stat)
ctx->nr_stat++;
ctx->generation++;
}
/*
* Initialize event state based on the perf_event_attr::disabled.
*/
static inline void perf_event__state_init(struct perf_event *event)
{
event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
PERF_EVENT_STATE_INACTIVE;
}
static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
{
int entry = sizeof(u64); /* value */
int size = 0;
int nr = 1;
if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
size += sizeof(u64);
if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
size += sizeof(u64);
if (event->attr.read_format & PERF_FORMAT_ID)
entry += sizeof(u64);
if (event->attr.read_format & PERF_FORMAT_GROUP) {
nr += nr_siblings;
size += sizeof(u64);
}
size += entry * nr;
event->read_size = size;
}
static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
{
struct perf_sample_data *data;
u16 size = 0;
if (sample_type & PERF_SAMPLE_IP)
size += sizeof(data->ip);
if (sample_type & PERF_SAMPLE_ADDR)
size += sizeof(data->addr);
if (sample_type & PERF_SAMPLE_PERIOD)
size += sizeof(data->period);
if (sample_type & PERF_SAMPLE_WEIGHT)
size += sizeof(data->weight);
if (sample_type & PERF_SAMPLE_READ)
size += event->read_size;
if (sample_type & PERF_SAMPLE_DATA_SRC)
size += sizeof(data->data_src.val);
if (sample_type & PERF_SAMPLE_TRANSACTION)
size += sizeof(data->txn);
event->header_size = size;
}
/*
* Called at perf_event creation and when events are attached/detached from a
* group.
*/
static void perf_event__header_size(struct perf_event *event)
{
__perf_event_read_size(event,
event->group_leader->nr_siblings);
__perf_event_header_size(event, event->attr.sample_type);
}
static void perf_event__id_header_size(struct perf_event *event)
{
struct perf_sample_data *data;
u64 sample_type = event->attr.sample_type;
u16 size = 0;
if (sample_type & PERF_SAMPLE_TID)
size += sizeof(data->tid_entry);
if (sample_type & PERF_SAMPLE_TIME)
size += sizeof(data->time);
if (sample_type & PERF_SAMPLE_IDENTIFIER)
size += sizeof(data->id);
if (sample_type & PERF_SAMPLE_ID)
size += sizeof(data->id);
if (sample_type & PERF_SAMPLE_STREAM_ID)
size += sizeof(data->stream_id);
if (sample_type & PERF_SAMPLE_CPU)
size += sizeof(data->cpu_entry);
event->id_header_size = size;
}
static bool perf_event_validate_size(struct perf_event *event)
{
/*
* The values computed here will be over-written when we actually
* attach the event.
*/
__perf_event_read_size(event, event->group_leader->nr_siblings + 1);
__perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
perf_event__id_header_size(event);
/*
* Sum the lot; should not exceed the 64k limit we have on records.
* Conservative limit to allow for callchains and other variable fields.
*/
if (event->read_size + event->header_size +
event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
return false;
return true;
}
static void perf_group_attach(struct perf_event *event)
{
struct perf_event *group_leader = event->group_leader, *pos;
/*
* We can have double attach due to group movement in perf_event_open.
*/
if (event->attach_state & PERF_ATTACH_GROUP)
return;
event->attach_state |= PERF_ATTACH_GROUP;
if (group_leader == event)
return;
WARN_ON_ONCE(group_leader->ctx != event->ctx);
if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
!is_software_event(event))
group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
list_add_tail(&event->group_entry, &group_leader->sibling_list);
group_leader->nr_siblings++;
perf_event__header_size(group_leader);
list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
perf_event__header_size(pos);
}
/*
* Remove a event from the lists for its context.
* Must be called with ctx->mutex and ctx->lock held.
*/
static void
list_del_event(struct perf_event *event, struct perf_event_context *ctx)
{
struct perf_cpu_context *cpuctx;
WARN_ON_ONCE(event->ctx != ctx);
lockdep_assert_held(&ctx->lock);
/*
* We can have double detach due to exit/hot-unplug + close.
*/
if (!(event->attach_state & PERF_ATTACH_CONTEXT))
return;
event->attach_state &= ~PERF_ATTACH_CONTEXT;
if (is_cgroup_event(event)) {
ctx->nr_cgroups--;
cpuctx = __get_cpu_context(ctx);
/*
* if there are no more cgroup events
* then cler cgrp to avoid stale pointer
* in update_cgrp_time_from_cpuctx()
*/
if (!ctx->nr_cgroups)
cpuctx->cgrp = NULL;
}
ctx->nr_events--;
if (event->attr.inherit_stat)
ctx->nr_stat--;
list_del_rcu(&event->event_entry);
if (event->group_leader == event)
list_del_init(&event->group_entry);
update_group_times(event);
/*
* If event was in error state, then keep it
* that way, otherwise bogus counts will be
* returned on read(). The only way to get out
* of error state is by explicit re-enabling
* of the event
*/
if (event->state > PERF_EVENT_STATE_OFF)
event->state = PERF_EVENT_STATE_OFF;
ctx->generation++;
}
static void perf_group_detach(struct perf_event *event)
{
struct perf_event *sibling, *tmp;
struct list_head *list = NULL;
/*
* We can have double detach due to exit/hot-unplug + close.
*/
if (!(event->attach_state & PERF_ATTACH_GROUP))
return;
event->attach_state &= ~PERF_ATTACH_GROUP;
/*
* If this is a sibling, remove it from its group.
*/
if (event->group_leader != event) {
list_del_init(&event->group_entry);
event->group_leader->nr_siblings--;
goto out;
}
if (!list_empty(&event->group_entry))
list = &event->group_entry;
/*
* If this was a group event with sibling events then
* upgrade the siblings to singleton events by adding them
* to whatever list we are on.
*/
list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
if (list)
list_move_tail(&sibling->group_entry, list);
sibling->group_leader = sibling;
/* Inherit group flags from the previous leader */
sibling->group_flags = event->group_flags;
WARN_ON_ONCE(sibling->ctx != event->ctx);
}
out:
perf_event__header_size(event->group_leader);
list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
perf_event__header_size(tmp);
}
/*
* User event without the task.
*/
static bool is_orphaned_event(struct perf_event *event)
{
return event && !is_kernel_event(event) && !event->owner;
}
/*
* Event has a parent but parent's task finished and it's
* alive only because of children holding refference.
*/
static bool is_orphaned_child(struct perf_event *event)
{
return is_orphaned_event(event->parent);
}
static void orphans_remove_work(struct work_struct *work);
static void schedule_orphans_remove(struct perf_event_context *ctx)
{
if (!ctx->task || ctx->orphans_remove_sched || !perf_wq)
return;
if (queue_delayed_work(perf_wq, &ctx->orphans_remove, 1)) {
get_ctx(ctx);
ctx->orphans_remove_sched = true;
}
}
static int __init perf_workqueue_init(void)
{
perf_wq = create_singlethread_workqueue("perf");
WARN(!perf_wq, "failed to create perf workqueue\n");
return perf_wq ? 0 : -1;
}
core_initcall(perf_workqueue_init);
static inline int pmu_filter_match(struct perf_event *event)
{
struct pmu *pmu = event->pmu;
return pmu->filter_match ? pmu->filter_match(event) : 1;
}
static inline int
event_filter_match(struct perf_event *event)
{
return (event->cpu == -1 || event->cpu == smp_processor_id())
&& perf_cgroup_match(event) && pmu_filter_match(event);
}
static void
event_sched_out(struct perf_event *event,
struct perf_cpu_context *cpuctx,
struct perf_event_context *ctx)
{
u64 tstamp = perf_event_time(event);
u64 delta;
WARN_ON_ONCE(event->ctx != ctx);
lockdep_assert_held(&ctx->lock);
/*
* An event which could not be activated because of
* filter mismatch still needs to have its timings
* maintained, otherwise bogus information is return
* via read() for time_enabled, time_running:
*/
if (event->state == PERF_EVENT_STATE_INACTIVE
&& !event_filter_match(event)) {
delta = tstamp - event->tstamp_stopped;
event->tstamp_running += delta;
event->tstamp_stopped = tstamp;
}
if (event->state != PERF_EVENT_STATE_ACTIVE)
return;
perf_pmu_disable(event->pmu);
event->state = PERF_EVENT_STATE_INACTIVE;
if (event->pending_disable) {
event->pending_disable = 0;
event->state = PERF_EVENT_STATE_OFF;
}
event->tstamp_stopped = tstamp;
event->pmu->del(event, 0);
event->oncpu = -1;
if (!is_software_event(event))
cpuctx->active_oncpu--;
if (!--ctx->nr_active)
perf_event_ctx_deactivate(ctx);
if (event->attr.freq && event->attr.sample_freq)
ctx->nr_freq--;
if (event->attr.exclusive || !cpuctx->active_oncpu)
cpuctx->exclusive = 0;
if (is_orphaned_child(event))
schedule_orphans_remove(ctx);
perf_pmu_enable(event->pmu);
}
static void
group_sched_out(struct perf_event *group_event,
struct perf_cpu_context *cpuctx,
struct perf_event_context *ctx)
{
struct perf_event *event;
int state = group_event->state;
event_sched_out(group_event, cpuctx, ctx);
/*
* Schedule out siblings (if any):
*/
list_for_each_entry(event, &group_event->sibling_list, group_entry)
event_sched_out(event, cpuctx, ctx);
if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
cpuctx->exclusive = 0;
}
struct remove_event {
struct perf_event *event;
bool detach_group;
};
/*
* Cross CPU call to remove a performance event
*
* We disable the event on the hardware level first. After that we
* remove it from the context list.
*/
static int __perf_remove_from_context(void *info)
{
struct remove_event *re = info;
struct perf_event *event = re->event;
struct perf_event_context *ctx = event->ctx;
struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
raw_spin_lock(&ctx->lock);
event_sched_out(event, cpuctx, ctx);
if (re->detach_group)
perf_group_detach(event);
list_del_event(event, ctx);
if (!ctx->nr_events && cpuctx->task_ctx == ctx) {
ctx->is_active = 0;
cpuctx->task_ctx = NULL;
}
raw_spin_unlock(&ctx->lock);
return 0;
}
/*
* Remove the event from a task's (or a CPU's) list of events.
*
* CPU events are removed with a smp call. For task events we only
* call when the task is on a CPU.
*
* If event->ctx is a cloned context, callers must make sure that
* every task struct that event->ctx->task could possibly point to
* remains valid. This is OK when called from perf_release since
* that only calls us on the top-level context, which can't be a clone.
* When called from perf_event_exit_task, it's OK because the
* context has been detached from its task.
*/
static void perf_remove_from_context(struct perf_event *event, bool detach_group)
{
struct perf_event_context *ctx = event->ctx;
struct task_struct *task = ctx->task;
struct remove_event re = {
.event = event,
.detach_group = detach_group,
};
lockdep_assert_held(&ctx->mutex);
if (!task) {
/*
* Per cpu events are removed via an smp call. The removal can
* fail if the CPU is currently offline, but in that case we
* already called __perf_remove_from_context from
* perf_event_exit_cpu.
*/
cpu_function_call(event->cpu, __perf_remove_from_context, &re);
return;
}
retry:
if (!task_function_call(task, __perf_remove_from_context, &re))
return;
raw_spin_lock_irq(&ctx->lock);
/*
* If we failed to find a running task, but find the context active now
* that we've acquired the ctx->lock, retry.
*/
if (ctx->is_active) {
raw_spin_unlock_irq(&ctx->lock);
/*
* Reload the task pointer, it might have been changed by
* a concurrent perf_event_context_sched_out().
*/
task = ctx->task;
goto retry;
}
/*
* Since the task isn't running, its safe to remove the event, us
* holding the ctx->lock ensures the task won't get scheduled in.
*/
if (detach_group)
perf_group_detach(event);
list_del_event(event, ctx);
raw_spin_unlock_irq(&ctx->lock);
}
/*
* Cross CPU call to disable a performance event
*/
int __perf_event_disable(void *info)
{
struct perf_event *event = info;
struct perf_event_context *ctx = event->ctx;
struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
/*
* If this is a per-task event, need to check whether this
* event's task is the current task on this cpu.
*
* Can trigger due to concurrent perf_event_context_sched_out()
* flipping contexts around.
*/
if (ctx->task && cpuctx->task_ctx != ctx)
return -EINVAL;
raw_spin_lock(&ctx->lock);
/*
* If the event is on, turn it off.
* If it is in error state, leave it in error state.
*/
if (event->state >= PERF_EVENT_STATE_INACTIVE) {
update_context_time(ctx);
update_cgrp_time_from_event(event);
update_group_times(event);
if (event == event->group_leader)
group_sched_out(event, cpuctx, ctx);
else
event_sched_out(event, cpuctx, ctx);
event->state = PERF_EVENT_STATE_OFF;
}
raw_spin_unlock(&ctx->lock);
return 0;
}
/*
* Disable a event.
*
* If event->ctx is a cloned context, callers must make sure that
* every task struct that event->ctx->task could possibly point to
* remains valid. This condition is satisifed when called through
* perf_event_for_each_child or perf_event_for_each because they
* hold the top-level event's child_mutex, so any descendant that
* goes to exit will block in sync_child_event.
* When called from perf_pending_event it's OK because event->ctx
* is the current context on this CPU and preemption is disabled,
* hence we can't get into perf_event_task_sched_out for this context.
*/
static void _perf_event_disable(struct perf_event *event)
{
struct perf_event_context *ctx = event->ctx;
struct task_struct *task = ctx->task;
if (!task) {
/*
* Disable the event on the cpu that it's on
*/
cpu_function_call(event->cpu, __perf_event_disable, event);
return;
}
retry:
if (!task_function_call(task, __perf_event_disable, event))
return;
raw_spin_lock_irq(&ctx->lock);
/*
* If the event is still active, we need to retry the cross-call.
*/
if (event->state == PERF_EVENT_STATE_ACTIVE) {
raw_spin_unlock_irq(&ctx->lock);
/*
* Reload the task pointer, it might have been changed by
* a concurrent perf_event_context_sched_out().
*/
task = ctx->task;
goto retry;
}
/*
* Since we have the lock this context can't be scheduled
* in, so we can change the state safely.
*/
if (event->state == PERF_EVENT_STATE_INACTIVE) {
update_group_times(event);
event->state = PERF_EVENT_STATE_OFF;
}
raw_spin_unlock_irq(&ctx->lock);
}
/*
* Strictly speaking kernel users cannot create groups and therefore this
* interface does not need the perf_event_ctx_lock() magic.
*/
void perf_event_disable(struct perf_event *event)
{
struct perf_event_context *ctx;
ctx = perf_event_ctx_lock(event);
_perf_event_disable(event);
perf_event_ctx_unlock(event, ctx);
}
EXPORT_SYMBOL_GPL(perf_event_disable);
static void perf_set_shadow_time(struct perf_event *event,
struct perf_event_context *ctx,
u64 tstamp)
{
/*
* use the correct time source for the time snapshot
*
* We could get by without this by leveraging the
* fact that to get to this function, the caller
* has most likely already called update_context_time()
* and update_cgrp_time_xx() and thus both timestamp
* are identical (or very close). Given that tstamp is,
* already adjusted for cgroup, we could say that:
* tstamp - ctx->timestamp
* is equivalent to
* tstamp - cgrp->timestamp.
*
* Then, in perf_output_read(), the calculation would
* work with no changes because:
* - event is guaranteed scheduled in
* - no scheduled out in between
* - thus the timestamp would be the same
*
* But this is a bit hairy.
*
* So instead, we have an explicit cgroup call to remain
* within the time time source all along. We believe it
* is cleaner and simpler to understand.
*/
if (is_cgroup_event(event))
perf_cgroup_set_shadow_time(event, tstamp);
else
event->shadow_ctx_time = tstamp - ctx->timestamp;
}
#define MAX_INTERRUPTS (~0ULL)
static void perf_log_throttle(struct perf_event *event, int enable);
static void perf_log_itrace_start(struct perf_event *event);
static int
event_sched_in(struct perf_event *event,
struct perf_cpu_context *cpuctx,
struct perf_event_context *ctx)
{
u64 tstamp = perf_event_time(event);
int ret = 0;
lockdep_assert_held(&ctx->lock);
if (event->state <= PERF_EVENT_STATE_OFF)
return 0;
event->state = PERF_EVENT_STATE_ACTIVE;
event->oncpu = smp_processor_id();
/*
* Unthrottle events, since we scheduled we might have missed several
* ticks already, also for a heavily scheduling task there is little
* guarantee it'll get a tick in a timely manner.
*/
if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
perf_log_throttle(event, 1);
event->hw.interrupts = 0;
}
/*
* The new state must be visible before we turn it on in the hardware:
*/
smp_wmb();
perf_pmu_disable(event->pmu);
perf_set_shadow_time(event, ctx, tstamp);
perf_log_itrace_start(event);
if (event->pmu->add(event, PERF_EF_START)) {
event->state = PERF_EVENT_STATE_INACTIVE;
event->oncpu = -1;
ret = -EAGAIN;
goto out;
}
event->tstamp_running += tstamp - event->tstamp_stopped;
if (!is_software_event(event))
cpuctx->active_oncpu++;
if (!ctx->nr_active++)
perf_event_ctx_activate(ctx);
if (event->attr.freq && event->attr.sample_freq)
ctx->nr_freq++;
if (event->attr.exclusive)
cpuctx->exclusive = 1;
if (is_orphaned_child(event))
schedule_orphans_remove(ctx);
out:
perf_pmu_enable(event->pmu);
return ret;
}
static int
group_sched_in(struct perf_event *group_event,
struct perf_cpu_context *cpuctx,
struct perf_event_context *ctx)
{
struct perf_event *event, *partial_group = NULL;
struct pmu *pmu = ctx->pmu;
u64 now = ctx->time;
bool simulate = false;
if (group_event->state == PERF_EVENT_STATE_OFF)
return 0;
pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
if (event_sched_in(group_event, cpuctx, ctx)) {
pmu->cancel_txn(pmu);
perf_mux_hrtimer_restart(cpuctx);
return -EAGAIN;
}
/*
* Schedule in siblings as one group (if any):
*/
list_for_each_entry(event, &group_event->sibling_list, group_entry) {
if (event_sched_in(event, cpuctx, ctx)) {
partial_group = event;
goto group_error;
}
}
if (!pmu->commit_txn(pmu))
return 0;
group_error:
/*
* Groups can be scheduled in as one unit only, so undo any
* partial group before returning:
* The events up to the failed event are scheduled out normally,
* tstamp_stopped will be updated.
*
* The failed events and the remaining siblings need to have
* their timings updated as if they had gone thru event_sched_in()
* and event_sched_out(). This is required to get consistent timings
* across the group. This also takes care of the case where the group
* could never be scheduled by ensuring tstamp_stopped is set to mark
* the time the event was actually stopped, such that time delta
* calculation in update_event_times() is correct.
*/
list_for_each_entry(event, &group_event->sibling_list, group_entry) {
if (event == partial_group)
simulate = true;
if (simulate) {
event->tstamp_running += now - event->tstamp_stopped;
event->tstamp_stopped = now;
} else {
event_sched_out(event, cpuctx, ctx);
}
}
event_sched_out(group_event, cpuctx, ctx);
pmu->cancel_txn(pmu);
perf_mux_hrtimer_restart(cpuctx);
return -EAGAIN;
}
/*
* Work out whether we can put this event group on the CPU now.
*/
static int group_can_go_on(struct perf_event *event,
struct perf_cpu_context *cpuctx,
int can_add_hw)
{
/*
* Groups consisting entirely of software events can always go on.
*/
if (event->group_flags & PERF_GROUP_SOFTWARE)
return 1;
/*
* If an exclusive group is already on, no other hardware
* events can go on.
*/
if (cpuctx->exclusive)
return 0;
/*
* If this group is exclusive and there are already
* events on the CPU, it can't go on.
*/
if (event->attr.exclusive && cpuctx->active_oncpu)
return 0;
/*
* Otherwise, try to add it if all previous groups were able
* to go on.
*/
return can_add_hw;
}
static void add_event_to_ctx(struct perf_event *event,
struct perf_event_context *ctx)
{
u64 tstamp = perf_event_time(event);
list_add_event(event, ctx);
perf_group_attach(event);
event->tstamp_enabled = tstamp;
event->tstamp_running = tstamp;
event->tstamp_stopped = tstamp;
}
static void task_ctx_sched_out(struct perf_event_context *ctx);
static void
ctx_sched_in(struct perf_event_context *ctx,
struct perf_cpu_context *cpuctx,
enum event_type_t event_type,
struct task_struct *task);
static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
struct perf_event_context *ctx,
struct task_struct *task)
{
cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
if (ctx)
ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
if (ctx)
ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
}
/*
* Cross CPU call to install and enable a performance event
*
* Must be called with ctx->mutex held
*/
static int __perf_install_in_context(void *info)
{
struct perf_event *event = info;
struct perf_event_context *ctx = event->ctx;
struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
struct perf_event_context *task_ctx = cpuctx->task_ctx;
struct task_struct *task = current;
perf_ctx_lock(cpuctx, task_ctx);
perf_pmu_disable(cpuctx->ctx.pmu);
/*
* If there was an active task_ctx schedule it out.
*/
if (task_ctx)
task_ctx_sched_out(task_ctx);
/*
* If the context we're installing events in is not the
* active task_ctx, flip them.
*/
if (ctx->task && task_ctx != ctx) {
if (task_ctx)
raw_spin_unlock(&task_ctx->lock);
raw_spin_lock(&ctx->lock);
task_ctx = ctx;
}
if (task_ctx) {
cpuctx->task_ctx = task_ctx;
task = task_ctx->task;
}
cpu_ctx_sched_out(cpuctx, EVENT_ALL);
update_context_time(ctx);
/*
* update cgrp time only if current cgrp
* matches event->cgrp. Must be done before
* calling add_event_to_ctx()
*/
update_cgrp_time_from_event(event);
add_event_to_ctx(event, ctx);
/*
* Schedule everything back in
*/
perf_event_sched_in(cpuctx, task_ctx, task);
perf_pmu_enable(cpuctx->ctx.pmu);
perf_ctx_unlock(cpuctx, task_ctx);
return 0;
}
/*
* Attach a performance event to a context
*
* First we add the event to the list with the hardware enable bit
* in event->hw_config cleared.
*
* If the event is attached to a task which is on a CPU we use a smp
* call to enable it in the task context. The task might have been
* scheduled away, but we check this in the smp call again.
*/
static void
perf_install_in_context(struct perf_event_context *ctx,
struct perf_event *event,
int cpu)
{
struct task_struct *task = ctx->task;
lockdep_assert_held(&ctx->mutex);
event->ctx = ctx;
if (event->cpu != -1)
event->cpu = cpu;
if (!task) {
/*
* Per cpu events are installed via an smp call and
* the install is always successful.
*/
cpu_function_call(cpu, __perf_install_in_context, event);
return;
}
retry:
if (!task_function_call(task, __perf_install_in_context, event))
return;
raw_spin_lock_irq(&ctx->lock);
/*
* If we failed to find a running task, but find the context active now
* that we've acquired the ctx->lock, retry.
*/
if (ctx->is_active) {
raw_spin_unlock_irq(&ctx->lock);
/*
* Reload the task pointer, it might have been changed by
* a concurrent perf_event_context_sched_out().
*/
task = ctx->task;
goto retry;
}
/*
* Since the task isn't running, its safe to add the event, us holding
* the ctx->lock ensures the task won't get scheduled in.
*/
add_event_to_ctx(event, ctx);
raw_spin_unlock_irq(&ctx->lock);
}
/*
* Put a event into inactive state and update time fields.
* Enabling the leader of a group effectively enables all
* the group members that aren't explicitly disabled, so we
* have to update their ->tstamp_enabled also.
* Note: this works for group members as well as group leaders
* since the non-leader members' sibling_lists will be empty.
*/
static void __perf_event_mark_enabled(struct perf_event *event)
{
struct perf_event *sub;
u64 tstamp = perf_event_time(event);
event->state = PERF_EVENT_STATE_INACTIVE;
event->tstamp_enabled = tstamp - event->total_time_enabled;
list_for_each_entry(sub, &event->sibling_list, group_entry) {
if (sub->state >= PERF_EVENT_STATE_INACTIVE)
sub->tstamp_enabled = tstamp - sub->total_time_enabled;
}
}
/*
* Cross CPU call to enable a performance event
*/
static int __perf_event_enable(void *info)
{
struct perf_event *event = info;
struct perf_event_context *ctx = event->ctx;
struct perf_event *leader = event->group_leader;
struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
int err;
/*
* There's a time window between 'ctx->is_active' check
* in perf_event_enable function and this place having:
* - IRQs on
* - ctx->lock unlocked
*
* where the task could be killed and 'ctx' deactivated
* by perf_event_exit_task.
*/
if (!ctx->is_active)
return -EINVAL;
raw_spin_lock(&ctx->lock);
update_context_time(ctx);
if (event->state >= PERF_EVENT_STATE_INACTIVE)
goto unlock;
/*
* set current task's cgroup time reference point
*/
perf_cgroup_set_timestamp(current, ctx);
__perf_event_mark_enabled(event);
if (!event_filter_match(event)) {
if (is_cgroup_event(event))
perf_cgroup_defer_enabled(event);
goto unlock;
}
/*
* If the event is in a group and isn't the group leader,
* then don't put it on unless the group is on.
*/
if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
goto unlock;
if (!group_can_go_on(event, cpuctx, 1)) {
err = -EEXIST;
} else {
if (event == leader)
err = group_sched_in(event, cpuctx, ctx);
else
err = event_sched_in(event, cpuctx, ctx);
}
if (err) {
/*
* If this event can't go on and it's part of a
* group, then the whole group has to come off.
*/
if (leader != event) {
group_sched_out(leader, cpuctx, ctx);
perf_mux_hrtimer_restart(cpuctx);
}
if (leader->attr.pinned) {
update_group_times(leader);
leader->state = PERF_EVENT_STATE_ERROR;
}
}
unlock:
raw_spin_unlock(&ctx->lock);
return 0;
}
/*
* Enable a event.
*
* If event->ctx is a cloned context, callers must make sure that
* every task struct that event->ctx->task could possibly point to
* remains valid. This condition is satisfied when called through
* perf_event_for_each_child or perf_event_for_each as described
* for perf_event_disable.
*/
static void _perf_event_enable(struct perf_event *event)
{
struct perf_event_context *ctx = event->ctx;
struct task_struct *task = ctx->task;
if (!task) {
/*
* Enable the event on the cpu that it's on
*/
cpu_function_call(event->cpu, __perf_event_enable, event);
return;
}
raw_spin_lock_irq(&ctx->lock);
if (event->state >= PERF_EVENT_STATE_INACTIVE)
goto out;
/*
* If the event is in error state, clear that first.
* That way, if we see the event in error state below, we
* know that it has gone back into error state, as distinct
* from the task having been scheduled away before the
* cross-call arrived.
*/
if (event->state == PERF_EVENT_STATE_ERROR)
event->state = PERF_EVENT_STATE_OFF;
retry:
if (!ctx->is_active) {
__perf_event_mark_enabled(event);
goto out;
}
raw_spin_unlock_irq(&ctx->lock);
if (!task_function_call(task, __perf_event_enable, event))
return;
raw_spin_lock_irq(&ctx->lock);
/*
* If the context is active and the event is still off,
* we need to retry the cross-call.
*/
if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
/*
* task could have been flipped by a concurrent
* perf_event_context_sched_out()
*/
task = ctx->task;
goto retry;
}
out:
raw_spin_unlock_irq(&ctx->lock);
}
/*
* See perf_event_disable();
*/
void perf_event_enable(struct perf_event *event)
{
struct perf_event_context *ctx;
ctx = perf_event_ctx_lock(event);
_perf_event_enable(event);
perf_event_ctx_unlock(event, ctx);
}
EXPORT_SYMBOL_GPL(perf_event_enable);
static int _perf_event_refresh(struct perf_event *event, int refresh)
{
/*
* not supported on inherited events
*/
if (event->attr.inherit || !is_sampling_event(event))
return -EINVAL;
atomic_add(refresh, &event->event_limit);
_perf_event_enable(event);
return 0;
}
/*
* See perf_event_disable()
*/
int perf_event_refresh(struct perf_event *event, int refresh)
{
struct perf_event_context *ctx;
int ret;
ctx = perf_event_ctx_lock(event);
ret = _perf_event_refresh(event, refresh);
perf_event_ctx_unlock(event, ctx);
return ret;
}
EXPORT_SYMBOL_GPL(perf_event_refresh);
static void ctx_sched_out(struct perf_event_context *ctx,
struct perf_cpu_context *cpuctx,
enum event_type_t event_type)
{
struct perf_event *event;
int is_active = ctx->is_active;
ctx->is_active &= ~event_type;
if (likely(!ctx->nr_events))
return;
update_context_time(ctx);
update_cgrp_time_from_cpuctx(cpuctx);
if (!ctx->nr_active)
return;
perf_pmu_disable(ctx->pmu);
if ((is_active & EVENT_PINNED) && (event_type & EVENT_PINNED)) {
list_for_each_entry(event, &ctx->pinned_groups, group_entry)
group_sched_out(event, cpuctx, ctx);
}
if ((is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE)) {
list_for_each_entry(event, &ctx->flexible_groups, group_entry)
group_sched_out(event, cpuctx, ctx);
}
perf_pmu_enable(ctx->pmu);
}
/*
* Test whether two contexts are equivalent, i.e. whether they have both been
* cloned from the same version of the same context.
*
* Equivalence is measured using a generation number in the context that is
* incremented on each modification to it; see unclone_ctx(), list_add_event()
* and list_del_event().
*/
static int context_equiv(struct perf_event_context *ctx1,
struct perf_event_context *ctx2)
{
lockdep_assert_held(&ctx1->lock);
lockdep_assert_held(&ctx2->lock);
/* Pinning disables the swap optimization */
if (ctx1->pin_count || ctx2->pin_count)
return 0;
/* If ctx1 is the parent of ctx2 */
if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
return 1;
/* If ctx2 is the parent of ctx1 */
if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
return 1;
/*
* If ctx1 and ctx2 have the same parent; we flatten the parent
* hierarchy, see perf_event_init_context().
*/
if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
ctx1->parent_gen == ctx2->parent_gen)
return 1;
/* Unmatched */
return 0;
}
static void __perf_event_sync_stat(struct perf_event *event,
struct perf_event *next_event)
{
u64 value;
if (!event->attr.inherit_stat)
return;
/*
* Update the event value, we cannot use perf_event_read()
* because we're in the middle of a context switch and have IRQs
* disabled, which upsets smp_call_function_single(), however
* we know the event must be on the current CPU, therefore we
* don't need to use it.
*/
switch (event->state) {
case PERF_EVENT_STATE_ACTIVE:
event->pmu->read(event);
/* fall-through */
case PERF_EVENT_STATE_INACTIVE:
update_event_times(event);
break;
default:
break;
}
/*
* In order to keep per-task stats reliable we need to flip the event
* values when we flip the contexts.
*/
value = local64_read(&next_event->count);
value = local64_xchg(&event->count, value);
local64_set(&next_event->count, value);
swap(event->total_time_enabled, next_event->total_time_enabled);
swap(event->total_time_running, next_event->total_time_running);
/*
* Since we swizzled the values, update the user visible data too.
*/
perf_event_update_userpage(event);
perf_event_update_userpage(next_event);
}
static void perf_event_sync_stat(struct perf_event_context *ctx,
struct perf_event_context *next_ctx)
{
struct perf_event *event, *next_event;
if (!ctx->nr_stat)
return;
update_context_time(ctx);
event = list_first_entry(&ctx->event_list,
struct perf_event, event_entry);
next_event = list_first_entry(&next_ctx->event_list,
struct perf_event, event_entry);
while (&event->event_entry != &ctx->event_list &&
&next_event->event_entry != &next_ctx->event_list) {
__perf_event_sync_stat(event, next_event);
event = list_next_entry(event, event_entry);
next_event = list_next_entry(next_event, event_entry);
}
}
static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
struct task_struct *next)
{
struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
struct perf_event_context *next_ctx;
struct perf_event_context *parent, *next_parent;
struct perf_cpu_context *cpuctx;
int do_switch = 1;
if (likely(!ctx))
return;
cpuctx = __get_cpu_context(ctx);
if (!cpuctx->task_ctx)
return;
rcu_read_lock();
next_ctx = next->perf_event_ctxp[ctxn];
if (!next_ctx)
goto unlock;
parent = rcu_dereference(ctx->parent_ctx);
next_parent = rcu_dereference(next_ctx->parent_ctx);
/* If neither context have a parent context; they cannot be clones. */
if (!parent && !next_parent)
goto unlock;
if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
/*
* Looks like the two contexts are clones, so we might be
* able to optimize the context switch. We lock both
* contexts and check that they are clones under the
* lock (including re-checking that neither has been
* uncloned in the meantime). It doesn't matter which
* order we take the locks because no other cpu could
* be trying to lock both of these tasks.
*/
raw_spin_lock(&ctx->lock);
raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
if (context_equiv(ctx, next_ctx)) {
/*
* XXX do we need a memory barrier of sorts
* wrt to rcu_dereference() of perf_event_ctxp
*/
task->perf_event_ctxp[ctxn] = next_ctx;
next->perf_event_ctxp[ctxn] = ctx;
ctx->task = next;
next_ctx->task = task;
swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
do_switch = 0;
perf_event_sync_stat(ctx, next_ctx);
}
raw_spin_unlock(&next_ctx->lock);
raw_spin_unlock(&ctx->lock);
}
unlock:
rcu_read_unlock();
if (do_switch) {
raw_spin_lock(&ctx->lock);
ctx_sched_out(ctx, cpuctx, EVENT_ALL);
cpuctx->task_ctx = NULL;
raw_spin_unlock(&ctx->lock);
}
}
void perf_sched_cb_dec(struct pmu *pmu)
{
this_cpu_dec(perf_sched_cb_usages);
}
void perf_sched_cb_inc(struct pmu *pmu)
{
this_cpu_inc(perf_sched_cb_usages);
}
/*
* This function provides the context switch callback to the lower code
* layer. It is invoked ONLY when the context switch callback is enabled.
*/
static void perf_pmu_sched_task(struct task_struct *prev,
struct task_struct *next,
bool sched_in)
{
struct perf_cpu_context *cpuctx;
struct pmu *pmu;
unsigned long flags;
if (prev == next)
return;
local_irq_save(flags);
rcu_read_lock();
list_for_each_entry_rcu(pmu, &pmus, entry) {
if (pmu->sched_task) {
cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
perf_ctx_lock(cpuctx, cpuctx->task_ctx);
perf_pmu_disable(pmu);
pmu->sched_task(cpuctx->task_ctx, sched_in);
perf_pmu_enable(pmu);
perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
}
}
rcu_read_unlock();
local_irq_restore(flags);
}
static void perf_event_switch(struct task_struct *task,
struct task_struct *next_prev, bool sched_in);
#define for_each_task_context_nr(ctxn) \
for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
/*
* Called from scheduler to remove the events of the current task,
* with interrupts disabled.
*
* We stop each event and update the event value in event->count.
*
* This does not protect us against NMI, but disable()
* sets the disabled bit in the control field of event _before_
* accessing the event control register. If a NMI hits, then it will
* not restart the event.
*/
void __perf_event_task_sched_out(struct task_struct *task,
struct task_struct *next)
{
int ctxn;
if (__this_cpu_read(perf_sched_cb_usages))
perf_pmu_sched_task(task, next, false);
if (atomic_read(&nr_switch_events))
perf_event_switch(task, next, false);
for_each_task_context_nr(ctxn)
perf_event_context_sched_out(task, ctxn, next);
/*
* if cgroup events exist on this CPU, then we need
* to check if we have to switch out PMU state.
* cgroup event are system-wide mode only
*/
if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
perf_cgroup_sched_out(task, next);
}
static void task_ctx_sched_out(struct perf_event_context *ctx)
{
struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
if (!cpuctx->task_ctx)
return;
if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
return;
ctx_sched_out(ctx, cpuctx, EVENT_ALL);
cpuctx->task_ctx = NULL;
}
/*
* Called with IRQs disabled
*/
static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
enum event_type_t event_type)
{
ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
}
static void
ctx_pinned_sched_in(struct perf_event_context *ctx,
struct perf_cpu_context *cpuctx)
{
struct perf_event *event;
list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
if (event->state <= PERF_EVENT_STATE_OFF)
continue;
if (!event_filter_match(event))
continue;
/* may need to reset tstamp_enabled */
if (is_cgroup_event(event))
perf_cgroup_mark_enabled(event, ctx);
if (group_can_go_on(event, cpuctx, 1))
group_sched_in(event, cpuctx, ctx);
/*
* If this pinned group hasn't been scheduled,
* put it in error state.
*/
if (event->state == PERF_EVENT_STATE_INACTIVE) {
update_group_times(event);
event->state = PERF_EVENT_STATE_ERROR;
}
}
}
static void
ctx_flexible_sched_in(struct perf_event_context *ctx,
struct perf_cpu_context *cpuctx)
{
struct perf_event *event;
int can_add_hw = 1;
list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
/* Ignore events in OFF or ERROR state */
if (event->state <= PERF_EVENT_STATE_OFF)
continue;
/*
* Listen to the 'cpu' scheduling filter constraint
* of events:
*/
if (!event_filter_match(event))
continue;
/* may need to reset tstamp_enabled */
if (is_cgroup_event(event))
perf_cgroup_mark_enabled(event, ctx);
if (group_can_go_on(event, cpuctx, can_add_hw)) {
if (group_sched_in(event, cpuctx, ctx))
can_add_hw = 0;
}
}
}
static void
ctx_sched_in(struct perf_event_context *ctx,
struct perf_cpu_context *cpuctx,
enum event_type_t event_type,
struct task_struct *task)
{
u64 now;
int is_active = ctx->is_active;
ctx->is_active |= event_type;
if (likely(!ctx->nr_events))
return;
now = perf_clock();
ctx->timestamp = now;
perf_cgroup_set_timestamp(task, ctx);
/*
* First go through the list and put on any pinned groups
* in order to give them the best chance of going on.
*/
if (!(is_active & EVENT_PINNED) && (event_type & EVENT_PINNED))
ctx_pinned_sched_in(ctx, cpuctx);
/* Then walk through the lower prio flexible groups */
if (!(is_active & EVENT_FLEXIBLE) && (event_type & EVENT_FLEXIBLE))
ctx_flexible_sched_in(ctx, cpuctx);
}
static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
enum event_type_t event_type,
struct task_struct *task)
{
struct perf_event_context *ctx = &cpuctx->ctx;
ctx_sched_in(ctx, cpuctx, event_type, task);
}
static void perf_event_context_sched_in(struct perf_event_context *ctx,
struct task_struct *task)
{
struct perf_cpu_context *cpuctx;
cpuctx = __get_cpu_context(ctx);
if (cpuctx->task_ctx == ctx)
return;
perf_ctx_lock(cpuctx, ctx);
perf_pmu_disable(ctx->pmu);
/*
* We want to keep the following priority order:
* cpu pinned (that don't need to move), task pinned,
* cpu flexible, task flexible.
*/
cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
if (ctx->nr_events)
cpuctx->task_ctx = ctx;
perf_event_sched_in(cpuctx, cpuctx->task_ctx, task);
perf_pmu_enable(ctx->pmu);
perf_ctx_unlock(cpuctx, ctx);
}
/*
* Called from scheduler to add the events of the current task
* with interrupts disabled.
*
* We restore the event value and then enable it.
*
* This does not protect us against NMI, but enable()
* sets the enabled bit in the control field of event _before_
* accessing the event control register. If a NMI hits, then it will
* keep the event running.
*/
void __perf_event_task_sched_in(struct task_struct *prev,
struct task_struct *task)
{
struct perf_event_context *ctx;
int ctxn;
for_each_task_context_nr(ctxn) {
ctx = task->perf_event_ctxp[ctxn];
if (likely(!ctx))
continue;
perf_event_context_sched_in(ctx, task);
}
/*
* if cgroup events exist on this CPU, then we need
* to check if we have to switch in PMU state.
* cgroup event are system-wide mode only
*/
if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
perf_cgroup_sched_in(prev, task);
if (atomic_read(&nr_switch_events))
perf_event_switch(task, prev, true);
if (__this_cpu_read(perf_sched_cb_usages))
perf_pmu_sched_task(prev, task, true);
}
static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
{
u64 frequency = event->attr.sample_freq;
u64 sec = NSEC_PER_SEC;
u64 divisor, dividend;
int count_fls, nsec_fls, frequency_fls, sec_fls;
count_fls = fls64(count);
nsec_fls = fls64(nsec);
frequency_fls = fls64(frequency);
sec_fls = 30;
/*
* We got @count in @nsec, with a target of sample_freq HZ
* the target period becomes:
*
* @count * 10^9
* period = -------------------
* @nsec * sample_freq
*
*/
/*
* Reduce accuracy by one bit such that @a and @b converge
* to a similar magnitude.
*/
#define REDUCE_FLS(a, b) \
do { \
if (a##_fls > b##_fls) { \
a >>= 1; \
a##_fls--; \
} else { \
b >>= 1; \
b##_fls--; \
} \
} while (0)
/*
* Reduce accuracy until either term fits in a u64, then proceed with
* the other, so that finally we can do a u64/u64 division.
*/
while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
REDUCE_FLS(nsec, frequency);
REDUCE_FLS(sec, count);
}
if (count_fls + sec_fls > 64) {
divisor = nsec * frequency;
while (count_fls + sec_fls > 64) {
REDUCE_FLS(count, sec);
divisor >>= 1;
}
dividend = count * sec;
} else {
dividend = count * sec;
while (nsec_fls + frequency_fls > 64) {
REDUCE_FLS(nsec, frequency);
dividend >>= 1;
}
divisor = nsec * frequency;
}
if (!divisor)
return dividend;
return div64_u64(dividend, divisor);
}
static DEFINE_PER_CPU(int, perf_throttled_count);
static DEFINE_PER_CPU(u64, perf_throttled_seq);
static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
{
struct hw_perf_event *hwc = &event->hw;
s64 period, sample_period;
s64 delta;
period = perf_calculate_period(event, nsec, count);
delta = (s64)(period - hwc->sample_period);
delta = (delta + 7) / 8; /* low pass filter */
sample_period = hwc->sample_period + delta;
if (!sample_period)
sample_period = 1;
hwc->sample_period = sample_period;
if (local64_read(&hwc->period_left) > 8*sample_period) {
if (disable)
event->pmu->stop(event, PERF_EF_UPDATE);
local64_set(&hwc->period_left, 0);
if (disable)
event->pmu->start(event, PERF_EF_RELOAD);
}
}
/*
* combine freq adjustment with unthrottling to avoid two passes over the
* events. At the same time, make sure, having freq events does not change
* the rate of unthrottling as that would introduce bias.
*/
static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
int needs_unthr)
{
struct perf_event *event;
struct hw_perf_event *hwc;
u64 now, period = TICK_NSEC;
s64 delta;
/*
* only need to iterate over all events iff:
* - context have events in frequency mode (needs freq adjust)
* - there are events to unthrottle on this cpu
*/
if (!(ctx->nr_freq || needs_unthr))
return;
raw_spin_lock(&ctx->lock);
perf_pmu_disable(ctx->pmu);
list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
if (event->state != PERF_EVENT_STATE_ACTIVE)
continue;
if (!event_filter_match(event))
continue;
perf_pmu_disable(event->pmu);
hwc = &event->hw;
if (hwc->interrupts == MAX_INTERRUPTS) {
hwc->interrupts = 0;
perf_log_throttle(event, 1);
event->pmu->start(event, 0);
}
if (!event->attr.freq || !event->attr.sample_freq)
goto next;
/*
* stop the event and update event->count
*/
event->pmu->stop(event, PERF_EF_UPDATE);
now = local64_read(&event->count);
delta = now - hwc->freq_count_stamp;
hwc->freq_count_stamp = now;
/*
* restart the event
* reload only if value has changed
* we have stopped the event so tell that
* to perf_adjust_period() to avoid stopping it
* twice.
*/
if (delta > 0)
perf_adjust_period(event, period, delta, false);
event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
next:
perf_pmu_enable(event->pmu);
}
perf_pmu_enable(ctx->pmu);
raw_spin_unlock(&ctx->lock);
}
/*
* Round-robin a context's events:
*/
static void rotate_ctx(struct perf_event_context *ctx)
{
/*
* Rotate the first entry last of non-pinned groups. Rotation might be
* disabled by the inheritance code.
*/
if (!ctx->rotate_disable)
list_rotate_left(&ctx->flexible_groups);
}
static int perf_rotate_context(struct perf_cpu_context *cpuctx)
{
struct perf_event_context *ctx = NULL;
int rotate = 0;
if (cpuctx->ctx.nr_events) {
if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
rotate = 1;
}
ctx = cpuctx->task_ctx;
if (ctx && ctx->nr_events) {
if (ctx->nr_events != ctx->nr_active)
rotate = 1;
}
if (!rotate)
goto done;
perf_ctx_lock(cpuctx, cpuctx->task_ctx);
perf_pmu_disable(cpuctx->ctx.pmu);
cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
if (ctx)
ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE);
rotate_ctx(&cpuctx->ctx);
if (ctx)
rotate_ctx(ctx);
perf_event_sched_in(cpuctx, ctx, current);
perf_pmu_enable(cpuctx->ctx.pmu);
perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
done:
return rotate;
}
#ifdef CONFIG_NO_HZ_FULL
bool perf_event_can_stop_tick(void)
{
if (atomic_read(&nr_freq_events) ||
__this_cpu_read(perf_throttled_count))
return false;
else
return true;
}
#endif
void perf_event_task_tick(void)
{
struct list_head *head = this_cpu_ptr(&active_ctx_list);
struct perf_event_context *ctx, *tmp;
int throttled;
WARN_ON(!irqs_disabled());
__this_cpu_inc(perf_throttled_seq);
throttled = __this_cpu_xchg(perf_throttled_count, 0);
list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
perf_adjust_freq_unthr_context(ctx, throttled);
}
static int event_enable_on_exec(struct perf_event *event,
struct perf_event_context *ctx)
{
if (!event->attr.enable_on_exec)
return 0;
event->attr.enable_on_exec = 0;
if (event->state >= PERF_EVENT_STATE_INACTIVE)
return 0;
__perf_event_mark_enabled(event);
return 1;
}
/*
* Enable all of a task's events that have been marked enable-on-exec.
* This expects task == current.
*/
static void perf_event_enable_on_exec(int ctxn)
{
struct perf_event_context *ctx, *clone_ctx = NULL;
struct perf_event *event;
unsigned long flags;
int enabled = 0;
int ret;
local_irq_save(flags);
ctx = current->perf_event_ctxp[ctxn];
if (!ctx || !ctx->nr_events)
goto out;
/*
* We must ctxsw out cgroup events to avoid conflict
* when invoking perf_task_event_sched_in() later on
* in this function. Otherwise we end up trying to
* ctxswin cgroup events which are already scheduled
* in.
*/
perf_cgroup_sched_out(current, NULL);
raw_spin_lock(&ctx->lock);
task_ctx_sched_out(ctx);
list_for_each_entry(event, &ctx->event_list, event_entry) {
ret = event_enable_on_exec(event, ctx);
if (ret)
enabled = 1;
}
/*
* Unclone this context if we enabled any event.
*/
if (enabled)
clone_ctx = unclone_ctx(ctx);
raw_spin_unlock(&ctx->lock);
/*
* Also calls ctxswin for cgroup events, if any:
*/
perf_event_context_sched_in(ctx, ctx->task);
out:
local_irq_restore(flags);
if (clone_ctx)
put_ctx(clone_ctx);
}
void perf_event_exec(void)
{
int ctxn;
rcu_read_lock();
for_each_task_context_nr(ctxn)
perf_event_enable_on_exec(ctxn);
rcu_read_unlock();
}
struct perf_read_data {
struct perf_event *event;
bool group;
int ret;
};
/*
* Cross CPU call to read the hardware event
*/
static void __perf_event_read(void *info)
{
struct perf_read_data *data = info;
struct perf_event *sub, *event = data->event;
struct perf_event_context *ctx = event->ctx;
struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
struct pmu *pmu = event->pmu;
/*
* If this is a task context, we need to check whether it is
* the current task context of this cpu. If not it has been
* scheduled out before the smp call arrived. In that case
* event->count would have been updated to a recent sample
* when the event was scheduled out.
*/
if (ctx->task && cpuctx->task_ctx != ctx)
return;
raw_spin_lock(&ctx->lock);
if (ctx->is_active) {
update_context_time(ctx);
update_cgrp_time_from_event(event);
}
update_event_times(event);
if (event->state != PERF_EVENT_STATE_ACTIVE)
goto unlock;
if (!data->group) {
pmu->read(event);
data->ret = 0;
goto unlock;
}
pmu->start_txn(pmu, PERF_PMU_TXN_READ);
pmu->read(event);
list_for_each_entry(sub, &event->sibling_list, group_entry) {
update_event_times(sub);
if (sub->state == PERF_EVENT_STATE_ACTIVE) {
/*
* Use sibling's PMU rather than @event's since
* sibling could be on different (eg: software) PMU.
*/
sub->pmu->read(sub);
}
}
data->ret = pmu->commit_txn(pmu);
unlock:
raw_spin_unlock(&ctx->lock);
}
static inline u64 perf_event_count(struct perf_event *event)
{
if (event->pmu->count)
return event->pmu->count(event);
return __perf_event_count(event);
}
/*
* NMI-safe method to read a local event, that is an event that
* is:
* - either for the current task, or for this CPU
* - does not have inherit set, for inherited task events
* will not be local and we cannot read them atomically
* - must not have a pmu::count method
*/
u64 perf_event_read_local(struct perf_event *event)
{
unsigned long flags;
u64 val;
/*
* Disabling interrupts avoids all counter scheduling (context
* switches, timer based rotation and IPIs).
*/
local_irq_save(flags);
/* If this is a per-task event, it must be for current */
WARN_ON_ONCE((event->attach_state & PERF_ATTACH_TASK) &&
event->hw.target != current);
/* If this is a per-CPU event, it must be for this CPU */
WARN_ON_ONCE(!(event->attach_state & PERF_ATTACH_TASK) &&
event->cpu != smp_processor_id());
/*
* It must not be an event with inherit set, we cannot read
* all child counters from atomic context.
*/
WARN_ON_ONCE(event->attr.inherit);
/*
* It must not have a pmu::count method, those are not
* NMI safe.
*/
WARN_ON_ONCE(event->pmu->count);
/*
* If the event is currently on this CPU, its either a per-task event,
* or local to this CPU. Furthermore it means its ACTIVE (otherwise
* oncpu == -1).
*/
if (event->oncpu == smp_processor_id())
event->pmu->read(event);
val = local64_read(&event->count);
local_irq_restore(flags);
return val;
}
static int perf_event_read(struct perf_event *event, bool group)
{
int ret = 0;
/*
* If event is enabled and currently active on a CPU, update the
* value in the event structure:
*/
if (event->state == PERF_EVENT_STATE_ACTIVE) {
struct perf_read_data data = {
.event = event,
.group = group,
.ret = 0,
};
smp_call_function_single(event->oncpu,
__perf_event_read, &data, 1);
ret = data.ret;
} else if (event->state == PERF_EVENT_STATE_INACTIVE) {
struct perf_event_context *ctx = event->ctx;
unsigned long flags;
raw_spin_lock_irqsave(&ctx->lock, flags);
/*
* may read while context is not active
* (e.g., thread is blocked), in that case
* we cannot update context time
*/
if (ctx->is_active) {
update_context_time(ctx);
update_cgrp_time_from_event(event);
}
if (group)
update_group_times(event);
else
update_event_times(event);
raw_spin_unlock_irqrestore(&ctx->lock, flags);
}
return ret;
}
/*
* Initialize the perf_event context in a task_struct:
*/
static void __perf_event_init_context(struct perf_event_context *ctx)
{
raw_spin_lock_init(&ctx->lock);
mutex_init(&ctx->mutex);
INIT_LIST_HEAD(&ctx->active_ctx_list);
INIT_LIST_HEAD(&ctx->pinned_groups);
INIT_LIST_HEAD(&ctx->flexible_groups);
INIT_LIST_HEAD(&ctx->event_list);
atomic_set(&ctx->refcount, 1);
INIT_DELAYED_WORK(&ctx->orphans_remove, orphans_remove_work);
}
static struct perf_event_context *
alloc_perf_context(struct pmu *pmu, struct task_struct *task)
{
struct perf_event_context *ctx;
ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
if (!ctx)
return NULL;
__perf_event_init_context(ctx);
if (task) {
ctx->task = task;
get_task_struct(task);
}
ctx->pmu = pmu;
return ctx;
}
static struct task_struct *
find_lively_task_by_vpid(pid_t vpid)
{
struct task_struct *task;
int err;
rcu_read_lock();
if (!vpid)
task = current;
else
task = find_task_by_vpid(vpid);
if (task)
get_task_struct(task);
rcu_read_unlock();
if (!task)
return ERR_PTR(-ESRCH);
/* Reuse ptrace permission checks for now. */
err = -EACCES;
if (!ptrace_may_access(task, PTRACE_MODE_READ))
goto errout;
return task;
errout:
put_task_struct(task);
return ERR_PTR(err);
}
/*
* Returns a matching context with refcount and pincount.
*/
static struct perf_event_context *
find_get_context(struct pmu *pmu, struct task_struct *task,
struct perf_event *event)
{
struct perf_event_context *ctx, *clone_ctx = NULL;
struct perf_cpu_context *cpuctx;
void *task_ctx_data = NULL;
unsigned long flags;
int ctxn, err;
int cpu = event->cpu;
if (!task) {
/* Must be root to operate on a CPU event: */
if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
return ERR_PTR(-EACCES);
/*
* We could be clever and allow to attach a event to an
* offline CPU and activate it when the CPU comes up, but
* that's for later.
*/
if (!cpu_online(cpu))
return ERR_PTR(-ENODEV);
cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
ctx = &cpuctx->ctx;
get_ctx(ctx);
++ctx->pin_count;
return ctx;
}
err = -EINVAL;
ctxn = pmu->task_ctx_nr;
if (ctxn < 0)
goto errout;
if (event->attach_state & PERF_ATTACH_TASK_DATA) {
task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
if (!task_ctx_data) {
err = -ENOMEM;
goto errout;
}
}
retry:
ctx = perf_lock_task_context(task, ctxn, &flags);
if (ctx) {
clone_ctx = unclone_ctx(ctx);
++ctx->pin_count;
if (task_ctx_data && !ctx->task_ctx_data) {
ctx->task_ctx_data = task_ctx_data;
task_ctx_data = NULL;
}
raw_spin_unlock_irqrestore(&ctx->lock, flags);
if (clone_ctx)
put_ctx(clone_ctx);
} else {
ctx = alloc_perf_context(pmu, task);
err = -ENOMEM;
if (!ctx)
goto errout;
if (task_ctx_data) {
ctx->task_ctx_data = task_ctx_data;
task_ctx_data = NULL;
}
err = 0;
mutex_lock(&task->perf_event_mutex);
/*
* If it has already passed perf_event_exit_task().
* we must see PF_EXITING, it takes this mutex too.
*/
if (task->flags & PF_EXITING)
err = -ESRCH;
else if (task->perf_event_ctxp[ctxn])
err = -EAGAIN;
else {
get_ctx(ctx);
++ctx->pin_count;
rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
}
mutex_unlock(&task->perf_event_mutex);
if (unlikely(err)) {
put_ctx(ctx);
if (err == -EAGAIN)
goto retry;
goto errout;
}
}
kfree(task_ctx_data);
return ctx;
errout:
kfree(task_ctx_data);
return ERR_PTR(err);
}
static void perf_event_free_filter(struct perf_event *event);
static void perf_event_free_bpf_prog(struct perf_event *event);
static void free_event_rcu(struct rcu_head *head)
{
struct perf_event *event;
event = container_of(head, struct perf_event, rcu_head);
if (event->ns)
put_pid_ns(event->ns);
perf_event_free_filter(event);
kfree(event);
}
static void ring_buffer_attach(struct perf_event *event,
struct ring_buffer *rb);
static void unaccount_event_cpu(struct perf_event *event, int cpu)
{
if (event->parent)
return;
if (is_cgroup_event(event))
atomic_dec(&per_cpu(perf_cgroup_events, cpu));
}
static void unaccount_event(struct perf_event *event)
{
if (event->parent)
return;
if (event->attach_state & PERF_ATTACH_TASK)
static_key_slow_dec_deferred(&perf_sched_events);
if (event->attr.mmap || event->attr.mmap_data)
atomic_dec(&nr_mmap_events);
if (event->attr.comm)
atomic_dec(&nr_comm_events);
if (event->attr.task)
atomic_dec(&nr_task_events);
if (event->attr.freq)
atomic_dec(&nr_freq_events);
if (event->attr.context_switch) {
static_key_slow_dec_deferred(&perf_sched_events);
atomic_dec(&nr_switch_events);
}
if (is_cgroup_event(event))
static_key_slow_dec_deferred(&perf_sched_events);
if (has_branch_stack(event))
static_key_slow_dec_deferred(&perf_sched_events);
unaccount_event_cpu(event, event->cpu);
}
/*
* The following implement mutual exclusion of events on "exclusive" pmus
* (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
* at a time, so we disallow creating events that might conflict, namely:
*
* 1) cpu-wide events in the presence of per-task events,
* 2) per-task events in the presence of cpu-wide events,
* 3) two matching events on the same context.
*
* The former two cases are handled in the allocation path (perf_event_alloc(),
* __free_event()), the latter -- before the first perf_install_in_context().
*/
static int exclusive_event_init(struct perf_event *event)
{
struct pmu *pmu = event->pmu;
if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
return 0;
/*
* Prevent co-existence of per-task and cpu-wide events on the
* same exclusive pmu.
*
* Negative pmu::exclusive_cnt means there are cpu-wide
* events on this "exclusive" pmu, positive means there are
* per-task events.
*
* Since this is called in perf_event_alloc() path, event::ctx
* doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
* to mean "per-task event", because unlike other attach states it
* never gets cleared.
*/
if (event->attach_state & PERF_ATTACH_TASK) {
if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
return -EBUSY;
} else {
if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
return -EBUSY;
}
return 0;
}
static void exclusive_event_destroy(struct perf_event *event)
{
struct pmu *pmu = event->pmu;
if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
return;
/* see comment in exclusive_event_init() */
if (event->attach_state & PERF_ATTACH_TASK)
atomic_dec(&pmu->exclusive_cnt);
else
atomic_inc(&pmu->exclusive_cnt);
}
static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
{
if ((e1->pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) &&
(e1->cpu == e2->cpu ||
e1->cpu == -1 ||
e2->cpu == -1))
return true;
return false;
}
/* Called under the same ctx::mutex as perf_install_in_context() */
static bool exclusive_event_installable(struct perf_event *event,
struct perf_event_context *ctx)
{
struct perf_event *iter_event;
struct pmu *pmu = event->pmu;
if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
return true;
list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
if (exclusive_event_match(iter_event, event))
return false;
}
return true;
}
static void __free_event(struct perf_event *event)
{
if (!event->parent) {
if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
put_callchain_buffers();
}
perf_event_free_bpf_prog(event);
if (event->destroy)
event->destroy(event);
if (event->ctx)
put_ctx(event->ctx);
if (event->pmu) {
exclusive_event_destroy(event);
module_put(event->pmu->module);
}
call_rcu(&event->rcu_head, free_event_rcu);
}
static void _free_event(struct perf_event *event)
{
irq_work_sync(&event->pending);
unaccount_event(event);
if (event->rb) {
/*
* Can happen when we close an event with re-directed output.
*
* Since we have a 0 refcount, perf_mmap_close() will skip
* over us; possibly making our ring_buffer_put() the last.
*/
mutex_lock(&event->mmap_mutex);
ring_buffer_attach(event, NULL);
mutex_unlock(&event->mmap_mutex);
}
if (is_cgroup_event(event))
perf_detach_cgroup(event);
__free_event(event);
}
/*
* Used to free events which have a known refcount of 1, such as in error paths
* where the event isn't exposed yet and inherited events.
*/
static void free_event(struct perf_event *event)
{
if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
"unexpected event refcount: %ld; ptr=%p\n",
atomic_long_read(&event->refcount), event)) {
/* leak to avoid use-after-free */
return;
}
_free_event(event);
}
/*
* Remove user event from the owner task.
*/
static void perf_remove_from_owner(struct perf_event *event)
{
struct task_struct *owner;
rcu_read_lock();
owner = ACCESS_ONCE(event->owner);
/*
* Matches the smp_wmb() in perf_event_exit_task(). If we observe
* !owner it means the list deletion is complete and we can indeed
* free this event, otherwise we need to serialize on
* owner->perf_event_mutex.
*/
smp_read_barrier_depends();
if (owner) {
/*
* Since delayed_put_task_struct() also drops the last
* task reference we can safely take a new reference
* while holding the rcu_read_lock().
*/
get_task_struct(owner);
}
rcu_read_unlock();
if (owner) {
/*
* If we're here through perf_event_exit_task() we're already
* holding ctx->mutex which would be an inversion wrt. the
* normal lock order.
*
* However we can safely take this lock because its the child
* ctx->mutex.
*/
mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
/*
* We have to re-check the event->owner field, if it is cleared
* we raced with perf_event_exit_task(), acquiring the mutex
* ensured they're done, and we can proceed with freeing the
* event.
*/
if (event->owner)
list_del_init(&event->owner_entry);
mutex_unlock(&owner->perf_event_mutex);
put_task_struct(owner);
}
}
static void put_event(struct perf_event *event)
{
struct perf_event_context *ctx;
if (!atomic_long_dec_and_test(&event->refcount))
return;
if (!is_kernel_event(event))
perf_remove_from_owner(event);
/*
* There are two ways this annotation is useful:
*
* 1) there is a lock recursion from perf_event_exit_task
* see the comment there.
*
* 2) there is a lock-inversion with mmap_sem through
* perf_read_group(), which takes faults while
* holding ctx->mutex, however this is called after
* the last filedesc died, so there is no possibility
* to trigger the AB-BA case.
*/
ctx = perf_event_ctx_lock_nested(event, SINGLE_DEPTH_NESTING);
WARN_ON_ONCE(ctx->parent_ctx);
perf_remove_from_context(event, true);
perf_event_ctx_unlock(event, ctx);
_free_event(event);
}
int perf_event_release_kernel(struct perf_event *event)
{
put_event(event);
return 0;
}
EXPORT_SYMBOL_GPL(perf_event_release_kernel);
/*
* Called when the last reference to the file is gone.
*/
static int perf_release(struct inode *inode, struct file *file)
{
put_event(file->private_data);
return 0;
}
/*
* Remove all orphanes events from the context.
*/
static void orphans_remove_work(struct work_struct *work)
{
struct perf_event_context *ctx;
struct perf_event *event, *tmp;
ctx = container_of(work, struct perf_event_context,
orphans_remove.work);
mutex_lock(&ctx->mutex);
list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) {
struct perf_event *parent_event = event->parent;
if (!is_orphaned_child(event))
continue;
perf_remove_from_context(event, true);
mutex_lock(&parent_event->child_mutex);
list_del_init(&event->child_list);
mutex_unlock(&parent_event->child_mutex);
free_event(event);
put_event(parent_event);
}
raw_spin_lock_irq(&ctx->lock);
ctx->orphans_remove_sched = false;
raw_spin_unlock_irq(&ctx->lock);
mutex_unlock(&ctx->mutex);
put_ctx(ctx);
}
u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
{
struct perf_event *child;
u64 total = 0;
*enabled = 0;
*running = 0;
mutex_lock(&event->child_mutex);
(void)perf_event_read(event, false);
total += perf_event_count(event);
*enabled += event->total_time_enabled +
atomic64_read(&event->child_total_time_enabled);
*running += event->total_time_running +
atomic64_read(&event->child_total_time_running);
list_for_each_entry(child, &event->child_list, child_list) {
(void)perf_event_read(child, false);
total += perf_event_count(child);
*enabled += child->total_time_enabled;
*running += child->total_time_running;
}
mutex_unlock(&event->child_mutex);
return total;
}
EXPORT_SYMBOL_GPL(perf_event_read_value);
static int __perf_read_group_add(struct perf_event *leader,
u64 read_format, u64 *values)
{
struct perf_event *sub;
int n = 1; /* skip @nr */
int ret;
ret = perf_event_read(leader, true);
if (ret)
return ret;
/*
* Since we co-schedule groups, {enabled,running} times of siblings
* will be identical to those of the leader, so we only publish one
* set.
*/
if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
values[n++] += leader->total_time_enabled +
atomic64_read(&leader->child_total_time_enabled);
}
if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
values[n++] += leader->total_time_running +
atomic64_read(&leader->child_total_time_running);
}
/*
* Write {count,id} tuples for every sibling.
*/
values[n++] += perf_event_count(leader);
if (read_format & PERF_FORMAT_ID)
values[n++] = primary_event_id(leader);
list_for_each_entry(sub, &leader->sibling_list, group_entry) {
values[n++] += perf_event_count(sub);
if (read_format & PERF_FORMAT_ID)
values[n++] = primary_event_id(sub);
}
return 0;
}
static int perf_read_group(struct perf_event *event,
u64 read_format, char __user *buf)
{
struct perf_event *leader = event->group_leader, *child;
struct perf_event_context *ctx = leader->ctx;
int ret;
u64 *values;
lockdep_assert_held(&ctx->mutex);
values = kzalloc(event->read_size, GFP_KERNEL);
if (!values)
return -ENOMEM;
values[0] = 1 + leader->nr_siblings;
/*
* By locking the child_mutex of the leader we effectively
* lock the child list of all siblings.. XXX explain how.
*/
mutex_lock(&leader->child_mutex);
ret = __perf_read_group_add(leader, read_format, values);
if (ret)
goto unlock;
list_for_each_entry(child, &leader->child_list, child_list) {
ret = __perf_read_group_add(child, read_format, values);
if (ret)
goto unlock;
}
mutex_unlock(&leader->child_mutex);
ret = event->read_size;
if (copy_to_user(buf, values, event->read_size))
ret = -EFAULT;
goto out;
unlock:
mutex_unlock(&leader->child_mutex);
out:
kfree(values);
return ret;
}
static int perf_read_one(struct perf_event *event,
u64 read_format, char __user *buf)
{
u64 enabled, running;
u64 values[4];
int n = 0;
values[n++] = perf_event_read_value(event, &enabled, &running);
if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
values[n++] = enabled;
if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
values[n++] = running;
if (read_format & PERF_FORMAT_ID)
values[n++] = primary_event_id(event);
if (copy_to_user(buf, values, n * sizeof(u64)))
return -EFAULT;
return n * sizeof(u64);
}
static bool is_event_hup(struct perf_event *event)
{
bool no_children;
if (event->state != PERF_EVENT_STATE_EXIT)
return false;
mutex_lock(&event->child_mutex);
no_children = list_empty(&event->child_list);
mutex_unlock(&event->child_mutex);
return no_children;
}
/*
* Read the performance event - simple non blocking version for now
*/
static ssize_t
__perf_read(struct perf_event *event, char __user *buf, size_t count)
{
u64 read_format = event->attr.read_format;
int ret;
/*
* Return end-of-file for a read on a event that is in
* error state (i.e. because it was pinned but it couldn't be
* scheduled on to the CPU at some point).
*/
if (event->state == PERF_EVENT_STATE_ERROR)
return 0;
if (count < event->read_size)
return -ENOSPC;
WARN_ON_ONCE(event->ctx->parent_ctx);
if (read_format & PERF_FORMAT_GROUP)
ret = perf_read_group(event, read_format, buf);
else
ret = perf_read_one(event, read_format, buf);
return ret;
}
static ssize_t
perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
{
struct perf_event *event = file->private_data;
struct perf_event_context *ctx;
int ret;
ctx = perf_event_ctx_lock(event);
ret = __perf_read(event, buf, count);
perf_event_ctx_unlock(event, ctx);
return ret;
}
static unsigned int perf_poll(struct file *file, poll_table *wait)
{
struct perf_event *event = file->private_data;
struct ring_buffer *rb;
unsigned int events = POLLHUP;
poll_wait(file, &event->waitq, wait);
if (is_event_hup(event))
return events;
/*
* Pin the event->rb by taking event->mmap_mutex; otherwise
* perf_event_set_output() can swizzle our rb and make us miss wakeups.
*/
mutex_lock(&event->mmap_mutex);
rb = event->rb;
if (rb)
events = atomic_xchg(&rb->poll, 0);
mutex_unlock(&event->mmap_mutex);
return events;
}
static void _perf_event_reset(struct perf_event *event)
{
(void)perf_event_read(event, false);
local64_set(&event->count, 0);
perf_event_update_userpage(event);
}
/*
* Holding the top-level event's child_mutex means that any
* descendant process that has inherited this event will block
* in sync_child_event if it goes to exit, thus satisfying the
* task existence requirements of perf_event_enable/disable.
*/
static void perf_event_for_each_child(struct perf_event *event,
void (*func)(struct perf_event *))
{
struct perf_event *child;
WARN_ON_ONCE(event->ctx->parent_ctx);
mutex_lock(&event->child_mutex);
func(event);
list_for_each_entry(child, &event->child_list, child_list)
func(child);
mutex_unlock(&event->child_mutex);
}
static void perf_event_for_each(struct perf_event *event,
void (*func)(struct perf_event *))
{
struct perf_event_context *ctx = event->ctx;
struct perf_event *sibling;
lockdep_assert_held(&ctx->mutex);
event = event->group_leader;
perf_event_for_each_child(event, func);
list_for_each_entry(sibling, &event->sibling_list, group_entry)
perf_event_for_each_child(sibling, func);
}
struct period_event {
struct perf_event *event;
u64 value;
};
static int __perf_event_period(void *info)
{
struct period_event *pe = info;
struct perf_event *event = pe->event;
struct perf_event_context *ctx = event->ctx;
u64 value = pe->value;
bool active;
raw_spin_lock(&ctx->lock);
if (event->attr.freq) {
event->attr.sample_freq = value;
} else {
event->attr.sample_period = value;
event->hw.sample_period = value;
}
active = (event->state == PERF_EVENT_STATE_ACTIVE);
if (active) {
perf_pmu_disable(ctx->pmu);
event->pmu->stop(event, PERF_EF_UPDATE);
}
local64_set(&event->hw.period_left, 0);
if (active) {
event->pmu->start(event, PERF_EF_RELOAD);
perf_pmu_enable(ctx->pmu);
}
raw_spin_unlock(&ctx->lock);
return 0;
}
static int perf_event_period(struct perf_event *event, u64 __user *arg)
{
struct period_event pe = { .event = event, };
struct perf_event_context *ctx = event->ctx;
struct task_struct *task;
u64 value;
if (!is_sampling_event(event))
return -EINVAL;
if (copy_from_user(&value, arg, sizeof(value)))
return -EFAULT;
if (!value)
return -EINVAL;
if (event->attr.freq && value > sysctl_perf_event_sample_rate)
return -EINVAL;
task = ctx->task;
pe.value = value;
if (!task) {
cpu_function_call(event->cpu, __perf_event_period, &pe);
return 0;
}
retry:
if (!task_function_call(task, __perf_event_period, &pe))
return 0;
raw_spin_lock_irq(&ctx->lock);
if (ctx->is_active) {
raw_spin_unlock_irq(&ctx->lock);
task = ctx->task;
goto retry;
}
if (event->attr.freq) {
event->attr.sample_freq = value;
} else {
event->attr.sample_period = value;
event->hw.sample_period = value;
}
local64_set(&event->hw.period_left, 0);
raw_spin_unlock_irq(&ctx->lock);
return 0;
}
static const struct file_operations perf_fops;
static inline int perf_fget_light(int fd, struct fd *p)
{
struct fd f = fdget(fd);
if (!f.file)
return -EBADF;
if (f.file->f_op != &perf_fops) {
fdput(f);
return -EBADF;
}
*p = f;
return 0;
}
static int perf_event_set_output(struct perf_event *event,
struct perf_event *output_event);
static int perf_event_set_filter(struct perf_event *event, void __user *arg);
static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
{
void (*func)(struct perf_event *);
u32 flags = arg;
switch (cmd) {
case PERF_EVENT_IOC_ENABLE:
func = _perf_event_enable;
break;
case PERF_EVENT_IOC_DISABLE:
func = _perf_event_disable;
break;
case PERF_EVENT_IOC_RESET:
func = _perf_event_reset;
break;
case PERF_EVENT_IOC_REFRESH:
return _perf_event_refresh(event, arg);
case PERF_EVENT_IOC_PERIOD:
return perf_event_period(event, (u64 __user *)arg);
case PERF_EVENT_IOC_ID:
{
u64 id = primary_event_id(event);
if (copy_to_user((void __user *)arg, &id, sizeof(id)))
return -EFAULT;
return 0;
}
case PERF_EVENT_IOC_SET_OUTPUT:
{
int ret;
if (arg != -1) {
struct perf_event *output_event;
struct fd output;
ret = perf_fget_light(arg, &output);
if (ret)
return ret;
output_event = output.file->private_data;
ret = perf_event_set_output(event, output_event);
fdput(output);
} else {
ret = perf_event_set_output(event, NULL);
}
return ret;
}
case PERF_EVENT_IOC_SET_FILTER:
return perf_event_set_filter(event, (void __user *)arg);
case PERF_EVENT_IOC_SET_BPF:
return perf_event_set_bpf_prog(event, arg);
default:
return -ENOTTY;
}
if (flags & PERF_IOC_FLAG_GROUP)
perf_event_for_each(event, func);
else
perf_event_for_each_child(event, func);
return 0;
}
static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct perf_event *event = file->private_data;
struct perf_event_context *ctx;
long ret;
ctx = perf_event_ctx_lock(event);
ret = _perf_ioctl(event, cmd, arg);
perf_event_ctx_unlock(event, ctx);
return ret;
}
#ifdef CONFIG_COMPAT
static long perf_compat_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
switch (_IOC_NR(cmd)) {
case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
case _IOC_NR(PERF_EVENT_IOC_ID):
/* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
cmd &= ~IOCSIZE_MASK;
cmd |= sizeof(void *) << IOCSIZE_SHIFT;
}
break;
}
return perf_ioctl(file, cmd, arg);
}
#else
# define perf_compat_ioctl NULL
#endif
int perf_event_task_enable(void)
{
struct perf_event_context *ctx;
struct perf_event *event;
mutex_lock(¤t->perf_event_mutex);
list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
ctx = perf_event_ctx_lock(event);
perf_event_for_each_child(event, _perf_event_enable);
perf_event_ctx_unlock(event, ctx);
}
mutex_unlock(¤t->perf_event_mutex);
return 0;
}
int perf_event_task_disable(void)
{
struct perf_event_context *ctx;
struct perf_event *event;
mutex_lock(¤t->perf_event_mutex);
list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
ctx = perf_event_ctx_lock(event);
perf_event_for_each_child(event, _perf_event_disable);
perf_event_ctx_unlock(event, ctx);
}
mutex_unlock(¤t->perf_event_mutex);
return 0;
}
static int perf_event_index(struct perf_event *event)
{
if (event->hw.state & PERF_HES_STOPPED)
return 0;
if (event->state != PERF_EVENT_STATE_ACTIVE)
return 0;
return event->pmu->event_idx(event);
}
static void calc_timer_values(struct perf_event *event,
u64 *now,
u64 *enabled,
u64 *running)
{
u64 ctx_time;
*now = perf_clock();
ctx_time = event->shadow_ctx_time + *now;
*enabled = ctx_time - event->tstamp_enabled;
*running = ctx_time - event->tstamp_running;
}
static void perf_event_init_userpage(struct perf_event *event)
{
struct perf_event_mmap_page *userpg;
struct ring_buffer *rb;
rcu_read_lock();
rb = rcu_dereference(event->rb);
if (!rb)
goto unlock;
userpg = rb->user_page;
/* Allow new userspace to detect that bit 0 is deprecated */
userpg->cap_bit0_is_deprecated = 1;
userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
userpg->data_offset = PAGE_SIZE;
userpg->data_size = perf_data_size(rb);
unlock:
rcu_read_unlock();
}
void __weak arch_perf_update_userpage(
struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
{
}
/*
* Callers need to ensure there can be no nesting of this function, otherwise
* the seqlock logic goes bad. We can not serialize this because the arch
* code calls this from NMI context.
*/
void perf_event_update_userpage(struct perf_event *event)
{
struct perf_event_mmap_page *userpg;
struct ring_buffer *rb;
u64 enabled, running, now;
rcu_read_lock();
rb = rcu_dereference(event->rb);
if (!rb)
goto unlock;
/*
* compute total_time_enabled, total_time_running
* based on snapshot values taken when the event
* was last scheduled in.
*
* we cannot simply called update_context_time()
* because of locking issue as we can be called in
* NMI context
*/
calc_timer_values(event, &now, &enabled, &running);
userpg = rb->user_page;
/*
* Disable preemption so as to not let the corresponding user-space
* spin too long if we get preempted.
*/
preempt_disable();
++userpg->lock;
barrier();
userpg->index = perf_event_index(event);
userpg->offset = perf_event_count(event);
if (userpg->index)
userpg->offset -= local64_read(&event->hw.prev_count);
userpg->time_enabled = enabled +
atomic64_read(&event->child_total_time_enabled);
userpg->time_running = running +
atomic64_read(&event->child_total_time_running);
arch_perf_update_userpage(event, userpg, now);
barrier();
++userpg->lock;
preempt_enable();
unlock:
rcu_read_unlock();
}
static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct perf_event *event = vma->vm_file->private_data;
struct ring_buffer *rb;
int ret = VM_FAULT_SIGBUS;
if (vmf->flags & FAULT_FLAG_MKWRITE) {
if (vmf->pgoff == 0)
ret = 0;
return ret;
}
rcu_read_lock();
rb = rcu_dereference(event->rb);
if (!rb)
goto unlock;
if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
goto unlock;
vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
if (!vmf->page)
goto unlock;
get_page(vmf->page);
vmf->page->mapping = vma->vm_file->f_mapping;
vmf->page->index = vmf->pgoff;
ret = 0;
unlock:
rcu_read_unlock();
return ret;
}
static void ring_buffer_attach(struct perf_event *event,
struct ring_buffer *rb)
{
struct ring_buffer *old_rb = NULL;
unsigned long flags;
if (event->rb) {
/*
* Should be impossible, we set this when removing
* event->rb_entry and wait/clear when adding event->rb_entry.
*/
WARN_ON_ONCE(event->rcu_pending);
old_rb = event->rb;
spin_lock_irqsave(&old_rb->event_lock, flags);
list_del_rcu(&event->rb_entry);
spin_unlock_irqrestore(&old_rb->event_lock, flags);
event->rcu_batches = get_state_synchronize_rcu();
event->rcu_pending = 1;
}
if (rb) {
if (event->rcu_pending) {
cond_synchronize_rcu(event->rcu_batches);
event->rcu_pending = 0;
}
spin_lock_irqsave(&rb->event_lock, flags);
list_add_rcu(&event->rb_entry, &rb->event_list);
spin_unlock_irqrestore(&rb->event_lock, flags);
}
rcu_assign_pointer(event->rb, rb);
if (old_rb) {
ring_buffer_put(old_rb);
/*
* Since we detached before setting the new rb, so that we
* could attach the new rb, we could have missed a wakeup.
* Provide it now.
*/
wake_up_all(&event->waitq);
}
}
static void ring_buffer_wakeup(struct perf_event *event)
{
struct ring_buffer *rb;
rcu_read_lock();
rb = rcu_dereference(event->rb);
if (rb) {
list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
wake_up_all(&event->waitq);
}
rcu_read_unlock();
}
struct ring_buffer *ring_buffer_get(struct perf_event *event)
{
struct ring_buffer *rb;
rcu_read_lock();
rb = rcu_dereference(event->rb);
if (rb) {
if (!atomic_inc_not_zero(&rb->refcount))
rb = NULL;
}
rcu_read_unlock();
return rb;
}
void ring_buffer_put(struct ring_buffer *rb)
{
if (!atomic_dec_and_test(&rb->refcount))
return;
WARN_ON_ONCE(!list_empty(&rb->event_list));
call_rcu(&rb->rcu_head, rb_free_rcu);
}
static void perf_mmap_open(struct vm_area_struct *vma)
{
struct perf_event *event = vma->vm_file->private_data;
atomic_inc(&event->mmap_count);
atomic_inc(&event->rb->mmap_count);
if (vma->vm_pgoff)
atomic_inc(&event->rb->aux_mmap_count);
if (event->pmu->event_mapped)
event->pmu->event_mapped(event);
}
/*
* A buffer can be mmap()ed multiple times; either directly through the same
* event, or through other events by use of perf_event_set_output().
*
* In order to undo the VM accounting done by perf_mmap() we need to destroy
* the buffer here, where we still have a VM context. This means we need
* to detach all events redirecting to us.
*/
static void perf_mmap_close(struct vm_area_struct *vma)
{
struct perf_event *event = vma->vm_file->private_data;
struct ring_buffer *rb = ring_buffer_get(event);
struct user_struct *mmap_user = rb->mmap_user;
int mmap_locked = rb->mmap_locked;
unsigned long size = perf_data_size(rb);
if (event->pmu->event_unmapped)
event->pmu->event_unmapped(event);
/*
* rb->aux_mmap_count will always drop before rb->mmap_count and
* event->mmap_count, so it is ok to use event->mmap_mutex to
* serialize with perf_mmap here.
*/
if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
rb_free_aux(rb);
mutex_unlock(&event->mmap_mutex);
}
atomic_dec(&rb->mmap_count);
if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
goto out_put;
ring_buffer_attach(event, NULL);
mutex_unlock(&event->mmap_mutex);
/* If there's still other mmap()s of this buffer, we're done. */
if (atomic_read(&rb->mmap_count))
goto out_put;
/*
* No other mmap()s, detach from all other events that might redirect
* into the now unreachable buffer. Somewhat complicated by the
* fact that rb::event_lock otherwise nests inside mmap_mutex.
*/
again:
rcu_read_lock();
list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
if (!atomic_long_inc_not_zero(&event->refcount)) {
/*
* This event is en-route to free_event() which will
* detach it and remove it from the list.
*/
continue;
}
rcu_read_unlock();
mutex_lock(&event->mmap_mutex);
/*
* Check we didn't race with perf_event_set_output() which can
* swizzle the rb from under us while we were waiting to
* acquire mmap_mutex.
*
* If we find a different rb; ignore this event, a next
* iteration will no longer find it on the list. We have to
* still restart the iteration to make sure we're not now
* iterating the wrong list.
*/
if (event->rb == rb)
ring_buffer_attach(event, NULL);
mutex_unlock(&event->mmap_mutex);
put_event(event);
/*
* Restart the iteration; either we're on the wrong list or
* destroyed its integrity by doing a deletion.
*/
goto again;
}
rcu_read_unlock();
/*
* It could be there's still a few 0-ref events on the list; they'll
* get cleaned up by free_event() -- they'll also still have their
* ref on the rb and will free it whenever they are done with it.
*
* Aside from that, this buffer is 'fully' detached and unmapped,
* undo the VM accounting.
*/
atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
vma->vm_mm->pinned_vm -= mmap_locked;
free_uid(mmap_user);
out_put:
ring_buffer_put(rb); /* could be last */
}
static const struct vm_operations_struct perf_mmap_vmops = {
.open = perf_mmap_open,
.close = perf_mmap_close, /* non mergable */
.fault = perf_mmap_fault,
.page_mkwrite = perf_mmap_fault,
};
static int perf_mmap(struct file *file, struct vm_area_struct *vma)
{
struct perf_event *event = file->private_data;
unsigned long user_locked, user_lock_limit;
struct user_struct *user = current_user();
unsigned long locked, lock_limit;
struct ring_buffer *rb = NULL;
unsigned long vma_size;
unsigned long nr_pages;
long user_extra = 0, extra = 0;
int ret = 0, flags = 0;
/*
* Don't allow mmap() of inherited per-task counters. This would
* create a performance issue due to all children writing to the
* same rb.
*/
if (event->cpu == -1 && event->attr.inherit)
return -EINVAL;
if (!(vma->vm_flags & VM_SHARED))
return -EINVAL;
vma_size = vma->vm_end - vma->vm_start;
if (vma->vm_pgoff == 0) {
nr_pages = (vma_size / PAGE_SIZE) - 1;
} else {
/*
* AUX area mapping: if rb->aux_nr_pages != 0, it's already
* mapped, all subsequent mappings should have the same size
* and offset. Must be above the normal perf buffer.
*/
u64 aux_offset, aux_size;
if (!event->rb)
return -EINVAL;
nr_pages = vma_size / PAGE_SIZE;
mutex_lock(&event->mmap_mutex);
ret = -EINVAL;
rb = event->rb;
if (!rb)
goto aux_unlock;
aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
aux_size = ACCESS_ONCE(rb->user_page->aux_size);
if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
goto aux_unlock;
if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
goto aux_unlock;
/* already mapped with a different offset */
if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
goto aux_unlock;
if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
goto aux_unlock;
/* already mapped with a different size */
if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
goto aux_unlock;
if (!is_power_of_2(nr_pages))
goto aux_unlock;
if (!atomic_inc_not_zero(&rb->mmap_count))
goto aux_unlock;
if (rb_has_aux(rb)) {
atomic_inc(&rb->aux_mmap_count);
ret = 0;
goto unlock;
}
atomic_set(&rb->aux_mmap_count, 1);
user_extra = nr_pages;
goto accounting;
}
/*
* If we have rb pages ensure they're a power-of-two number, so we
* can do bitmasks instead of modulo.
*/
if (nr_pages != 0 && !is_power_of_2(nr_pages))
return -EINVAL;
if (vma_size != PAGE_SIZE * (1 + nr_pages))
return -EINVAL;
WARN_ON_ONCE(event->ctx->parent_ctx);
again:
mutex_lock(&event->mmap_mutex);
if (event->rb) {
if (event->rb->nr_pages != nr_pages) {
ret = -EINVAL;
goto unlock;
}
if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
/*
* Raced against perf_mmap_close() through
* perf_event_set_output(). Try again, hope for better
* luck.
*/
mutex_unlock(&event->mmap_mutex);
goto again;
}
goto unlock;
}
user_extra = nr_pages + 1;
accounting:
user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
/*
* Increase the limit linearly with more CPUs:
*/
user_lock_limit *= num_online_cpus();
user_locked = atomic_long_read(&user->locked_vm) + user_extra;
if (user_locked > user_lock_limit)
extra = user_locked - user_lock_limit;
lock_limit = rlimit(RLIMIT_MEMLOCK);
lock_limit >>= PAGE_SHIFT;
locked = vma->vm_mm->pinned_vm + extra;
if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
!capable(CAP_IPC_LOCK)) {
ret = -EPERM;
goto unlock;
}
WARN_ON(!rb && event->rb);
if (vma->vm_flags & VM_WRITE)
flags |= RING_BUFFER_WRITABLE;
if (!rb) {
rb = rb_alloc(nr_pages,
event->attr.watermark ? event->attr.wakeup_watermark : 0,
event->cpu, flags);
if (!rb) {
ret = -ENOMEM;
goto unlock;
}
atomic_set(&rb->mmap_count, 1);
rb->mmap_user = get_current_user();
rb->mmap_locked = extra;
ring_buffer_attach(event, rb);
perf_event_init_userpage(event);
perf_event_update_userpage(event);
} else {
ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
event->attr.aux_watermark, flags);
if (!ret)
rb->aux_mmap_locked = extra;
}
unlock:
if (!ret) {
atomic_long_add(user_extra, &user->locked_vm);
vma->vm_mm->pinned_vm += extra;
atomic_inc(&event->mmap_count);
} else if (rb) {
atomic_dec(&rb->mmap_count);
}
aux_unlock:
mutex_unlock(&event->mmap_mutex);
/*
* Since pinned accounting is per vm we cannot allow fork() to copy our
* vma.
*/
vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
vma->vm_ops = &perf_mmap_vmops;
if (event->pmu->event_mapped)
event->pmu->event_mapped(event);
return ret;
}
static int perf_fasync(int fd, struct file *filp, int on)
{
struct inode *inode = file_inode(filp);
struct perf_event *event = filp->private_data;
int retval;
mutex_lock(&inode->i_mutex);
retval = fasync_helper(fd, filp, on, &event->fasync);
mutex_unlock(&inode->i_mutex);
if (retval < 0)
return retval;
return 0;
}
static const struct file_operations perf_fops = {
.llseek = no_llseek,
.release = perf_release,
.read = perf_read,
.poll = perf_poll,
.unlocked_ioctl = perf_ioctl,
.compat_ioctl = perf_compat_ioctl,
.mmap = perf_mmap,
.fasync = perf_fasync,
};
/*
* Perf event wakeup
*
* If there's data, ensure we set the poll() state and publish everything
* to user-space before waking everybody up.
*/
static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
{
/* only the parent has fasync state */
if (event->parent)
event = event->parent;
return &event->fasync;
}
void perf_event_wakeup(struct perf_event *event)
{
ring_buffer_wakeup(event);
if (event->pending_kill) {
kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
event->pending_kill = 0;
}
}
static void perf_pending_event(struct irq_work *entry)
{
struct perf_event *event = container_of(entry,
struct perf_event, pending);
int rctx;
rctx = perf_swevent_get_recursion_context();
/*
* If we 'fail' here, that's OK, it means recursion is already disabled
* and we won't recurse 'further'.
*/
if (event->pending_disable) {
event->pending_disable = 0;
__perf_event_disable(event);
}
if (event->pending_wakeup) {
event->pending_wakeup = 0;
perf_event_wakeup(event);
}
if (rctx >= 0)
perf_swevent_put_recursion_context(rctx);
}
/*
* We assume there is only KVM supporting the callbacks.
* Later on, we might change it to a list if there is
* another virtualization implementation supporting the callbacks.
*/
struct perf_guest_info_callbacks *perf_guest_cbs;
int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
{
perf_guest_cbs = cbs;
return 0;
}
EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
{
perf_guest_cbs = NULL;
return 0;
}
EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
static void
perf_output_sample_regs(struct perf_output_handle *handle,
struct pt_regs *regs, u64 mask)
{
int bit;
for_each_set_bit(bit, (const unsigned long *) &mask,
sizeof(mask) * BITS_PER_BYTE) {
u64 val;
val = perf_reg_value(regs, bit);
perf_output_put(handle, val);
}
}
static void perf_sample_regs_user(struct perf_regs *regs_user,
struct pt_regs *regs,
struct pt_regs *regs_user_copy)
{
if (user_mode(regs)) {
regs_user->abi = perf_reg_abi(current);
regs_user->regs = regs;
} else if (current->mm) {
perf_get_regs_user(regs_user, regs, regs_user_copy);
} else {
regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
regs_user->regs = NULL;
}
}
static void perf_sample_regs_intr(struct perf_regs *regs_intr,
struct pt_regs *regs)
{
regs_intr->regs = regs;
regs_intr->abi = perf_reg_abi(current);
}
/*
* Get remaining task size from user stack pointer.
*
* It'd be better to take stack vma map and limit this more
* precisly, but there's no way to get it safely under interrupt,
* so using TASK_SIZE as limit.
*/
static u64 perf_ustack_task_size(struct pt_regs *regs)
{
unsigned long addr = perf_user_stack_pointer(regs);
if (!addr || addr >= TASK_SIZE)
return 0;
return TASK_SIZE - addr;
}
static u16
perf_sample_ustack_size(u16 stack_size, u16 header_size,
struct pt_regs *regs)
{
u64 task_size;
/* No regs, no stack pointer, no dump. */
if (!regs)
return 0;
/*
* Check if we fit in with the requested stack size into the:
* - TASK_SIZE
* If we don't, we limit the size to the TASK_SIZE.
*
* - remaining sample size
* If we don't, we customize the stack size to
* fit in to the remaining sample size.
*/
task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
stack_size = min(stack_size, (u16) task_size);
/* Current header size plus static size and dynamic size. */
header_size += 2 * sizeof(u64);
/* Do we fit in with the current stack dump size? */
if ((u16) (header_size + stack_size) < header_size) {
/*
* If we overflow the maximum size for the sample,
* we customize the stack dump size to fit in.
*/
stack_size = USHRT_MAX - header_size - sizeof(u64);
stack_size = round_up(stack_size, sizeof(u64));
}
return stack_size;
}
static void
perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
struct pt_regs *regs)
{
/* Case of a kernel thread, nothing to dump */
if (!regs) {
u64 size = 0;
perf_output_put(handle, size);
} else {
unsigned long sp;
unsigned int rem;
u64 dyn_size;
/*
* We dump:
* static size
* - the size requested by user or the best one we can fit
* in to the sample max size
* data
* - user stack dump data
* dynamic size
* - the actual dumped size
*/
/* Static size. */
perf_output_put(handle, dump_size);
/* Data. */
sp = perf_user_stack_pointer(regs);
rem = __output_copy_user(handle, (void *) sp, dump_size);
dyn_size = dump_size - rem;
perf_output_skip(handle, rem);
/* Dynamic size. */
perf_output_put(handle, dyn_size);
}
}
static void __perf_event_header__init_id(struct perf_event_header *header,
struct perf_sample_data *data,
struct perf_event *event)
{
u64 sample_type = event->attr.sample_type;
data->type = sample_type;
header->size += event->id_header_size;
if (sample_type & PERF_SAMPLE_TID) {
/* namespace issues */
data->tid_entry.pid = perf_event_pid(event, current);
data->tid_entry.tid = perf_event_tid(event, current);
}
if (sample_type & PERF_SAMPLE_TIME)
data->time = perf_event_clock(event);
if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
data->id = primary_event_id(event);
if (sample_type & PERF_SAMPLE_STREAM_ID)
data->stream_id = event->id;
if (sample_type & PERF_SAMPLE_CPU) {
data->cpu_entry.cpu = raw_smp_processor_id();
data->cpu_entry.reserved = 0;
}
}
void perf_event_header__init_id(struct perf_event_header *header,
struct perf_sample_data *data,
struct perf_event *event)
{
if (event->attr.sample_id_all)
__perf_event_header__init_id(header, data, event);
}
static void __perf_event__output_id_sample(struct perf_output_handle *handle,
struct perf_sample_data *data)
{
u64 sample_type = data->type;
if (sample_type & PERF_SAMPLE_TID)
perf_output_put(handle, data->tid_entry);
if (sample_type & PERF_SAMPLE_TIME)
perf_output_put(handle, data->time);
if (sample_type & PERF_SAMPLE_ID)
perf_output_put(handle, data->id);
if (sample_type & PERF_SAMPLE_STREAM_ID)
perf_output_put(handle, data->stream_id);
if (sample_type & PERF_SAMPLE_CPU)
perf_output_put(handle, data->cpu_entry);
if (sample_type & PERF_SAMPLE_IDENTIFIER)
perf_output_put(handle, data->id);
}
void perf_event__output_id_sample(struct perf_event *event,
struct perf_output_handle *handle,
struct perf_sample_data *sample)
{
if (event->attr.sample_id_all)
__perf_event__output_id_sample(handle, sample);
}
static void perf_output_read_one(struct perf_output_handle *handle,
struct perf_event *event,
u64 enabled, u64 running)
{
u64 read_format = event->attr.read_format;
u64 values[4];
int n = 0;
values[n++] = perf_event_count(event);
if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
values[n++] = enabled +
atomic64_read(&event->child_total_time_enabled);
}
if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
values[n++] = running +
atomic64_read(&event->child_total_time_running);
}
if (read_format & PERF_FORMAT_ID)
values[n++] = primary_event_id(event);
__output_copy(handle, values, n * sizeof(u64));
}
/*
* XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
*/
static void perf_output_read_group(struct perf_output_handle *handle,
struct perf_event *event,
u64 enabled, u64 running)
{
struct perf_event *leader = event->group_leader, *sub;
u64 read_format = event->attr.read_format;
u64 values[5];
int n = 0;
values[n++] = 1 + leader->nr_siblings;
if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
values[n++] = enabled;
if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
values[n++] = running;
if (leader != event)
leader->pmu->read(leader);
values[n++] = perf_event_count(leader);
if (read_format & PERF_FORMAT_ID)
values[n++] = primary_event_id(leader);
__output_copy(handle, values, n * sizeof(u64));
list_for_each_entry(sub, &leader->sibling_list, group_entry) {
n = 0;
if ((sub != event) &&
(sub->state == PERF_EVENT_STATE_ACTIVE))
sub->pmu->read(sub);
values[n++] = perf_event_count(sub);
if (read_format & PERF_FORMAT_ID)
values[n++] = primary_event_id(sub);
__output_copy(handle, values, n * sizeof(u64));
}
}
#define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
PERF_FORMAT_TOTAL_TIME_RUNNING)
static void perf_output_read(struct perf_output_handle *handle,
struct perf_event *event)
{
u64 enabled = 0, running = 0, now;
u64 read_format = event->attr.read_format;
/*
* compute total_time_enabled, total_time_running
* based on snapshot values taken when the event
* was last scheduled in.
*
* we cannot simply called update_context_time()
* because of locking issue as we are called in
* NMI context
*/
if (read_format & PERF_FORMAT_TOTAL_TIMES)
calc_timer_values(event, &now, &enabled, &running);
if (event->attr.read_format & PERF_FORMAT_GROUP)
perf_output_read_group(handle, event, enabled, running);
else
perf_output_read_one(handle, event, enabled, running);
}
void perf_output_sample(struct perf_output_handle *handle,
struct perf_event_header *header,
struct perf_sample_data *data,
struct perf_event *event)
{
u64 sample_type = data->type;
perf_output_put(handle, *header);
if (sample_type & PERF_SAMPLE_IDENTIFIER)
perf_output_put(handle, data->id);
if (sample_type & PERF_SAMPLE_IP)
perf_output_put(handle, data->ip);
if (sample_type & PERF_SAMPLE_TID)
perf_output_put(handle, data->tid_entry);
if (sample_type & PERF_SAMPLE_TIME)
perf_output_put(handle, data->time);
if (sample_type & PERF_SAMPLE_ADDR)
perf_output_put(handle, data->addr);
if (sample_type & PERF_SAMPLE_ID)
perf_output_put(handle, data->id);
if (sample_type & PERF_SAMPLE_STREAM_ID)
perf_output_put(handle, data->stream_id);
if (sample_type & PERF_SAMPLE_CPU)
perf_output_put(handle, data->cpu_entry);
if (sample_type & PERF_SAMPLE_PERIOD)
perf_output_put(handle, data->period);
if (sample_type & PERF_SAMPLE_READ)
perf_output_read(handle, event);
if (sample_type & PERF_SAMPLE_CALLCHAIN) {
if (data->callchain) {
int size = 1;
if (data->callchain)
size += data->callchain->nr;
size *= sizeof(u64);
__output_copy(handle, data->callchain, size);
} else {
u64 nr = 0;
perf_output_put(handle, nr);
}
}
if (sample_type & PERF_SAMPLE_RAW) {
if (data->raw) {
u32 raw_size = data->raw->size;
u32 real_size = round_up(raw_size + sizeof(u32),
sizeof(u64)) - sizeof(u32);
u64 zero = 0;
perf_output_put(handle, real_size);
__output_copy(handle, data->raw->data, raw_size);
if (real_size - raw_size)
__output_copy(handle, &zero, real_size - raw_size);
} else {
struct {
u32 size;
u32 data;
} raw = {
.size = sizeof(u32),
.data = 0,
};
perf_output_put(handle, raw);
}
}
if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
if (data->br_stack) {
size_t size;
size = data->br_stack->nr
* sizeof(struct perf_branch_entry);
perf_output_put(handle, data->br_stack->nr);
perf_output_copy(handle, data->br_stack->entries, size);
} else {
/*
* we always store at least the value of nr
*/
u64 nr = 0;
perf_output_put(handle, nr);
}
}
if (sample_type & PERF_SAMPLE_REGS_USER) {
u64 abi = data->regs_user.abi;
/*
* If there are no regs to dump, notice it through
* first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
*/
perf_output_put(handle, abi);
if (abi) {
u64 mask = event->attr.sample_regs_user;
perf_output_sample_regs(handle,
data->regs_user.regs,
mask);
}
}
if (sample_type & PERF_SAMPLE_STACK_USER) {
perf_output_sample_ustack(handle,
data->stack_user_size,
data->regs_user.regs);
}
if (sample_type & PERF_SAMPLE_WEIGHT)
perf_output_put(handle, data->weight);
if (sample_type & PERF_SAMPLE_DATA_SRC)
perf_output_put(handle, data->data_src.val);
if (sample_type & PERF_SAMPLE_TRANSACTION)
perf_output_put(handle, data->txn);
if (sample_type & PERF_SAMPLE_REGS_INTR) {
u64 abi = data->regs_intr.abi;
/*
* If there are no regs to dump, notice it through
* first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
*/
perf_output_put(handle, abi);
if (abi) {
u64 mask = event->attr.sample_regs_intr;
perf_output_sample_regs(handle,
data->regs_intr.regs,
mask);
}
}
if (!event->attr.watermark) {
int wakeup_events = event->attr.wakeup_events;
if (wakeup_events) {
struct ring_buffer *rb = handle->rb;
int events = local_inc_return(&rb->events);
if (events >= wakeup_events) {
local_sub(wakeup_events, &rb->events);
local_inc(&rb->wakeup);
}
}
}
}
void perf_prepare_sample(struct perf_event_header *header,
struct perf_sample_data *data,
struct perf_event *event,
struct pt_regs *regs)
{
u64 sample_type = event->attr.sample_type;
header->type = PERF_RECORD_SAMPLE;
header->size = sizeof(*header) + event->header_size;
header->misc = 0;
header->misc |= perf_misc_flags(regs);
__perf_event_header__init_id(header, data, event);
if (sample_type & PERF_SAMPLE_IP)
data->ip = perf_instruction_pointer(regs);
if (sample_type & PERF_SAMPLE_CALLCHAIN) {
int size = 1;
data->callchain = perf_callchain(event, regs);
if (data->callchain)
size += data->callchain->nr;
header->size += size * sizeof(u64);
}
if (sample_type & PERF_SAMPLE_RAW) {
int size = sizeof(u32);
if (data->raw)
size += data->raw->size;
else
size += sizeof(u32);
header->size += round_up(size, sizeof(u64));
}
if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
int size = sizeof(u64); /* nr */
if (data->br_stack) {
size += data->br_stack->nr
* sizeof(struct perf_branch_entry);
}
header->size += size;
}
if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
perf_sample_regs_user(&data->regs_user, regs,
&data->regs_user_copy);
if (sample_type & PERF_SAMPLE_REGS_USER) {
/* regs dump ABI info */
int size = sizeof(u64);
if (data->regs_user.regs) {
u64 mask = event->attr.sample_regs_user;
size += hweight64(mask) * sizeof(u64);
}
header->size += size;
}
if (sample_type & PERF_SAMPLE_STACK_USER) {
/*
* Either we need PERF_SAMPLE_STACK_USER bit to be allways
* processed as the last one or have additional check added
* in case new sample type is added, because we could eat
* up the rest of the sample size.
*/
u16 stack_size = event->attr.sample_stack_user;
u16 size = sizeof(u64);
stack_size = perf_sample_ustack_size(stack_size, header->size,
data->regs_user.regs);
/*
* If there is something to dump, add space for the dump
* itself and for the field that tells the dynamic size,
* which is how many have been actually dumped.
*/
if (stack_size)
size += sizeof(u64) + stack_size;
data->stack_user_size = stack_size;
header->size += size;
}
if (sample_type & PERF_SAMPLE_REGS_INTR) {
/* regs dump ABI info */
int size = sizeof(u64);
perf_sample_regs_intr(&data->regs_intr, regs);
if (data->regs_intr.regs) {
u64 mask = event->attr.sample_regs_intr;
size += hweight64(mask) * sizeof(u64);
}
header->size += size;
}
}
void perf_event_output(struct perf_event *event,
struct perf_sample_data *data,
struct pt_regs *regs)
{
struct perf_output_handle handle;
struct perf_event_header header;
/* protect the callchain buffers */
rcu_read_lock();
perf_prepare_sample(&header, data, event, regs);
if (perf_output_begin(&handle, event, header.size))
goto exit;
perf_output_sample(&handle, &header, data, event);
perf_output_end(&handle);
exit:
rcu_read_unlock();
}
/*
* read event_id
*/
struct perf_read_event {
struct perf_event_header header;
u32 pid;
u32 tid;
};
static void
perf_event_read_event(struct perf_event *event,
struct task_struct *task)
{
struct perf_output_handle handle;
struct perf_sample_data sample;
struct perf_read_event read_event = {
.header = {
.type = PERF_RECORD_READ,
.misc = 0,
.size = sizeof(read_event) + event->read_size,
},
.pid = perf_event_pid(event, task),
.tid = perf_event_tid(event, task),
};
int ret;
perf_event_header__init_id(&read_event.header, &sample, event);
ret = perf_output_begin(&handle, event, read_event.header.size);
if (ret)
return;
perf_output_put(&handle, read_event);
perf_output_read(&handle, event);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
}
typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
static void
perf_event_aux_ctx(struct perf_event_context *ctx,
perf_event_aux_output_cb output,
void *data)
{
struct perf_event *event;
list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
if (event->state < PERF_EVENT_STATE_INACTIVE)
continue;
if (!event_filter_match(event))
continue;
output(event, data);
}
}
static void
perf_event_aux_task_ctx(perf_event_aux_output_cb output, void *data,
struct perf_event_context *task_ctx)
{
rcu_read_lock();
preempt_disable();
perf_event_aux_ctx(task_ctx, output, data);
preempt_enable();
rcu_read_unlock();
}
static void
perf_event_aux(perf_event_aux_output_cb output, void *data,
struct perf_event_context *task_ctx)
{
struct perf_cpu_context *cpuctx;
struct perf_event_context *ctx;
struct pmu *pmu;
int ctxn;
/*
* If we have task_ctx != NULL we only notify
* the task context itself. The task_ctx is set
* only for EXIT events before releasing task
* context.
*/
if (task_ctx) {
perf_event_aux_task_ctx(output, data, task_ctx);
return;
}
rcu_read_lock();
list_for_each_entry_rcu(pmu, &pmus, entry) {
cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
if (cpuctx->unique_pmu != pmu)
goto next;
perf_event_aux_ctx(&cpuctx->ctx, output, data);
ctxn = pmu->task_ctx_nr;
if (ctxn < 0)
goto next;
ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
if (ctx)
perf_event_aux_ctx(ctx, output, data);
next:
put_cpu_ptr(pmu->pmu_cpu_context);
}
rcu_read_unlock();
}
/*
* task tracking -- fork/exit
*
* enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
*/
struct perf_task_event {
struct task_struct *task;
struct perf_event_context *task_ctx;
struct {
struct perf_event_header header;
u32 pid;
u32 ppid;
u32 tid;
u32 ptid;
u64 time;
} event_id;
};
static int perf_event_task_match(struct perf_event *event)
{
return event->attr.comm || event->attr.mmap ||
event->attr.mmap2 || event->attr.mmap_data ||
event->attr.task;
}
static void perf_event_task_output(struct perf_event *event,
void *data)
{
struct perf_task_event *task_event = data;
struct perf_output_handle handle;
struct perf_sample_data sample;
struct task_struct *task = task_event->task;
int ret, size = task_event->event_id.header.size;
if (!perf_event_task_match(event))
return;
perf_event_header__init_id(&task_event->event_id.header, &sample, event);
ret = perf_output_begin(&handle, event,
task_event->event_id.header.size);
if (ret)
goto out;
task_event->event_id.pid = perf_event_pid(event, task);
task_event->event_id.ppid = perf_event_pid(event, current);
task_event->event_id.tid = perf_event_tid(event, task);
task_event->event_id.ptid = perf_event_tid(event, current);
task_event->event_id.time = perf_event_clock(event);
perf_output_put(&handle, task_event->event_id);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
out:
task_event->event_id.header.size = size;
}
static void perf_event_task(struct task_struct *task,
struct perf_event_context *task_ctx,
int new)
{
struct perf_task_event task_event;
if (!atomic_read(&nr_comm_events) &&
!atomic_read(&nr_mmap_events) &&
!atomic_read(&nr_task_events))
return;
task_event = (struct perf_task_event){
.task = task,
.task_ctx = task_ctx,
.event_id = {
.header = {
.type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
.misc = 0,
.size = sizeof(task_event.event_id),
},
/* .pid */
/* .ppid */
/* .tid */
/* .ptid */
/* .time */
},
};
perf_event_aux(perf_event_task_output,
&task_event,
task_ctx);
}
void perf_event_fork(struct task_struct *task)
{
perf_event_task(task, NULL, 1);
}
/*
* comm tracking
*/
struct perf_comm_event {
struct task_struct *task;
char *comm;
int comm_size;
struct {
struct perf_event_header header;
u32 pid;
u32 tid;
} event_id;
};
static int perf_event_comm_match(struct perf_event *event)
{
return event->attr.comm;
}
static void perf_event_comm_output(struct perf_event *event,
void *data)
{
struct perf_comm_event *comm_event = data;
struct perf_output_handle handle;
struct perf_sample_data sample;
int size = comm_event->event_id.header.size;
int ret;
if (!perf_event_comm_match(event))
return;
perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
ret = perf_output_begin(&handle, event,
comm_event->event_id.header.size);
if (ret)
goto out;
comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
perf_output_put(&handle, comm_event->event_id);
__output_copy(&handle, comm_event->comm,
comm_event->comm_size);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
out:
comm_event->event_id.header.size = size;
}
static void perf_event_comm_event(struct perf_comm_event *comm_event)
{
char comm[TASK_COMM_LEN];
unsigned int size;
memset(comm, 0, sizeof(comm));
strlcpy(comm, comm_event->task->comm, sizeof(comm));
size = ALIGN(strlen(comm)+1, sizeof(u64));
comm_event->comm = comm;
comm_event->comm_size = size;
comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
perf_event_aux(perf_event_comm_output,
comm_event,
NULL);
}
void perf_event_comm(struct task_struct *task, bool exec)
{
struct perf_comm_event comm_event;
if (!atomic_read(&nr_comm_events))
return;
comm_event = (struct perf_comm_event){
.task = task,
/* .comm */
/* .comm_size */
.event_id = {
.header = {
.type = PERF_RECORD_COMM,
.misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
/* .size */
},
/* .pid */
/* .tid */
},
};
perf_event_comm_event(&comm_event);
}
/*
* mmap tracking
*/
struct perf_mmap_event {
struct vm_area_struct *vma;
const char *file_name;
int file_size;
int maj, min;
u64 ino;
u64 ino_generation;
u32 prot, flags;
struct {
struct perf_event_header header;
u32 pid;
u32 tid;
u64 start;
u64 len;
u64 pgoff;
} event_id;
};
static int perf_event_mmap_match(struct perf_event *event,
void *data)
{
struct perf_mmap_event *mmap_event = data;
struct vm_area_struct *vma = mmap_event->vma;
int executable = vma->vm_flags & VM_EXEC;
return (!executable && event->attr.mmap_data) ||
(executable && (event->attr.mmap || event->attr.mmap2));
}
static void perf_event_mmap_output(struct perf_event *event,
void *data)
{
struct perf_mmap_event *mmap_event = data;
struct perf_output_handle handle;
struct perf_sample_data sample;
int size = mmap_event->event_id.header.size;
int ret;
if (!perf_event_mmap_match(event, data))
return;
if (event->attr.mmap2) {
mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
mmap_event->event_id.header.size += sizeof(mmap_event->maj);
mmap_event->event_id.header.size += sizeof(mmap_event->min);
mmap_event->event_id.header.size += sizeof(mmap_event->ino);
mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
mmap_event->event_id.header.size += sizeof(mmap_event->prot);
mmap_event->event_id.header.size += sizeof(mmap_event->flags);
}
perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
ret = perf_output_begin(&handle, event,
mmap_event->event_id.header.size);
if (ret)
goto out;
mmap_event->event_id.pid = perf_event_pid(event, current);
mmap_event->event_id.tid = perf_event_tid(event, current);
perf_output_put(&handle, mmap_event->event_id);
if (event->attr.mmap2) {
perf_output_put(&handle, mmap_event->maj);
perf_output_put(&handle, mmap_event->min);
perf_output_put(&handle, mmap_event->ino);
perf_output_put(&handle, mmap_event->ino_generation);
perf_output_put(&handle, mmap_event->prot);
perf_output_put(&handle, mmap_event->flags);
}
__output_copy(&handle, mmap_event->file_name,
mmap_event->file_size);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
out:
mmap_event->event_id.header.size = size;
}
static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
{
struct vm_area_struct *vma = mmap_event->vma;
struct file *file = vma->vm_file;
int maj = 0, min = 0;
u64 ino = 0, gen = 0;
u32 prot = 0, flags = 0;
unsigned int size;
char tmp[16];
char *buf = NULL;
char *name;
if (file) {
struct inode *inode;
dev_t dev;
buf = kmalloc(PATH_MAX, GFP_KERNEL);
if (!buf) {
name = "//enomem";
goto cpy_name;
}
/*
* d_path() works from the end of the rb backwards, so we
* need to add enough zero bytes after the string to handle
* the 64bit alignment we do later.
*/
name = file_path(file, buf, PATH_MAX - sizeof(u64));
if (IS_ERR(name)) {
name = "//toolong";
goto cpy_name;
}
inode = file_inode(vma->vm_file);
dev = inode->i_sb->s_dev;
ino = inode->i_ino;
gen = inode->i_generation;
maj = MAJOR(dev);
min = MINOR(dev);
if (vma->vm_flags & VM_READ)
prot |= PROT_READ;
if (vma->vm_flags & VM_WRITE)
prot |= PROT_WRITE;
if (vma->vm_flags & VM_EXEC)
prot |= PROT_EXEC;
if (vma->vm_flags & VM_MAYSHARE)
flags = MAP_SHARED;
else
flags = MAP_PRIVATE;
if (vma->vm_flags & VM_DENYWRITE)
flags |= MAP_DENYWRITE;
if (vma->vm_flags & VM_MAYEXEC)
flags |= MAP_EXECUTABLE;
if (vma->vm_flags & VM_LOCKED)
flags |= MAP_LOCKED;
if (vma->vm_flags & VM_HUGETLB)
flags |= MAP_HUGETLB;
goto got_name;
} else {
if (vma->vm_ops && vma->vm_ops->name) {
name = (char *) vma->vm_ops->name(vma);
if (name)
goto cpy_name;
}
name = (char *)arch_vma_name(vma);
if (name)
goto cpy_name;
if (vma->vm_start <= vma->vm_mm->start_brk &&
vma->vm_end >= vma->vm_mm->brk) {
name = "[heap]";
goto cpy_name;
}
if (vma->vm_start <= vma->vm_mm->start_stack &&
vma->vm_end >= vma->vm_mm->start_stack) {
name = "[stack]";
goto cpy_name;
}
name = "//anon";
goto cpy_name;
}
cpy_name:
strlcpy(tmp, name, sizeof(tmp));
name = tmp;
got_name:
/*
* Since our buffer works in 8 byte units we need to align our string
* size to a multiple of 8. However, we must guarantee the tail end is
* zero'd out to avoid leaking random bits to userspace.
*/
size = strlen(name)+1;
while (!IS_ALIGNED(size, sizeof(u64)))
name[size++] = '\0';
mmap_event->file_name = name;
mmap_event->file_size = size;
mmap_event->maj = maj;
mmap_event->min = min;
mmap_event->ino = ino;
mmap_event->ino_generation = gen;
mmap_event->prot = prot;
mmap_event->flags = flags;
if (!(vma->vm_flags & VM_EXEC))
mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
perf_event_aux(perf_event_mmap_output,
mmap_event,
NULL);
kfree(buf);
}
void perf_event_mmap(struct vm_area_struct *vma)
{
struct perf_mmap_event mmap_event;
if (!atomic_read(&nr_mmap_events))
return;
mmap_event = (struct perf_mmap_event){
.vma = vma,
/* .file_name */
/* .file_size */
.event_id = {
.header = {
.type = PERF_RECORD_MMAP,
.misc = PERF_RECORD_MISC_USER,
/* .size */
},
/* .pid */
/* .tid */
.start = vma->vm_start,
.len = vma->vm_end - vma->vm_start,
.pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
},
/* .maj (attr_mmap2 only) */
/* .min (attr_mmap2 only) */
/* .ino (attr_mmap2 only) */
/* .ino_generation (attr_mmap2 only) */
/* .prot (attr_mmap2 only) */
/* .flags (attr_mmap2 only) */
};
perf_event_mmap_event(&mmap_event);
}
void perf_event_aux_event(struct perf_event *event, unsigned long head,
unsigned long size, u64 flags)
{
struct perf_output_handle handle;
struct perf_sample_data sample;
struct perf_aux_event {
struct perf_event_header header;
u64 offset;
u64 size;
u64 flags;
} rec = {
.header = {
.type = PERF_RECORD_AUX,
.misc = 0,
.size = sizeof(rec),
},
.offset = head,
.size = size,
.flags = flags,
};
int ret;
perf_event_header__init_id(&rec.header, &sample, event);
ret = perf_output_begin(&handle, event, rec.header.size);
if (ret)
return;
perf_output_put(&handle, rec);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
}
/*
* Lost/dropped samples logging
*/
void perf_log_lost_samples(struct perf_event *event, u64 lost)
{
struct perf_output_handle handle;
struct perf_sample_data sample;
int ret;
struct {
struct perf_event_header header;
u64 lost;
} lost_samples_event = {
.header = {
.type = PERF_RECORD_LOST_SAMPLES,
.misc = 0,
.size = sizeof(lost_samples_event),
},
.lost = lost,
};
perf_event_header__init_id(&lost_samples_event.header, &sample, event);
ret = perf_output_begin(&handle, event,
lost_samples_event.header.size);
if (ret)
return;
perf_output_put(&handle, lost_samples_event);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
}
/*
* context_switch tracking
*/
struct perf_switch_event {
struct task_struct *task;
struct task_struct *next_prev;
struct {
struct perf_event_header header;
u32 next_prev_pid;
u32 next_prev_tid;
} event_id;
};
static int perf_event_switch_match(struct perf_event *event)
{
return event->attr.context_switch;
}
static void perf_event_switch_output(struct perf_event *event, void *data)
{
struct perf_switch_event *se = data;
struct perf_output_handle handle;
struct perf_sample_data sample;
int ret;
if (!perf_event_switch_match(event))
return;
/* Only CPU-wide events are allowed to see next/prev pid/tid */
if (event->ctx->task) {
se->event_id.header.type = PERF_RECORD_SWITCH;
se->event_id.header.size = sizeof(se->event_id.header);
} else {
se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
se->event_id.header.size = sizeof(se->event_id);
se->event_id.next_prev_pid =
perf_event_pid(event, se->next_prev);
se->event_id.next_prev_tid =
perf_event_tid(event, se->next_prev);
}
perf_event_header__init_id(&se->event_id.header, &sample, event);
ret = perf_output_begin(&handle, event, se->event_id.header.size);
if (ret)
return;
if (event->ctx->task)
perf_output_put(&handle, se->event_id.header);
else
perf_output_put(&handle, se->event_id);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
}
static void perf_event_switch(struct task_struct *task,
struct task_struct *next_prev, bool sched_in)
{
struct perf_switch_event switch_event;
/* N.B. caller checks nr_switch_events != 0 */
switch_event = (struct perf_switch_event){
.task = task,
.next_prev = next_prev,
.event_id = {
.header = {
/* .type */
.misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
/* .size */
},
/* .next_prev_pid */
/* .next_prev_tid */
},
};
perf_event_aux(perf_event_switch_output,
&switch_event,
NULL);
}
/*
* IRQ throttle logging
*/
static void perf_log_throttle(struct perf_event *event, int enable)
{
struct perf_output_handle handle;
struct perf_sample_data sample;
int ret;
struct {
struct perf_event_header header;
u64 time;
u64 id;
u64 stream_id;
} throttle_event = {
.header = {
.type = PERF_RECORD_THROTTLE,
.misc = 0,
.size = sizeof(throttle_event),
},
.time = perf_event_clock(event),
.id = primary_event_id(event),
.stream_id = event->id,
};
if (enable)
throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
perf_event_header__init_id(&throttle_event.header, &sample, event);
ret = perf_output_begin(&handle, event,
throttle_event.header.size);
if (ret)
return;
perf_output_put(&handle, throttle_event);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
}
static void perf_log_itrace_start(struct perf_event *event)
{
struct perf_output_handle handle;
struct perf_sample_data sample;
struct perf_aux_event {
struct perf_event_header header;
u32 pid;
u32 tid;
} rec;
int ret;
if (event->parent)
event = event->parent;
if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
event->hw.itrace_started)
return;
rec.header.type = PERF_RECORD_ITRACE_START;
rec.header.misc = 0;
rec.header.size = sizeof(rec);
rec.pid = perf_event_pid(event, current);
rec.tid = perf_event_tid(event, current);
perf_event_header__init_id(&rec.header, &sample, event);
ret = perf_output_begin(&handle, event, rec.header.size);
if (ret)
return;
perf_output_put(&handle, rec);
perf_event__output_id_sample(event, &handle, &sample);
perf_output_end(&handle);
}
/*
* Generic event overflow handling, sampling.
*/
static int __perf_event_overflow(struct perf_event *event,
int throttle, struct perf_sample_data *data,
struct pt_regs *regs)
{
int events = atomic_read(&event->event_limit);
struct hw_perf_event *hwc = &event->hw;
u64 seq;
int ret = 0;
/*
* Non-sampling counters might still use the PMI to fold short
* hardware counters, ignore those.
*/
if (unlikely(!is_sampling_event(event)))
return 0;
seq = __this_cpu_read(perf_throttled_seq);
if (seq != hwc->interrupts_seq) {
hwc->interrupts_seq = seq;
hwc->interrupts = 1;
} else {
hwc->interrupts++;
if (unlikely(throttle
&& hwc->interrupts >= max_samples_per_tick)) {
__this_cpu_inc(perf_throttled_count);
hwc->interrupts = MAX_INTERRUPTS;
perf_log_throttle(event, 0);
tick_nohz_full_kick();
ret = 1;
}
}
if (event->attr.freq) {
u64 now = perf_clock();
s64 delta = now - hwc->freq_time_stamp;
hwc->freq_time_stamp = now;
if (delta > 0 && delta < 2*TICK_NSEC)
perf_adjust_period(event, delta, hwc->last_period, true);
}
/*
* XXX event_limit might not quite work as expected on inherited
* events
*/
event->pending_kill = POLL_IN;
if (events && atomic_dec_and_test(&event->event_limit)) {
ret = 1;
event->pending_kill = POLL_HUP;
event->pending_disable = 1;
irq_work_queue(&event->pending);
}
if (event->overflow_handler)
event->overflow_handler(event, data, regs);
else
perf_event_output(event, data, regs);
if (*perf_event_fasync(event) && event->pending_kill) {
event->pending_wakeup = 1;
irq_work_queue(&event->pending);
}
return ret;
}
int perf_event_overflow(struct perf_event *event,
struct perf_sample_data *data,
struct pt_regs *regs)
{
return __perf_event_overflow(event, 1, data, regs);
}
/*
* Generic software event infrastructure
*/
struct swevent_htable {
struct swevent_hlist *swevent_hlist;
struct mutex hlist_mutex;
int hlist_refcount;
/* Recursion avoidance in each contexts */
int recursion[PERF_NR_CONTEXTS];
};
static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
/*
* We directly increment event->count and keep a second value in
* event->hw.period_left to count intervals. This period event
* is kept in the range [-sample_period, 0] so that we can use the
* sign as trigger.
*/
u64 perf_swevent_set_period(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
u64 period = hwc->last_period;
u64 nr, offset;
s64 old, val;
hwc->last_period = hwc->sample_period;
again:
old = val = local64_read(&hwc->period_left);
if (val < 0)
return 0;
nr = div64_u64(period + val, period);
offset = nr * period;
val -= offset;
if (local64_cmpxchg(&hwc->period_left, old, val) != old)
goto again;
return nr;
}
static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
struct perf_sample_data *data,
struct pt_regs *regs)
{
struct hw_perf_event *hwc = &event->hw;
int throttle = 0;
if (!overflow)
overflow = perf_swevent_set_period(event);
if (hwc->interrupts == MAX_INTERRUPTS)
return;
for (; overflow; overflow--) {
if (__perf_event_overflow(event, throttle,
data, regs)) {
/*
* We inhibit the overflow from happening when
* hwc->interrupts == MAX_INTERRUPTS.
*/
break;
}
throttle = 1;
}
}
static void perf_swevent_event(struct perf_event *event, u64 nr,
struct perf_sample_data *data,
struct pt_regs *regs)
{
struct hw_perf_event *hwc = &event->hw;
local64_add(nr, &event->count);
if (!regs)
return;
if (!is_sampling_event(event))
return;
if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
data->period = nr;
return perf_swevent_overflow(event, 1, data, regs);
} else
data->period = event->hw.last_period;
if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
return perf_swevent_overflow(event, 1, data, regs);
if (local64_add_negative(nr, &hwc->period_left))
return;
perf_swevent_overflow(event, 0, data, regs);
}
static int perf_exclude_event(struct perf_event *event,
struct pt_regs *regs)
{
if (event->hw.state & PERF_HES_STOPPED)
return 1;
if (regs) {
if (event->attr.exclude_user && user_mode(regs))
return 1;
if (event->attr.exclude_kernel && !user_mode(regs))
return 1;
}
return 0;
}
static int perf_swevent_match(struct perf_event *event,
enum perf_type_id type,
u32 event_id,
struct perf_sample_data *data,
struct pt_regs *regs)
{
if (event->attr.type != type)
return 0;
if (event->attr.config != event_id)
return 0;
if (perf_exclude_event(event, regs))
return 0;
return 1;
}
static inline u64 swevent_hash(u64 type, u32 event_id)
{
u64 val = event_id | (type << 32);
return hash_64(val, SWEVENT_HLIST_BITS);
}
static inline struct hlist_head *
__find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
{
u64 hash = swevent_hash(type, event_id);
return &hlist->heads[hash];
}
/* For the read side: events when they trigger */
static inline struct hlist_head *
find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
{
struct swevent_hlist *hlist;
hlist = rcu_dereference(swhash->swevent_hlist);
if (!hlist)
return NULL;
return __find_swevent_head(hlist, type, event_id);
}
/* For the event head insertion and removal in the hlist */
static inline struct hlist_head *
find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
{
struct swevent_hlist *hlist;
u32 event_id = event->attr.config;
u64 type = event->attr.type;
/*
* Event scheduling is always serialized against hlist allocation
* and release. Which makes the protected version suitable here.
* The context lock guarantees that.
*/
hlist = rcu_dereference_protected(swhash->swevent_hlist,
lockdep_is_held(&event->ctx->lock));
if (!hlist)
return NULL;
return __find_swevent_head(hlist, type, event_id);
}
static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
u64 nr,
struct perf_sample_data *data,
struct pt_regs *regs)
{
struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
struct perf_event *event;
struct hlist_head *head;
rcu_read_lock();
head = find_swevent_head_rcu(swhash, type, event_id);
if (!head)
goto end;
hlist_for_each_entry_rcu(event, head, hlist_entry) {
if (perf_swevent_match(event, type, event_id, data, regs))
perf_swevent_event(event, nr, data, regs);
}
end:
rcu_read_unlock();
}
DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
int perf_swevent_get_recursion_context(void)
{
struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
return get_recursion_context(swhash->recursion);
}
EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
inline void perf_swevent_put_recursion_context(int rctx)
{
struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
put_recursion_context(swhash->recursion, rctx);
}
void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
{
struct perf_sample_data data;
if (WARN_ON_ONCE(!regs))
return;
perf_sample_data_init(&data, addr, 0);
do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
}
void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
{
int rctx;
preempt_disable_notrace();
rctx = perf_swevent_get_recursion_context();
if (unlikely(rctx < 0))
goto fail;
___perf_sw_event(event_id, nr, regs, addr);
perf_swevent_put_recursion_context(rctx);
fail:
preempt_enable_notrace();
}
static void perf_swevent_read(struct perf_event *event)
{
}
static int perf_swevent_add(struct perf_event *event, int flags)
{
struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
struct hw_perf_event *hwc = &event->hw;
struct hlist_head *head;
if (is_sampling_event(event)) {
hwc->last_period = hwc->sample_period;
perf_swevent_set_period(event);
}
hwc->state = !(flags & PERF_EF_START);
head = find_swevent_head(swhash, event);
if (WARN_ON_ONCE(!head))
return -EINVAL;
hlist_add_head_rcu(&event->hlist_entry, head);
perf_event_update_userpage(event);
return 0;
}
static void perf_swevent_del(struct perf_event *event, int flags)
{
hlist_del_rcu(&event->hlist_entry);
}
static void perf_swevent_start(struct perf_event *event, int flags)
{
event->hw.state = 0;
}
static void perf_swevent_stop(struct perf_event *event, int flags)
{
event->hw.state = PERF_HES_STOPPED;
}
/* Deref the hlist from the update side */
static inline struct swevent_hlist *
swevent_hlist_deref(struct swevent_htable *swhash)
{
return rcu_dereference_protected(swhash->swevent_hlist,
lockdep_is_held(&swhash->hlist_mutex));
}
static void swevent_hlist_release(struct swevent_htable *swhash)
{
struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
if (!hlist)
return;
RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
kfree_rcu(hlist, rcu_head);
}
static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
{
struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
mutex_lock(&swhash->hlist_mutex);
if (!--swhash->hlist_refcount)
swevent_hlist_release(swhash);
mutex_unlock(&swhash->hlist_mutex);
}
static void swevent_hlist_put(struct perf_event *event)
{
int cpu;
for_each_possible_cpu(cpu)
swevent_hlist_put_cpu(event, cpu);
}
static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
{
struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
int err = 0;
mutex_lock(&swhash->hlist_mutex);
if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
struct swevent_hlist *hlist;
hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
if (!hlist) {
err = -ENOMEM;
goto exit;
}
rcu_assign_pointer(swhash->swevent_hlist, hlist);
}
swhash->hlist_refcount++;
exit:
mutex_unlock(&swhash->hlist_mutex);
return err;
}
static int swevent_hlist_get(struct perf_event *event)
{
int err;
int cpu, failed_cpu;
get_online_cpus();
for_each_possible_cpu(cpu) {
err = swevent_hlist_get_cpu(event, cpu);
if (err) {
failed_cpu = cpu;
goto fail;
}
}
put_online_cpus();
return 0;
fail:
for_each_possible_cpu(cpu) {
if (cpu == failed_cpu)
break;
swevent_hlist_put_cpu(event, cpu);
}
put_online_cpus();
return err;
}
struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
static void sw_perf_event_destroy(struct perf_event *event)
{
u64 event_id = event->attr.config;
WARN_ON(event->parent);
static_key_slow_dec(&perf_swevent_enabled[event_id]);
swevent_hlist_put(event);
}
static int perf_swevent_init(struct perf_event *event)
{
u64 event_id = event->attr.config;
if (event->attr.type != PERF_TYPE_SOFTWARE)
return -ENOENT;
/*
* no branch sampling for software events
*/
if (has_branch_stack(event))
return -EOPNOTSUPP;
switch (event_id) {
case PERF_COUNT_SW_CPU_CLOCK:
case PERF_COUNT_SW_TASK_CLOCK:
return -ENOENT;
default:
break;
}
if (event_id >= PERF_COUNT_SW_MAX)
return -ENOENT;
if (!event->parent) {
int err;
err = swevent_hlist_get(event);
if (err)
return err;
static_key_slow_inc(&perf_swevent_enabled[event_id]);
event->destroy = sw_perf_event_destroy;
}
return 0;
}
static struct pmu perf_swevent = {
.task_ctx_nr = perf_sw_context,
.capabilities = PERF_PMU_CAP_NO_NMI,
.event_init = perf_swevent_init,
.add = perf_swevent_add,
.del = perf_swevent_del,
.start = perf_swevent_start,
.stop = perf_swevent_stop,
.read = perf_swevent_read,
};
#ifdef CONFIG_EVENT_TRACING
static int perf_tp_filter_match(struct perf_event *event,
struct perf_sample_data *data)
{
void *record = data->raw->data;
/* only top level events have filters set */
if (event->parent)
event = event->parent;
if (likely(!event->filter) || filter_match_preds(event->filter, record))
return 1;
return 0;
}
static int perf_tp_event_match(struct perf_event *event,
struct perf_sample_data *data,
struct pt_regs *regs)
{
if (event->hw.state & PERF_HES_STOPPED)
return 0;
/*
* All tracepoints are from kernel-space.
*/
if (event->attr.exclude_kernel)
return 0;
if (!perf_tp_filter_match(event, data))
return 0;
return 1;
}
void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
struct pt_regs *regs, struct hlist_head *head, int rctx,
struct task_struct *task)
{
struct perf_sample_data data;
struct perf_event *event;
struct perf_raw_record raw = {
.size = entry_size,
.data = record,
};
perf_sample_data_init(&data, addr, 0);
data.raw = &raw;
hlist_for_each_entry_rcu(event, head, hlist_entry) {
if (perf_tp_event_match(event, &data, regs))
perf_swevent_event(event, count, &data, regs);
}
/*
* If we got specified a target task, also iterate its context and
* deliver this event there too.
*/
if (task && task != current) {
struct perf_event_context *ctx;
struct trace_entry *entry = record;
rcu_read_lock();
ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
if (!ctx)
goto unlock;
list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
if (event->attr.type != PERF_TYPE_TRACEPOINT)
continue;
if (event->attr.config != entry->type)
continue;
if (perf_tp_event_match(event, &data, regs))
perf_swevent_event(event, count, &data, regs);
}
unlock:
rcu_read_unlock();
}
perf_swevent_put_recursion_context(rctx);
}
EXPORT_SYMBOL_GPL(perf_tp_event);
static void tp_perf_event_destroy(struct perf_event *event)
{
perf_trace_destroy(event);
}
static int perf_tp_event_init(struct perf_event *event)
{
int err;
if (event->attr.type != PERF_TYPE_TRACEPOINT)
return -ENOENT;
/*
* no branch sampling for tracepoint events
*/
if (has_branch_stack(event))
return -EOPNOTSUPP;
err = perf_trace_init(event);
if (err)
return err;
event->destroy = tp_perf_event_destroy;
return 0;
}
static struct pmu perf_tracepoint = {
.task_ctx_nr = perf_sw_context,
.event_init = perf_tp_event_init,
.add = perf_trace_add,
.del = perf_trace_del,
.start = perf_swevent_start,
.stop = perf_swevent_stop,
.read = perf_swevent_read,
};
static inline void perf_tp_register(void)
{
perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
}
static int perf_event_set_filter(struct perf_event *event, void __user *arg)
{
char *filter_str;
int ret;
if (event->attr.type != PERF_TYPE_TRACEPOINT)
return -EINVAL;
filter_str = strndup_user(arg, PAGE_SIZE);
if (IS_ERR(filter_str))
return PTR_ERR(filter_str);
ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
kfree(filter_str);
return ret;
}
static void perf_event_free_filter(struct perf_event *event)
{
ftrace_profile_free_filter(event);
}
static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
{
struct bpf_prog *prog;
if (event->attr.type != PERF_TYPE_TRACEPOINT)
return -EINVAL;
if (event->tp_event->prog)
return -EEXIST;
if (!(event->tp_event->flags & TRACE_EVENT_FL_UKPROBE))
/* bpf programs can only be attached to u/kprobes */
return -EINVAL;
prog = bpf_prog_get(prog_fd);
if (IS_ERR(prog))
return PTR_ERR(prog);
if (prog->type != BPF_PROG_TYPE_KPROBE) {
/* valid fd, but invalid bpf program type */
bpf_prog_put(prog);
return -EINVAL;
}
event->tp_event->prog = prog;
return 0;
}
static void perf_event_free_bpf_prog(struct perf_event *event)
{
struct bpf_prog *prog;
if (!event->tp_event)
return;
prog = event->tp_event->prog;
if (prog) {
event->tp_event->prog = NULL;
bpf_prog_put(prog);
}
}
#else
static inline void perf_tp_register(void)
{
}
static int perf_event_set_filter(struct perf_event *event, void __user *arg)
{
return -ENOENT;
}
static void perf_event_free_filter(struct perf_event *event)
{
}
static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
{
return -ENOENT;
}
static void perf_event_free_bpf_prog(struct perf_event *event)
{
}
#endif /* CONFIG_EVENT_TRACING */
#ifdef CONFIG_HAVE_HW_BREAKPOINT
void perf_bp_event(struct perf_event *bp, void *data)
{
struct perf_sample_data sample;
struct pt_regs *regs = data;
perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
if (!bp->hw.state && !perf_exclude_event(bp, regs))
perf_swevent_event(bp, 1, &sample, regs);
}
#endif
/*
* hrtimer based swevent callback
*/
static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
{
enum hrtimer_restart ret = HRTIMER_RESTART;
struct perf_sample_data data;
struct pt_regs *regs;
struct perf_event *event;
u64 period;
event = container_of(hrtimer, struct perf_event, hw.hrtimer);
if (event->state != PERF_EVENT_STATE_ACTIVE)
return HRTIMER_NORESTART;
event->pmu->read(event);
perf_sample_data_init(&data, 0, event->hw.last_period);
regs = get_irq_regs();
if (regs && !perf_exclude_event(event, regs)) {
if (!(event->attr.exclude_idle && is_idle_task(current)))
if (__perf_event_overflow(event, 1, &data, regs))
ret = HRTIMER_NORESTART;
}
period = max_t(u64, 10000, event->hw.sample_period);
hrtimer_forward_now(hrtimer, ns_to_ktime(period));
return ret;
}
static void perf_swevent_start_hrtimer(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
s64 period;
if (!is_sampling_event(event))
return;
period = local64_read(&hwc->period_left);
if (period) {
if (period < 0)
period = 10000;
local64_set(&hwc->period_left, 0);
} else {
period = max_t(u64, 10000, hwc->sample_period);
}
hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
HRTIMER_MODE_REL_PINNED);
}
static void perf_swevent_cancel_hrtimer(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
if (is_sampling_event(event)) {
ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
local64_set(&hwc->period_left, ktime_to_ns(remaining));
hrtimer_cancel(&hwc->hrtimer);
}
}
static void perf_swevent_init_hrtimer(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
if (!is_sampling_event(event))
return;
hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
hwc->hrtimer.function = perf_swevent_hrtimer;
/*
* Since hrtimers have a fixed rate, we can do a static freq->period
* mapping and avoid the whole period adjust feedback stuff.
*/
if (event->attr.freq) {
long freq = event->attr.sample_freq;
event->attr.sample_period = NSEC_PER_SEC / freq;
hwc->sample_period = event->attr.sample_period;
local64_set(&hwc->period_left, hwc->sample_period);
hwc->last_period = hwc->sample_period;
event->attr.freq = 0;
}
}
/*
* Software event: cpu wall time clock
*/
static void cpu_clock_event_update(struct perf_event *event)
{
s64 prev;
u64 now;
now = local_clock();
prev = local64_xchg(&event->hw.prev_count, now);
local64_add(now - prev, &event->count);
}
static void cpu_clock_event_start(struct perf_event *event, int flags)
{
local64_set(&event->hw.prev_count, local_clock());
perf_swevent_start_hrtimer(event);
}
static void cpu_clock_event_stop(struct perf_event *event, int flags)
{
perf_swevent_cancel_hrtimer(event);
cpu_clock_event_update(event);
}
static int cpu_clock_event_add(struct perf_event *event, int flags)
{
if (flags & PERF_EF_START)
cpu_clock_event_start(event, flags);
perf_event_update_userpage(event);
return 0;
}
static void cpu_clock_event_del(struct perf_event *event, int flags)
{
cpu_clock_event_stop(event, flags);
}
static void cpu_clock_event_read(struct perf_event *event)
{
cpu_clock_event_update(event);
}
static int cpu_clock_event_init(struct perf_event *event)
{
if (event->attr.type != PERF_TYPE_SOFTWARE)
return -ENOENT;
if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
return -ENOENT;
/*
* no branch sampling for software events
*/
if (has_branch_stack(event))
return -EOPNOTSUPP;
perf_swevent_init_hrtimer(event);
return 0;
}
static struct pmu perf_cpu_clock = {
.task_ctx_nr = perf_sw_context,
.capabilities = PERF_PMU_CAP_NO_NMI,
.event_init = cpu_clock_event_init,
.add = cpu_clock_event_add,
.del = cpu_clock_event_del,
.start = cpu_clock_event_start,
.stop = cpu_clock_event_stop,
.read = cpu_clock_event_read,
};
/*
* Software event: task time clock
*/
static void task_clock_event_update(struct perf_event *event, u64 now)
{
u64 prev;
s64 delta;
prev = local64_xchg(&event->hw.prev_count, now);
delta = now - prev;
local64_add(delta, &event->count);
}
static void task_clock_event_start(struct perf_event *event, int flags)
{
local64_set(&event->hw.prev_count, event->ctx->time);
perf_swevent_start_hrtimer(event);
}
static void task_clock_event_stop(struct perf_event *event, int flags)
{
perf_swevent_cancel_hrtimer(event);
task_clock_event_update(event, event->ctx->time);
}
static int task_clock_event_add(struct perf_event *event, int flags)
{
if (flags & PERF_EF_START)
task_clock_event_start(event, flags);
perf_event_update_userpage(event);
return 0;
}
static void task_clock_event_del(struct perf_event *event, int flags)
{
task_clock_event_stop(event, PERF_EF_UPDATE);
}
static void task_clock_event_read(struct perf_event *event)
{
u64 now = perf_clock();
u64 delta = now - event->ctx->timestamp;
u64 time = event->ctx->time + delta;
task_clock_event_update(event, time);
}
static int task_clock_event_init(struct perf_event *event)
{
if (event->attr.type != PERF_TYPE_SOFTWARE)
return -ENOENT;
if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
return -ENOENT;
/*
* no branch sampling for software events
*/
if (has_branch_stack(event))
return -EOPNOTSUPP;
perf_swevent_init_hrtimer(event);
return 0;
}
static struct pmu perf_task_clock = {
.task_ctx_nr = perf_sw_context,
.capabilities = PERF_PMU_CAP_NO_NMI,
.event_init = task_clock_event_init,
.add = task_clock_event_add,
.del = task_clock_event_del,
.start = task_clock_event_start,
.stop = task_clock_event_stop,
.read = task_clock_event_read,
};
static void perf_pmu_nop_void(struct pmu *pmu)
{
}
static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
{
}
static int perf_pmu_nop_int(struct pmu *pmu)
{
return 0;
}
static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
{
__this_cpu_write(nop_txn_flags, flags);
if (flags & ~PERF_PMU_TXN_ADD)
return;
perf_pmu_disable(pmu);
}
static int perf_pmu_commit_txn(struct pmu *pmu)
{
unsigned int flags = __this_cpu_read(nop_txn_flags);
__this_cpu_write(nop_txn_flags, 0);
if (flags & ~PERF_PMU_TXN_ADD)
return 0;
perf_pmu_enable(pmu);
return 0;
}
static void perf_pmu_cancel_txn(struct pmu *pmu)
{
unsigned int flags = __this_cpu_read(nop_txn_flags);
__this_cpu_write(nop_txn_flags, 0);
if (flags & ~PERF_PMU_TXN_ADD)
return;
perf_pmu_enable(pmu);
}
static int perf_event_idx_default(struct perf_event *event)
{
return 0;
}
/*
* Ensures all contexts with the same task_ctx_nr have the same
* pmu_cpu_context too.
*/
static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
{
struct pmu *pmu;
if (ctxn < 0)
return NULL;
list_for_each_entry(pmu, &pmus, entry) {
if (pmu->task_ctx_nr == ctxn)
return pmu->pmu_cpu_context;
}
return NULL;
}
static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
{
int cpu;
for_each_possible_cpu(cpu) {
struct perf_cpu_context *cpuctx;
cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
if (cpuctx->unique_pmu == old_pmu)
cpuctx->unique_pmu = pmu;
}
}
static void free_pmu_context(struct pmu *pmu)
{
struct pmu *i;
mutex_lock(&pmus_lock);
/*
* Like a real lame refcount.
*/
list_for_each_entry(i, &pmus, entry) {
if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
update_pmu_context(i, pmu);
goto out;
}
}
free_percpu(pmu->pmu_cpu_context);
out:
mutex_unlock(&pmus_lock);
}
static struct idr pmu_idr;
static ssize_t
type_show(struct device *dev, struct device_attribute *attr, char *page)
{
struct pmu *pmu = dev_get_drvdata(dev);
return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
}
static DEVICE_ATTR_RO(type);
static ssize_t
perf_event_mux_interval_ms_show(struct device *dev,
struct device_attribute *attr,
char *page)
{
struct pmu *pmu = dev_get_drvdata(dev);
return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
}
static DEFINE_MUTEX(mux_interval_mutex);
static ssize_t
perf_event_mux_interval_ms_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct pmu *pmu = dev_get_drvdata(dev);
int timer, cpu, ret;
ret = kstrtoint(buf, 0, &timer);
if (ret)
return ret;
if (timer < 1)
return -EINVAL;
/* same value, noting to do */
if (timer == pmu->hrtimer_interval_ms)
return count;
mutex_lock(&mux_interval_mutex);
pmu->hrtimer_interval_ms = timer;
/* update all cpuctx for this PMU */
get_online_cpus();
for_each_online_cpu(cpu) {
struct perf_cpu_context *cpuctx;
cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
cpu_function_call(cpu,
(remote_function_f)perf_mux_hrtimer_restart, cpuctx);
}
put_online_cpus();
mutex_unlock(&mux_interval_mutex);
return count;
}
static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
static struct attribute *pmu_dev_attrs[] = {
&dev_attr_type.attr,
&dev_attr_perf_event_mux_interval_ms.attr,
NULL,
};
ATTRIBUTE_GROUPS(pmu_dev);
static int pmu_bus_running;
static struct bus_type pmu_bus = {
.name = "event_source",
.dev_groups = pmu_dev_groups,
};
static void pmu_dev_release(struct device *dev)
{
kfree(dev);
}
static int pmu_dev_alloc(struct pmu *pmu)
{
int ret = -ENOMEM;
pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
if (!pmu->dev)
goto out;
pmu->dev->groups = pmu->attr_groups;
device_initialize(pmu->dev);
ret = dev_set_name(pmu->dev, "%s", pmu->name);
if (ret)
goto free_dev;
dev_set_drvdata(pmu->dev, pmu);
pmu->dev->bus = &pmu_bus;
pmu->dev->release = pmu_dev_release;
ret = device_add(pmu->dev);
if (ret)
goto free_dev;
out:
return ret;
free_dev:
put_device(pmu->dev);
goto out;
}
static struct lock_class_key cpuctx_mutex;
static struct lock_class_key cpuctx_lock;
int perf_pmu_register(struct pmu *pmu, const char *name, int type)
{
int cpu, ret;
mutex_lock(&pmus_lock);
ret = -ENOMEM;
pmu->pmu_disable_count = alloc_percpu(int);
if (!pmu->pmu_disable_count)
goto unlock;
pmu->type = -1;
if (!name)
goto skip_type;
pmu->name = name;
if (type < 0) {
type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
if (type < 0) {
ret = type;
goto free_pdc;
}
}
pmu->type = type;
if (pmu_bus_running) {
ret = pmu_dev_alloc(pmu);
if (ret)
goto free_idr;
}
skip_type:
pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
if (pmu->pmu_cpu_context)
goto got_cpu_context;
ret = -ENOMEM;
pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
if (!pmu->pmu_cpu_context)
goto free_dev;
for_each_possible_cpu(cpu) {
struct perf_cpu_context *cpuctx;
cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
__perf_event_init_context(&cpuctx->ctx);
lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
cpuctx->ctx.pmu = pmu;
__perf_mux_hrtimer_init(cpuctx, cpu);
cpuctx->unique_pmu = pmu;
}
got_cpu_context:
if (!pmu->start_txn) {
if (pmu->pmu_enable) {
/*
* If we have pmu_enable/pmu_disable calls, install
* transaction stubs that use that to try and batch
* hardware accesses.
*/
pmu->start_txn = perf_pmu_start_txn;
pmu->commit_txn = perf_pmu_commit_txn;
pmu->cancel_txn = perf_pmu_cancel_txn;
} else {
pmu->start_txn = perf_pmu_nop_txn;
pmu->commit_txn = perf_pmu_nop_int;
pmu->cancel_txn = perf_pmu_nop_void;
}
}
if (!pmu->pmu_enable) {
pmu->pmu_enable = perf_pmu_nop_void;
pmu->pmu_disable = perf_pmu_nop_void;
}
if (!pmu->event_idx)
pmu->event_idx = perf_event_idx_default;
list_add_rcu(&pmu->entry, &pmus);
atomic_set(&pmu->exclusive_cnt, 0);
ret = 0;
unlock:
mutex_unlock(&pmus_lock);
return ret;
free_dev:
device_del(pmu->dev);
put_device(pmu->dev);
free_idr:
if (pmu->type >= PERF_TYPE_MAX)
idr_remove(&pmu_idr, pmu->type);
free_pdc:
free_percpu(pmu->pmu_disable_count);
goto unlock;
}
EXPORT_SYMBOL_GPL(perf_pmu_register);
void perf_pmu_unregister(struct pmu *pmu)
{
mutex_lock(&pmus_lock);
list_del_rcu(&pmu->entry);
mutex_unlock(&pmus_lock);
/*
* We dereference the pmu list under both SRCU and regular RCU, so
* synchronize against both of those.
*/
synchronize_srcu(&pmus_srcu);
synchronize_rcu();
free_percpu(pmu->pmu_disable_count);
if (pmu->type >= PERF_TYPE_MAX)
idr_remove(&pmu_idr, pmu->type);
device_del(pmu->dev);
put_device(pmu->dev);
free_pmu_context(pmu);
}
EXPORT_SYMBOL_GPL(perf_pmu_unregister);
static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
{
struct perf_event_context *ctx = NULL;
int ret;
if (!try_module_get(pmu->module))
return -ENODEV;
if (event->group_leader != event) {
/*
* This ctx->mutex can nest when we're called through
* inheritance. See the perf_event_ctx_lock_nested() comment.
*/
ctx = perf_event_ctx_lock_nested(event->group_leader,
SINGLE_DEPTH_NESTING);
BUG_ON(!ctx);
}
event->pmu = pmu;
ret = pmu->event_init(event);
if (ctx)
perf_event_ctx_unlock(event->group_leader, ctx);
if (ret)
module_put(pmu->module);
return ret;
}
static struct pmu *perf_init_event(struct perf_event *event)
{
struct pmu *pmu = NULL;
int idx;
int ret;
idx = srcu_read_lock(&pmus_srcu);
rcu_read_lock();
pmu = idr_find(&pmu_idr, event->attr.type);
rcu_read_unlock();
if (pmu) {
ret = perf_try_init_event(pmu, event);
if (ret)
pmu = ERR_PTR(ret);
goto unlock;
}
list_for_each_entry_rcu(pmu, &pmus, entry) {
ret = perf_try_init_event(pmu, event);
if (!ret)
goto unlock;
if (ret != -ENOENT) {
pmu = ERR_PTR(ret);
goto unlock;
}
}
pmu = ERR_PTR(-ENOENT);
unlock:
srcu_read_unlock(&pmus_srcu, idx);
return pmu;
}
static void account_event_cpu(struct perf_event *event, int cpu)
{
if (event->parent)
return;
if (is_cgroup_event(event))
atomic_inc(&per_cpu(perf_cgroup_events, cpu));
}
static void account_event(struct perf_event *event)
{
if (event->parent)
return;
if (event->attach_state & PERF_ATTACH_TASK)
static_key_slow_inc(&perf_sched_events.key);
if (event->attr.mmap || event->attr.mmap_data)
atomic_inc(&nr_mmap_events);
if (event->attr.comm)
atomic_inc(&nr_comm_events);
if (event->attr.task)
atomic_inc(&nr_task_events);
if (event->attr.freq) {
if (atomic_inc_return(&nr_freq_events) == 1)
tick_nohz_full_kick_all();
}
if (event->attr.context_switch) {
atomic_inc(&nr_switch_events);
static_key_slow_inc(&perf_sched_events.key);
}
if (has_branch_stack(event))
static_key_slow_inc(&perf_sched_events.key);
if (is_cgroup_event(event))
static_key_slow_inc(&perf_sched_events.key);
account_event_cpu(event, event->cpu);
}
/*
* Allocate and initialize a event structure
*/
static struct perf_event *
perf_event_alloc(struct perf_event_attr *attr, int cpu,
struct task_struct *task,
struct perf_event *group_leader,
struct perf_event *parent_event,
perf_overflow_handler_t overflow_handler,
void *context, int cgroup_fd)
{
struct pmu *pmu;
struct perf_event *event;
struct hw_perf_event *hwc;
long err = -EINVAL;
if ((unsigned)cpu >= nr_cpu_ids) {
if (!task || cpu != -1)
return ERR_PTR(-EINVAL);
}
event = kzalloc(sizeof(*event), GFP_KERNEL);
if (!event)
return ERR_PTR(-ENOMEM);
/*
* Single events are their own group leaders, with an
* empty sibling list:
*/
if (!group_leader)
group_leader = event;
mutex_init(&event->child_mutex);
INIT_LIST_HEAD(&event->child_list);
INIT_LIST_HEAD(&event->group_entry);
INIT_LIST_HEAD(&event->event_entry);
INIT_LIST_HEAD(&event->sibling_list);
INIT_LIST_HEAD(&event->rb_entry);
INIT_LIST_HEAD(&event->active_entry);
INIT_HLIST_NODE(&event->hlist_entry);
init_waitqueue_head(&event->waitq);
init_irq_work(&event->pending, perf_pending_event);
mutex_init(&event->mmap_mutex);
atomic_long_set(&event->refcount, 1);
event->cpu = cpu;
event->attr = *attr;
event->group_leader = group_leader;
event->pmu = NULL;
event->oncpu = -1;
event->parent = parent_event;
event->ns = get_pid_ns(task_active_pid_ns(current));
event->id = atomic64_inc_return(&perf_event_id);
event->state = PERF_EVENT_STATE_INACTIVE;
if (task) {
event->attach_state = PERF_ATTACH_TASK;
/*
* XXX pmu::event_init needs to know what task to account to
* and we cannot use the ctx information because we need the
* pmu before we get a ctx.
*/
event->hw.target = task;
}
event->clock = &local_clock;
if (parent_event)
event->clock = parent_event->clock;
if (!overflow_handler && parent_event) {
overflow_handler = parent_event->overflow_handler;
context = parent_event->overflow_handler_context;
}
event->overflow_handler = overflow_handler;
event->overflow_handler_context = context;
perf_event__state_init(event);
pmu = NULL;
hwc = &event->hw;
hwc->sample_period = attr->sample_period;
if (attr->freq && attr->sample_freq)
hwc->sample_period = 1;
hwc->last_period = hwc->sample_period;
local64_set(&hwc->period_left, hwc->sample_period);
/*
* we currently do not support PERF_FORMAT_GROUP on inherited events
*/
if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
goto err_ns;
if (!has_branch_stack(event))
event->attr.branch_sample_type = 0;
if (cgroup_fd != -1) {
err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
if (err)
goto err_ns;
}
pmu = perf_init_event(event);
if (!pmu)
goto err_ns;
else if (IS_ERR(pmu)) {
err = PTR_ERR(pmu);
goto err_ns;
}
err = exclusive_event_init(event);
if (err)
goto err_pmu;
if (!event->parent) {
if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
err = get_callchain_buffers();
if (err)
goto err_per_task;
}
}
return event;
err_per_task:
exclusive_event_destroy(event);
err_pmu:
if (event->destroy)
event->destroy(event);
module_put(pmu->module);
err_ns:
if (is_cgroup_event(event))
perf_detach_cgroup(event);
if (event->ns)
put_pid_ns(event->ns);
kfree(event);
return ERR_PTR(err);
}
static int perf_copy_attr(struct perf_event_attr __user *uattr,
struct perf_event_attr *attr)
{
u32 size;
int ret;
if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
return -EFAULT;
/*
* zero the full structure, so that a short copy will be nice.
*/
memset(attr, 0, sizeof(*attr));
ret = get_user(size, &uattr->size);
if (ret)
return ret;
if (size > PAGE_SIZE) /* silly large */
goto err_size;
if (!size) /* abi compat */
size = PERF_ATTR_SIZE_VER0;
if (size < PERF_ATTR_SIZE_VER0)
goto err_size;
/*
* If we're handed a bigger struct than we know of,
* ensure all the unknown bits are 0 - i.e. new
* user-space does not rely on any kernel feature
* extensions we dont know about yet.
*/
if (size > sizeof(*attr)) {
unsigned char __user *addr;
unsigned char __user *end;
unsigned char val;
addr = (void __user *)uattr + sizeof(*attr);
end = (void __user *)uattr + size;
for (; addr < end; addr++) {
ret = get_user(val, addr);
if (ret)
return ret;
if (val)
goto err_size;
}
size = sizeof(*attr);
}
ret = copy_from_user(attr, uattr, size);
if (ret)
return -EFAULT;
if (attr->__reserved_1)
return -EINVAL;
if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
return -EINVAL;
if (attr->read_format & ~(PERF_FORMAT_MAX-1))
return -EINVAL;
if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
u64 mask = attr->branch_sample_type;
/* only using defined bits */
if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
return -EINVAL;
/* at least one branch bit must be set */
if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
return -EINVAL;
/* propagate priv level, when not set for branch */
if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
/* exclude_kernel checked on syscall entry */
if (!attr->exclude_kernel)
mask |= PERF_SAMPLE_BRANCH_KERNEL;
if (!attr->exclude_user)
mask |= PERF_SAMPLE_BRANCH_USER;
if (!attr->exclude_hv)
mask |= PERF_SAMPLE_BRANCH_HV;
/*
* adjust user setting (for HW filter setup)
*/
attr->branch_sample_type = mask;
}
/* privileged levels capture (kernel, hv): check permissions */
if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
&& perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
return -EACCES;
}
if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
ret = perf_reg_validate(attr->sample_regs_user);
if (ret)
return ret;
}
if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
if (!arch_perf_have_user_stack_dump())
return -ENOSYS;
/*
* We have __u32 type for the size, but so far
* we can only use __u16 as maximum due to the
* __u16 sample size limit.
*/
if (attr->sample_stack_user >= USHRT_MAX)
ret = -EINVAL;
else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
ret = -EINVAL;
}
if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
ret = perf_reg_validate(attr->sample_regs_intr);
out:
return ret;
err_size:
put_user(sizeof(*attr), &uattr->size);
ret = -E2BIG;
goto out;
}
static int
perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
{
struct ring_buffer *rb = NULL;
int ret = -EINVAL;
if (!output_event)
goto set;
/* don't allow circular references */
if (event == output_event)
goto out;
/*
* Don't allow cross-cpu buffers
*/
if (output_event->cpu != event->cpu)
goto out;
/*
* If its not a per-cpu rb, it must be the same task.
*/
if (output_event->cpu == -1 && output_event->ctx != event->ctx)
goto out;
/*
* Mixing clocks in the same buffer is trouble you don't need.
*/
if (output_event->clock != event->clock)
goto out;
/*
* If both events generate aux data, they must be on the same PMU
*/
if (has_aux(event) && has_aux(output_event) &&
event->pmu != output_event->pmu)
goto out;
set:
mutex_lock(&event->mmap_mutex);
/* Can't redirect output if we've got an active mmap() */
if (atomic_read(&event->mmap_count))
goto unlock;
if (output_event) {
/* get the rb we want to redirect to */
rb = ring_buffer_get(output_event);
if (!rb)
goto unlock;
}
ring_buffer_attach(event, rb);
ret = 0;
unlock:
mutex_unlock(&event->mmap_mutex);
out:
return ret;
}
static void mutex_lock_double(struct mutex *a, struct mutex *b)
{
if (b < a)
swap(a, b);
mutex_lock(a);
mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
}
static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
{
bool nmi_safe = false;
switch (clk_id) {
case CLOCK_MONOTONIC:
event->clock = &ktime_get_mono_fast_ns;
nmi_safe = true;
break;
case CLOCK_MONOTONIC_RAW:
event->clock = &ktime_get_raw_fast_ns;
nmi_safe = true;
break;
case CLOCK_REALTIME:
event->clock = &ktime_get_real_ns;
break;
case CLOCK_BOOTTIME:
event->clock = &ktime_get_boot_ns;
break;
case CLOCK_TAI:
event->clock = &ktime_get_tai_ns;
break;
default:
return -EINVAL;
}
if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
return -EINVAL;
return 0;
}
/**
* sys_perf_event_open - open a performance event, associate it to a task/cpu
*
* @attr_uptr: event_id type attributes for monitoring/sampling
* @pid: target pid
* @cpu: target cpu
* @group_fd: group leader event fd
*/
SYSCALL_DEFINE5(perf_event_open,
struct perf_event_attr __user *, attr_uptr,
pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
{
struct perf_event *group_leader = NULL, *output_event = NULL;
struct perf_event *event, *sibling;
struct perf_event_attr attr;
struct perf_event_context *ctx, *uninitialized_var(gctx);
struct file *event_file = NULL;
struct fd group = {NULL, 0};
struct task_struct *task = NULL;
struct pmu *pmu;
int event_fd;
int move_group = 0;
int err;
int f_flags = O_RDWR;
int cgroup_fd = -1;
/* for future expandability... */
if (flags & ~PERF_FLAG_ALL)
return -EINVAL;
err = perf_copy_attr(attr_uptr, &attr);
if (err)
return err;
if (!attr.exclude_kernel) {
if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
return -EACCES;
}
if (attr.freq) {
if (attr.sample_freq > sysctl_perf_event_sample_rate)
return -EINVAL;
} else {
if (attr.sample_period & (1ULL << 63))
return -EINVAL;
}
/*
* In cgroup mode, the pid argument is used to pass the fd
* opened to the cgroup directory in cgroupfs. The cpu argument
* designates the cpu on which to monitor threads from that
* cgroup.
*/
if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
return -EINVAL;
if (flags & PERF_FLAG_FD_CLOEXEC)
f_flags |= O_CLOEXEC;
event_fd = get_unused_fd_flags(f_flags);
if (event_fd < 0)
return event_fd;
if (group_fd != -1) {
err = perf_fget_light(group_fd, &group);
if (err)
goto err_fd;
group_leader = group.file->private_data;
if (flags & PERF_FLAG_FD_OUTPUT)
output_event = group_leader;
if (flags & PERF_FLAG_FD_NO_GROUP)
group_leader = NULL;
}
if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
task = find_lively_task_by_vpid(pid);
if (IS_ERR(task)) {
err = PTR_ERR(task);
goto err_group_fd;
}
}
if (task && group_leader &&
group_leader->attr.inherit != attr.inherit) {
err = -EINVAL;
goto err_task;
}
get_online_cpus();
if (flags & PERF_FLAG_PID_CGROUP)
cgroup_fd = pid;
event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
NULL, NULL, cgroup_fd);
if (IS_ERR(event)) {
err = PTR_ERR(event);
goto err_cpus;
}
if (is_sampling_event(event)) {
if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
err = -ENOTSUPP;
goto err_alloc;
}
}
account_event(event);
/*
* Special case software events and allow them to be part of
* any hardware group.
*/
pmu = event->pmu;
if (attr.use_clockid) {
err = perf_event_set_clock(event, attr.clockid);
if (err)
goto err_alloc;
}
if (group_leader &&
(is_software_event(event) != is_software_event(group_leader))) {
if (is_software_event(event)) {
/*
* If event and group_leader are not both a software
* event, and event is, then group leader is not.
*
* Allow the addition of software events to !software
* groups, this is safe because software events never
* fail to schedule.
*/
pmu = group_leader->pmu;
} else if (is_software_event(group_leader) &&
(group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
/*
* In case the group is a pure software group, and we
* try to add a hardware event, move the whole group to
* the hardware context.
*/
move_group = 1;
}
}
/*
* Get the target context (task or percpu):
*/
ctx = find_get_context(pmu, task, event);
if (IS_ERR(ctx)) {
err = PTR_ERR(ctx);
goto err_alloc;
}
if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
err = -EBUSY;
goto err_context;
}
if (task) {
put_task_struct(task);
task = NULL;
}
/*
* Look up the group leader (we will attach this event to it):
*/
if (group_leader) {
err = -EINVAL;
/*
* Do not allow a recursive hierarchy (this new sibling
* becoming part of another group-sibling):
*/
if (group_leader->group_leader != group_leader)
goto err_context;
/* All events in a group should have the same clock */
if (group_leader->clock != event->clock)
goto err_context;
/*
* Do not allow to attach to a group in a different
* task or CPU context:
*/
if (move_group) {
/*
* Make sure we're both on the same task, or both
* per-cpu events.
*/
if (group_leader->ctx->task != ctx->task)
goto err_context;
/*
* Make sure we're both events for the same CPU;
* grouping events for different CPUs is broken; since
* you can never concurrently schedule them anyhow.
*/
if (group_leader->cpu != event->cpu)
goto err_context;
} else {
if (group_leader->ctx != ctx)
goto err_context;
}
/*
* Only a group leader can be exclusive or pinned
*/
if (attr.exclusive || attr.pinned)
goto err_context;
}
if (output_event) {
err = perf_event_set_output(event, output_event);
if (err)
goto err_context;
}
event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
f_flags);
if (IS_ERR(event_file)) {
err = PTR_ERR(event_file);
goto err_context;
}
if (move_group) {
gctx = group_leader->ctx;
mutex_lock_double(&gctx->mutex, &ctx->mutex);
} else {
mutex_lock(&ctx->mutex);
}
if (!perf_event_validate_size(event)) {
err = -E2BIG;
goto err_locked;
}
/*
* Must be under the same ctx::mutex as perf_install_in_context(),
* because we need to serialize with concurrent event creation.
*/
if (!exclusive_event_installable(event, ctx)) {
/* exclusive and group stuff are assumed mutually exclusive */
WARN_ON_ONCE(move_group);
err = -EBUSY;
goto err_locked;
}
WARN_ON_ONCE(ctx->parent_ctx);
if (move_group) {
/*
* See perf_event_ctx_lock() for comments on the details
* of swizzling perf_event::ctx.
*/
perf_remove_from_context(group_leader, false);
list_for_each_entry(sibling, &group_leader->sibling_list,
group_entry) {
perf_remove_from_context(sibling, false);
put_ctx(gctx);
}
/*
* Wait for everybody to stop referencing the events through
* the old lists, before installing it on new lists.
*/
synchronize_rcu();
/*
* Install the group siblings before the group leader.
*
* Because a group leader will try and install the entire group
* (through the sibling list, which is still in-tact), we can
* end up with siblings installed in the wrong context.
*
* By installing siblings first we NO-OP because they're not
* reachable through the group lists.
*/
list_for_each_entry(sibling, &group_leader->sibling_list,
group_entry) {
perf_event__state_init(sibling);
perf_install_in_context(ctx, sibling, sibling->cpu);
get_ctx(ctx);
}
/*
* Removing from the context ends up with disabled
* event. What we want here is event in the initial
* startup state, ready to be add into new context.
*/
perf_event__state_init(group_leader);
perf_install_in_context(ctx, group_leader, group_leader->cpu);
get_ctx(ctx);
/*
* Now that all events are installed in @ctx, nothing
* references @gctx anymore, so drop the last reference we have
* on it.
*/
put_ctx(gctx);
}
/*
* Precalculate sample_data sizes; do while holding ctx::mutex such
* that we're serialized against further additions and before
* perf_install_in_context() which is the point the event is active and
* can use these values.
*/
perf_event__header_size(event);
perf_event__id_header_size(event);
perf_install_in_context(ctx, event, event->cpu);
perf_unpin_context(ctx);
if (move_group)
mutex_unlock(&gctx->mutex);
mutex_unlock(&ctx->mutex);
put_online_cpus();
event->owner = current;
mutex_lock(¤t->perf_event_mutex);
list_add_tail(&event->owner_entry, ¤t->perf_event_list);
mutex_unlock(¤t->perf_event_mutex);
/*
* Drop the reference on the group_event after placing the
* new event on the sibling_list. This ensures destruction
* of the group leader will find the pointer to itself in
* perf_group_detach().
*/
fdput(group);
fd_install(event_fd, event_file);
return event_fd;
err_locked:
if (move_group)
mutex_unlock(&gctx->mutex);
mutex_unlock(&ctx->mutex);
/* err_file: */
fput(event_file);
err_context:
perf_unpin_context(ctx);
put_ctx(ctx);
err_alloc:
free_event(event);
err_cpus:
put_online_cpus();
err_task:
if (task)
put_task_struct(task);
err_group_fd:
fdput(group);
err_fd:
put_unused_fd(event_fd);
return err;
}
/**
* perf_event_create_kernel_counter
*
* @attr: attributes of the counter to create
* @cpu: cpu in which the counter is bound
* @task: task to profile (NULL for percpu)
*/
struct perf_event *
perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
struct task_struct *task,
perf_overflow_handler_t overflow_handler,
void *context)
{
struct perf_event_context *ctx;
struct perf_event *event;
int err;
/*
* Get the target context (task or percpu):
*/
event = perf_event_alloc(attr, cpu, task, NULL, NULL,
overflow_handler, context, -1);
if (IS_ERR(event)) {
err = PTR_ERR(event);
goto err;
}
/* Mark owner so we could distinguish it from user events. */
event->owner = EVENT_OWNER_KERNEL;
account_event(event);
ctx = find_get_context(event->pmu, task, event);
if (IS_ERR(ctx)) {
err = PTR_ERR(ctx);
goto err_free;
}
WARN_ON_ONCE(ctx->parent_ctx);
mutex_lock(&ctx->mutex);
if (!exclusive_event_installable(event, ctx)) {
mutex_unlock(&ctx->mutex);
perf_unpin_context(ctx);
put_ctx(ctx);
err = -EBUSY;
goto err_free;
}
perf_install_in_context(ctx, event, cpu);
perf_unpin_context(ctx);
mutex_unlock(&ctx->mutex);
return event;
err_free:
free_event(event);
err:
return ERR_PTR(err);
}
EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
{
struct perf_event_context *src_ctx;
struct perf_event_context *dst_ctx;
struct perf_event *event, *tmp;
LIST_HEAD(events);
src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
/*
* See perf_event_ctx_lock() for comments on the details
* of swizzling perf_event::ctx.
*/
mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
event_entry) {
perf_remove_from_context(event, false);
unaccount_event_cpu(event, src_cpu);
put_ctx(src_ctx);
list_add(&event->migrate_entry, &events);
}
/*
* Wait for the events to quiesce before re-instating them.
*/
synchronize_rcu();
/*
* Re-instate events in 2 passes.
*
* Skip over group leaders and only install siblings on this first
* pass, siblings will not get enabled without a leader, however a
* leader will enable its siblings, even if those are still on the old
* context.
*/
list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
if (event->group_leader == event)
continue;
list_del(&event->migrate_entry);
if (event->state >= PERF_EVENT_STATE_OFF)
event->state = PERF_EVENT_STATE_INACTIVE;
account_event_cpu(event, dst_cpu);
perf_install_in_context(dst_ctx, event, dst_cpu);
get_ctx(dst_ctx);
}
/*
* Once all the siblings are setup properly, install the group leaders
* to make it go.
*/
list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
list_del(&event->migrate_entry);
if (event->state >= PERF_EVENT_STATE_OFF)
event->state = PERF_EVENT_STATE_INACTIVE;
account_event_cpu(event, dst_cpu);
perf_install_in_context(dst_ctx, event, dst_cpu);
get_ctx(dst_ctx);
}
mutex_unlock(&dst_ctx->mutex);
mutex_unlock(&src_ctx->mutex);
}
EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
static void sync_child_event(struct perf_event *child_event,
struct task_struct *child)
{
struct perf_event *parent_event = child_event->parent;
u64 child_val;
if (child_event->attr.inherit_stat)
perf_event_read_event(child_event, child);
child_val = perf_event_count(child_event);
/*
* Add back the child's count to the parent's count:
*/
atomic64_add(child_val, &parent_event->child_count);
atomic64_add(child_event->total_time_enabled,
&parent_event->child_total_time_enabled);
atomic64_add(child_event->total_time_running,
&parent_event->child_total_time_running);
/*
* Remove this event from the parent's list
*/
WARN_ON_ONCE(parent_event->ctx->parent_ctx);
mutex_lock(&parent_event->child_mutex);
list_del_init(&child_event->child_list);
mutex_unlock(&parent_event->child_mutex);
/*
* Make sure user/parent get notified, that we just
* lost one event.
*/
perf_event_wakeup(parent_event);
/*
* Release the parent event, if this was the last
* reference to it.
*/
put_event(parent_event);
}
static void
__perf_event_exit_task(struct perf_event *child_event,
struct perf_event_context *child_ctx,
struct task_struct *child)
{
/*
* Do not destroy the 'original' grouping; because of the context
* switch optimization the original events could've ended up in a
* random child task.
*
* If we were to destroy the original group, all group related
* operations would cease to function properly after this random
* child dies.
*
* Do destroy all inherited groups, we don't care about those
* and being thorough is better.
*/
perf_remove_from_context(child_event, !!child_event->parent);
/*
* It can happen that the parent exits first, and has events
* that are still around due to the child reference. These
* events need to be zapped.
*/
if (child_event->parent) {
sync_child_event(child_event, child);
free_event(child_event);
} else {
child_event->state = PERF_EVENT_STATE_EXIT;
perf_event_wakeup(child_event);
}
}
static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
{
struct perf_event *child_event, *next;
struct perf_event_context *child_ctx, *clone_ctx = NULL;
unsigned long flags;
if (likely(!child->perf_event_ctxp[ctxn]))
return;
local_irq_save(flags);
/*
* We can't reschedule here because interrupts are disabled,
* and either child is current or it is a task that can't be
* scheduled, so we are now safe from rescheduling changing
* our context.
*/
child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
/*
* Take the context lock here so that if find_get_context is
* reading child->perf_event_ctxp, we wait until it has
* incremented the context's refcount before we do put_ctx below.
*/
raw_spin_lock(&child_ctx->lock);
task_ctx_sched_out(child_ctx);
child->perf_event_ctxp[ctxn] = NULL;
/*
* If this context is a clone; unclone it so it can't get
* swapped to another process while we're removing all
* the events from it.
*/
clone_ctx = unclone_ctx(child_ctx);
update_context_time(child_ctx);
raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
if (clone_ctx)
put_ctx(clone_ctx);
/*
* Report the task dead after unscheduling the events so that we
* won't get any samples after PERF_RECORD_EXIT. We can however still
* get a few PERF_RECORD_READ events.
*/
perf_event_task(child, child_ctx, 0);
/*
* We can recurse on the same lock type through:
*
* __perf_event_exit_task()
* sync_child_event()
* put_event()
* mutex_lock(&ctx->mutex)
*
* But since its the parent context it won't be the same instance.
*/
mutex_lock(&child_ctx->mutex);
list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
__perf_event_exit_task(child_event, child_ctx, child);
mutex_unlock(&child_ctx->mutex);
put_ctx(child_ctx);
}
/*
* When a child task exits, feed back event values to parent events.
*/
void perf_event_exit_task(struct task_struct *child)
{
struct perf_event *event, *tmp;
int ctxn;
mutex_lock(&child->perf_event_mutex);
list_for_each_entry_safe(event, tmp, &child->perf_event_list,
owner_entry) {
list_del_init(&event->owner_entry);
/*
* Ensure the list deletion is visible before we clear
* the owner, closes a race against perf_release() where
* we need to serialize on the owner->perf_event_mutex.
*/
smp_wmb();
event->owner = NULL;
}
mutex_unlock(&child->perf_event_mutex);
for_each_task_context_nr(ctxn)
perf_event_exit_task_context(child, ctxn);
/*
* The perf_event_exit_task_context calls perf_event_task
* with child's task_ctx, which generates EXIT events for
* child contexts and sets child->perf_event_ctxp[] to NULL.
* At this point we need to send EXIT events to cpu contexts.
*/
perf_event_task(child, NULL, 0);
}
static void perf_free_event(struct perf_event *event,
struct perf_event_context *ctx)
{
struct perf_event *parent = event->parent;
if (WARN_ON_ONCE(!parent))
return;
mutex_lock(&parent->child_mutex);
list_del_init(&event->child_list);
mutex_unlock(&parent->child_mutex);
put_event(parent);
raw_spin_lock_irq(&ctx->lock);
perf_group_detach(event);
list_del_event(event, ctx);
raw_spin_unlock_irq(&ctx->lock);
free_event(event);
}
/*
* Free an unexposed, unused context as created by inheritance by
* perf_event_init_task below, used by fork() in case of fail.
*
* Not all locks are strictly required, but take them anyway to be nice and
* help out with the lockdep assertions.
*/
void perf_event_free_task(struct task_struct *task)
{
struct perf_event_context *ctx;
struct perf_event *event, *tmp;
int ctxn;
for_each_task_context_nr(ctxn) {
ctx = task->perf_event_ctxp[ctxn];
if (!ctx)
continue;
mutex_lock(&ctx->mutex);
again:
list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
group_entry)
perf_free_event(event, ctx);
list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
group_entry)
perf_free_event(event, ctx);
if (!list_empty(&ctx->pinned_groups) ||
!list_empty(&ctx->flexible_groups))
goto again;
mutex_unlock(&ctx->mutex);
put_ctx(ctx);
}
}
void perf_event_delayed_put(struct task_struct *task)
{
int ctxn;
for_each_task_context_nr(ctxn)
WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
}
struct perf_event *perf_event_get(unsigned int fd)
{
int err;
struct fd f;
struct perf_event *event;
err = perf_fget_light(fd, &f);
if (err)
return ERR_PTR(err);
event = f.file->private_data;
atomic_long_inc(&event->refcount);
fdput(f);
return event;
}
const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
{
if (!event)
return ERR_PTR(-EINVAL);
return &event->attr;
}
/*
* inherit a event from parent task to child task:
*/
static struct perf_event *
inherit_event(struct perf_event *parent_event,
struct task_struct *parent,
struct perf_event_context *parent_ctx,
struct task_struct *child,
struct perf_event *group_leader,
struct perf_event_context *child_ctx)
{
enum perf_event_active_state parent_state = parent_event->state;
struct perf_event *child_event;
unsigned long flags;
/*
* Instead of creating recursive hierarchies of events,
* we link inherited events back to the original parent,
* which has a filp for sure, which we use as the reference
* count:
*/
if (parent_event->parent)
parent_event = parent_event->parent;
child_event = perf_event_alloc(&parent_event->attr,
parent_event->cpu,
child,
group_leader, parent_event,
NULL, NULL, -1);
if (IS_ERR(child_event))
return child_event;
if (is_orphaned_event(parent_event) ||
!atomic_long_inc_not_zero(&parent_event->refcount)) {
free_event(child_event);
return NULL;
}
get_ctx(child_ctx);
/*
* Make the child state follow the state of the parent event,
* not its attr.disabled bit. We hold the parent's mutex,
* so we won't race with perf_event_{en, dis}able_family.
*/
if (parent_state >= PERF_EVENT_STATE_INACTIVE)
child_event->state = PERF_EVENT_STATE_INACTIVE;
else
child_event->state = PERF_EVENT_STATE_OFF;
if (parent_event->attr.freq) {
u64 sample_period = parent_event->hw.sample_period;
struct hw_perf_event *hwc = &child_event->hw;
hwc->sample_period = sample_period;
hwc->last_period = sample_period;
local64_set(&hwc->period_left, sample_period);
}
child_event->ctx = child_ctx;
child_event->overflow_handler = parent_event->overflow_handler;
child_event->overflow_handler_context
= parent_event->overflow_handler_context;
/*
* Precalculate sample_data sizes
*/
perf_event__header_size(child_event);
perf_event__id_header_size(child_event);
/*
* Link it up in the child's context:
*/
raw_spin_lock_irqsave(&child_ctx->lock, flags);
add_event_to_ctx(child_event, child_ctx);
raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
/*
* Link this into the parent event's child list
*/
WARN_ON_ONCE(parent_event->ctx->parent_ctx);
mutex_lock(&parent_event->child_mutex);
list_add_tail(&child_event->child_list, &parent_event->child_list);
mutex_unlock(&parent_event->child_mutex);
return child_event;
}
static int inherit_group(struct perf_event *parent_event,
struct task_struct *parent,
struct perf_event_context *parent_ctx,
struct task_struct *child,
struct perf_event_context *child_ctx)
{
struct perf_event *leader;
struct perf_event *sub;
struct perf_event *child_ctr;
leader = inherit_event(parent_event, parent, parent_ctx,
child, NULL, child_ctx);
if (IS_ERR(leader))
return PTR_ERR(leader);
list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
child_ctr = inherit_event(sub, parent, parent_ctx,
child, leader, child_ctx);
if (IS_ERR(child_ctr))
return PTR_ERR(child_ctr);
}
return 0;
}
static int
inherit_task_group(struct perf_event *event, struct task_struct *parent,
struct perf_event_context *parent_ctx,
struct task_struct *child, int ctxn,
int *inherited_all)
{
int ret;
struct perf_event_context *child_ctx;
if (!event->attr.inherit) {
*inherited_all = 0;
return 0;
}
child_ctx = child->perf_event_ctxp[ctxn];
if (!child_ctx) {
/*
* This is executed from the parent task context, so
* inherit events that have been marked for cloning.
* First allocate and initialize a context for the
* child.
*/
child_ctx = alloc_perf_context(parent_ctx->pmu, child);
if (!child_ctx)
return -ENOMEM;
child->perf_event_ctxp[ctxn] = child_ctx;
}
ret = inherit_group(event, parent, parent_ctx,
child, child_ctx);
if (ret)
*inherited_all = 0;
return ret;
}
/*
* Initialize the perf_event context in task_struct
*/
static int perf_event_init_context(struct task_struct *child, int ctxn)
{
struct perf_event_context *child_ctx, *parent_ctx;
struct perf_event_context *cloned_ctx;
struct perf_event *event;
struct task_struct *parent = current;
int inherited_all = 1;
unsigned long flags;
int ret = 0;
if (likely(!parent->perf_event_ctxp[ctxn]))
return 0;
/*
* If the parent's context is a clone, pin it so it won't get
* swapped under us.
*/
parent_ctx = perf_pin_task_context(parent, ctxn);
if (!parent_ctx)
return 0;
/*
* No need to check if parent_ctx != NULL here; since we saw
* it non-NULL earlier, the only reason for it to become NULL
* is if we exit, and since we're currently in the middle of
* a fork we can't be exiting at the same time.
*/
/*
* Lock the parent list. No need to lock the child - not PID
* hashed yet and not running, so nobody can access it.
*/
mutex_lock(&parent_ctx->mutex);
/*
* We dont have to disable NMIs - we are only looking at
* the list, not manipulating it:
*/
list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
ret = inherit_task_group(event, parent, parent_ctx,
child, ctxn, &inherited_all);
if (ret)
break;
}
/*
* We can't hold ctx->lock when iterating the ->flexible_group list due
* to allocations, but we need to prevent rotation because
* rotate_ctx() will change the list from interrupt context.
*/
raw_spin_lock_irqsave(&parent_ctx->lock, flags);
parent_ctx->rotate_disable = 1;
raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
ret = inherit_task_group(event, parent, parent_ctx,
child, ctxn, &inherited_all);
if (ret)
break;
}
raw_spin_lock_irqsave(&parent_ctx->lock, flags);
parent_ctx->rotate_disable = 0;
child_ctx = child->perf_event_ctxp[ctxn];
if (child_ctx && inherited_all) {
/*
* Mark the child context as a clone of the parent
* context, or of whatever the parent is a clone of.
*
* Note that if the parent is a clone, the holding of
* parent_ctx->lock avoids it from being uncloned.
*/
cloned_ctx = parent_ctx->parent_ctx;
if (cloned_ctx) {
child_ctx->parent_ctx = cloned_ctx;
child_ctx->parent_gen = parent_ctx->parent_gen;
} else {
child_ctx->parent_ctx = parent_ctx;
child_ctx->parent_gen = parent_ctx->generation;
}
get_ctx(child_ctx->parent_ctx);
}
raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
mutex_unlock(&parent_ctx->mutex);
perf_unpin_context(parent_ctx);
put_ctx(parent_ctx);
return ret;
}
/*
* Initialize the perf_event context in task_struct
*/
int perf_event_init_task(struct task_struct *child)
{
int ctxn, ret;
memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
mutex_init(&child->perf_event_mutex);
INIT_LIST_HEAD(&child->perf_event_list);
for_each_task_context_nr(ctxn) {
ret = perf_event_init_context(child, ctxn);
if (ret) {
perf_event_free_task(child);
return ret;
}
}
return 0;
}
static void __init perf_event_init_all_cpus(void)
{
struct swevent_htable *swhash;
int cpu;
for_each_possible_cpu(cpu) {
swhash = &per_cpu(swevent_htable, cpu);
mutex_init(&swhash->hlist_mutex);
INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
}
}
static void perf_event_init_cpu(int cpu)
{
struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
mutex_lock(&swhash->hlist_mutex);
if (swhash->hlist_refcount > 0) {
struct swevent_hlist *hlist;
hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
WARN_ON(!hlist);
rcu_assign_pointer(swhash->swevent_hlist, hlist);
}
mutex_unlock(&swhash->hlist_mutex);
}
#if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
static void __perf_event_exit_context(void *__info)
{
struct remove_event re = { .detach_group = true };
struct perf_event_context *ctx = __info;
rcu_read_lock();
list_for_each_entry_rcu(re.event, &ctx->event_list, event_entry)
__perf_remove_from_context(&re);
rcu_read_unlock();
}
static void perf_event_exit_cpu_context(int cpu)
{
struct perf_event_context *ctx;
struct pmu *pmu;
int idx;
idx = srcu_read_lock(&pmus_srcu);
list_for_each_entry_rcu(pmu, &pmus, entry) {
ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
mutex_lock(&ctx->mutex);
smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
mutex_unlock(&ctx->mutex);
}
srcu_read_unlock(&pmus_srcu, idx);
}
static void perf_event_exit_cpu(int cpu)
{
perf_event_exit_cpu_context(cpu);
}
#else
static inline void perf_event_exit_cpu(int cpu) { }
#endif
static int
perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
{
int cpu;
for_each_online_cpu(cpu)
perf_event_exit_cpu(cpu);
return NOTIFY_OK;
}
/*
* Run the perf reboot notifier at the very last possible moment so that
* the generic watchdog code runs as long as possible.
*/
static struct notifier_block perf_reboot_notifier = {
.notifier_call = perf_reboot,
.priority = INT_MIN,
};
static int
perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
{
unsigned int cpu = (long)hcpu;
switch (action & ~CPU_TASKS_FROZEN) {
case CPU_UP_PREPARE:
case CPU_DOWN_FAILED:
perf_event_init_cpu(cpu);
break;
case CPU_UP_CANCELED:
case CPU_DOWN_PREPARE:
perf_event_exit_cpu(cpu);
break;
default:
break;
}
return NOTIFY_OK;
}
void __init perf_event_init(void)
{
int ret;
idr_init(&pmu_idr);
perf_event_init_all_cpus();
init_srcu_struct(&pmus_srcu);
perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
perf_pmu_register(&perf_cpu_clock, NULL, -1);
perf_pmu_register(&perf_task_clock, NULL, -1);
perf_tp_register();
perf_cpu_notifier(perf_cpu_notify);
register_reboot_notifier(&perf_reboot_notifier);
ret = init_hw_breakpoint();
WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
/* do not patch jump label more than once per second */
jump_label_rate_limit(&perf_sched_events, HZ);
/*
* Build time assertion that we keep the data_head at the intended
* location. IOW, validation we got the __reserved[] size right.
*/
BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
!= 1024);
}
ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
char *page)
{
struct perf_pmu_events_attr *pmu_attr =
container_of(attr, struct perf_pmu_events_attr, attr);
if (pmu_attr->event_str)
return sprintf(page, "%s\n", pmu_attr->event_str);
return 0;
}
static int __init perf_event_sysfs_init(void)
{
struct pmu *pmu;
int ret;
mutex_lock(&pmus_lock);
ret = bus_register(&pmu_bus);
if (ret)
goto unlock;
list_for_each_entry(pmu, &pmus, entry) {
if (!pmu->name || pmu->type < 0)
continue;
ret = pmu_dev_alloc(pmu);
WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
}
pmu_bus_running = 1;
ret = 0;
unlock:
mutex_unlock(&pmus_lock);
return ret;
}
device_initcall(perf_event_sysfs_init);
#ifdef CONFIG_CGROUP_PERF
static struct cgroup_subsys_state *
perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
{
struct perf_cgroup *jc;
jc = kzalloc(sizeof(*jc), GFP_KERNEL);
if (!jc)
return ERR_PTR(-ENOMEM);
jc->info = alloc_percpu(struct perf_cgroup_info);
if (!jc->info) {
kfree(jc);
return ERR_PTR(-ENOMEM);
}
return &jc->css;
}
static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
{
struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
free_percpu(jc->info);
kfree(jc);
}
static int __perf_cgroup_move(void *info)
{
struct task_struct *task = info;
rcu_read_lock();
perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
rcu_read_unlock();
return 0;
}
static void perf_cgroup_attach(struct cgroup_subsys_state *css,
struct cgroup_taskset *tset)
{
struct task_struct *task;
cgroup_taskset_for_each(task, tset)
task_function_call(task, __perf_cgroup_move, task);
}
struct cgroup_subsys perf_event_cgrp_subsys = {
.css_alloc = perf_cgroup_css_alloc,
.css_free = perf_cgroup_css_free,
.attach = perf_cgroup_attach,
};
#endif /* CONFIG_CGROUP_PERF */
| ./CrossVul/dataset_final_sorted/CWE-416/c/good_1859_0 |
crossvul-cpp_data_good_832_2 | // SPDX-License-Identifier: GPL-2.0+
#include <linux/io.h>
#include "ipmi_si.h"
static unsigned char port_inb(const struct si_sm_io *io, unsigned int offset)
{
unsigned int addr = io->addr_data;
return inb(addr + (offset * io->regspacing));
}
static void port_outb(const struct si_sm_io *io, unsigned int offset,
unsigned char b)
{
unsigned int addr = io->addr_data;
outb(b, addr + (offset * io->regspacing));
}
static unsigned char port_inw(const struct si_sm_io *io, unsigned int offset)
{
unsigned int addr = io->addr_data;
return (inw(addr + (offset * io->regspacing)) >> io->regshift) & 0xff;
}
static void port_outw(const struct si_sm_io *io, unsigned int offset,
unsigned char b)
{
unsigned int addr = io->addr_data;
outw(b << io->regshift, addr + (offset * io->regspacing));
}
static unsigned char port_inl(const struct si_sm_io *io, unsigned int offset)
{
unsigned int addr = io->addr_data;
return (inl(addr + (offset * io->regspacing)) >> io->regshift) & 0xff;
}
static void port_outl(const struct si_sm_io *io, unsigned int offset,
unsigned char b)
{
unsigned int addr = io->addr_data;
outl(b << io->regshift, addr+(offset * io->regspacing));
}
static void port_cleanup(struct si_sm_io *io)
{
unsigned int addr = io->addr_data;
int idx;
if (addr) {
for (idx = 0; idx < io->io_size; idx++)
release_region(addr + idx * io->regspacing,
io->regsize);
}
}
int ipmi_si_port_setup(struct si_sm_io *io)
{
unsigned int addr = io->addr_data;
int idx;
if (!addr)
return -ENODEV;
/*
* Figure out the actual inb/inw/inl/etc routine to use based
* upon the register size.
*/
switch (io->regsize) {
case 1:
io->inputb = port_inb;
io->outputb = port_outb;
break;
case 2:
io->inputb = port_inw;
io->outputb = port_outw;
break;
case 4:
io->inputb = port_inl;
io->outputb = port_outl;
break;
default:
dev_warn(io->dev, "Invalid register size: %d\n",
io->regsize);
return -EINVAL;
}
/*
* Some BIOSes reserve disjoint I/O regions in their ACPI
* tables. This causes problems when trying to register the
* entire I/O region. Therefore we must register each I/O
* port separately.
*/
for (idx = 0; idx < io->io_size; idx++) {
if (request_region(addr + idx * io->regspacing,
io->regsize, DEVICE_NAME) == NULL) {
/* Undo allocations */
while (idx--)
release_region(addr + idx * io->regspacing,
io->regsize);
return -EIO;
}
}
io->io_cleanup = port_cleanup;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-416/c/good_832_2 |
crossvul-cpp_data_good_3348_6 | /*
Copyright (c) 2014. The YARA Authors. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <string.h>
#include <yara/mem.h>
#include <yara/sizedstr.h>
int sized_string_cmp(
SIZED_STRING* s1,
SIZED_STRING* s2)
{
size_t i = 0;
while (s1->length > i &&
s2->length > i &&
s1->c_string[i] == s2->c_string[i])
{
i++;
}
if (i == s1->length && i == s2->length)
return 0;
else if (i == s1->length)
return -1;
else if (i == s2->length)
return 1;
else if (s1->c_string[i] < s2->c_string[i])
return -1;
else
return 1;
}
SIZED_STRING* sized_string_dup(
SIZED_STRING* s)
{
SIZED_STRING* result = (SIZED_STRING*) yr_malloc(
sizeof(SIZED_STRING) + s->length);
if (result == NULL)
return NULL;
result->length = s->length;
result->flags = s->flags;
strncpy(result->c_string, s->c_string, s->length + 1);
return result;
}
| ./CrossVul/dataset_final_sorted/CWE-416/c/good_3348_6 |
crossvul-cpp_data_bad_1316_0 | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* Timers abstract layer
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*/
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/time.h>
#include <linux/mutex.h>
#include <linux/device.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/sched/signal.h>
#include <sound/core.h>
#include <sound/timer.h>
#include <sound/control.h>
#include <sound/info.h>
#include <sound/minors.h>
#include <sound/initval.h>
#include <linux/kmod.h>
/* internal flags */
#define SNDRV_TIMER_IFLG_PAUSED 0x00010000
#define SNDRV_TIMER_IFLG_DEAD 0x00020000
#if IS_ENABLED(CONFIG_SND_HRTIMER)
#define DEFAULT_TIMER_LIMIT 4
#else
#define DEFAULT_TIMER_LIMIT 1
#endif
static int timer_limit = DEFAULT_TIMER_LIMIT;
static int timer_tstamp_monotonic = 1;
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>, Takashi Iwai <tiwai@suse.de>");
MODULE_DESCRIPTION("ALSA timer interface");
MODULE_LICENSE("GPL");
module_param(timer_limit, int, 0444);
MODULE_PARM_DESC(timer_limit, "Maximum global timers in system.");
module_param(timer_tstamp_monotonic, int, 0444);
MODULE_PARM_DESC(timer_tstamp_monotonic, "Use posix monotonic clock source for timestamps (default).");
MODULE_ALIAS_CHARDEV(CONFIG_SND_MAJOR, SNDRV_MINOR_TIMER);
MODULE_ALIAS("devname:snd/timer");
struct snd_timer_user {
struct snd_timer_instance *timeri;
int tread; /* enhanced read with timestamps and events */
unsigned long ticks;
unsigned long overrun;
int qhead;
int qtail;
int qused;
int queue_size;
bool disconnected;
struct snd_timer_read *queue;
struct snd_timer_tread *tqueue;
spinlock_t qlock;
unsigned long last_resolution;
unsigned int filter;
struct timespec tstamp; /* trigger tstamp */
wait_queue_head_t qchange_sleep;
struct fasync_struct *fasync;
struct mutex ioctl_lock;
};
/* list of timers */
static LIST_HEAD(snd_timer_list);
/* list of slave instances */
static LIST_HEAD(snd_timer_slave_list);
/* lock for slave active lists */
static DEFINE_SPINLOCK(slave_active_lock);
static DEFINE_MUTEX(register_mutex);
static int snd_timer_free(struct snd_timer *timer);
static int snd_timer_dev_free(struct snd_device *device);
static int snd_timer_dev_register(struct snd_device *device);
static int snd_timer_dev_disconnect(struct snd_device *device);
static void snd_timer_reschedule(struct snd_timer * timer, unsigned long ticks_left);
/*
* create a timer instance with the given owner string.
* when timer is not NULL, increments the module counter
*/
static struct snd_timer_instance *snd_timer_instance_new(char *owner,
struct snd_timer *timer)
{
struct snd_timer_instance *timeri;
timeri = kzalloc(sizeof(*timeri), GFP_KERNEL);
if (timeri == NULL)
return NULL;
timeri->owner = kstrdup(owner, GFP_KERNEL);
if (! timeri->owner) {
kfree(timeri);
return NULL;
}
INIT_LIST_HEAD(&timeri->open_list);
INIT_LIST_HEAD(&timeri->active_list);
INIT_LIST_HEAD(&timeri->ack_list);
INIT_LIST_HEAD(&timeri->slave_list_head);
INIT_LIST_HEAD(&timeri->slave_active_head);
timeri->timer = timer;
if (timer && !try_module_get(timer->module)) {
kfree(timeri->owner);
kfree(timeri);
return NULL;
}
return timeri;
}
/*
* find a timer instance from the given timer id
*/
static struct snd_timer *snd_timer_find(struct snd_timer_id *tid)
{
struct snd_timer *timer = NULL;
list_for_each_entry(timer, &snd_timer_list, device_list) {
if (timer->tmr_class != tid->dev_class)
continue;
if ((timer->tmr_class == SNDRV_TIMER_CLASS_CARD ||
timer->tmr_class == SNDRV_TIMER_CLASS_PCM) &&
(timer->card == NULL ||
timer->card->number != tid->card))
continue;
if (timer->tmr_device != tid->device)
continue;
if (timer->tmr_subdevice != tid->subdevice)
continue;
return timer;
}
return NULL;
}
#ifdef CONFIG_MODULES
static void snd_timer_request(struct snd_timer_id *tid)
{
switch (tid->dev_class) {
case SNDRV_TIMER_CLASS_GLOBAL:
if (tid->device < timer_limit)
request_module("snd-timer-%i", tid->device);
break;
case SNDRV_TIMER_CLASS_CARD:
case SNDRV_TIMER_CLASS_PCM:
if (tid->card < snd_ecards_limit)
request_module("snd-card-%i", tid->card);
break;
default:
break;
}
}
#endif
/*
* look for a master instance matching with the slave id of the given slave.
* when found, relink the open_link of the slave.
*
* call this with register_mutex down.
*/
static int snd_timer_check_slave(struct snd_timer_instance *slave)
{
struct snd_timer *timer;
struct snd_timer_instance *master;
/* FIXME: it's really dumb to look up all entries.. */
list_for_each_entry(timer, &snd_timer_list, device_list) {
list_for_each_entry(master, &timer->open_list_head, open_list) {
if (slave->slave_class == master->slave_class &&
slave->slave_id == master->slave_id) {
if (master->timer->num_instances >=
master->timer->max_instances)
return -EBUSY;
list_move_tail(&slave->open_list,
&master->slave_list_head);
master->timer->num_instances++;
spin_lock_irq(&slave_active_lock);
slave->master = master;
slave->timer = master->timer;
spin_unlock_irq(&slave_active_lock);
return 0;
}
}
}
return 0;
}
/*
* look for slave instances matching with the slave id of the given master.
* when found, relink the open_link of slaves.
*
* call this with register_mutex down.
*/
static int snd_timer_check_master(struct snd_timer_instance *master)
{
struct snd_timer_instance *slave, *tmp;
/* check all pending slaves */
list_for_each_entry_safe(slave, tmp, &snd_timer_slave_list, open_list) {
if (slave->slave_class == master->slave_class &&
slave->slave_id == master->slave_id) {
if (master->timer->num_instances >=
master->timer->max_instances)
return -EBUSY;
list_move_tail(&slave->open_list, &master->slave_list_head);
master->timer->num_instances++;
spin_lock_irq(&slave_active_lock);
spin_lock(&master->timer->lock);
slave->master = master;
slave->timer = master->timer;
if (slave->flags & SNDRV_TIMER_IFLG_RUNNING)
list_add_tail(&slave->active_list,
&master->slave_active_head);
spin_unlock(&master->timer->lock);
spin_unlock_irq(&slave_active_lock);
}
}
return 0;
}
static int snd_timer_close_locked(struct snd_timer_instance *timeri,
struct device **card_devp_to_put);
/*
* open a timer instance
* when opening a master, the slave id must be here given.
*/
int snd_timer_open(struct snd_timer_instance **ti,
char *owner, struct snd_timer_id *tid,
unsigned int slave_id)
{
struct snd_timer *timer;
struct snd_timer_instance *timeri = NULL;
struct device *card_dev_to_put = NULL;
int err;
mutex_lock(®ister_mutex);
if (tid->dev_class == SNDRV_TIMER_CLASS_SLAVE) {
/* open a slave instance */
if (tid->dev_sclass <= SNDRV_TIMER_SCLASS_NONE ||
tid->dev_sclass > SNDRV_TIMER_SCLASS_OSS_SEQUENCER) {
pr_debug("ALSA: timer: invalid slave class %i\n",
tid->dev_sclass);
err = -EINVAL;
goto unlock;
}
timeri = snd_timer_instance_new(owner, NULL);
if (!timeri) {
err = -ENOMEM;
goto unlock;
}
timeri->slave_class = tid->dev_sclass;
timeri->slave_id = tid->device;
timeri->flags |= SNDRV_TIMER_IFLG_SLAVE;
list_add_tail(&timeri->open_list, &snd_timer_slave_list);
err = snd_timer_check_slave(timeri);
if (err < 0) {
snd_timer_close_locked(timeri, &card_dev_to_put);
timeri = NULL;
}
goto unlock;
}
/* open a master instance */
timer = snd_timer_find(tid);
#ifdef CONFIG_MODULES
if (!timer) {
mutex_unlock(®ister_mutex);
snd_timer_request(tid);
mutex_lock(®ister_mutex);
timer = snd_timer_find(tid);
}
#endif
if (!timer) {
err = -ENODEV;
goto unlock;
}
if (!list_empty(&timer->open_list_head)) {
timeri = list_entry(timer->open_list_head.next,
struct snd_timer_instance, open_list);
if (timeri->flags & SNDRV_TIMER_IFLG_EXCLUSIVE) {
err = -EBUSY;
timeri = NULL;
goto unlock;
}
}
if (timer->num_instances >= timer->max_instances) {
err = -EBUSY;
goto unlock;
}
timeri = snd_timer_instance_new(owner, timer);
if (!timeri) {
err = -ENOMEM;
goto unlock;
}
/* take a card refcount for safe disconnection */
if (timer->card)
get_device(&timer->card->card_dev);
timeri->slave_class = tid->dev_sclass;
timeri->slave_id = slave_id;
if (list_empty(&timer->open_list_head) && timer->hw.open) {
err = timer->hw.open(timer);
if (err) {
kfree(timeri->owner);
kfree(timeri);
timeri = NULL;
if (timer->card)
card_dev_to_put = &timer->card->card_dev;
module_put(timer->module);
goto unlock;
}
}
list_add_tail(&timeri->open_list, &timer->open_list_head);
timer->num_instances++;
err = snd_timer_check_master(timeri);
if (err < 0) {
snd_timer_close_locked(timeri, &card_dev_to_put);
timeri = NULL;
}
unlock:
mutex_unlock(®ister_mutex);
/* put_device() is called after unlock for avoiding deadlock */
if (card_dev_to_put)
put_device(card_dev_to_put);
*ti = timeri;
return err;
}
EXPORT_SYMBOL(snd_timer_open);
/*
* close a timer instance
* call this with register_mutex down.
*/
static int snd_timer_close_locked(struct snd_timer_instance *timeri,
struct device **card_devp_to_put)
{
struct snd_timer *timer = timeri->timer;
struct snd_timer_instance *slave, *tmp;
if (timer) {
spin_lock_irq(&timer->lock);
timeri->flags |= SNDRV_TIMER_IFLG_DEAD;
spin_unlock_irq(&timer->lock);
}
list_del(&timeri->open_list);
/* force to stop the timer */
snd_timer_stop(timeri);
if (timer) {
timer->num_instances--;
/* wait, until the active callback is finished */
spin_lock_irq(&timer->lock);
while (timeri->flags & SNDRV_TIMER_IFLG_CALLBACK) {
spin_unlock_irq(&timer->lock);
udelay(10);
spin_lock_irq(&timer->lock);
}
spin_unlock_irq(&timer->lock);
/* remove slave links */
spin_lock_irq(&slave_active_lock);
spin_lock(&timer->lock);
list_for_each_entry_safe(slave, tmp, &timeri->slave_list_head,
open_list) {
list_move_tail(&slave->open_list, &snd_timer_slave_list);
timer->num_instances--;
slave->master = NULL;
slave->timer = NULL;
list_del_init(&slave->ack_list);
list_del_init(&slave->active_list);
}
spin_unlock(&timer->lock);
spin_unlock_irq(&slave_active_lock);
/* slave doesn't need to release timer resources below */
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
timer = NULL;
}
if (timeri->private_free)
timeri->private_free(timeri);
kfree(timeri->owner);
kfree(timeri);
if (timer) {
if (list_empty(&timer->open_list_head) && timer->hw.close)
timer->hw.close(timer);
/* release a card refcount for safe disconnection */
if (timer->card)
*card_devp_to_put = &timer->card->card_dev;
module_put(timer->module);
}
return 0;
}
/*
* close a timer instance
*/
int snd_timer_close(struct snd_timer_instance *timeri)
{
struct device *card_dev_to_put = NULL;
int err;
if (snd_BUG_ON(!timeri))
return -ENXIO;
mutex_lock(®ister_mutex);
err = snd_timer_close_locked(timeri, &card_dev_to_put);
mutex_unlock(®ister_mutex);
/* put_device() is called after unlock for avoiding deadlock */
if (card_dev_to_put)
put_device(card_dev_to_put);
return err;
}
EXPORT_SYMBOL(snd_timer_close);
static unsigned long snd_timer_hw_resolution(struct snd_timer *timer)
{
if (timer->hw.c_resolution)
return timer->hw.c_resolution(timer);
else
return timer->hw.resolution;
}
unsigned long snd_timer_resolution(struct snd_timer_instance *timeri)
{
struct snd_timer * timer;
unsigned long ret = 0;
unsigned long flags;
if (timeri == NULL)
return 0;
timer = timeri->timer;
if (timer) {
spin_lock_irqsave(&timer->lock, flags);
ret = snd_timer_hw_resolution(timer);
spin_unlock_irqrestore(&timer->lock, flags);
}
return ret;
}
EXPORT_SYMBOL(snd_timer_resolution);
static void snd_timer_notify1(struct snd_timer_instance *ti, int event)
{
struct snd_timer *timer = ti->timer;
unsigned long resolution = 0;
struct snd_timer_instance *ts;
struct timespec tstamp;
if (timer_tstamp_monotonic)
ktime_get_ts(&tstamp);
else
getnstimeofday(&tstamp);
if (snd_BUG_ON(event < SNDRV_TIMER_EVENT_START ||
event > SNDRV_TIMER_EVENT_PAUSE))
return;
if (timer &&
(event == SNDRV_TIMER_EVENT_START ||
event == SNDRV_TIMER_EVENT_CONTINUE))
resolution = snd_timer_hw_resolution(timer);
if (ti->ccallback)
ti->ccallback(ti, event, &tstamp, resolution);
if (ti->flags & SNDRV_TIMER_IFLG_SLAVE)
return;
if (timer == NULL)
return;
if (timer->hw.flags & SNDRV_TIMER_HW_SLAVE)
return;
list_for_each_entry(ts, &ti->slave_active_head, active_list)
if (ts->ccallback)
ts->ccallback(ts, event + 100, &tstamp, resolution);
}
/* start/continue a master timer */
static int snd_timer_start1(struct snd_timer_instance *timeri,
bool start, unsigned long ticks)
{
struct snd_timer *timer;
int result;
unsigned long flags;
timer = timeri->timer;
if (!timer)
return -EINVAL;
spin_lock_irqsave(&timer->lock, flags);
if (timeri->flags & SNDRV_TIMER_IFLG_DEAD) {
result = -EINVAL;
goto unlock;
}
if (timer->card && timer->card->shutdown) {
result = -ENODEV;
goto unlock;
}
if (timeri->flags & (SNDRV_TIMER_IFLG_RUNNING |
SNDRV_TIMER_IFLG_START)) {
result = -EBUSY;
goto unlock;
}
if (start)
timeri->ticks = timeri->cticks = ticks;
else if (!timeri->cticks)
timeri->cticks = 1;
timeri->pticks = 0;
list_move_tail(&timeri->active_list, &timer->active_list_head);
if (timer->running) {
if (timer->hw.flags & SNDRV_TIMER_HW_SLAVE)
goto __start_now;
timer->flags |= SNDRV_TIMER_FLG_RESCHED;
timeri->flags |= SNDRV_TIMER_IFLG_START;
result = 1; /* delayed start */
} else {
if (start)
timer->sticks = ticks;
timer->hw.start(timer);
__start_now:
timer->running++;
timeri->flags |= SNDRV_TIMER_IFLG_RUNNING;
result = 0;
}
snd_timer_notify1(timeri, start ? SNDRV_TIMER_EVENT_START :
SNDRV_TIMER_EVENT_CONTINUE);
unlock:
spin_unlock_irqrestore(&timer->lock, flags);
return result;
}
/* start/continue a slave timer */
static int snd_timer_start_slave(struct snd_timer_instance *timeri,
bool start)
{
unsigned long flags;
int err;
spin_lock_irqsave(&slave_active_lock, flags);
if (timeri->flags & SNDRV_TIMER_IFLG_DEAD) {
err = -EINVAL;
goto unlock;
}
if (timeri->flags & SNDRV_TIMER_IFLG_RUNNING) {
err = -EBUSY;
goto unlock;
}
timeri->flags |= SNDRV_TIMER_IFLG_RUNNING;
if (timeri->master && timeri->timer) {
spin_lock(&timeri->timer->lock);
list_add_tail(&timeri->active_list,
&timeri->master->slave_active_head);
snd_timer_notify1(timeri, start ? SNDRV_TIMER_EVENT_START :
SNDRV_TIMER_EVENT_CONTINUE);
spin_unlock(&timeri->timer->lock);
}
err = 1; /* delayed start */
unlock:
spin_unlock_irqrestore(&slave_active_lock, flags);
return err;
}
/* stop/pause a master timer */
static int snd_timer_stop1(struct snd_timer_instance *timeri, bool stop)
{
struct snd_timer *timer;
int result = 0;
unsigned long flags;
timer = timeri->timer;
if (!timer)
return -EINVAL;
spin_lock_irqsave(&timer->lock, flags);
if (!(timeri->flags & (SNDRV_TIMER_IFLG_RUNNING |
SNDRV_TIMER_IFLG_START))) {
result = -EBUSY;
goto unlock;
}
list_del_init(&timeri->ack_list);
list_del_init(&timeri->active_list);
if (timer->card && timer->card->shutdown)
goto unlock;
if (stop) {
timeri->cticks = timeri->ticks;
timeri->pticks = 0;
}
if ((timeri->flags & SNDRV_TIMER_IFLG_RUNNING) &&
!(--timer->running)) {
timer->hw.stop(timer);
if (timer->flags & SNDRV_TIMER_FLG_RESCHED) {
timer->flags &= ~SNDRV_TIMER_FLG_RESCHED;
snd_timer_reschedule(timer, 0);
if (timer->flags & SNDRV_TIMER_FLG_CHANGE) {
timer->flags &= ~SNDRV_TIMER_FLG_CHANGE;
timer->hw.start(timer);
}
}
}
timeri->flags &= ~(SNDRV_TIMER_IFLG_RUNNING | SNDRV_TIMER_IFLG_START);
if (stop)
timeri->flags &= ~SNDRV_TIMER_IFLG_PAUSED;
else
timeri->flags |= SNDRV_TIMER_IFLG_PAUSED;
snd_timer_notify1(timeri, stop ? SNDRV_TIMER_EVENT_STOP :
SNDRV_TIMER_EVENT_PAUSE);
unlock:
spin_unlock_irqrestore(&timer->lock, flags);
return result;
}
/* stop/pause a slave timer */
static int snd_timer_stop_slave(struct snd_timer_instance *timeri, bool stop)
{
unsigned long flags;
spin_lock_irqsave(&slave_active_lock, flags);
if (!(timeri->flags & SNDRV_TIMER_IFLG_RUNNING)) {
spin_unlock_irqrestore(&slave_active_lock, flags);
return -EBUSY;
}
timeri->flags &= ~SNDRV_TIMER_IFLG_RUNNING;
if (timeri->timer) {
spin_lock(&timeri->timer->lock);
list_del_init(&timeri->ack_list);
list_del_init(&timeri->active_list);
snd_timer_notify1(timeri, stop ? SNDRV_TIMER_EVENT_STOP :
SNDRV_TIMER_EVENT_PAUSE);
spin_unlock(&timeri->timer->lock);
}
spin_unlock_irqrestore(&slave_active_lock, flags);
return 0;
}
/*
* start the timer instance
*/
int snd_timer_start(struct snd_timer_instance *timeri, unsigned int ticks)
{
if (timeri == NULL || ticks < 1)
return -EINVAL;
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
return snd_timer_start_slave(timeri, true);
else
return snd_timer_start1(timeri, true, ticks);
}
EXPORT_SYMBOL(snd_timer_start);
/*
* stop the timer instance.
*
* do not call this from the timer callback!
*/
int snd_timer_stop(struct snd_timer_instance *timeri)
{
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
return snd_timer_stop_slave(timeri, true);
else
return snd_timer_stop1(timeri, true);
}
EXPORT_SYMBOL(snd_timer_stop);
/*
* start again.. the tick is kept.
*/
int snd_timer_continue(struct snd_timer_instance *timeri)
{
/* timer can continue only after pause */
if (!(timeri->flags & SNDRV_TIMER_IFLG_PAUSED))
return -EINVAL;
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
return snd_timer_start_slave(timeri, false);
else
return snd_timer_start1(timeri, false, 0);
}
EXPORT_SYMBOL(snd_timer_continue);
/*
* pause.. remember the ticks left
*/
int snd_timer_pause(struct snd_timer_instance * timeri)
{
if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
return snd_timer_stop_slave(timeri, false);
else
return snd_timer_stop1(timeri, false);
}
EXPORT_SYMBOL(snd_timer_pause);
/*
* reschedule the timer
*
* start pending instances and check the scheduling ticks.
* when the scheduling ticks is changed set CHANGE flag to reprogram the timer.
*/
static void snd_timer_reschedule(struct snd_timer * timer, unsigned long ticks_left)
{
struct snd_timer_instance *ti;
unsigned long ticks = ~0UL;
list_for_each_entry(ti, &timer->active_list_head, active_list) {
if (ti->flags & SNDRV_TIMER_IFLG_START) {
ti->flags &= ~SNDRV_TIMER_IFLG_START;
ti->flags |= SNDRV_TIMER_IFLG_RUNNING;
timer->running++;
}
if (ti->flags & SNDRV_TIMER_IFLG_RUNNING) {
if (ticks > ti->cticks)
ticks = ti->cticks;
}
}
if (ticks == ~0UL) {
timer->flags &= ~SNDRV_TIMER_FLG_RESCHED;
return;
}
if (ticks > timer->hw.ticks)
ticks = timer->hw.ticks;
if (ticks_left != ticks)
timer->flags |= SNDRV_TIMER_FLG_CHANGE;
timer->sticks = ticks;
}
/* call callbacks in timer ack list */
static void snd_timer_process_callbacks(struct snd_timer *timer,
struct list_head *head)
{
struct snd_timer_instance *ti;
unsigned long resolution, ticks;
while (!list_empty(head)) {
ti = list_first_entry(head, struct snd_timer_instance,
ack_list);
/* remove from ack_list and make empty */
list_del_init(&ti->ack_list);
if (!(ti->flags & SNDRV_TIMER_IFLG_DEAD)) {
ticks = ti->pticks;
ti->pticks = 0;
resolution = ti->resolution;
ti->flags |= SNDRV_TIMER_IFLG_CALLBACK;
spin_unlock(&timer->lock);
if (ti->callback)
ti->callback(ti, resolution, ticks);
spin_lock(&timer->lock);
ti->flags &= ~SNDRV_TIMER_IFLG_CALLBACK;
}
}
}
/* clear pending instances from ack list */
static void snd_timer_clear_callbacks(struct snd_timer *timer,
struct list_head *head)
{
unsigned long flags;
spin_lock_irqsave(&timer->lock, flags);
while (!list_empty(head))
list_del_init(head->next);
spin_unlock_irqrestore(&timer->lock, flags);
}
/*
* timer tasklet
*
*/
static void snd_timer_tasklet(unsigned long arg)
{
struct snd_timer *timer = (struct snd_timer *) arg;
unsigned long flags;
if (timer->card && timer->card->shutdown) {
snd_timer_clear_callbacks(timer, &timer->sack_list_head);
return;
}
spin_lock_irqsave(&timer->lock, flags);
snd_timer_process_callbacks(timer, &timer->sack_list_head);
spin_unlock_irqrestore(&timer->lock, flags);
}
/*
* timer interrupt
*
* ticks_left is usually equal to timer->sticks.
*
*/
void snd_timer_interrupt(struct snd_timer * timer, unsigned long ticks_left)
{
struct snd_timer_instance *ti, *ts, *tmp;
unsigned long resolution;
struct list_head *ack_list_head;
unsigned long flags;
int use_tasklet = 0;
if (timer == NULL)
return;
if (timer->card && timer->card->shutdown) {
snd_timer_clear_callbacks(timer, &timer->ack_list_head);
return;
}
spin_lock_irqsave(&timer->lock, flags);
/* remember the current resolution */
resolution = snd_timer_hw_resolution(timer);
/* loop for all active instances
* Here we cannot use list_for_each_entry because the active_list of a
* processed instance is relinked to done_list_head before the callback
* is called.
*/
list_for_each_entry_safe(ti, tmp, &timer->active_list_head,
active_list) {
if (ti->flags & SNDRV_TIMER_IFLG_DEAD)
continue;
if (!(ti->flags & SNDRV_TIMER_IFLG_RUNNING))
continue;
ti->pticks += ticks_left;
ti->resolution = resolution;
if (ti->cticks < ticks_left)
ti->cticks = 0;
else
ti->cticks -= ticks_left;
if (ti->cticks) /* not expired */
continue;
if (ti->flags & SNDRV_TIMER_IFLG_AUTO) {
ti->cticks = ti->ticks;
} else {
ti->flags &= ~SNDRV_TIMER_IFLG_RUNNING;
--timer->running;
list_del_init(&ti->active_list);
}
if ((timer->hw.flags & SNDRV_TIMER_HW_TASKLET) ||
(ti->flags & SNDRV_TIMER_IFLG_FAST))
ack_list_head = &timer->ack_list_head;
else
ack_list_head = &timer->sack_list_head;
if (list_empty(&ti->ack_list))
list_add_tail(&ti->ack_list, ack_list_head);
list_for_each_entry(ts, &ti->slave_active_head, active_list) {
ts->pticks = ti->pticks;
ts->resolution = resolution;
if (list_empty(&ts->ack_list))
list_add_tail(&ts->ack_list, ack_list_head);
}
}
if (timer->flags & SNDRV_TIMER_FLG_RESCHED)
snd_timer_reschedule(timer, timer->sticks);
if (timer->running) {
if (timer->hw.flags & SNDRV_TIMER_HW_STOP) {
timer->hw.stop(timer);
timer->flags |= SNDRV_TIMER_FLG_CHANGE;
}
if (!(timer->hw.flags & SNDRV_TIMER_HW_AUTO) ||
(timer->flags & SNDRV_TIMER_FLG_CHANGE)) {
/* restart timer */
timer->flags &= ~SNDRV_TIMER_FLG_CHANGE;
timer->hw.start(timer);
}
} else {
timer->hw.stop(timer);
}
/* now process all fast callbacks */
snd_timer_process_callbacks(timer, &timer->ack_list_head);
/* do we have any slow callbacks? */
use_tasklet = !list_empty(&timer->sack_list_head);
spin_unlock_irqrestore(&timer->lock, flags);
if (use_tasklet)
tasklet_schedule(&timer->task_queue);
}
EXPORT_SYMBOL(snd_timer_interrupt);
/*
*/
int snd_timer_new(struct snd_card *card, char *id, struct snd_timer_id *tid,
struct snd_timer **rtimer)
{
struct snd_timer *timer;
int err;
static struct snd_device_ops ops = {
.dev_free = snd_timer_dev_free,
.dev_register = snd_timer_dev_register,
.dev_disconnect = snd_timer_dev_disconnect,
};
if (snd_BUG_ON(!tid))
return -EINVAL;
if (tid->dev_class == SNDRV_TIMER_CLASS_CARD ||
tid->dev_class == SNDRV_TIMER_CLASS_PCM) {
if (WARN_ON(!card))
return -EINVAL;
}
if (rtimer)
*rtimer = NULL;
timer = kzalloc(sizeof(*timer), GFP_KERNEL);
if (!timer)
return -ENOMEM;
timer->tmr_class = tid->dev_class;
timer->card = card;
timer->tmr_device = tid->device;
timer->tmr_subdevice = tid->subdevice;
if (id)
strlcpy(timer->id, id, sizeof(timer->id));
timer->sticks = 1;
INIT_LIST_HEAD(&timer->device_list);
INIT_LIST_HEAD(&timer->open_list_head);
INIT_LIST_HEAD(&timer->active_list_head);
INIT_LIST_HEAD(&timer->ack_list_head);
INIT_LIST_HEAD(&timer->sack_list_head);
spin_lock_init(&timer->lock);
tasklet_init(&timer->task_queue, snd_timer_tasklet,
(unsigned long)timer);
timer->max_instances = 1000; /* default limit per timer */
if (card != NULL) {
timer->module = card->module;
err = snd_device_new(card, SNDRV_DEV_TIMER, timer, &ops);
if (err < 0) {
snd_timer_free(timer);
return err;
}
}
if (rtimer)
*rtimer = timer;
return 0;
}
EXPORT_SYMBOL(snd_timer_new);
static int snd_timer_free(struct snd_timer *timer)
{
if (!timer)
return 0;
mutex_lock(®ister_mutex);
if (! list_empty(&timer->open_list_head)) {
struct list_head *p, *n;
struct snd_timer_instance *ti;
pr_warn("ALSA: timer %p is busy?\n", timer);
list_for_each_safe(p, n, &timer->open_list_head) {
list_del_init(p);
ti = list_entry(p, struct snd_timer_instance, open_list);
ti->timer = NULL;
}
}
list_del(&timer->device_list);
mutex_unlock(®ister_mutex);
if (timer->private_free)
timer->private_free(timer);
kfree(timer);
return 0;
}
static int snd_timer_dev_free(struct snd_device *device)
{
struct snd_timer *timer = device->device_data;
return snd_timer_free(timer);
}
static int snd_timer_dev_register(struct snd_device *dev)
{
struct snd_timer *timer = dev->device_data;
struct snd_timer *timer1;
if (snd_BUG_ON(!timer || !timer->hw.start || !timer->hw.stop))
return -ENXIO;
if (!(timer->hw.flags & SNDRV_TIMER_HW_SLAVE) &&
!timer->hw.resolution && timer->hw.c_resolution == NULL)
return -EINVAL;
mutex_lock(®ister_mutex);
list_for_each_entry(timer1, &snd_timer_list, device_list) {
if (timer1->tmr_class > timer->tmr_class)
break;
if (timer1->tmr_class < timer->tmr_class)
continue;
if (timer1->card && timer->card) {
if (timer1->card->number > timer->card->number)
break;
if (timer1->card->number < timer->card->number)
continue;
}
if (timer1->tmr_device > timer->tmr_device)
break;
if (timer1->tmr_device < timer->tmr_device)
continue;
if (timer1->tmr_subdevice > timer->tmr_subdevice)
break;
if (timer1->tmr_subdevice < timer->tmr_subdevice)
continue;
/* conflicts.. */
mutex_unlock(®ister_mutex);
return -EBUSY;
}
list_add_tail(&timer->device_list, &timer1->device_list);
mutex_unlock(®ister_mutex);
return 0;
}
static int snd_timer_dev_disconnect(struct snd_device *device)
{
struct snd_timer *timer = device->device_data;
struct snd_timer_instance *ti;
mutex_lock(®ister_mutex);
list_del_init(&timer->device_list);
/* wake up pending sleepers */
list_for_each_entry(ti, &timer->open_list_head, open_list) {
if (ti->disconnect)
ti->disconnect(ti);
}
mutex_unlock(®ister_mutex);
return 0;
}
void snd_timer_notify(struct snd_timer *timer, int event, struct timespec *tstamp)
{
unsigned long flags;
unsigned long resolution = 0;
struct snd_timer_instance *ti, *ts;
if (timer->card && timer->card->shutdown)
return;
if (! (timer->hw.flags & SNDRV_TIMER_HW_SLAVE))
return;
if (snd_BUG_ON(event < SNDRV_TIMER_EVENT_MSTART ||
event > SNDRV_TIMER_EVENT_MRESUME))
return;
spin_lock_irqsave(&timer->lock, flags);
if (event == SNDRV_TIMER_EVENT_MSTART ||
event == SNDRV_TIMER_EVENT_MCONTINUE ||
event == SNDRV_TIMER_EVENT_MRESUME)
resolution = snd_timer_hw_resolution(timer);
list_for_each_entry(ti, &timer->active_list_head, active_list) {
if (ti->ccallback)
ti->ccallback(ti, event, tstamp, resolution);
list_for_each_entry(ts, &ti->slave_active_head, active_list)
if (ts->ccallback)
ts->ccallback(ts, event, tstamp, resolution);
}
spin_unlock_irqrestore(&timer->lock, flags);
}
EXPORT_SYMBOL(snd_timer_notify);
/*
* exported functions for global timers
*/
int snd_timer_global_new(char *id, int device, struct snd_timer **rtimer)
{
struct snd_timer_id tid;
tid.dev_class = SNDRV_TIMER_CLASS_GLOBAL;
tid.dev_sclass = SNDRV_TIMER_SCLASS_NONE;
tid.card = -1;
tid.device = device;
tid.subdevice = 0;
return snd_timer_new(NULL, id, &tid, rtimer);
}
EXPORT_SYMBOL(snd_timer_global_new);
int snd_timer_global_free(struct snd_timer *timer)
{
return snd_timer_free(timer);
}
EXPORT_SYMBOL(snd_timer_global_free);
int snd_timer_global_register(struct snd_timer *timer)
{
struct snd_device dev;
memset(&dev, 0, sizeof(dev));
dev.device_data = timer;
return snd_timer_dev_register(&dev);
}
EXPORT_SYMBOL(snd_timer_global_register);
/*
* System timer
*/
struct snd_timer_system_private {
struct timer_list tlist;
struct snd_timer *snd_timer;
unsigned long last_expires;
unsigned long last_jiffies;
unsigned long correction;
};
static void snd_timer_s_function(struct timer_list *t)
{
struct snd_timer_system_private *priv = from_timer(priv, t,
tlist);
struct snd_timer *timer = priv->snd_timer;
unsigned long jiff = jiffies;
if (time_after(jiff, priv->last_expires))
priv->correction += (long)jiff - (long)priv->last_expires;
snd_timer_interrupt(timer, (long)jiff - (long)priv->last_jiffies);
}
static int snd_timer_s_start(struct snd_timer * timer)
{
struct snd_timer_system_private *priv;
unsigned long njiff;
priv = (struct snd_timer_system_private *) timer->private_data;
njiff = (priv->last_jiffies = jiffies);
if (priv->correction > timer->sticks - 1) {
priv->correction -= timer->sticks - 1;
njiff++;
} else {
njiff += timer->sticks - priv->correction;
priv->correction = 0;
}
priv->last_expires = njiff;
mod_timer(&priv->tlist, njiff);
return 0;
}
static int snd_timer_s_stop(struct snd_timer * timer)
{
struct snd_timer_system_private *priv;
unsigned long jiff;
priv = (struct snd_timer_system_private *) timer->private_data;
del_timer(&priv->tlist);
jiff = jiffies;
if (time_before(jiff, priv->last_expires))
timer->sticks = priv->last_expires - jiff;
else
timer->sticks = 1;
priv->correction = 0;
return 0;
}
static int snd_timer_s_close(struct snd_timer *timer)
{
struct snd_timer_system_private *priv;
priv = (struct snd_timer_system_private *)timer->private_data;
del_timer_sync(&priv->tlist);
return 0;
}
static struct snd_timer_hardware snd_timer_system =
{
.flags = SNDRV_TIMER_HW_FIRST | SNDRV_TIMER_HW_TASKLET,
.resolution = 1000000000L / HZ,
.ticks = 10000000L,
.close = snd_timer_s_close,
.start = snd_timer_s_start,
.stop = snd_timer_s_stop
};
static void snd_timer_free_system(struct snd_timer *timer)
{
kfree(timer->private_data);
}
static int snd_timer_register_system(void)
{
struct snd_timer *timer;
struct snd_timer_system_private *priv;
int err;
err = snd_timer_global_new("system", SNDRV_TIMER_GLOBAL_SYSTEM, &timer);
if (err < 0)
return err;
strcpy(timer->name, "system timer");
timer->hw = snd_timer_system;
priv = kzalloc(sizeof(*priv), GFP_KERNEL);
if (priv == NULL) {
snd_timer_free(timer);
return -ENOMEM;
}
priv->snd_timer = timer;
timer_setup(&priv->tlist, snd_timer_s_function, 0);
timer->private_data = priv;
timer->private_free = snd_timer_free_system;
return snd_timer_global_register(timer);
}
#ifdef CONFIG_SND_PROC_FS
/*
* Info interface
*/
static void snd_timer_proc_read(struct snd_info_entry *entry,
struct snd_info_buffer *buffer)
{
struct snd_timer *timer;
struct snd_timer_instance *ti;
mutex_lock(®ister_mutex);
list_for_each_entry(timer, &snd_timer_list, device_list) {
if (timer->card && timer->card->shutdown)
continue;
switch (timer->tmr_class) {
case SNDRV_TIMER_CLASS_GLOBAL:
snd_iprintf(buffer, "G%i: ", timer->tmr_device);
break;
case SNDRV_TIMER_CLASS_CARD:
snd_iprintf(buffer, "C%i-%i: ",
timer->card->number, timer->tmr_device);
break;
case SNDRV_TIMER_CLASS_PCM:
snd_iprintf(buffer, "P%i-%i-%i: ", timer->card->number,
timer->tmr_device, timer->tmr_subdevice);
break;
default:
snd_iprintf(buffer, "?%i-%i-%i-%i: ", timer->tmr_class,
timer->card ? timer->card->number : -1,
timer->tmr_device, timer->tmr_subdevice);
}
snd_iprintf(buffer, "%s :", timer->name);
if (timer->hw.resolution)
snd_iprintf(buffer, " %lu.%03luus (%lu ticks)",
timer->hw.resolution / 1000,
timer->hw.resolution % 1000,
timer->hw.ticks);
if (timer->hw.flags & SNDRV_TIMER_HW_SLAVE)
snd_iprintf(buffer, " SLAVE");
snd_iprintf(buffer, "\n");
list_for_each_entry(ti, &timer->open_list_head, open_list)
snd_iprintf(buffer, " Client %s : %s\n",
ti->owner ? ti->owner : "unknown",
ti->flags & (SNDRV_TIMER_IFLG_START |
SNDRV_TIMER_IFLG_RUNNING)
? "running" : "stopped");
}
mutex_unlock(®ister_mutex);
}
static struct snd_info_entry *snd_timer_proc_entry;
static void __init snd_timer_proc_init(void)
{
struct snd_info_entry *entry;
entry = snd_info_create_module_entry(THIS_MODULE, "timers", NULL);
if (entry != NULL) {
entry->c.text.read = snd_timer_proc_read;
if (snd_info_register(entry) < 0) {
snd_info_free_entry(entry);
entry = NULL;
}
}
snd_timer_proc_entry = entry;
}
static void __exit snd_timer_proc_done(void)
{
snd_info_free_entry(snd_timer_proc_entry);
}
#else /* !CONFIG_SND_PROC_FS */
#define snd_timer_proc_init()
#define snd_timer_proc_done()
#endif
/*
* USER SPACE interface
*/
static void snd_timer_user_interrupt(struct snd_timer_instance *timeri,
unsigned long resolution,
unsigned long ticks)
{
struct snd_timer_user *tu = timeri->callback_data;
struct snd_timer_read *r;
int prev;
spin_lock(&tu->qlock);
if (tu->qused > 0) {
prev = tu->qtail == 0 ? tu->queue_size - 1 : tu->qtail - 1;
r = &tu->queue[prev];
if (r->resolution == resolution) {
r->ticks += ticks;
goto __wake;
}
}
if (tu->qused >= tu->queue_size) {
tu->overrun++;
} else {
r = &tu->queue[tu->qtail++];
tu->qtail %= tu->queue_size;
r->resolution = resolution;
r->ticks = ticks;
tu->qused++;
}
__wake:
spin_unlock(&tu->qlock);
kill_fasync(&tu->fasync, SIGIO, POLL_IN);
wake_up(&tu->qchange_sleep);
}
static void snd_timer_user_append_to_tqueue(struct snd_timer_user *tu,
struct snd_timer_tread *tread)
{
if (tu->qused >= tu->queue_size) {
tu->overrun++;
} else {
memcpy(&tu->tqueue[tu->qtail++], tread, sizeof(*tread));
tu->qtail %= tu->queue_size;
tu->qused++;
}
}
static void snd_timer_user_ccallback(struct snd_timer_instance *timeri,
int event,
struct timespec *tstamp,
unsigned long resolution)
{
struct snd_timer_user *tu = timeri->callback_data;
struct snd_timer_tread r1;
unsigned long flags;
if (event >= SNDRV_TIMER_EVENT_START &&
event <= SNDRV_TIMER_EVENT_PAUSE)
tu->tstamp = *tstamp;
if ((tu->filter & (1 << event)) == 0 || !tu->tread)
return;
memset(&r1, 0, sizeof(r1));
r1.event = event;
r1.tstamp = *tstamp;
r1.val = resolution;
spin_lock_irqsave(&tu->qlock, flags);
snd_timer_user_append_to_tqueue(tu, &r1);
spin_unlock_irqrestore(&tu->qlock, flags);
kill_fasync(&tu->fasync, SIGIO, POLL_IN);
wake_up(&tu->qchange_sleep);
}
static void snd_timer_user_disconnect(struct snd_timer_instance *timeri)
{
struct snd_timer_user *tu = timeri->callback_data;
tu->disconnected = true;
wake_up(&tu->qchange_sleep);
}
static void snd_timer_user_tinterrupt(struct snd_timer_instance *timeri,
unsigned long resolution,
unsigned long ticks)
{
struct snd_timer_user *tu = timeri->callback_data;
struct snd_timer_tread *r, r1;
struct timespec tstamp;
int prev, append = 0;
memset(&r1, 0, sizeof(r1));
memset(&tstamp, 0, sizeof(tstamp));
spin_lock(&tu->qlock);
if ((tu->filter & ((1 << SNDRV_TIMER_EVENT_RESOLUTION) |
(1 << SNDRV_TIMER_EVENT_TICK))) == 0) {
spin_unlock(&tu->qlock);
return;
}
if (tu->last_resolution != resolution || ticks > 0) {
if (timer_tstamp_monotonic)
ktime_get_ts(&tstamp);
else
getnstimeofday(&tstamp);
}
if ((tu->filter & (1 << SNDRV_TIMER_EVENT_RESOLUTION)) &&
tu->last_resolution != resolution) {
r1.event = SNDRV_TIMER_EVENT_RESOLUTION;
r1.tstamp = tstamp;
r1.val = resolution;
snd_timer_user_append_to_tqueue(tu, &r1);
tu->last_resolution = resolution;
append++;
}
if ((tu->filter & (1 << SNDRV_TIMER_EVENT_TICK)) == 0)
goto __wake;
if (ticks == 0)
goto __wake;
if (tu->qused > 0) {
prev = tu->qtail == 0 ? tu->queue_size - 1 : tu->qtail - 1;
r = &tu->tqueue[prev];
if (r->event == SNDRV_TIMER_EVENT_TICK) {
r->tstamp = tstamp;
r->val += ticks;
append++;
goto __wake;
}
}
r1.event = SNDRV_TIMER_EVENT_TICK;
r1.tstamp = tstamp;
r1.val = ticks;
snd_timer_user_append_to_tqueue(tu, &r1);
append++;
__wake:
spin_unlock(&tu->qlock);
if (append == 0)
return;
kill_fasync(&tu->fasync, SIGIO, POLL_IN);
wake_up(&tu->qchange_sleep);
}
static int realloc_user_queue(struct snd_timer_user *tu, int size)
{
struct snd_timer_read *queue = NULL;
struct snd_timer_tread *tqueue = NULL;
if (tu->tread) {
tqueue = kcalloc(size, sizeof(*tqueue), GFP_KERNEL);
if (!tqueue)
return -ENOMEM;
} else {
queue = kcalloc(size, sizeof(*queue), GFP_KERNEL);
if (!queue)
return -ENOMEM;
}
spin_lock_irq(&tu->qlock);
kfree(tu->queue);
kfree(tu->tqueue);
tu->queue_size = size;
tu->queue = queue;
tu->tqueue = tqueue;
tu->qhead = tu->qtail = tu->qused = 0;
spin_unlock_irq(&tu->qlock);
return 0;
}
static int snd_timer_user_open(struct inode *inode, struct file *file)
{
struct snd_timer_user *tu;
int err;
err = stream_open(inode, file);
if (err < 0)
return err;
tu = kzalloc(sizeof(*tu), GFP_KERNEL);
if (tu == NULL)
return -ENOMEM;
spin_lock_init(&tu->qlock);
init_waitqueue_head(&tu->qchange_sleep);
mutex_init(&tu->ioctl_lock);
tu->ticks = 1;
if (realloc_user_queue(tu, 128) < 0) {
kfree(tu);
return -ENOMEM;
}
file->private_data = tu;
return 0;
}
static int snd_timer_user_release(struct inode *inode, struct file *file)
{
struct snd_timer_user *tu;
if (file->private_data) {
tu = file->private_data;
file->private_data = NULL;
mutex_lock(&tu->ioctl_lock);
if (tu->timeri)
snd_timer_close(tu->timeri);
mutex_unlock(&tu->ioctl_lock);
kfree(tu->queue);
kfree(tu->tqueue);
kfree(tu);
}
return 0;
}
static void snd_timer_user_zero_id(struct snd_timer_id *id)
{
id->dev_class = SNDRV_TIMER_CLASS_NONE;
id->dev_sclass = SNDRV_TIMER_SCLASS_NONE;
id->card = -1;
id->device = -1;
id->subdevice = -1;
}
static void snd_timer_user_copy_id(struct snd_timer_id *id, struct snd_timer *timer)
{
id->dev_class = timer->tmr_class;
id->dev_sclass = SNDRV_TIMER_SCLASS_NONE;
id->card = timer->card ? timer->card->number : -1;
id->device = timer->tmr_device;
id->subdevice = timer->tmr_subdevice;
}
static int snd_timer_user_next_device(struct snd_timer_id __user *_tid)
{
struct snd_timer_id id;
struct snd_timer *timer;
struct list_head *p;
if (copy_from_user(&id, _tid, sizeof(id)))
return -EFAULT;
mutex_lock(®ister_mutex);
if (id.dev_class < 0) { /* first item */
if (list_empty(&snd_timer_list))
snd_timer_user_zero_id(&id);
else {
timer = list_entry(snd_timer_list.next,
struct snd_timer, device_list);
snd_timer_user_copy_id(&id, timer);
}
} else {
switch (id.dev_class) {
case SNDRV_TIMER_CLASS_GLOBAL:
id.device = id.device < 0 ? 0 : id.device + 1;
list_for_each(p, &snd_timer_list) {
timer = list_entry(p, struct snd_timer, device_list);
if (timer->tmr_class > SNDRV_TIMER_CLASS_GLOBAL) {
snd_timer_user_copy_id(&id, timer);
break;
}
if (timer->tmr_device >= id.device) {
snd_timer_user_copy_id(&id, timer);
break;
}
}
if (p == &snd_timer_list)
snd_timer_user_zero_id(&id);
break;
case SNDRV_TIMER_CLASS_CARD:
case SNDRV_TIMER_CLASS_PCM:
if (id.card < 0) {
id.card = 0;
} else {
if (id.device < 0) {
id.device = 0;
} else {
if (id.subdevice < 0)
id.subdevice = 0;
else if (id.subdevice < INT_MAX)
id.subdevice++;
}
}
list_for_each(p, &snd_timer_list) {
timer = list_entry(p, struct snd_timer, device_list);
if (timer->tmr_class > id.dev_class) {
snd_timer_user_copy_id(&id, timer);
break;
}
if (timer->tmr_class < id.dev_class)
continue;
if (timer->card->number > id.card) {
snd_timer_user_copy_id(&id, timer);
break;
}
if (timer->card->number < id.card)
continue;
if (timer->tmr_device > id.device) {
snd_timer_user_copy_id(&id, timer);
break;
}
if (timer->tmr_device < id.device)
continue;
if (timer->tmr_subdevice > id.subdevice) {
snd_timer_user_copy_id(&id, timer);
break;
}
if (timer->tmr_subdevice < id.subdevice)
continue;
snd_timer_user_copy_id(&id, timer);
break;
}
if (p == &snd_timer_list)
snd_timer_user_zero_id(&id);
break;
default:
snd_timer_user_zero_id(&id);
}
}
mutex_unlock(®ister_mutex);
if (copy_to_user(_tid, &id, sizeof(*_tid)))
return -EFAULT;
return 0;
}
static int snd_timer_user_ginfo(struct file *file,
struct snd_timer_ginfo __user *_ginfo)
{
struct snd_timer_ginfo *ginfo;
struct snd_timer_id tid;
struct snd_timer *t;
struct list_head *p;
int err = 0;
ginfo = memdup_user(_ginfo, sizeof(*ginfo));
if (IS_ERR(ginfo))
return PTR_ERR(ginfo);
tid = ginfo->tid;
memset(ginfo, 0, sizeof(*ginfo));
ginfo->tid = tid;
mutex_lock(®ister_mutex);
t = snd_timer_find(&tid);
if (t != NULL) {
ginfo->card = t->card ? t->card->number : -1;
if (t->hw.flags & SNDRV_TIMER_HW_SLAVE)
ginfo->flags |= SNDRV_TIMER_FLG_SLAVE;
strlcpy(ginfo->id, t->id, sizeof(ginfo->id));
strlcpy(ginfo->name, t->name, sizeof(ginfo->name));
ginfo->resolution = t->hw.resolution;
if (t->hw.resolution_min > 0) {
ginfo->resolution_min = t->hw.resolution_min;
ginfo->resolution_max = t->hw.resolution_max;
}
list_for_each(p, &t->open_list_head) {
ginfo->clients++;
}
} else {
err = -ENODEV;
}
mutex_unlock(®ister_mutex);
if (err >= 0 && copy_to_user(_ginfo, ginfo, sizeof(*ginfo)))
err = -EFAULT;
kfree(ginfo);
return err;
}
static int timer_set_gparams(struct snd_timer_gparams *gparams)
{
struct snd_timer *t;
int err;
mutex_lock(®ister_mutex);
t = snd_timer_find(&gparams->tid);
if (!t) {
err = -ENODEV;
goto _error;
}
if (!list_empty(&t->open_list_head)) {
err = -EBUSY;
goto _error;
}
if (!t->hw.set_period) {
err = -ENOSYS;
goto _error;
}
err = t->hw.set_period(t, gparams->period_num, gparams->period_den);
_error:
mutex_unlock(®ister_mutex);
return err;
}
static int snd_timer_user_gparams(struct file *file,
struct snd_timer_gparams __user *_gparams)
{
struct snd_timer_gparams gparams;
if (copy_from_user(&gparams, _gparams, sizeof(gparams)))
return -EFAULT;
return timer_set_gparams(&gparams);
}
static int snd_timer_user_gstatus(struct file *file,
struct snd_timer_gstatus __user *_gstatus)
{
struct snd_timer_gstatus gstatus;
struct snd_timer_id tid;
struct snd_timer *t;
int err = 0;
if (copy_from_user(&gstatus, _gstatus, sizeof(gstatus)))
return -EFAULT;
tid = gstatus.tid;
memset(&gstatus, 0, sizeof(gstatus));
gstatus.tid = tid;
mutex_lock(®ister_mutex);
t = snd_timer_find(&tid);
if (t != NULL) {
spin_lock_irq(&t->lock);
gstatus.resolution = snd_timer_hw_resolution(t);
if (t->hw.precise_resolution) {
t->hw.precise_resolution(t, &gstatus.resolution_num,
&gstatus.resolution_den);
} else {
gstatus.resolution_num = gstatus.resolution;
gstatus.resolution_den = 1000000000uL;
}
spin_unlock_irq(&t->lock);
} else {
err = -ENODEV;
}
mutex_unlock(®ister_mutex);
if (err >= 0 && copy_to_user(_gstatus, &gstatus, sizeof(gstatus)))
err = -EFAULT;
return err;
}
static int snd_timer_user_tselect(struct file *file,
struct snd_timer_select __user *_tselect)
{
struct snd_timer_user *tu;
struct snd_timer_select tselect;
char str[32];
int err = 0;
tu = file->private_data;
if (tu->timeri) {
snd_timer_close(tu->timeri);
tu->timeri = NULL;
}
if (copy_from_user(&tselect, _tselect, sizeof(tselect))) {
err = -EFAULT;
goto __err;
}
sprintf(str, "application %i", current->pid);
if (tselect.id.dev_class != SNDRV_TIMER_CLASS_SLAVE)
tselect.id.dev_sclass = SNDRV_TIMER_SCLASS_APPLICATION;
err = snd_timer_open(&tu->timeri, str, &tselect.id, current->pid);
if (err < 0)
goto __err;
tu->timeri->flags |= SNDRV_TIMER_IFLG_FAST;
tu->timeri->callback = tu->tread
? snd_timer_user_tinterrupt : snd_timer_user_interrupt;
tu->timeri->ccallback = snd_timer_user_ccallback;
tu->timeri->callback_data = (void *)tu;
tu->timeri->disconnect = snd_timer_user_disconnect;
__err:
return err;
}
static int snd_timer_user_info(struct file *file,
struct snd_timer_info __user *_info)
{
struct snd_timer_user *tu;
struct snd_timer_info *info;
struct snd_timer *t;
int err = 0;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
t = tu->timeri->timer;
if (!t)
return -EBADFD;
info = kzalloc(sizeof(*info), GFP_KERNEL);
if (! info)
return -ENOMEM;
info->card = t->card ? t->card->number : -1;
if (t->hw.flags & SNDRV_TIMER_HW_SLAVE)
info->flags |= SNDRV_TIMER_FLG_SLAVE;
strlcpy(info->id, t->id, sizeof(info->id));
strlcpy(info->name, t->name, sizeof(info->name));
info->resolution = t->hw.resolution;
if (copy_to_user(_info, info, sizeof(*_info)))
err = -EFAULT;
kfree(info);
return err;
}
static int snd_timer_user_params(struct file *file,
struct snd_timer_params __user *_params)
{
struct snd_timer_user *tu;
struct snd_timer_params params;
struct snd_timer *t;
int err;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
t = tu->timeri->timer;
if (!t)
return -EBADFD;
if (copy_from_user(¶ms, _params, sizeof(params)))
return -EFAULT;
if (!(t->hw.flags & SNDRV_TIMER_HW_SLAVE)) {
u64 resolution;
if (params.ticks < 1) {
err = -EINVAL;
goto _end;
}
/* Don't allow resolution less than 1ms */
resolution = snd_timer_resolution(tu->timeri);
resolution *= params.ticks;
if (resolution < 1000000) {
err = -EINVAL;
goto _end;
}
}
if (params.queue_size > 0 &&
(params.queue_size < 32 || params.queue_size > 1024)) {
err = -EINVAL;
goto _end;
}
if (params.filter & ~((1<<SNDRV_TIMER_EVENT_RESOLUTION)|
(1<<SNDRV_TIMER_EVENT_TICK)|
(1<<SNDRV_TIMER_EVENT_START)|
(1<<SNDRV_TIMER_EVENT_STOP)|
(1<<SNDRV_TIMER_EVENT_CONTINUE)|
(1<<SNDRV_TIMER_EVENT_PAUSE)|
(1<<SNDRV_TIMER_EVENT_SUSPEND)|
(1<<SNDRV_TIMER_EVENT_RESUME)|
(1<<SNDRV_TIMER_EVENT_MSTART)|
(1<<SNDRV_TIMER_EVENT_MSTOP)|
(1<<SNDRV_TIMER_EVENT_MCONTINUE)|
(1<<SNDRV_TIMER_EVENT_MPAUSE)|
(1<<SNDRV_TIMER_EVENT_MSUSPEND)|
(1<<SNDRV_TIMER_EVENT_MRESUME))) {
err = -EINVAL;
goto _end;
}
snd_timer_stop(tu->timeri);
spin_lock_irq(&t->lock);
tu->timeri->flags &= ~(SNDRV_TIMER_IFLG_AUTO|
SNDRV_TIMER_IFLG_EXCLUSIVE|
SNDRV_TIMER_IFLG_EARLY_EVENT);
if (params.flags & SNDRV_TIMER_PSFLG_AUTO)
tu->timeri->flags |= SNDRV_TIMER_IFLG_AUTO;
if (params.flags & SNDRV_TIMER_PSFLG_EXCLUSIVE)
tu->timeri->flags |= SNDRV_TIMER_IFLG_EXCLUSIVE;
if (params.flags & SNDRV_TIMER_PSFLG_EARLY_EVENT)
tu->timeri->flags |= SNDRV_TIMER_IFLG_EARLY_EVENT;
spin_unlock_irq(&t->lock);
if (params.queue_size > 0 &&
(unsigned int)tu->queue_size != params.queue_size) {
err = realloc_user_queue(tu, params.queue_size);
if (err < 0)
goto _end;
}
spin_lock_irq(&tu->qlock);
tu->qhead = tu->qtail = tu->qused = 0;
if (tu->timeri->flags & SNDRV_TIMER_IFLG_EARLY_EVENT) {
if (tu->tread) {
struct snd_timer_tread tread;
memset(&tread, 0, sizeof(tread));
tread.event = SNDRV_TIMER_EVENT_EARLY;
tread.tstamp.tv_sec = 0;
tread.tstamp.tv_nsec = 0;
tread.val = 0;
snd_timer_user_append_to_tqueue(tu, &tread);
} else {
struct snd_timer_read *r = &tu->queue[0];
r->resolution = 0;
r->ticks = 0;
tu->qused++;
tu->qtail++;
}
}
tu->filter = params.filter;
tu->ticks = params.ticks;
spin_unlock_irq(&tu->qlock);
err = 0;
_end:
if (copy_to_user(_params, ¶ms, sizeof(params)))
return -EFAULT;
return err;
}
static int snd_timer_user_status(struct file *file,
struct snd_timer_status __user *_status)
{
struct snd_timer_user *tu;
struct snd_timer_status status;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
memset(&status, 0, sizeof(status));
status.tstamp = tu->tstamp;
status.resolution = snd_timer_resolution(tu->timeri);
status.lost = tu->timeri->lost;
status.overrun = tu->overrun;
spin_lock_irq(&tu->qlock);
status.queue = tu->qused;
spin_unlock_irq(&tu->qlock);
if (copy_to_user(_status, &status, sizeof(status)))
return -EFAULT;
return 0;
}
static int snd_timer_user_start(struct file *file)
{
int err;
struct snd_timer_user *tu;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
snd_timer_stop(tu->timeri);
tu->timeri->lost = 0;
tu->last_resolution = 0;
err = snd_timer_start(tu->timeri, tu->ticks);
if (err < 0)
return err;
return 0;
}
static int snd_timer_user_stop(struct file *file)
{
int err;
struct snd_timer_user *tu;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
err = snd_timer_stop(tu->timeri);
if (err < 0)
return err;
return 0;
}
static int snd_timer_user_continue(struct file *file)
{
int err;
struct snd_timer_user *tu;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
/* start timer instead of continue if it's not used before */
if (!(tu->timeri->flags & SNDRV_TIMER_IFLG_PAUSED))
return snd_timer_user_start(file);
tu->timeri->lost = 0;
err = snd_timer_continue(tu->timeri);
if (err < 0)
return err;
return 0;
}
static int snd_timer_user_pause(struct file *file)
{
int err;
struct snd_timer_user *tu;
tu = file->private_data;
if (!tu->timeri)
return -EBADFD;
err = snd_timer_pause(tu->timeri);
if (err < 0)
return err;
return 0;
}
enum {
SNDRV_TIMER_IOCTL_START_OLD = _IO('T', 0x20),
SNDRV_TIMER_IOCTL_STOP_OLD = _IO('T', 0x21),
SNDRV_TIMER_IOCTL_CONTINUE_OLD = _IO('T', 0x22),
SNDRV_TIMER_IOCTL_PAUSE_OLD = _IO('T', 0x23),
};
static long __snd_timer_user_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct snd_timer_user *tu;
void __user *argp = (void __user *)arg;
int __user *p = argp;
tu = file->private_data;
switch (cmd) {
case SNDRV_TIMER_IOCTL_PVERSION:
return put_user(SNDRV_TIMER_VERSION, p) ? -EFAULT : 0;
case SNDRV_TIMER_IOCTL_NEXT_DEVICE:
return snd_timer_user_next_device(argp);
case SNDRV_TIMER_IOCTL_TREAD:
{
int xarg, old_tread;
if (tu->timeri) /* too late */
return -EBUSY;
if (get_user(xarg, p))
return -EFAULT;
old_tread = tu->tread;
tu->tread = xarg ? 1 : 0;
if (tu->tread != old_tread &&
realloc_user_queue(tu, tu->queue_size) < 0) {
tu->tread = old_tread;
return -ENOMEM;
}
return 0;
}
case SNDRV_TIMER_IOCTL_GINFO:
return snd_timer_user_ginfo(file, argp);
case SNDRV_TIMER_IOCTL_GPARAMS:
return snd_timer_user_gparams(file, argp);
case SNDRV_TIMER_IOCTL_GSTATUS:
return snd_timer_user_gstatus(file, argp);
case SNDRV_TIMER_IOCTL_SELECT:
return snd_timer_user_tselect(file, argp);
case SNDRV_TIMER_IOCTL_INFO:
return snd_timer_user_info(file, argp);
case SNDRV_TIMER_IOCTL_PARAMS:
return snd_timer_user_params(file, argp);
case SNDRV_TIMER_IOCTL_STATUS:
return snd_timer_user_status(file, argp);
case SNDRV_TIMER_IOCTL_START:
case SNDRV_TIMER_IOCTL_START_OLD:
return snd_timer_user_start(file);
case SNDRV_TIMER_IOCTL_STOP:
case SNDRV_TIMER_IOCTL_STOP_OLD:
return snd_timer_user_stop(file);
case SNDRV_TIMER_IOCTL_CONTINUE:
case SNDRV_TIMER_IOCTL_CONTINUE_OLD:
return snd_timer_user_continue(file);
case SNDRV_TIMER_IOCTL_PAUSE:
case SNDRV_TIMER_IOCTL_PAUSE_OLD:
return snd_timer_user_pause(file);
}
return -ENOTTY;
}
static long snd_timer_user_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct snd_timer_user *tu = file->private_data;
long ret;
mutex_lock(&tu->ioctl_lock);
ret = __snd_timer_user_ioctl(file, cmd, arg);
mutex_unlock(&tu->ioctl_lock);
return ret;
}
static int snd_timer_user_fasync(int fd, struct file * file, int on)
{
struct snd_timer_user *tu;
tu = file->private_data;
return fasync_helper(fd, file, on, &tu->fasync);
}
static ssize_t snd_timer_user_read(struct file *file, char __user *buffer,
size_t count, loff_t *offset)
{
struct snd_timer_user *tu;
long result = 0, unit;
int qhead;
int err = 0;
tu = file->private_data;
unit = tu->tread ? sizeof(struct snd_timer_tread) : sizeof(struct snd_timer_read);
mutex_lock(&tu->ioctl_lock);
spin_lock_irq(&tu->qlock);
while ((long)count - result >= unit) {
while (!tu->qused) {
wait_queue_entry_t wait;
if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) {
err = -EAGAIN;
goto _error;
}
set_current_state(TASK_INTERRUPTIBLE);
init_waitqueue_entry(&wait, current);
add_wait_queue(&tu->qchange_sleep, &wait);
spin_unlock_irq(&tu->qlock);
mutex_unlock(&tu->ioctl_lock);
schedule();
mutex_lock(&tu->ioctl_lock);
spin_lock_irq(&tu->qlock);
remove_wait_queue(&tu->qchange_sleep, &wait);
if (tu->disconnected) {
err = -ENODEV;
goto _error;
}
if (signal_pending(current)) {
err = -ERESTARTSYS;
goto _error;
}
}
qhead = tu->qhead++;
tu->qhead %= tu->queue_size;
tu->qused--;
spin_unlock_irq(&tu->qlock);
if (tu->tread) {
if (copy_to_user(buffer, &tu->tqueue[qhead],
sizeof(struct snd_timer_tread)))
err = -EFAULT;
} else {
if (copy_to_user(buffer, &tu->queue[qhead],
sizeof(struct snd_timer_read)))
err = -EFAULT;
}
spin_lock_irq(&tu->qlock);
if (err < 0)
goto _error;
result += unit;
buffer += unit;
}
_error:
spin_unlock_irq(&tu->qlock);
mutex_unlock(&tu->ioctl_lock);
return result > 0 ? result : err;
}
static __poll_t snd_timer_user_poll(struct file *file, poll_table * wait)
{
__poll_t mask;
struct snd_timer_user *tu;
tu = file->private_data;
poll_wait(file, &tu->qchange_sleep, wait);
mask = 0;
spin_lock_irq(&tu->qlock);
if (tu->qused)
mask |= EPOLLIN | EPOLLRDNORM;
if (tu->disconnected)
mask |= EPOLLERR;
spin_unlock_irq(&tu->qlock);
return mask;
}
#ifdef CONFIG_COMPAT
#include "timer_compat.c"
#else
#define snd_timer_user_ioctl_compat NULL
#endif
static const struct file_operations snd_timer_f_ops =
{
.owner = THIS_MODULE,
.read = snd_timer_user_read,
.open = snd_timer_user_open,
.release = snd_timer_user_release,
.llseek = no_llseek,
.poll = snd_timer_user_poll,
.unlocked_ioctl = snd_timer_user_ioctl,
.compat_ioctl = snd_timer_user_ioctl_compat,
.fasync = snd_timer_user_fasync,
};
/* unregister the system timer */
static void snd_timer_free_all(void)
{
struct snd_timer *timer, *n;
list_for_each_entry_safe(timer, n, &snd_timer_list, device_list)
snd_timer_free(timer);
}
static struct device timer_dev;
/*
* ENTRY functions
*/
static int __init alsa_timer_init(void)
{
int err;
snd_device_initialize(&timer_dev, NULL);
dev_set_name(&timer_dev, "timer");
#ifdef SNDRV_OSS_INFO_DEV_TIMERS
snd_oss_info_register(SNDRV_OSS_INFO_DEV_TIMERS, SNDRV_CARDS - 1,
"system timer");
#endif
err = snd_timer_register_system();
if (err < 0) {
pr_err("ALSA: unable to register system timer (%i)\n", err);
goto put_timer;
}
err = snd_register_device(SNDRV_DEVICE_TYPE_TIMER, NULL, 0,
&snd_timer_f_ops, NULL, &timer_dev);
if (err < 0) {
pr_err("ALSA: unable to register timer device (%i)\n", err);
snd_timer_free_all();
goto put_timer;
}
snd_timer_proc_init();
return 0;
put_timer:
put_device(&timer_dev);
return err;
}
static void __exit alsa_timer_exit(void)
{
snd_unregister_device(&timer_dev);
snd_timer_free_all();
put_device(&timer_dev);
snd_timer_proc_done();
#ifdef SNDRV_OSS_INFO_DEV_TIMERS
snd_oss_info_unregister(SNDRV_OSS_INFO_DEV_TIMERS, SNDRV_CARDS - 1);
#endif
}
module_init(alsa_timer_init)
module_exit(alsa_timer_exit)
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_1316_0 |
crossvul-cpp_data_good_3242_0 | #include "mongoose.h"
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/internal.h"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#ifndef CS_MONGOOSE_SRC_INTERNAL_H_
#define CS_MONGOOSE_SRC_INTERNAL_H_
/* Amalgamated: #include "common/mg_mem.h" */
#ifndef MBUF_REALLOC
#define MBUF_REALLOC MG_REALLOC
#endif
#ifndef MBUF_FREE
#define MBUF_FREE MG_FREE
#endif
#define MG_SET_PTRPTR(_ptr, _v) \
do { \
if (_ptr) *(_ptr) = _v; \
} while (0)
#ifndef MG_INTERNAL
#define MG_INTERNAL static
#endif
#ifdef PICOTCP
#define NO_LIBC
#define MG_DISABLE_PFS
#endif
/* Amalgamated: #include "mongoose/src/net.h" */
/* Amalgamated: #include "mongoose/src/http.h" */
/* Amalgamated: #include "common/cs_dbg.h" */
#define MG_CTL_MSG_MESSAGE_SIZE 8192
/* internals that need to be accessible in unit tests */
MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
int proto,
union socket_address *sa);
MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
int *proto, char *host, size_t host_len);
MG_INTERNAL void mg_call(struct mg_connection *nc,
mg_event_handler_t ev_handler, void *user_data, int ev,
void *ev_data);
void mg_forward(struct mg_connection *from, struct mg_connection *to);
MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c);
MG_INTERNAL void mg_remove_conn(struct mg_connection *c);
MG_INTERNAL struct mg_connection *mg_create_connection(
struct mg_mgr *mgr, mg_event_handler_t callback,
struct mg_add_sock_opts opts);
#ifdef _WIN32
/* Retur value is the same as for MultiByteToWideChar. */
int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len);
#endif
struct ctl_msg {
mg_event_handler_t callback;
char message[MG_CTL_MSG_MESSAGE_SIZE];
};
#if MG_ENABLE_MQTT
struct mg_mqtt_message;
MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm);
#endif
/* Forward declarations for testing. */
extern void *(*test_malloc)(size_t size);
extern void *(*test_calloc)(size_t count, size_t size);
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
#if MG_ENABLE_HTTP
struct mg_serve_http_opts;
/*
* Reassemble the content of the buffer (buf, blen) which should be
* in the HTTP chunked encoding, by collapsing data chunks to the
* beginning of the buffer.
*
* If chunks get reassembled, modify hm->body to point to the reassembled
* body and fire MG_EV_HTTP_CHUNK event. If handler sets MG_F_DELETE_CHUNK
* in nc->flags, delete reassembled body from the mbuf.
*
* Return reassembled body size.
*/
MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
struct http_message *hm, char *buf,
size_t blen);
MG_INTERNAL int mg_http_common_url_parse(const char *url, const char *schema,
const char *schema_tls, int *use_ssl,
char **user, char **pass, char **addr,
int *port_i, const char **path);
#if MG_ENABLE_FILESYSTEM
MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
const struct mg_serve_http_opts *opts,
char **local_path,
struct mg_str *remainder);
MG_INTERNAL time_t mg_parse_date_string(const char *datetime);
MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st);
#endif
#if MG_ENABLE_HTTP_CGI
MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog,
const struct mg_str *path_info,
const struct http_message *hm,
const struct mg_serve_http_opts *opts);
struct mg_http_proto_data_cgi;
MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d);
#endif
#if MG_ENABLE_HTTP_SSI
MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
struct http_message *hm,
const char *path,
const struct mg_serve_http_opts *opts);
#endif
#if MG_ENABLE_HTTP_WEBDAV
MG_INTERNAL int mg_is_dav_request(const struct mg_str *s);
MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path,
cs_stat_t *stp, struct http_message *hm,
struct mg_serve_http_opts *opts);
MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path);
MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
struct http_message *hm);
MG_INTERNAL void mg_handle_move(struct mg_connection *c,
const struct mg_serve_http_opts *opts,
const char *path, struct http_message *hm);
MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
const struct mg_serve_http_opts *opts,
const char *path);
MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
struct http_message *hm);
#endif
#if MG_ENABLE_HTTP_WEBSOCKET
MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data));
MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
const struct mg_str *key);
#endif
#endif /* MG_ENABLE_HTTP */
MG_INTERNAL int mg_get_errno(void);
MG_INTERNAL void mg_close_conn(struct mg_connection *conn);
MG_INTERNAL int mg_http_common_url_parse(const char *url, const char *schema,
const char *schema_tls, int *use_ssl,
char **user, char **pass, char **addr,
int *port_i, const char **path);
#if MG_ENABLE_SNTP
MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
struct mg_sntp_message *msg);
#endif
#endif /* CS_MONGOOSE_SRC_INTERNAL_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/mg_mem.h"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#ifndef CS_COMMON_MG_MEM_H_
#define CS_COMMON_MG_MEM_H_
#ifndef MG_MALLOC
#define MG_MALLOC malloc
#endif
#ifndef MG_CALLOC
#define MG_CALLOC calloc
#endif
#ifndef MG_REALLOC
#define MG_REALLOC realloc
#endif
#ifndef MG_FREE
#define MG_FREE free
#endif
#endif /* CS_COMMON_MG_MEM_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/cs_dbg.h"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#ifndef CS_COMMON_CS_DBG_H_
#define CS_COMMON_CS_DBG_H_
/* Amalgamated: #include "common/platform.h" */
#if CS_ENABLE_STDIO
#include <stdio.h>
#endif
#ifndef CS_ENABLE_DEBUG
#define CS_ENABLE_DEBUG 0
#endif
#ifndef CS_LOG_ENABLE_TS_DIFF
#define CS_LOG_ENABLE_TS_DIFF 0
#endif
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
enum cs_log_level {
LL_NONE = -1,
LL_ERROR = 0,
LL_WARN = 1,
LL_INFO = 2,
LL_DEBUG = 3,
LL_VERBOSE_DEBUG = 4,
_LL_MIN = -2,
_LL_MAX = 5,
};
void cs_log_set_level(enum cs_log_level level);
#if CS_ENABLE_STDIO
void cs_log_set_file(FILE *file);
extern enum cs_log_level cs_log_level;
void cs_log_print_prefix(const char *func);
void cs_log_printf(const char *fmt, ...);
#define LOG(l, x) \
do { \
if (cs_log_level >= l) { \
cs_log_print_prefix(__func__); \
cs_log_printf x; \
} \
} while (0)
#ifndef CS_NDEBUG
#define DBG(x) \
do { \
if (cs_log_level >= LL_VERBOSE_DEBUG) { \
cs_log_print_prefix(__func__); \
cs_log_printf x; \
} \
} while (0)
#else /* NDEBUG */
#define DBG(x)
#endif
#else /* CS_ENABLE_STDIO */
#define LOG(l, x)
#define DBG(x)
#endif
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_COMMON_CS_DBG_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/cs_dbg.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
/* Amalgamated: #include "common/cs_dbg.h" */
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
/* Amalgamated: #include "common/cs_time.h" */
enum cs_log_level cs_log_level WEAK =
#if CS_ENABLE_DEBUG
LL_VERBOSE_DEBUG;
#else
LL_ERROR;
#endif
#if CS_ENABLE_STDIO
FILE *cs_log_file WEAK = NULL;
#if CS_LOG_ENABLE_TS_DIFF
double cs_log_ts WEAK;
#endif
void cs_log_print_prefix(const char *func) WEAK;
void cs_log_print_prefix(const char *func) {
char prefix[21];
strncpy(prefix, func, 20);
prefix[20] = '\0';
if (cs_log_file == NULL) cs_log_file = stderr;
fprintf(cs_log_file, "%-20s ", prefix);
#if CS_LOG_ENABLE_TS_DIFF
{
double now = cs_time();
fprintf(cs_log_file, "%7u ", (unsigned int) ((now - cs_log_ts) * 1000000));
cs_log_ts = now;
}
#endif
}
void cs_log_printf(const char *fmt, ...) WEAK;
void cs_log_printf(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
vfprintf(cs_log_file, fmt, ap);
va_end(ap);
fputc('\n', cs_log_file);
fflush(cs_log_file);
}
void cs_log_set_file(FILE *file) WEAK;
void cs_log_set_file(FILE *file) {
cs_log_file = file;
}
#endif /* CS_ENABLE_STDIO */
void cs_log_set_level(enum cs_log_level level) WEAK;
void cs_log_set_level(enum cs_log_level level) {
cs_log_level = level;
#if CS_LOG_ENABLE_TS_DIFF && CS_ENABLE_STDIO
cs_log_ts = cs_time();
#endif
}
#ifdef MG_MODULE_LINES
#line 1 "common/base64.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#ifndef EXCLUDE_COMMON
/* Amalgamated: #include "common/base64.h" */
#include <string.h>
/* Amalgamated: #include "common/cs_dbg.h" */
/* ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ */
#define NUM_UPPERCASES ('Z' - 'A' + 1)
#define NUM_LETTERS (NUM_UPPERCASES * 2)
#define NUM_DIGITS ('9' - '0' + 1)
/*
* Emit a base64 code char.
*
* Doesn't use memory, thus it's safe to use to safely dump memory in crashdumps
*/
static void cs_base64_emit_code(struct cs_base64_ctx *ctx, int v) {
if (v < NUM_UPPERCASES) {
ctx->b64_putc(v + 'A', ctx->user_data);
} else if (v < (NUM_LETTERS)) {
ctx->b64_putc(v - NUM_UPPERCASES + 'a', ctx->user_data);
} else if (v < (NUM_LETTERS + NUM_DIGITS)) {
ctx->b64_putc(v - NUM_LETTERS + '0', ctx->user_data);
} else {
ctx->b64_putc(v - NUM_LETTERS - NUM_DIGITS == 0 ? '+' : '/',
ctx->user_data);
}
}
static void cs_base64_emit_chunk(struct cs_base64_ctx *ctx) {
int a, b, c;
a = ctx->chunk[0];
b = ctx->chunk[1];
c = ctx->chunk[2];
cs_base64_emit_code(ctx, a >> 2);
cs_base64_emit_code(ctx, ((a & 3) << 4) | (b >> 4));
if (ctx->chunk_size > 1) {
cs_base64_emit_code(ctx, (b & 15) << 2 | (c >> 6));
}
if (ctx->chunk_size > 2) {
cs_base64_emit_code(ctx, c & 63);
}
}
void cs_base64_init(struct cs_base64_ctx *ctx, cs_base64_putc_t b64_putc,
void *user_data) {
ctx->chunk_size = 0;
ctx->b64_putc = b64_putc;
ctx->user_data = user_data;
}
void cs_base64_update(struct cs_base64_ctx *ctx, const char *str, size_t len) {
const unsigned char *src = (const unsigned char *) str;
size_t i;
for (i = 0; i < len; i++) {
ctx->chunk[ctx->chunk_size++] = src[i];
if (ctx->chunk_size == 3) {
cs_base64_emit_chunk(ctx);
ctx->chunk_size = 0;
}
}
}
void cs_base64_finish(struct cs_base64_ctx *ctx) {
if (ctx->chunk_size > 0) {
int i;
memset(&ctx->chunk[ctx->chunk_size], 0, 3 - ctx->chunk_size);
cs_base64_emit_chunk(ctx);
for (i = 0; i < (3 - ctx->chunk_size); i++) {
ctx->b64_putc('=', ctx->user_data);
}
}
}
#define BASE64_ENCODE_BODY \
static const char *b64 = \
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; \
int i, j, a, b, c; \
\
for (i = j = 0; i < src_len; i += 3) { \
a = src[i]; \
b = i + 1 >= src_len ? 0 : src[i + 1]; \
c = i + 2 >= src_len ? 0 : src[i + 2]; \
\
BASE64_OUT(b64[a >> 2]); \
BASE64_OUT(b64[((a & 3) << 4) | (b >> 4)]); \
if (i + 1 < src_len) { \
BASE64_OUT(b64[(b & 15) << 2 | (c >> 6)]); \
} \
if (i + 2 < src_len) { \
BASE64_OUT(b64[c & 63]); \
} \
} \
\
while (j % 4 != 0) { \
BASE64_OUT('='); \
} \
BASE64_FLUSH()
#define BASE64_OUT(ch) \
do { \
dst[j++] = (ch); \
} while (0)
#define BASE64_FLUSH() \
do { \
dst[j++] = '\0'; \
} while (0)
void cs_base64_encode(const unsigned char *src, int src_len, char *dst) {
BASE64_ENCODE_BODY;
}
#undef BASE64_OUT
#undef BASE64_FLUSH
#if CS_ENABLE_STDIO
#define BASE64_OUT(ch) \
do { \
fprintf(f, "%c", (ch)); \
j++; \
} while (0)
#define BASE64_FLUSH()
void cs_fprint_base64(FILE *f, const unsigned char *src, int src_len) {
BASE64_ENCODE_BODY;
}
#undef BASE64_OUT
#undef BASE64_FLUSH
#endif /* CS_ENABLE_STDIO */
/* Convert one byte of encoded base64 input stream to 6-bit chunk */
static unsigned char from_b64(unsigned char ch) {
/* Inverse lookup map */
static const unsigned char tab[128] = {
255, 255, 255, 255,
255, 255, 255, 255, /* 0 */
255, 255, 255, 255,
255, 255, 255, 255, /* 8 */
255, 255, 255, 255,
255, 255, 255, 255, /* 16 */
255, 255, 255, 255,
255, 255, 255, 255, /* 24 */
255, 255, 255, 255,
255, 255, 255, 255, /* 32 */
255, 255, 255, 62,
255, 255, 255, 63, /* 40 */
52, 53, 54, 55,
56, 57, 58, 59, /* 48 */
60, 61, 255, 255,
255, 200, 255, 255, /* 56 '=' is 200, on index 61 */
255, 0, 1, 2,
3, 4, 5, 6, /* 64 */
7, 8, 9, 10,
11, 12, 13, 14, /* 72 */
15, 16, 17, 18,
19, 20, 21, 22, /* 80 */
23, 24, 25, 255,
255, 255, 255, 255, /* 88 */
255, 26, 27, 28,
29, 30, 31, 32, /* 96 */
33, 34, 35, 36,
37, 38, 39, 40, /* 104 */
41, 42, 43, 44,
45, 46, 47, 48, /* 112 */
49, 50, 51, 255,
255, 255, 255, 255, /* 120 */
};
return tab[ch & 127];
}
int cs_base64_decode(const unsigned char *s, int len, char *dst, int *dec_len) {
unsigned char a, b, c, d;
int orig_len = len;
char *orig_dst = dst;
while (len >= 4 && (a = from_b64(s[0])) != 255 &&
(b = from_b64(s[1])) != 255 && (c = from_b64(s[2])) != 255 &&
(d = from_b64(s[3])) != 255) {
s += 4;
len -= 4;
if (a == 200 || b == 200) break; /* '=' can't be there */
*dst++ = a << 2 | b >> 4;
if (c == 200) break;
*dst++ = b << 4 | c >> 2;
if (d == 200) break;
*dst++ = c << 6 | d;
}
*dst = 0;
if (dec_len != NULL) *dec_len = (dst - orig_dst);
return orig_len - len;
}
#endif /* EXCLUDE_COMMON */
#ifdef MG_MODULE_LINES
#line 1 "common/cs_dirent.h"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#ifndef CS_COMMON_CS_DIRENT_H_
#define CS_COMMON_CS_DIRENT_H_
#include <limits.h>
/* Amalgamated: #include "common/platform.h" */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#ifdef CS_DEFINE_DIRENT
typedef struct { int dummy; } DIR;
struct dirent {
int d_ino;
#ifdef _WIN32
char d_name[MAX_PATH];
#else
/* TODO(rojer): Use PATH_MAX but make sure it's sane on every platform */
char d_name[256];
#endif
};
DIR *opendir(const char *dir_name);
int closedir(DIR *dir);
struct dirent *readdir(DIR *dir);
#endif /* CS_DEFINE_DIRENT */
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_COMMON_CS_DIRENT_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/cs_dirent.c"
#endif
/*
* Copyright (c) 2015 Cesanta Software Limited
* All rights reserved
*/
#ifndef EXCLUDE_COMMON
/* Amalgamated: #include "common/mg_mem.h" */
/* Amalgamated: #include "common/cs_dirent.h" */
/*
* This file contains POSIX opendir/closedir/readdir API implementation
* for systems which do not natively support it (e.g. Windows).
*/
#ifdef _WIN32
struct win32_dir {
DIR d;
HANDLE handle;
WIN32_FIND_DATAW info;
struct dirent result;
};
DIR *opendir(const char *name) {
struct win32_dir *dir = NULL;
wchar_t wpath[MAX_PATH];
DWORD attrs;
if (name == NULL) {
SetLastError(ERROR_BAD_ARGUMENTS);
} else if ((dir = (struct win32_dir *) MG_MALLOC(sizeof(*dir))) == NULL) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
} else {
to_wchar(name, wpath, ARRAY_SIZE(wpath));
attrs = GetFileAttributesW(wpath);
if (attrs != 0xFFFFFFFF && (attrs & FILE_ATTRIBUTE_DIRECTORY)) {
(void) wcscat(wpath, L"\\*");
dir->handle = FindFirstFileW(wpath, &dir->info);
dir->result.d_name[0] = '\0';
} else {
MG_FREE(dir);
dir = NULL;
}
}
return (DIR *) dir;
}
int closedir(DIR *d) {
struct win32_dir *dir = (struct win32_dir *) d;
int result = 0;
if (dir != NULL) {
if (dir->handle != INVALID_HANDLE_VALUE)
result = FindClose(dir->handle) ? 0 : -1;
MG_FREE(dir);
} else {
result = -1;
SetLastError(ERROR_BAD_ARGUMENTS);
}
return result;
}
struct dirent *readdir(DIR *d) {
struct win32_dir *dir = (struct win32_dir *) d;
struct dirent *result = NULL;
if (dir) {
memset(&dir->result, 0, sizeof(dir->result));
if (dir->handle != INVALID_HANDLE_VALUE) {
result = &dir->result;
(void) WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1,
result->d_name, sizeof(result->d_name), NULL,
NULL);
if (!FindNextFileW(dir->handle, &dir->info)) {
(void) FindClose(dir->handle);
dir->handle = INVALID_HANDLE_VALUE;
}
} else {
SetLastError(ERROR_FILE_NOT_FOUND);
}
} else {
SetLastError(ERROR_BAD_ARGUMENTS);
}
return result;
}
#endif
#endif /* EXCLUDE_COMMON */
/* ISO C requires a translation unit to contain at least one declaration */
typedef int cs_dirent_dummy;
#ifdef MG_MODULE_LINES
#line 1 "common/cs_time.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
/* Amalgamated: #include "common/cs_time.h" */
#ifndef _WIN32
#include <stddef.h>
/*
* There is no sys/time.h on ARMCC.
*/
#if !(defined(__ARMCC_VERSION) || defined(__ICCARM__)) && \
!defined(__TI_COMPILER_VERSION__) && \
(!defined(CS_PLATFORM) || CS_PLATFORM != CS_P_NXP_LPC)
#include <sys/time.h>
#endif
#else
#include <windows.h>
#endif
double cs_time(void) WEAK;
double cs_time(void) {
double now;
#ifndef _WIN32
struct timeval tv;
if (gettimeofday(&tv, NULL /* tz */) != 0) return 0;
now = (double) tv.tv_sec + (((double) tv.tv_usec) / 1000000.0);
#else
SYSTEMTIME sysnow;
FILETIME ftime;
GetLocalTime(&sysnow);
SystemTimeToFileTime(&sysnow, &ftime);
/*
* 1. VC 6.0 doesn't support conversion uint64 -> double, so, using int64
* This should not cause a problems in this (21th) century
* 2. Windows FILETIME is a number of 100-nanosecond intervals since January
* 1, 1601 while time_t is a number of _seconds_ since January 1, 1970 UTC,
* thus, we need to convert to seconds and adjust amount (subtract 11644473600
* seconds)
*/
now = (double) (((int64_t) ftime.dwLowDateTime +
((int64_t) ftime.dwHighDateTime << 32)) /
10000000.0) -
11644473600;
#endif /* _WIN32 */
return now;
}
#ifdef MG_MODULE_LINES
#line 1 "common/cs_endian.h"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#ifndef CS_COMMON_CS_ENDIAN_H_
#define CS_COMMON_CS_ENDIAN_H_
/*
* clang with std=-c99 uses __LITTLE_ENDIAN, by default
* while for ex, RTOS gcc - LITTLE_ENDIAN, by default
* it depends on __USE_BSD, but let's have everything
*/
#if !defined(BYTE_ORDER) && defined(__BYTE_ORDER)
#define BYTE_ORDER __BYTE_ORDER
#ifndef LITTLE_ENDIAN
#define LITTLE_ENDIAN __LITTLE_ENDIAN
#endif /* LITTLE_ENDIAN */
#ifndef BIG_ENDIAN
#define BIG_ENDIAN __LITTLE_ENDIAN
#endif /* BIG_ENDIAN */
#endif /* BYTE_ORDER */
#endif /* CS_COMMON_CS_ENDIAN_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/md5.c"
#endif
/*
* This code implements the MD5 message-digest algorithm.
* The algorithm is due to Ron Rivest. This code was
* written by Colin Plumb in 1993, no copyright is claimed.
* This code is in the public domain; do with it what you wish.
*
* Equivalent code is available from RSA Data Security, Inc.
* This code has been tested against that, and is equivalent,
* except that you don't need to include two pages of legalese
* with every copy.
*
* To compute the message digest of a chunk of bytes, declare an
* MD5Context structure, pass it to MD5Init, call MD5Update as
* needed on buffers full of bytes, and then call MD5Final, which
* will fill a supplied 16-byte array with the digest.
*/
/* Amalgamated: #include "common/md5.h" */
/* Amalgamated: #include "common/str_util.h" */
#if !defined(EXCLUDE_COMMON)
#if !CS_DISABLE_MD5
/* Amalgamated: #include "common/cs_endian.h" */
static void byteReverse(unsigned char *buf, unsigned longs) {
/* Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN */
#if BYTE_ORDER == BIG_ENDIAN
do {
uint32_t t = (uint32_t)((unsigned) buf[3] << 8 | buf[2]) << 16 |
((unsigned) buf[1] << 8 | buf[0]);
*(uint32_t *) buf = t;
buf += 4;
} while (--longs);
#else
(void) buf;
(void) longs;
#endif
}
#define F1(x, y, z) (z ^ (x & (y ^ z)))
#define F2(x, y, z) F1(z, x, y)
#define F3(x, y, z) (x ^ y ^ z)
#define F4(x, y, z) (y ^ (x | ~z))
#define MD5STEP(f, w, x, y, z, data, s) \
(w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)
/*
* Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
* initialization constants.
*/
void MD5_Init(MD5_CTX *ctx) {
ctx->buf[0] = 0x67452301;
ctx->buf[1] = 0xefcdab89;
ctx->buf[2] = 0x98badcfe;
ctx->buf[3] = 0x10325476;
ctx->bits[0] = 0;
ctx->bits[1] = 0;
}
static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
register uint32_t a, b, c, d;
a = buf[0];
b = buf[1];
c = buf[2];
d = buf[3];
MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
buf[0] += a;
buf[1] += b;
buf[2] += c;
buf[3] += d;
}
void MD5_Update(MD5_CTX *ctx, const unsigned char *buf, size_t len) {
uint32_t t;
t = ctx->bits[0];
if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t) ctx->bits[1]++;
ctx->bits[1] += (uint32_t) len >> 29;
t = (t >> 3) & 0x3f;
if (t) {
unsigned char *p = (unsigned char *) ctx->in + t;
t = 64 - t;
if (len < t) {
memcpy(p, buf, len);
return;
}
memcpy(p, buf, t);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (uint32_t *) ctx->in);
buf += t;
len -= t;
}
while (len >= 64) {
memcpy(ctx->in, buf, 64);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (uint32_t *) ctx->in);
buf += 64;
len -= 64;
}
memcpy(ctx->in, buf, len);
}
void MD5_Final(unsigned char digest[16], MD5_CTX *ctx) {
unsigned count;
unsigned char *p;
uint32_t *a;
count = (ctx->bits[0] >> 3) & 0x3F;
p = ctx->in + count;
*p++ = 0x80;
count = 64 - 1 - count;
if (count < 8) {
memset(p, 0, count);
byteReverse(ctx->in, 16);
MD5Transform(ctx->buf, (uint32_t *) ctx->in);
memset(ctx->in, 0, 56);
} else {
memset(p, 0, count - 8);
}
byteReverse(ctx->in, 14);
a = (uint32_t *) ctx->in;
a[14] = ctx->bits[0];
a[15] = ctx->bits[1];
MD5Transform(ctx->buf, (uint32_t *) ctx->in);
byteReverse((unsigned char *) ctx->buf, 4);
memcpy(digest, ctx->buf, 16);
memset((char *) ctx, 0, sizeof(*ctx));
}
char *cs_md5(char buf[33], ...) {
unsigned char hash[16];
const unsigned char *p;
va_list ap;
MD5_CTX ctx;
MD5_Init(&ctx);
va_start(ap, buf);
while ((p = va_arg(ap, const unsigned char *) ) != NULL) {
size_t len = va_arg(ap, size_t);
MD5_Update(&ctx, p, len);
}
va_end(ap);
MD5_Final(hash, &ctx);
cs_to_hex(buf, hash, sizeof(hash));
return buf;
}
#endif /* CS_DISABLE_MD5 */
#endif /* EXCLUDE_COMMON */
#ifdef MG_MODULE_LINES
#line 1 "common/mbuf.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#ifndef EXCLUDE_COMMON
#include <assert.h>
#include <string.h>
/* Amalgamated: #include "common/mbuf.h" */
#ifndef MBUF_REALLOC
#define MBUF_REALLOC realloc
#endif
#ifndef MBUF_FREE
#define MBUF_FREE free
#endif
void mbuf_init(struct mbuf *mbuf, size_t initial_size) WEAK;
void mbuf_init(struct mbuf *mbuf, size_t initial_size) {
mbuf->len = mbuf->size = 0;
mbuf->buf = NULL;
mbuf_resize(mbuf, initial_size);
}
void mbuf_free(struct mbuf *mbuf) WEAK;
void mbuf_free(struct mbuf *mbuf) {
if (mbuf->buf != NULL) {
MBUF_FREE(mbuf->buf);
mbuf_init(mbuf, 0);
}
}
void mbuf_resize(struct mbuf *a, size_t new_size) WEAK;
void mbuf_resize(struct mbuf *a, size_t new_size) {
if (new_size > a->size || (new_size < a->size && new_size >= a->len)) {
char *buf = (char *) MBUF_REALLOC(a->buf, new_size);
/*
* In case realloc fails, there's not much we can do, except keep things as
* they are. Note that NULL is a valid return value from realloc when
* size == 0, but that is covered too.
*/
if (buf == NULL && new_size != 0) return;
a->buf = buf;
a->size = new_size;
}
}
void mbuf_trim(struct mbuf *mbuf) WEAK;
void mbuf_trim(struct mbuf *mbuf) {
mbuf_resize(mbuf, mbuf->len);
}
size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t) WEAK;
size_t mbuf_insert(struct mbuf *a, size_t off, const void *buf, size_t len) {
char *p = NULL;
assert(a != NULL);
assert(a->len <= a->size);
assert(off <= a->len);
/* check overflow */
if (~(size_t) 0 - (size_t) a->buf < len) return 0;
if (a->len + len <= a->size) {
memmove(a->buf + off + len, a->buf + off, a->len - off);
if (buf != NULL) {
memcpy(a->buf + off, buf, len);
}
a->len += len;
} else {
size_t new_size = (size_t)((a->len + len) * MBUF_SIZE_MULTIPLIER);
if ((p = (char *) MBUF_REALLOC(a->buf, new_size)) != NULL) {
a->buf = p;
memmove(a->buf + off + len, a->buf + off, a->len - off);
if (buf != NULL) memcpy(a->buf + off, buf, len);
a->len += len;
a->size = new_size;
} else {
len = 0;
}
}
return len;
}
size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) WEAK;
size_t mbuf_append(struct mbuf *a, const void *buf, size_t len) {
return mbuf_insert(a, a->len, buf, len);
}
void mbuf_remove(struct mbuf *mb, size_t n) WEAK;
void mbuf_remove(struct mbuf *mb, size_t n) {
if (n > 0 && n <= mb->len) {
memmove(mb->buf, mb->buf + n, mb->len - n);
mb->len -= n;
}
}
#endif /* EXCLUDE_COMMON */
#ifdef MG_MODULE_LINES
#line 1 "common/mg_str.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
/* Amalgamated: #include "common/mg_mem.h" */
/* Amalgamated: #include "common/mg_str.h" */
#include <stdlib.h>
#include <string.h>
int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK;
struct mg_str mg_mk_str(const char *s) WEAK;
struct mg_str mg_mk_str(const char *s) {
struct mg_str ret = {s, 0};
if (s != NULL) ret.len = strlen(s);
return ret;
}
struct mg_str mg_mk_str_n(const char *s, size_t len) WEAK;
struct mg_str mg_mk_str_n(const char *s, size_t len) {
struct mg_str ret = {s, len};
return ret;
}
int mg_vcmp(const struct mg_str *str1, const char *str2) WEAK;
int mg_vcmp(const struct mg_str *str1, const char *str2) {
size_t n2 = strlen(str2), n1 = str1->len;
int r = strncmp(str1->p, str2, (n1 < n2) ? n1 : n2);
if (r == 0) {
return n1 - n2;
}
return r;
}
int mg_vcasecmp(const struct mg_str *str1, const char *str2) WEAK;
int mg_vcasecmp(const struct mg_str *str1, const char *str2) {
size_t n2 = strlen(str2), n1 = str1->len;
int r = mg_ncasecmp(str1->p, str2, (n1 < n2) ? n1 : n2);
if (r == 0) {
return n1 - n2;
}
return r;
}
struct mg_str mg_strdup(const struct mg_str s) WEAK;
struct mg_str mg_strdup(const struct mg_str s) {
struct mg_str r = {NULL, 0};
if (s.len > 0 && s.p != NULL) {
r.p = (char *) MG_MALLOC(s.len);
if (r.p != NULL) {
memcpy((char *) r.p, s.p, s.len);
r.len = s.len;
}
}
return r;
}
int mg_strcmp(const struct mg_str str1, const struct mg_str str2) WEAK;
int mg_strcmp(const struct mg_str str1, const struct mg_str str2) {
size_t i = 0;
while (i < str1.len && i < str2.len) {
if (str1.p[i] < str2.p[i]) return -1;
if (str1.p[i] > str2.p[i]) return 1;
i++;
}
if (i < str1.len) return 1;
if (i < str2.len) return -1;
return 0;
}
int mg_strncmp(const struct mg_str, const struct mg_str, size_t n) WEAK;
int mg_strncmp(const struct mg_str str1, const struct mg_str str2, size_t n) {
struct mg_str s1 = str1;
struct mg_str s2 = str2;
if (s1.len > n) {
s1.len = n;
}
if (s2.len > n) {
s2.len = n;
}
return mg_strcmp(s1, s2);
}
#ifdef MG_MODULE_LINES
#line 1 "common/sha1.c"
#endif
/* Copyright(c) By Steve Reid <steve@edmweb.com> */
/* 100% Public Domain */
/* Amalgamated: #include "common/sha1.h" */
#if !CS_DISABLE_SHA1 && !defined(EXCLUDE_COMMON)
/* Amalgamated: #include "common/cs_endian.h" */
#define SHA1HANDSOFF
#if defined(__sun)
/* Amalgamated: #include "common/solarisfixes.h" */
#endif
union char64long16 {
unsigned char c[64];
uint32_t l[16];
};
#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
static uint32_t blk0(union char64long16 *block, int i) {
/* Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN */
#if BYTE_ORDER == LITTLE_ENDIAN
block->l[i] =
(rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF);
#endif
return block->l[i];
}
/* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
#undef blk
#undef R0
#undef R1
#undef R2
#undef R3
#undef R4
#define blk(i) \
(block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \
block->l[(i + 2) & 15] ^ block->l[i & 15], \
1))
#define R0(v, w, x, y, z, i) \
z += ((w & (x ^ y)) ^ y) + blk0(block, i) + 0x5A827999 + rol(v, 5); \
w = rol(w, 30);
#define R1(v, w, x, y, z, i) \
z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \
w = rol(w, 30);
#define R2(v, w, x, y, z, i) \
z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \
w = rol(w, 30);
#define R3(v, w, x, y, z, i) \
z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \
w = rol(w, 30);
#define R4(v, w, x, y, z, i) \
z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \
w = rol(w, 30);
void cs_sha1_transform(uint32_t state[5], const unsigned char buffer[64]) {
uint32_t a, b, c, d, e;
union char64long16 block[1];
memcpy(block, buffer, 64);
a = state[0];
b = state[1];
c = state[2];
d = state[3];
e = state[4];
R0(a, b, c, d, e, 0);
R0(e, a, b, c, d, 1);
R0(d, e, a, b, c, 2);
R0(c, d, e, a, b, 3);
R0(b, c, d, e, a, 4);
R0(a, b, c, d, e, 5);
R0(e, a, b, c, d, 6);
R0(d, e, a, b, c, 7);
R0(c, d, e, a, b, 8);
R0(b, c, d, e, a, 9);
R0(a, b, c, d, e, 10);
R0(e, a, b, c, d, 11);
R0(d, e, a, b, c, 12);
R0(c, d, e, a, b, 13);
R0(b, c, d, e, a, 14);
R0(a, b, c, d, e, 15);
R1(e, a, b, c, d, 16);
R1(d, e, a, b, c, 17);
R1(c, d, e, a, b, 18);
R1(b, c, d, e, a, 19);
R2(a, b, c, d, e, 20);
R2(e, a, b, c, d, 21);
R2(d, e, a, b, c, 22);
R2(c, d, e, a, b, 23);
R2(b, c, d, e, a, 24);
R2(a, b, c, d, e, 25);
R2(e, a, b, c, d, 26);
R2(d, e, a, b, c, 27);
R2(c, d, e, a, b, 28);
R2(b, c, d, e, a, 29);
R2(a, b, c, d, e, 30);
R2(e, a, b, c, d, 31);
R2(d, e, a, b, c, 32);
R2(c, d, e, a, b, 33);
R2(b, c, d, e, a, 34);
R2(a, b, c, d, e, 35);
R2(e, a, b, c, d, 36);
R2(d, e, a, b, c, 37);
R2(c, d, e, a, b, 38);
R2(b, c, d, e, a, 39);
R3(a, b, c, d, e, 40);
R3(e, a, b, c, d, 41);
R3(d, e, a, b, c, 42);
R3(c, d, e, a, b, 43);
R3(b, c, d, e, a, 44);
R3(a, b, c, d, e, 45);
R3(e, a, b, c, d, 46);
R3(d, e, a, b, c, 47);
R3(c, d, e, a, b, 48);
R3(b, c, d, e, a, 49);
R3(a, b, c, d, e, 50);
R3(e, a, b, c, d, 51);
R3(d, e, a, b, c, 52);
R3(c, d, e, a, b, 53);
R3(b, c, d, e, a, 54);
R3(a, b, c, d, e, 55);
R3(e, a, b, c, d, 56);
R3(d, e, a, b, c, 57);
R3(c, d, e, a, b, 58);
R3(b, c, d, e, a, 59);
R4(a, b, c, d, e, 60);
R4(e, a, b, c, d, 61);
R4(d, e, a, b, c, 62);
R4(c, d, e, a, b, 63);
R4(b, c, d, e, a, 64);
R4(a, b, c, d, e, 65);
R4(e, a, b, c, d, 66);
R4(d, e, a, b, c, 67);
R4(c, d, e, a, b, 68);
R4(b, c, d, e, a, 69);
R4(a, b, c, d, e, 70);
R4(e, a, b, c, d, 71);
R4(d, e, a, b, c, 72);
R4(c, d, e, a, b, 73);
R4(b, c, d, e, a, 74);
R4(a, b, c, d, e, 75);
R4(e, a, b, c, d, 76);
R4(d, e, a, b, c, 77);
R4(c, d, e, a, b, 78);
R4(b, c, d, e, a, 79);
state[0] += a;
state[1] += b;
state[2] += c;
state[3] += d;
state[4] += e;
/* Erase working structures. The order of operations is important,
* used to ensure that compiler doesn't optimize those out. */
memset(block, 0, sizeof(block));
a = b = c = d = e = 0;
(void) a;
(void) b;
(void) c;
(void) d;
(void) e;
}
void cs_sha1_init(cs_sha1_ctx *context) {
context->state[0] = 0x67452301;
context->state[1] = 0xEFCDAB89;
context->state[2] = 0x98BADCFE;
context->state[3] = 0x10325476;
context->state[4] = 0xC3D2E1F0;
context->count[0] = context->count[1] = 0;
}
void cs_sha1_update(cs_sha1_ctx *context, const unsigned char *data,
uint32_t len) {
uint32_t i, j;
j = context->count[0];
if ((context->count[0] += len << 3) < j) context->count[1]++;
context->count[1] += (len >> 29);
j = (j >> 3) & 63;
if ((j + len) > 63) {
memcpy(&context->buffer[j], data, (i = 64 - j));
cs_sha1_transform(context->state, context->buffer);
for (; i + 63 < len; i += 64) {
cs_sha1_transform(context->state, &data[i]);
}
j = 0;
} else
i = 0;
memcpy(&context->buffer[j], &data[i], len - i);
}
void cs_sha1_final(unsigned char digest[20], cs_sha1_ctx *context) {
unsigned i;
unsigned char finalcount[8], c;
for (i = 0; i < 8; i++) {
finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >>
((3 - (i & 3)) * 8)) &
255);
}
c = 0200;
cs_sha1_update(context, &c, 1);
while ((context->count[0] & 504) != 448) {
c = 0000;
cs_sha1_update(context, &c, 1);
}
cs_sha1_update(context, finalcount, 8);
for (i = 0; i < 20; i++) {
digest[i] =
(unsigned char) ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
}
memset(context, '\0', sizeof(*context));
memset(&finalcount, '\0', sizeof(finalcount));
}
void cs_hmac_sha1(const unsigned char *key, size_t keylen,
const unsigned char *data, size_t datalen,
unsigned char out[20]) {
cs_sha1_ctx ctx;
unsigned char buf1[64], buf2[64], tmp_key[20], i;
if (keylen > sizeof(buf1)) {
cs_sha1_init(&ctx);
cs_sha1_update(&ctx, key, keylen);
cs_sha1_final(tmp_key, &ctx);
key = tmp_key;
keylen = sizeof(tmp_key);
}
memset(buf1, 0, sizeof(buf1));
memset(buf2, 0, sizeof(buf2));
memcpy(buf1, key, keylen);
memcpy(buf2, key, keylen);
for (i = 0; i < sizeof(buf1); i++) {
buf1[i] ^= 0x36;
buf2[i] ^= 0x5c;
}
cs_sha1_init(&ctx);
cs_sha1_update(&ctx, buf1, sizeof(buf1));
cs_sha1_update(&ctx, data, datalen);
cs_sha1_final(out, &ctx);
cs_sha1_init(&ctx);
cs_sha1_update(&ctx, buf2, sizeof(buf2));
cs_sha1_update(&ctx, out, 20);
cs_sha1_final(out, &ctx);
}
#endif /* EXCLUDE_COMMON */
#ifdef MG_MODULE_LINES
#line 1 "common/str_util.c"
#endif
/*
* Copyright (c) 2015 Cesanta Software Limited
* All rights reserved
*/
#ifndef EXCLUDE_COMMON
/* Amalgamated: #include "common/mg_mem.h" */
/* Amalgamated: #include "common/platform.h" */
/* Amalgamated: #include "common/str_util.h" */
#ifndef C_DISABLE_BUILTIN_SNPRINTF
#define C_DISABLE_BUILTIN_SNPRINTF 0
#endif
/* Amalgamated: #include "common/mg_mem.h" */
size_t c_strnlen(const char *s, size_t maxlen) WEAK;
size_t c_strnlen(const char *s, size_t maxlen) {
size_t l = 0;
for (; l < maxlen && s[l] != '\0'; l++) {
}
return l;
}
#define C_SNPRINTF_APPEND_CHAR(ch) \
do { \
if (i < (int) buf_size) buf[i] = ch; \
i++; \
} while (0)
#define C_SNPRINTF_FLAG_ZERO 1
#if C_DISABLE_BUILTIN_SNPRINTF
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK;
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
return vsnprintf(buf, buf_size, fmt, ap);
}
#else
static int c_itoa(char *buf, size_t buf_size, int64_t num, int base, int flags,
int field_width) {
char tmp[40];
int i = 0, k = 0, neg = 0;
if (num < 0) {
neg++;
num = -num;
}
/* Print into temporary buffer - in reverse order */
do {
int rem = num % base;
if (rem < 10) {
tmp[k++] = '0' + rem;
} else {
tmp[k++] = 'a' + (rem - 10);
}
num /= base;
} while (num > 0);
/* Zero padding */
if (flags && C_SNPRINTF_FLAG_ZERO) {
while (k < field_width && k < (int) sizeof(tmp) - 1) {
tmp[k++] = '0';
}
}
/* And sign */
if (neg) {
tmp[k++] = '-';
}
/* Now output */
while (--k >= 0) {
C_SNPRINTF_APPEND_CHAR(tmp[k]);
}
return i;
}
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) WEAK;
int c_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list ap) {
int ch, i = 0, len_mod, flags, precision, field_width;
while ((ch = *fmt++) != '\0') {
if (ch != '%') {
C_SNPRINTF_APPEND_CHAR(ch);
} else {
/*
* Conversion specification:
* zero or more flags (one of: # 0 - <space> + ')
* an optional minimum field width (digits)
* an optional precision (. followed by digits, or *)
* an optional length modifier (one of: hh h l ll L q j z t)
* conversion specifier (one of: d i o u x X e E f F g G a A c s p n)
*/
flags = field_width = precision = len_mod = 0;
/* Flags. only zero-pad flag is supported. */
if (*fmt == '0') {
flags |= C_SNPRINTF_FLAG_ZERO;
}
/* Field width */
while (*fmt >= '0' && *fmt <= '9') {
field_width *= 10;
field_width += *fmt++ - '0';
}
/* Dynamic field width */
if (*fmt == '*') {
field_width = va_arg(ap, int);
fmt++;
}
/* Precision */
if (*fmt == '.') {
fmt++;
if (*fmt == '*') {
precision = va_arg(ap, int);
fmt++;
} else {
while (*fmt >= '0' && *fmt <= '9') {
precision *= 10;
precision += *fmt++ - '0';
}
}
}
/* Length modifier */
switch (*fmt) {
case 'h':
case 'l':
case 'L':
case 'I':
case 'q':
case 'j':
case 'z':
case 't':
len_mod = *fmt++;
if (*fmt == 'h') {
len_mod = 'H';
fmt++;
}
if (*fmt == 'l') {
len_mod = 'q';
fmt++;
}
break;
}
ch = *fmt++;
if (ch == 's') {
const char *s = va_arg(ap, const char *); /* Always fetch parameter */
int j;
int pad = field_width - (precision >= 0 ? c_strnlen(s, precision) : 0);
for (j = 0; j < pad; j++) {
C_SNPRINTF_APPEND_CHAR(' ');
}
/* `s` may be NULL in case of %.*s */
if (s != NULL) {
/* Ignore negative and 0 precisions */
for (j = 0; (precision <= 0 || j < precision) && s[j] != '\0'; j++) {
C_SNPRINTF_APPEND_CHAR(s[j]);
}
}
} else if (ch == 'c') {
ch = va_arg(ap, int); /* Always fetch parameter */
C_SNPRINTF_APPEND_CHAR(ch);
} else if (ch == 'd' && len_mod == 0) {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, int), 10, flags,
field_width);
} else if (ch == 'd' && len_mod == 'l') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, long), 10, flags,
field_width);
#ifdef SSIZE_MAX
} else if (ch == 'd' && len_mod == 'z') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, ssize_t), 10, flags,
field_width);
#endif
} else if (ch == 'd' && len_mod == 'q') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, int64_t), 10, flags,
field_width);
} else if ((ch == 'x' || ch == 'u') && len_mod == 0) {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned),
ch == 'x' ? 16 : 10, flags, field_width);
} else if ((ch == 'x' || ch == 'u') && len_mod == 'l') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, unsigned long),
ch == 'x' ? 16 : 10, flags, field_width);
} else if ((ch == 'x' || ch == 'u') && len_mod == 'z') {
i += c_itoa(buf + i, buf_size - i, va_arg(ap, size_t),
ch == 'x' ? 16 : 10, flags, field_width);
} else if (ch == 'p') {
unsigned long num = (unsigned long) (uintptr_t) va_arg(ap, void *);
C_SNPRINTF_APPEND_CHAR('0');
C_SNPRINTF_APPEND_CHAR('x');
i += c_itoa(buf + i, buf_size - i, num, 16, flags, 0);
} else {
#ifndef NO_LIBC
/*
* TODO(lsm): abort is not nice in a library, remove it
* Also, ESP8266 SDK doesn't have it
*/
abort();
#endif
}
}
}
/* Zero-terminate the result */
if (buf_size > 0) {
buf[i < (int) buf_size ? i : (int) buf_size - 1] = '\0';
}
return i;
}
#endif
int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) WEAK;
int c_snprintf(char *buf, size_t buf_size, const char *fmt, ...) {
int result;
va_list ap;
va_start(ap, fmt);
result = c_vsnprintf(buf, buf_size, fmt, ap);
va_end(ap);
return result;
}
#ifdef _WIN32
int to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
int ret;
char buf[MAX_PATH * 2], buf2[MAX_PATH * 2], *p;
strncpy(buf, path, sizeof(buf));
buf[sizeof(buf) - 1] = '\0';
/* Trim trailing slashes. Leave backslash for paths like "X:\" */
p = buf + strlen(buf) - 1;
while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
ret = MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
/*
* Convert back to Unicode. If doubly-converted string does not match the
* original, something is fishy, reject.
*/
WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
NULL, NULL);
if (strcmp(buf, buf2) != 0) {
wbuf[0] = L'\0';
ret = 0;
}
return ret;
}
#endif /* _WIN32 */
/* The simplest O(mn) algorithm. Better implementation are GPLed */
const char *c_strnstr(const char *s, const char *find, size_t slen) WEAK;
const char *c_strnstr(const char *s, const char *find, size_t slen) {
size_t find_length = strlen(find);
size_t i;
for (i = 0; i < slen; i++) {
if (i + find_length > slen) {
return NULL;
}
if (strncmp(&s[i], find, find_length) == 0) {
return &s[i];
}
}
return NULL;
}
#if CS_ENABLE_STRDUP
char *strdup(const char *src) WEAK;
char *strdup(const char *src) {
size_t len = strlen(src) + 1;
char *ret = MG_MALLOC(len);
if (ret != NULL) {
strcpy(ret, src);
}
return ret;
}
#endif
void cs_to_hex(char *to, const unsigned char *p, size_t len) WEAK;
void cs_to_hex(char *to, const unsigned char *p, size_t len) {
static const char *hex = "0123456789abcdef";
for (; len--; p++) {
*to++ = hex[p[0] >> 4];
*to++ = hex[p[0] & 0x0f];
}
*to = '\0';
}
static int fourbit(int ch) {
if (ch >= '0' && ch <= '9') {
return ch - '0';
} else if (ch >= 'a' && ch <= 'f') {
return ch - 'a' + 10;
} else if (ch >= 'A' && ch <= 'F') {
return ch - 'A' + 10;
}
return 0;
}
void cs_from_hex(char *to, const char *p, size_t len) WEAK;
void cs_from_hex(char *to, const char *p, size_t len) {
size_t i;
for (i = 0; i < len; i += 2) {
*to++ = (fourbit(p[i]) << 4) + fourbit(p[i + 1]);
}
*to = '\0';
}
#if CS_ENABLE_TO64
int64_t cs_to64(const char *s) WEAK;
int64_t cs_to64(const char *s) {
int64_t result = 0;
int64_t neg = 1;
while (*s && isspace((unsigned char) *s)) s++;
if (*s == '-') {
neg = -1;
s++;
}
while (isdigit((unsigned char) *s)) {
result *= 10;
result += (*s - '0');
s++;
}
return result * neg;
}
#endif
static int str_util_lowercase(const char *s) {
return tolower(*(const unsigned char *) s);
}
int mg_ncasecmp(const char *s1, const char *s2, size_t len) WEAK;
int mg_ncasecmp(const char *s1, const char *s2, size_t len) {
int diff = 0;
if (len > 0) do {
diff = str_util_lowercase(s1++) - str_util_lowercase(s2++);
} while (diff == 0 && s1[-1] != '\0' && --len > 0);
return diff;
}
int mg_casecmp(const char *s1, const char *s2) WEAK;
int mg_casecmp(const char *s1, const char *s2) {
return mg_ncasecmp(s1, s2, (size_t) ~0);
}
int mg_asprintf(char **buf, size_t size, const char *fmt, ...) WEAK;
int mg_asprintf(char **buf, size_t size, const char *fmt, ...) {
int ret;
va_list ap;
va_start(ap, fmt);
ret = mg_avprintf(buf, size, fmt, ap);
va_end(ap);
return ret;
}
int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) WEAK;
int mg_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
va_list ap_copy;
int len;
va_copy(ap_copy, ap);
len = vsnprintf(*buf, size, fmt, ap_copy);
va_end(ap_copy);
if (len < 0) {
/* eCos and Windows are not standard-compliant and return -1 when
* the buffer is too small. Keep allocating larger buffers until we
* succeed or out of memory. */
*buf = NULL; /* LCOV_EXCL_START */
while (len < 0) {
MG_FREE(*buf);
size *= 2;
if ((*buf = (char *) MG_MALLOC(size)) == NULL) break;
va_copy(ap_copy, ap);
len = vsnprintf(*buf, size, fmt, ap_copy);
va_end(ap_copy);
}
/* LCOV_EXCL_STOP */
} else if (len >= (int) size) {
/* Standard-compliant code path. Allocate a buffer that is large enough. */
if ((*buf = (char *) MG_MALLOC(len + 1)) == NULL) {
len = -1; /* LCOV_EXCL_LINE */
} else { /* LCOV_EXCL_LINE */
va_copy(ap_copy, ap);
len = vsnprintf(*buf, len + 1, fmt, ap_copy);
va_end(ap_copy);
}
}
return len;
}
#endif /* EXCLUDE_COMMON */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/tun.h"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#ifndef CS_MONGOOSE_SRC_TUN_H_
#define CS_MONGOOSE_SRC_TUN_H_
#if MG_ENABLE_TUN
/* Amalgamated: #include "mongoose/src/net.h" */
/* Amalgamated: #include "common/mg_str.h" */
#ifndef MG_TUN_RECONNECT_INTERVAL
#define MG_TUN_RECONNECT_INTERVAL 1
#endif
#define MG_TUN_PROTO_NAME "mg_tun"
#define MG_TUN_DATA_FRAME 0x0
#define MG_TUN_F_END_STREAM 0x1
/*
* MG TUN frame format is loosely based on HTTP/2.
* However since the communication happens via WebSocket
* there is no need to encode the frame length, since that's
* solved by WebSocket framing.
*
* TODO(mkm): Detailed description of the protocol.
*/
struct mg_tun_frame {
uint8_t type;
uint8_t flags;
uint32_t stream_id; /* opaque stream identifier */
struct mg_str body;
};
struct mg_tun_ssl_opts {
#if MG_ENABLE_SSL
const char *ssl_cert;
const char *ssl_key;
const char *ssl_ca_cert;
#else
int dummy; /* some compilers don't like empty structs */
#endif
};
struct mg_tun_client {
struct mg_mgr *mgr;
struct mg_iface *iface;
const char *disp_url;
struct mg_tun_ssl_opts ssl;
uint32_t last_stream_id; /* stream id of most recently accepted connection */
struct mg_connection *disp;
struct mg_connection *listener;
struct mg_connection *reconnect;
};
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
struct mg_connection *mg_tun_bind_opt(struct mg_mgr *mgr,
const char *dispatcher,
MG_CB(mg_event_handler_t handler,
void *user_data),
struct mg_bind_opts opts);
int mg_tun_parse_frame(void *data, size_t len, struct mg_tun_frame *frame);
void mg_tun_send_frame(struct mg_connection *ws, uint32_t stream_id,
uint8_t type, uint8_t flags, struct mg_str msg);
void mg_tun_destroy_client(struct mg_tun_client *client);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* MG_ENABLE_TUN */
#endif /* CS_MONGOOSE_SRC_TUN_H_ */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/net.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*
* This software is dual-licensed: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation. For the terms of this
* license, see <http://www.gnu.org/licenses/>.
*
* You are free to use this software under the terms of the GNU General
* Public License, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* Alternatively, you can license this software under a commercial
* license, as set out in <https://www.cesanta.com/license>.
*/
/* Amalgamated: #include "common/cs_time.h" */
/* Amalgamated: #include "mongoose/src/dns.h" */
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/resolv.h" */
/* Amalgamated: #include "mongoose/src/util.h" */
/* Amalgamated: #include "mongoose/src/tun.h" */
#define MG_MAX_HOST_LEN 200
#define MG_COPY_COMMON_CONNECTION_OPTIONS(dst, src) \
memcpy(dst, src, sizeof(*dst));
/* Which flags can be pre-set by the user at connection creation time. */
#define _MG_ALLOWED_CONNECT_FLAGS_MASK \
(MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_ENABLE_BROADCAST)
/* Which flags should be modifiable by user's callbacks. */
#define _MG_CALLBACK_MODIFIABLE_FLAGS_MASK \
(MG_F_USER_1 | MG_F_USER_2 | MG_F_USER_3 | MG_F_USER_4 | MG_F_USER_5 | \
MG_F_USER_6 | MG_F_WEBSOCKET_NO_DEFRAG | MG_F_SEND_AND_CLOSE | \
MG_F_CLOSE_IMMEDIATELY | MG_F_IS_WEBSOCKET | MG_F_DELETE_CHUNK)
#ifndef intptr_t
#define intptr_t long
#endif
MG_INTERNAL void mg_add_conn(struct mg_mgr *mgr, struct mg_connection *c) {
DBG(("%p %p", mgr, c));
c->mgr = mgr;
c->next = mgr->active_connections;
mgr->active_connections = c;
c->prev = NULL;
if (c->next != NULL) c->next->prev = c;
if (c->sock != INVALID_SOCKET) {
c->iface->vtable->add_conn(c);
}
}
MG_INTERNAL void mg_remove_conn(struct mg_connection *conn) {
if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
if (conn->prev) conn->prev->next = conn->next;
if (conn->next) conn->next->prev = conn->prev;
conn->prev = conn->next = NULL;
conn->iface->vtable->remove_conn(conn);
}
MG_INTERNAL void mg_call(struct mg_connection *nc,
mg_event_handler_t ev_handler, void *user_data, int ev,
void *ev_data) {
if (ev_handler == NULL) {
/*
* If protocol handler is specified, call it. Otherwise, call user-specified
* event handler.
*/
ev_handler = nc->proto_handler ? nc->proto_handler : nc->handler;
}
if (ev != MG_EV_POLL) {
DBG(("%p %s ev=%d ev_data=%p flags=%lu rmbl=%d smbl=%d", nc,
ev_handler == nc->handler ? "user" : "proto", ev, ev_data, nc->flags,
(int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
}
#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
/* LCOV_EXCL_START */
if (nc->mgr->hexdump_file != NULL && ev != MG_EV_POLL &&
ev != MG_EV_SEND /* handled separately */) {
if (ev == MG_EV_RECV) {
mg_hexdump_connection(nc, nc->mgr->hexdump_file, nc->recv_mbuf.buf,
*(int *) ev_data, ev);
} else {
mg_hexdump_connection(nc, nc->mgr->hexdump_file, NULL, 0, ev);
}
}
/* LCOV_EXCL_STOP */
#endif
if (ev_handler != NULL) {
unsigned long flags_before = nc->flags;
size_t recv_mbuf_before = nc->recv_mbuf.len, recved;
ev_handler(nc, ev, ev_data MG_UD_ARG(user_data));
recved = (recv_mbuf_before - nc->recv_mbuf.len);
/* Prevent user handler from fiddling with system flags. */
if (ev_handler == nc->handler && nc->flags != flags_before) {
nc->flags = (flags_before & ~_MG_CALLBACK_MODIFIABLE_FLAGS_MASK) |
(nc->flags & _MG_CALLBACK_MODIFIABLE_FLAGS_MASK);
}
if (recved > 0 && !(nc->flags & MG_F_UDP)) {
nc->iface->vtable->recved(nc, recved);
}
}
if (ev != MG_EV_POLL) {
DBG(("%p after %s flags=%lu rmbl=%d smbl=%d", nc,
ev_handler == nc->handler ? "user" : "proto", nc->flags,
(int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
}
#if !MG_ENABLE_CALLBACK_USERDATA
(void) user_data;
#endif
}
void mg_if_timer(struct mg_connection *c, double now) {
if (c->ev_timer_time > 0 && now >= c->ev_timer_time) {
double old_value = c->ev_timer_time;
mg_call(c, NULL, c->user_data, MG_EV_TIMER, &now);
/*
* To prevent timer firing all the time, reset the timer after delivery.
* However, in case user sets it to new value, do not reset.
*/
if (c->ev_timer_time == old_value) {
c->ev_timer_time = 0;
}
}
}
void mg_if_poll(struct mg_connection *nc, time_t now) {
if (!(nc->flags & MG_F_SSL) || (nc->flags & MG_F_SSL_HANDSHAKE_DONE)) {
mg_call(nc, NULL, nc->user_data, MG_EV_POLL, &now);
}
}
static void mg_destroy_conn(struct mg_connection *conn, int destroy_if) {
if (destroy_if) conn->iface->vtable->destroy_conn(conn);
if (conn->proto_data != NULL && conn->proto_data_destructor != NULL) {
conn->proto_data_destructor(conn->proto_data);
}
#if MG_ENABLE_SSL
mg_ssl_if_conn_free(conn);
#endif
mbuf_free(&conn->recv_mbuf);
mbuf_free(&conn->send_mbuf);
memset(conn, 0, sizeof(*conn));
MG_FREE(conn);
}
void mg_close_conn(struct mg_connection *conn) {
DBG(("%p %lu %d", conn, conn->flags, conn->sock));
#if MG_ENABLE_SSL
if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
mg_ssl_if_conn_close_notify(conn);
}
#endif
mg_remove_conn(conn);
conn->iface->vtable->destroy_conn(conn);
mg_call(conn, NULL, conn->user_data, MG_EV_CLOSE, NULL);
mg_destroy_conn(conn, 0 /* destroy_if */);
}
void mg_mgr_init(struct mg_mgr *m, void *user_data) {
struct mg_mgr_init_opts opts;
memset(&opts, 0, sizeof(opts));
mg_mgr_init_opt(m, user_data, opts);
}
void mg_mgr_init_opt(struct mg_mgr *m, void *user_data,
struct mg_mgr_init_opts opts) {
memset(m, 0, sizeof(*m));
#if MG_ENABLE_BROADCAST
m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
#endif
m->user_data = user_data;
#ifdef _WIN32
{
WSADATA data;
WSAStartup(MAKEWORD(2, 2), &data);
}
#elif defined(__unix__)
/* Ignore SIGPIPE signal, so if client cancels the request, it
* won't kill the whole process. */
signal(SIGPIPE, SIG_IGN);
#endif
#if MG_ENABLE_SSL
{
static int init_done;
if (!init_done) {
mg_ssl_if_init();
init_done++;
}
}
#endif
{
int i;
if (opts.num_ifaces == 0) {
opts.num_ifaces = mg_num_ifaces;
opts.ifaces = mg_ifaces;
}
if (opts.main_iface != NULL) {
opts.ifaces[MG_MAIN_IFACE] = opts.main_iface;
}
m->num_ifaces = opts.num_ifaces;
m->ifaces =
(struct mg_iface **) MG_MALLOC(sizeof(*m->ifaces) * opts.num_ifaces);
for (i = 0; i < mg_num_ifaces; i++) {
m->ifaces[i] = mg_if_create_iface(opts.ifaces[i], m);
m->ifaces[i]->vtable->init(m->ifaces[i]);
}
}
if (opts.nameserver != NULL) {
m->nameserver = strdup(opts.nameserver);
}
DBG(("=================================="));
DBG(("init mgr=%p", m));
}
#if MG_ENABLE_JAVASCRIPT
static enum v7_err mg_send_js(struct v7 *v7, v7_val_t *res) {
v7_val_t arg0 = v7_arg(v7, 0);
v7_val_t arg1 = v7_arg(v7, 1);
struct mg_connection *c = (struct mg_connection *) v7_get_ptr(v7, arg0);
size_t len = 0;
if (v7_is_string(arg1)) {
const char *data = v7_get_string(v7, &arg1, &len);
mg_send(c, data, len);
}
*res = v7_mk_number(v7, len);
return V7_OK;
}
enum v7_err mg_enable_javascript(struct mg_mgr *m, struct v7 *v7,
const char *init_file_name) {
v7_val_t v;
m->v7 = v7;
v7_set_method(v7, v7_get_global(v7), "mg_send", mg_send_js);
return v7_exec_file(v7, init_file_name, &v);
}
#endif
void mg_mgr_free(struct mg_mgr *m) {
struct mg_connection *conn, *tmp_conn;
DBG(("%p", m));
if (m == NULL) return;
/* Do one last poll, see https://github.com/cesanta/mongoose/issues/286 */
mg_mgr_poll(m, 0);
#if MG_ENABLE_BROADCAST
if (m->ctl[0] != INVALID_SOCKET) closesocket(m->ctl[0]);
if (m->ctl[1] != INVALID_SOCKET) closesocket(m->ctl[1]);
m->ctl[0] = m->ctl[1] = INVALID_SOCKET;
#endif
for (conn = m->active_connections; conn != NULL; conn = tmp_conn) {
tmp_conn = conn->next;
mg_close_conn(conn);
}
{
int i;
for (i = 0; i < m->num_ifaces; i++) {
m->ifaces[i]->vtable->free(m->ifaces[i]);
MG_FREE(m->ifaces[i]);
}
MG_FREE(m->ifaces);
}
MG_FREE((char *) m->nameserver);
}
time_t mg_mgr_poll(struct mg_mgr *m, int timeout_ms) {
int i;
time_t now = 0; /* oh GCC, seriously ? */
if (m->num_ifaces == 0) {
LOG(LL_ERROR, ("cannot poll: no interfaces"));
return 0;
}
for (i = 0; i < m->num_ifaces; i++) {
now = m->ifaces[i]->vtable->poll(m->ifaces[i], timeout_ms);
}
return now;
}
int mg_vprintf(struct mg_connection *nc, const char *fmt, va_list ap) {
char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
int len;
if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
mg_send(nc, buf, len);
}
if (buf != mem && buf != NULL) {
MG_FREE(buf); /* LCOV_EXCL_LINE */
} /* LCOV_EXCL_LINE */
return len;
}
int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
int len;
va_list ap;
va_start(ap, fmt);
len = mg_vprintf(conn, fmt, ap);
va_end(ap);
return len;
}
#if MG_ENABLE_SYNC_RESOLVER
/* TODO(lsm): use non-blocking resolver */
static int mg_resolve2(const char *host, struct in_addr *ina) {
#if MG_ENABLE_GETADDRINFO
int rv = 0;
struct addrinfo hints, *servinfo, *p;
struct sockaddr_in *h = NULL;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if ((rv = getaddrinfo(host, NULL, NULL, &servinfo)) != 0) {
DBG(("getaddrinfo(%s) failed: %s", host, strerror(mg_get_errno())));
return 0;
}
for (p = servinfo; p != NULL; p = p->ai_next) {
memcpy(&h, &p->ai_addr, sizeof(struct sockaddr_in *));
memcpy(ina, &h->sin_addr, sizeof(ina));
}
freeaddrinfo(servinfo);
return 1;
#else
struct hostent *he;
if ((he = gethostbyname(host)) == NULL) {
DBG(("gethostbyname(%s) failed: %s", host, strerror(mg_get_errno())));
} else {
memcpy(ina, he->h_addr_list[0], sizeof(*ina));
return 1;
}
return 0;
#endif /* MG_ENABLE_GETADDRINFO */
}
int mg_resolve(const char *host, char *buf, size_t n) {
struct in_addr ad;
return mg_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
}
#endif /* MG_ENABLE_SYNC_RESOLVER */
MG_INTERNAL struct mg_connection *mg_create_connection_base(
struct mg_mgr *mgr, mg_event_handler_t callback,
struct mg_add_sock_opts opts) {
struct mg_connection *conn;
if ((conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn))) != NULL) {
conn->sock = INVALID_SOCKET;
conn->handler = callback;
conn->mgr = mgr;
conn->last_io_time = (time_t) mg_time();
conn->iface =
(opts.iface != NULL ? opts.iface : mgr->ifaces[MG_MAIN_IFACE]);
conn->flags = opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
conn->user_data = opts.user_data;
/*
* SIZE_MAX is defined as a long long constant in
* system headers on some platforms and so it
* doesn't compile with pedantic ansi flags.
*/
conn->recv_mbuf_limit = ~0;
} else {
MG_SET_PTRPTR(opts.error_string, "failed to create connection");
}
return conn;
}
MG_INTERNAL struct mg_connection *mg_create_connection(
struct mg_mgr *mgr, mg_event_handler_t callback,
struct mg_add_sock_opts opts) {
struct mg_connection *conn = mg_create_connection_base(mgr, callback, opts);
if (conn != NULL && !conn->iface->vtable->create_conn(conn)) {
MG_FREE(conn);
conn = NULL;
}
if (conn == NULL) {
MG_SET_PTRPTR(opts.error_string, "failed to init connection");
}
return conn;
}
/*
* Address format: [PROTO://][HOST]:PORT
*
* HOST could be IPv4/IPv6 address or a host name.
* `host` is a destination buffer to hold parsed HOST part. Should be at least
* MG_MAX_HOST_LEN bytes long.
* `proto` is a returned socket type, either SOCK_STREAM or SOCK_DGRAM
*
* Return:
* -1 on parse error
* 0 if HOST needs DNS lookup
* >0 length of the address string
*/
MG_INTERNAL int mg_parse_address(const char *str, union socket_address *sa,
int *proto, char *host, size_t host_len) {
unsigned int a, b, c, d, port = 0;
int ch, len = 0;
#if MG_ENABLE_IPV6
char buf[100];
#endif
/*
* MacOS needs that. If we do not zero it, subsequent bind() will fail.
* Also, all-zeroes in the socket address means binding to all addresses
* for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
*/
memset(sa, 0, sizeof(*sa));
sa->sin.sin_family = AF_INET;
*proto = SOCK_STREAM;
if (strncmp(str, "udp://", 6) == 0) {
str += 6;
*proto = SOCK_DGRAM;
} else if (strncmp(str, "tcp://", 6) == 0) {
str += 6;
}
if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
/* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */
sa->sin.sin_addr.s_addr =
htonl(((uint32_t) a << 24) | ((uint32_t) b << 16) | c << 8 | d);
sa->sin.sin_port = htons((uint16_t) port);
#if MG_ENABLE_IPV6
} else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
/* IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080 */
sa->sin6.sin6_family = AF_INET6;
sa->sin.sin_port = htons((uint16_t) port);
#endif
#if MG_ENABLE_ASYNC_RESOLVER
} else if (strlen(str) < host_len &&
sscanf(str, "%[^ :]:%u%n", host, &port, &len) == 2) {
sa->sin.sin_port = htons((uint16_t) port);
if (mg_resolve_from_hosts_file(host, sa) != 0) {
/*
* if resolving from hosts file failed and the host
* we are trying to resolve is `localhost` - we should
* try to resolve it using `gethostbyname` and do not try
* to resolve it via DNS server if gethostbyname has failed too
*/
if (mg_ncasecmp(host, "localhost", 9) != 0) {
return 0;
}
#if MG_ENABLE_SYNC_RESOLVER
if (!mg_resolve2(host, &sa->sin.sin_addr)) {
return -1;
}
#else
return -1;
#endif
}
#endif
} else if (sscanf(str, ":%u%n", &port, &len) == 1 ||
sscanf(str, "%u%n", &port, &len) == 1) {
/* If only port is specified, bind to IPv4, INADDR_ANY */
sa->sin.sin_port = htons((uint16_t) port);
} else {
return -1;
}
/* Required for MG_ENABLE_ASYNC_RESOLVER=0 */
(void) host;
(void) host_len;
ch = str[len]; /* Character that follows the address */
return port < 0xffffUL && (ch == '\0' || ch == ',' || isspace(ch)) ? len : -1;
}
struct mg_connection *mg_if_accept_new_conn(struct mg_connection *lc) {
struct mg_add_sock_opts opts;
struct mg_connection *nc;
memset(&opts, 0, sizeof(opts));
nc = mg_create_connection(lc->mgr, lc->handler, opts);
if (nc == NULL) return NULL;
nc->listener = lc;
nc->proto_handler = lc->proto_handler;
nc->user_data = lc->user_data;
nc->recv_mbuf_limit = lc->recv_mbuf_limit;
nc->iface = lc->iface;
if (lc->flags & MG_F_SSL) nc->flags |= MG_F_SSL;
mg_add_conn(nc->mgr, nc);
DBG(("%p %p %d %d", lc, nc, nc->sock, (int) nc->flags));
return nc;
}
void mg_if_accept_tcp_cb(struct mg_connection *nc, union socket_address *sa,
size_t sa_len) {
(void) sa_len;
nc->sa = *sa;
mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa);
}
void mg_send(struct mg_connection *nc, const void *buf, int len) {
nc->last_io_time = (time_t) mg_time();
if (nc->flags & MG_F_UDP) {
nc->iface->vtable->udp_send(nc, buf, len);
} else {
nc->iface->vtable->tcp_send(nc, buf, len);
}
#if !defined(NO_LIBC) && MG_ENABLE_HEXDUMP
if (nc->mgr && nc->mgr->hexdump_file != NULL) {
mg_hexdump_connection(nc, nc->mgr->hexdump_file, buf, len, MG_EV_SEND);
}
#endif
}
void mg_if_sent_cb(struct mg_connection *nc, int num_sent) {
if (num_sent < 0) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
mg_call(nc, NULL, nc->user_data, MG_EV_SEND, &num_sent);
}
MG_INTERNAL void mg_recv_common(struct mg_connection *nc, void *buf, int len,
int own) {
DBG(("%p %d %u", nc, len, (unsigned int) nc->recv_mbuf.len));
if (nc->flags & MG_F_CLOSE_IMMEDIATELY) {
DBG(("%p discarded %d bytes", nc, len));
/*
* This connection will not survive next poll. Do not deliver events,
* send data to /dev/null without acking.
*/
if (own) {
MG_FREE(buf);
}
return;
}
nc->last_io_time = (time_t) mg_time();
if (!own) {
mbuf_append(&nc->recv_mbuf, buf, len);
} else if (nc->recv_mbuf.len == 0) {
/* Adopt buf as recv_mbuf's backing store. */
mbuf_free(&nc->recv_mbuf);
nc->recv_mbuf.buf = (char *) buf;
nc->recv_mbuf.size = nc->recv_mbuf.len = len;
} else {
mbuf_append(&nc->recv_mbuf, buf, len);
MG_FREE(buf);
}
mg_call(nc, NULL, nc->user_data, MG_EV_RECV, &len);
}
void mg_if_recv_tcp_cb(struct mg_connection *nc, void *buf, int len, int own) {
mg_recv_common(nc, buf, len, own);
}
void mg_if_recv_udp_cb(struct mg_connection *nc, void *buf, int len,
union socket_address *sa, size_t sa_len) {
assert(nc->flags & MG_F_UDP);
DBG(("%p %u", nc, (unsigned int) len));
if (nc->flags & MG_F_LISTENING) {
struct mg_connection *lc = nc;
/*
* Do we have an existing connection for this source?
* This is very inefficient for long connection lists.
*/
for (nc = mg_next(lc->mgr, NULL); nc != NULL; nc = mg_next(lc->mgr, nc)) {
if (memcmp(&nc->sa.sa, &sa->sa, sa_len) == 0 && nc->listener == lc) {
break;
}
}
if (nc == NULL) {
struct mg_add_sock_opts opts;
memset(&opts, 0, sizeof(opts));
/* Create fake connection w/out sock initialization */
nc = mg_create_connection_base(lc->mgr, lc->handler, opts);
if (nc != NULL) {
nc->sock = lc->sock;
nc->listener = lc;
nc->sa = *sa;
nc->proto_handler = lc->proto_handler;
nc->user_data = lc->user_data;
nc->recv_mbuf_limit = lc->recv_mbuf_limit;
nc->flags = MG_F_UDP;
/*
* Long-lived UDP "connections" i.e. interactions that involve more
* than one request and response are rare, most are transactional:
* response is sent and the "connection" is closed. Or - should be.
* But users (including ourselves) tend to forget about that part,
* because UDP is connectionless and one does not think about
* processing a UDP request as handling a connection that needs to be
* closed. Thus, we begin with SEND_AND_CLOSE flag set, which should
* be a reasonable default for most use cases, but it is possible to
* turn it off the connection should be kept alive after processing.
*/
nc->flags |= MG_F_SEND_AND_CLOSE;
mg_add_conn(lc->mgr, nc);
mg_call(nc, NULL, nc->user_data, MG_EV_ACCEPT, &nc->sa);
} else {
DBG(("OOM"));
/* No return here, we still need to drop on the floor */
}
}
}
if (nc != NULL) {
mg_recv_common(nc, buf, len, 1);
} else {
/* Drop on the floor. */
MG_FREE(buf);
nc->iface->vtable->recved(nc, len);
}
}
/*
* Schedules an async connect for a resolved address and proto.
* Called from two places: `mg_connect_opt()` and from async resolver.
* When called from the async resolver, it must trigger `MG_EV_CONNECT` event
* with a failure flag to indicate connection failure.
*/
MG_INTERNAL struct mg_connection *mg_do_connect(struct mg_connection *nc,
int proto,
union socket_address *sa) {
DBG(("%p %s://%s:%hu", nc, proto == SOCK_DGRAM ? "udp" : "tcp",
inet_ntoa(sa->sin.sin_addr), ntohs(sa->sin.sin_port)));
nc->flags |= MG_F_CONNECTING;
if (proto == SOCK_DGRAM) {
nc->iface->vtable->connect_udp(nc);
} else {
nc->iface->vtable->connect_tcp(nc, sa);
}
mg_add_conn(nc->mgr, nc);
return nc;
}
void mg_if_connect_cb(struct mg_connection *nc, int err) {
DBG(("%p connect, err=%d", nc, err));
nc->flags &= ~MG_F_CONNECTING;
if (err != 0) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &err);
}
#if MG_ENABLE_ASYNC_RESOLVER
/*
* Callback for the async resolver on mg_connect_opt() call.
* Main task of this function is to trigger MG_EV_CONNECT event with
* either failure (and dealloc the connection)
* or success (and proceed with connect()
*/
static void resolve_cb(struct mg_dns_message *msg, void *data,
enum mg_resolve_err e) {
struct mg_connection *nc = (struct mg_connection *) data;
int i;
int failure = -1;
nc->flags &= ~MG_F_RESOLVING;
if (msg != NULL) {
/*
* Take the first DNS A answer and run...
*/
for (i = 0; i < msg->num_answers; i++) {
if (msg->answers[i].rtype == MG_DNS_A_RECORD) {
/*
* Async resolver guarantees that there is at least one answer.
* TODO(lsm): handle IPv6 answers too
*/
mg_dns_parse_record_data(msg, &msg->answers[i], &nc->sa.sin.sin_addr,
4);
mg_do_connect(nc, nc->flags & MG_F_UDP ? SOCK_DGRAM : SOCK_STREAM,
&nc->sa);
return;
}
}
}
if (e == MG_RESOLVE_TIMEOUT) {
double now = mg_time();
mg_call(nc, NULL, nc->user_data, MG_EV_TIMER, &now);
}
/*
* If we get there was no MG_DNS_A_RECORD in the answer
*/
mg_call(nc, NULL, nc->user_data, MG_EV_CONNECT, &failure);
mg_call(nc, NULL, nc->user_data, MG_EV_CLOSE, NULL);
mg_destroy_conn(nc, 1 /* destroy_if */);
}
#endif
struct mg_connection *mg_connect(struct mg_mgr *mgr, const char *address,
MG_CB(mg_event_handler_t callback,
void *user_data)) {
struct mg_connect_opts opts;
memset(&opts, 0, sizeof(opts));
return mg_connect_opt(mgr, address, MG_CB(callback, user_data), opts);
}
struct mg_connection *mg_connect_opt(struct mg_mgr *mgr, const char *address,
MG_CB(mg_event_handler_t callback,
void *user_data),
struct mg_connect_opts opts) {
struct mg_connection *nc = NULL;
int proto, rc;
struct mg_add_sock_opts add_sock_opts;
char host[MG_MAX_HOST_LEN];
MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
if ((nc = mg_create_connection(mgr, callback, add_sock_opts)) == NULL) {
return NULL;
}
if ((rc = mg_parse_address(address, &nc->sa, &proto, host, sizeof(host))) <
0) {
/* Address is malformed */
MG_SET_PTRPTR(opts.error_string, "cannot parse address");
mg_destroy_conn(nc, 1 /* destroy_if */);
return NULL;
}
nc->flags |= opts.flags & _MG_ALLOWED_CONNECT_FLAGS_MASK;
nc->flags |= (proto == SOCK_DGRAM) ? MG_F_UDP : 0;
#if MG_ENABLE_CALLBACK_USERDATA
nc->user_data = user_data;
#else
nc->user_data = opts.user_data;
#endif
#if MG_ENABLE_SSL
DBG(("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"),
(opts.ssl_key ? opts.ssl_key : "-"),
(opts.ssl_ca_cert ? opts.ssl_ca_cert : "-")));
if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL ||
opts.ssl_psk_identity != NULL) {
const char *err_msg = NULL;
struct mg_ssl_if_conn_params params;
if (nc->flags & MG_F_UDP) {
MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported");
mg_destroy_conn(nc, 1 /* destroy_if */);
return NULL;
}
memset(¶ms, 0, sizeof(params));
params.cert = opts.ssl_cert;
params.key = opts.ssl_key;
params.ca_cert = opts.ssl_ca_cert;
params.cipher_suites = opts.ssl_cipher_suites;
params.psk_identity = opts.ssl_psk_identity;
params.psk_key = opts.ssl_psk_key;
if (opts.ssl_ca_cert != NULL) {
if (opts.ssl_server_name != NULL) {
if (strcmp(opts.ssl_server_name, "*") != 0) {
params.server_name = opts.ssl_server_name;
}
} else if (rc == 0) { /* If it's a DNS name, use host. */
params.server_name = host;
}
}
if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) {
MG_SET_PTRPTR(opts.error_string, err_msg);
mg_destroy_conn(nc, 1 /* destroy_if */);
return NULL;
}
nc->flags |= MG_F_SSL;
}
#endif /* MG_ENABLE_SSL */
if (rc == 0) {
#if MG_ENABLE_ASYNC_RESOLVER
/*
* DNS resolution is required for host.
* mg_parse_address() fills port in nc->sa, which we pass to resolve_cb()
*/
struct mg_connection *dns_conn = NULL;
struct mg_resolve_async_opts o;
memset(&o, 0, sizeof(o));
o.dns_conn = &dns_conn;
o.nameserver = opts.nameserver;
if (mg_resolve_async_opt(nc->mgr, host, MG_DNS_A_RECORD, resolve_cb, nc,
o) != 0) {
MG_SET_PTRPTR(opts.error_string, "cannot schedule DNS lookup");
mg_destroy_conn(nc, 1 /* destroy_if */);
return NULL;
}
nc->priv_2 = dns_conn;
nc->flags |= MG_F_RESOLVING;
return nc;
#else
MG_SET_PTRPTR(opts.error_string, "Resolver is disabled");
mg_destroy_conn(nc, 1 /* destroy_if */);
return NULL;
#endif
} else {
/* Address is parsed and resolved to IP. proceed with connect() */
return mg_do_connect(nc, proto, &nc->sa);
}
}
struct mg_connection *mg_bind(struct mg_mgr *srv, const char *address,
MG_CB(mg_event_handler_t event_handler,
void *user_data)) {
struct mg_bind_opts opts;
memset(&opts, 0, sizeof(opts));
return mg_bind_opt(srv, address, MG_CB(event_handler, user_data), opts);
}
struct mg_connection *mg_bind_opt(struct mg_mgr *mgr, const char *address,
MG_CB(mg_event_handler_t callback,
void *user_data),
struct mg_bind_opts opts) {
union socket_address sa;
struct mg_connection *nc = NULL;
int proto, rc;
struct mg_add_sock_opts add_sock_opts;
char host[MG_MAX_HOST_LEN];
MG_COPY_COMMON_CONNECTION_OPTIONS(&add_sock_opts, &opts);
#if MG_ENABLE_TUN
if (mg_strncmp(mg_mk_str(address), mg_mk_str("ws://"), 5) == 0 ||
mg_strncmp(mg_mk_str(address), mg_mk_str("wss://"), 6) == 0) {
return mg_tun_bind_opt(mgr, address, MG_CB(callback, user_data), opts);
}
#endif
if (mg_parse_address(address, &sa, &proto, host, sizeof(host)) <= 0) {
MG_SET_PTRPTR(opts.error_string, "cannot parse address");
return NULL;
}
nc = mg_create_connection(mgr, callback, add_sock_opts);
if (nc == NULL) {
return NULL;
}
nc->sa = sa;
nc->flags |= MG_F_LISTENING;
if (proto == SOCK_DGRAM) nc->flags |= MG_F_UDP;
#if MG_ENABLE_SSL
DBG(("%p %s %s,%s,%s", nc, address, (opts.ssl_cert ? opts.ssl_cert : "-"),
(opts.ssl_key ? opts.ssl_key : "-"),
(opts.ssl_ca_cert ? opts.ssl_ca_cert : "-")));
if (opts.ssl_cert != NULL || opts.ssl_ca_cert != NULL) {
const char *err_msg = NULL;
struct mg_ssl_if_conn_params params;
if (nc->flags & MG_F_UDP) {
MG_SET_PTRPTR(opts.error_string, "SSL for UDP is not supported");
mg_destroy_conn(nc, 1 /* destroy_if */);
return NULL;
}
memset(¶ms, 0, sizeof(params));
params.cert = opts.ssl_cert;
params.key = opts.ssl_key;
params.ca_cert = opts.ssl_ca_cert;
params.cipher_suites = opts.ssl_cipher_suites;
if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) {
MG_SET_PTRPTR(opts.error_string, err_msg);
mg_destroy_conn(nc, 1 /* destroy_if */);
return NULL;
}
nc->flags |= MG_F_SSL;
}
#endif /* MG_ENABLE_SSL */
if (nc->flags & MG_F_UDP) {
rc = nc->iface->vtable->listen_udp(nc, &nc->sa);
} else {
rc = nc->iface->vtable->listen_tcp(nc, &nc->sa);
}
if (rc != 0) {
DBG(("Failed to open listener: %d", rc));
MG_SET_PTRPTR(opts.error_string, "failed to open listener");
mg_destroy_conn(nc, 1 /* destroy_if */);
return NULL;
}
mg_add_conn(nc->mgr, nc);
#if MG_ENABLE_CALLBACK_USERDATA
(void) user_data;
#endif
return nc;
}
struct mg_connection *mg_next(struct mg_mgr *s, struct mg_connection *conn) {
return conn == NULL ? s->active_connections : conn->next;
}
#if MG_ENABLE_BROADCAST
void mg_broadcast(struct mg_mgr *mgr, mg_event_handler_t cb, void *data,
size_t len) {
struct ctl_msg ctl_msg;
/*
* Mongoose manager has a socketpair, `struct mg_mgr::ctl`,
* where `mg_broadcast()` pushes the message.
* `mg_mgr_poll()` wakes up, reads a message from the socket pair, and calls
* specified callback for each connection. Thus the callback function executes
* in event manager thread.
*/
if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
len < sizeof(ctl_msg.message)) {
size_t dummy;
ctl_msg.callback = cb;
memcpy(ctl_msg.message, data, len);
dummy = MG_SEND_FUNC(mgr->ctl[0], (char *) &ctl_msg,
offsetof(struct ctl_msg, message) + len, 0);
dummy = MG_RECV_FUNC(mgr->ctl[0], (char *) &len, 1, 0);
(void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
}
}
#endif /* MG_ENABLE_BROADCAST */
static int isbyte(int n) {
return n >= 0 && n <= 255;
}
static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
int n, a, b, c, d, slash = 32, len = 0;
if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && slash >= 0 &&
slash < 33) {
len = n;
*net =
((uint32_t) a << 24) | ((uint32_t) b << 16) | ((uint32_t) c << 8) | d;
*mask = slash ? 0xffffffffU << (32 - slash) : 0;
}
return len;
}
int mg_check_ip_acl(const char *acl, uint32_t remote_ip) {
int allowed, flag;
uint32_t net, mask;
struct mg_str vec;
/* If any ACL is set, deny by default */
allowed = (acl == NULL || *acl == '\0') ? '+' : '-';
while ((acl = mg_next_comma_list_entry(acl, &vec, NULL)) != NULL) {
flag = vec.p[0];
if ((flag != '+' && flag != '-') ||
parse_net(&vec.p[1], &net, &mask) == 0) {
return -1;
}
if (net == (remote_ip & mask)) {
allowed = flag;
}
}
DBG(("%08x %c", remote_ip, allowed));
return allowed == '+';
}
/* Move data from one connection to another */
void mg_forward(struct mg_connection *from, struct mg_connection *to) {
mg_send(to, from->recv_mbuf.buf, from->recv_mbuf.len);
mbuf_remove(&from->recv_mbuf, from->recv_mbuf.len);
}
double mg_set_timer(struct mg_connection *c, double timestamp) {
double result = c->ev_timer_time;
c->ev_timer_time = timestamp;
/*
* If this connection is resolving, it's not in the list of active
* connections, so not processed yet. It has a DNS resolver connection
* linked to it. Set up a timer for the DNS connection.
*/
DBG(("%p %p %d -> %lu", c, c->priv_2, c->flags & MG_F_RESOLVING,
(unsigned long) timestamp));
if ((c->flags & MG_F_RESOLVING) && c->priv_2 != NULL) {
((struct mg_connection *) c->priv_2)->ev_timer_time = timestamp;
}
return result;
}
void mg_sock_set(struct mg_connection *nc, sock_t sock) {
if (sock != INVALID_SOCKET) {
nc->iface->vtable->sock_set(nc, sock);
}
}
void mg_if_get_conn_addr(struct mg_connection *nc, int remote,
union socket_address *sa) {
nc->iface->vtable->get_conn_addr(nc, remote, sa);
}
struct mg_connection *mg_add_sock_opt(struct mg_mgr *s, sock_t sock,
MG_CB(mg_event_handler_t callback,
void *user_data),
struct mg_add_sock_opts opts) {
#if MG_ENABLE_CALLBACK_USERDATA
opts.user_data = user_data;
#endif
struct mg_connection *nc = mg_create_connection_base(s, callback, opts);
if (nc != NULL) {
mg_sock_set(nc, sock);
mg_add_conn(nc->mgr, nc);
}
return nc;
}
struct mg_connection *mg_add_sock(struct mg_mgr *s, sock_t sock,
MG_CB(mg_event_handler_t callback,
void *user_data)) {
struct mg_add_sock_opts opts;
memset(&opts, 0, sizeof(opts));
return mg_add_sock_opt(s, sock, MG_CB(callback, user_data), opts);
}
double mg_time(void) {
return cs_time();
}
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/net_if_socket.h"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#ifndef CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
#define CS_MONGOOSE_SRC_NET_IF_SOCKET_H_
/* Amalgamated: #include "mongoose/src/net_if.h" */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#ifndef MG_ENABLE_NET_IF_SOCKET
#define MG_ENABLE_NET_IF_SOCKET MG_NET_IF == MG_NET_IF_SOCKET
#endif
extern const struct mg_iface_vtable mg_socket_iface_vtable;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_MONGOOSE_SRC_NET_IF_SOCKET_H_ */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/net_if_tun.h"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#ifndef CS_MONGOOSE_SRC_NET_IF_TUN_H_
#define CS_MONGOOSE_SRC_NET_IF_TUN_H_
#if MG_ENABLE_TUN
/* Amalgamated: #include "mongoose/src/net_if.h" */
struct mg_tun_client;
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
extern const struct mg_iface_vtable mg_tun_iface_vtable;
struct mg_connection *mg_tun_if_find_conn(struct mg_tun_client *client,
uint32_t stream_id);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* MG_ENABLE_TUN */
#endif /* CS_MONGOOSE_SRC_NET_IF_TUN_H_ */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/net_if.c"
#endif
/* Amalgamated: #include "mongoose/src/net_if.h" */
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/net_if_socket.h" */
/* Amalgamated: #include "mongoose/src/net_if_tun.h" */
extern const struct mg_iface_vtable mg_default_iface_vtable;
#if MG_ENABLE_TUN
const struct mg_iface_vtable *mg_ifaces[] = {&mg_default_iface_vtable,
&mg_tun_iface_vtable};
#else
const struct mg_iface_vtable *mg_ifaces[] = {&mg_default_iface_vtable};
#endif
int mg_num_ifaces = (int) (sizeof(mg_ifaces) / sizeof(mg_ifaces[0]));
struct mg_iface *mg_if_create_iface(const struct mg_iface_vtable *vtable,
struct mg_mgr *mgr) {
struct mg_iface *iface = (struct mg_iface *) MG_CALLOC(1, sizeof(*iface));
iface->mgr = mgr;
iface->data = NULL;
iface->vtable = vtable;
return iface;
}
struct mg_iface *mg_find_iface(struct mg_mgr *mgr,
const struct mg_iface_vtable *vtable,
struct mg_iface *from) {
int i = 0;
if (from != NULL) {
for (i = 0; i < mgr->num_ifaces; i++) {
if (mgr->ifaces[i] == from) {
i++;
break;
}
}
}
for (; i < mgr->num_ifaces; i++) {
if (mgr->ifaces[i]->vtable == vtable) {
return mgr->ifaces[i];
}
}
return NULL;
}
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/net_if_socket.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_NET_IF_SOCKET
/* Amalgamated: #include "mongoose/src/net_if_socket.h" */
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/util.h" */
#define MG_TCP_RECV_BUFFER_SIZE 1024
#define MG_UDP_RECV_BUFFER_SIZE 1500
static sock_t mg_open_listening_socket(union socket_address *sa, int type,
int proto);
#if MG_ENABLE_SSL
static void mg_ssl_begin(struct mg_connection *nc);
#endif
void mg_set_non_blocking_mode(sock_t sock) {
#ifdef _WIN32
unsigned long on = 1;
ioctlsocket(sock, FIONBIO, &on);
#else
int flags = fcntl(sock, F_GETFL, 0);
fcntl(sock, F_SETFL, flags | O_NONBLOCK);
#endif
}
static int mg_is_error(int n) {
int err = mg_get_errno();
return (n < 0 && err != EINPROGRESS && err != EWOULDBLOCK
#ifndef WINCE
&& err != EAGAIN && err != EINTR
#endif
#ifdef _WIN32
&& WSAGetLastError() != WSAEINTR &&
WSAGetLastError() != WSAEWOULDBLOCK
#endif
);
}
void mg_socket_if_connect_tcp(struct mg_connection *nc,
const union socket_address *sa) {
int rc, proto = 0;
nc->sock = socket(AF_INET, SOCK_STREAM, proto);
if (nc->sock == INVALID_SOCKET) {
nc->err = mg_get_errno() ? mg_get_errno() : 1;
return;
}
#if !defined(MG_ESP8266)
mg_set_non_blocking_mode(nc->sock);
#endif
rc = connect(nc->sock, &sa->sa, sizeof(sa->sin));
nc->err = mg_is_error(rc) ? mg_get_errno() : 0;
DBG(("%p sock %d rc %d errno %d err %d", nc, nc->sock, rc, mg_get_errno(),
nc->err));
}
void mg_socket_if_connect_udp(struct mg_connection *nc) {
nc->sock = socket(AF_INET, SOCK_DGRAM, 0);
if (nc->sock == INVALID_SOCKET) {
nc->err = mg_get_errno() ? mg_get_errno() : 1;
return;
}
if (nc->flags & MG_F_ENABLE_BROADCAST) {
int optval = 1;
setsockopt(nc->sock, SOL_SOCKET, SO_BROADCAST, (const char *) &optval,
sizeof(optval));
}
nc->err = 0;
}
int mg_socket_if_listen_tcp(struct mg_connection *nc,
union socket_address *sa) {
int proto = 0;
sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM, proto);
if (sock == INVALID_SOCKET) {
return (mg_get_errno() ? mg_get_errno() : 1);
}
mg_sock_set(nc, sock);
return 0;
}
int mg_socket_if_listen_udp(struct mg_connection *nc,
union socket_address *sa) {
sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM, 0);
if (sock == INVALID_SOCKET) return (mg_get_errno() ? mg_get_errno() : 1);
mg_sock_set(nc, sock);
return 0;
}
void mg_socket_if_tcp_send(struct mg_connection *nc, const void *buf,
size_t len) {
mbuf_append(&nc->send_mbuf, buf, len);
}
void mg_socket_if_udp_send(struct mg_connection *nc, const void *buf,
size_t len) {
mbuf_append(&nc->send_mbuf, buf, len);
}
void mg_socket_if_recved(struct mg_connection *nc, size_t len) {
(void) nc;
(void) len;
}
int mg_socket_if_create_conn(struct mg_connection *nc) {
(void) nc;
return 1;
}
void mg_socket_if_destroy_conn(struct mg_connection *nc) {
if (nc->sock == INVALID_SOCKET) return;
if (!(nc->flags & MG_F_UDP)) {
closesocket(nc->sock);
} else {
/* Only close outgoing UDP sockets or listeners. */
if (nc->listener == NULL) closesocket(nc->sock);
}
nc->sock = INVALID_SOCKET;
}
static int mg_accept_conn(struct mg_connection *lc) {
struct mg_connection *nc;
union socket_address sa;
socklen_t sa_len = sizeof(sa);
/* NOTE(lsm): on Windows, sock is always > FD_SETSIZE */
sock_t sock = accept(lc->sock, &sa.sa, &sa_len);
if (sock == INVALID_SOCKET) {
if (mg_is_error(-1)) DBG(("%p: failed to accept: %d", lc, mg_get_errno()));
return 0;
}
nc = mg_if_accept_new_conn(lc);
if (nc == NULL) {
closesocket(sock);
return 0;
}
DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr),
ntohs(sa.sin.sin_port)));
mg_sock_set(nc, sock);
#if MG_ENABLE_SSL
if (lc->flags & MG_F_SSL) {
if (mg_ssl_if_conn_accept(nc, lc) != MG_SSL_OK) mg_close_conn(nc);
} else
#endif
{
mg_if_accept_tcp_cb(nc, &sa, sa_len);
}
return 1;
}
/* 'sa' must be an initialized address to bind to */
static sock_t mg_open_listening_socket(union socket_address *sa, int type,
int proto) {
socklen_t sa_len =
(sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
sock_t sock = INVALID_SOCKET;
#if !MG_LWIP
int on = 1;
#endif
if ((sock = socket(sa->sa.sa_family, type, proto)) != INVALID_SOCKET &&
#if !MG_LWIP /* LWIP doesn't support either */
#if defined(_WIN32) && defined(SO_EXCLUSIVEADDRUSE) && !defined(WINCE)
/* "Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE" http://goo.gl/RmrFTm */
!setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (void *) &on,
sizeof(on)) &&
#endif
#if !defined(_WIN32) || !defined(SO_EXCLUSIVEADDRUSE)
/*
* SO_RESUSEADDR is not enabled on Windows because the semantics of
* SO_REUSEADDR on UNIX and Windows is different. On Windows,
* SO_REUSEADDR allows to bind a socket to a port without error even if
* the port is already open by another program. This is not the behavior
* SO_REUSEADDR was designed for, and leads to hard-to-track failure
* scenarios. Therefore, SO_REUSEADDR was disabled on Windows unless
* SO_EXCLUSIVEADDRUSE is supported and set on a socket.
*/
!setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
#endif
#endif /* !MG_LWIP */
!bind(sock, &sa->sa, sa_len) &&
(type == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
#if !MG_LWIP
mg_set_non_blocking_mode(sock);
/* In case port was set to 0, get the real port number */
(void) getsockname(sock, &sa->sa, &sa_len);
#endif
} else if (sock != INVALID_SOCKET) {
closesocket(sock);
sock = INVALID_SOCKET;
}
return sock;
}
static void mg_write_to_socket(struct mg_connection *nc) {
struct mbuf *io = &nc->send_mbuf;
int n = 0;
#if MG_LWIP
/* With LWIP we don't know if the socket is ready */
if (io->len == 0) return;
#endif
assert(io->len > 0);
if (nc->flags & MG_F_UDP) {
int n =
sendto(nc->sock, io->buf, io->len, 0, &nc->sa.sa, sizeof(nc->sa.sin));
DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, mg_get_errno(),
inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port)));
if (n > 0) {
mbuf_remove(io, n);
mg_if_sent_cb(nc, n);
}
return;
}
#if MG_ENABLE_SSL
if (nc->flags & MG_F_SSL) {
if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
n = mg_ssl_if_write(nc, io->buf, io->len);
DBG(("%p %d bytes -> %d (SSL)", nc, n, nc->sock));
if (n < 0) {
if (n != MG_SSL_WANT_READ && n != MG_SSL_WANT_WRITE) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
return;
} else {
/* Successful SSL operation, clear off SSL wait flags */
nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
}
} else {
mg_ssl_begin(nc);
return;
}
} else
#endif
{
n = (int) MG_SEND_FUNC(nc->sock, io->buf, io->len, 0);
DBG(("%p %d bytes -> %d", nc, n, nc->sock));
if (n < 0 && mg_is_error(n)) {
/* Something went wrong, drop the connection. */
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return;
}
}
if (n > 0) {
mbuf_remove(io, n);
mg_if_sent_cb(nc, n);
}
}
MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) {
size_t avail;
if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
return avail > max ? max : avail;
}
static void mg_handle_tcp_read(struct mg_connection *conn) {
int n = 0;
char *buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
if (buf == NULL) {
DBG(("OOM"));
return;
}
#if MG_ENABLE_SSL
if (conn->flags & MG_F_SSL) {
if (conn->flags & MG_F_SSL_HANDSHAKE_DONE) {
/* SSL library may have more bytes ready to read than we ask to read.
* Therefore, read in a loop until we read everything. Without the loop,
* we skip to the next select() cycle which can just timeout. */
while ((n = mg_ssl_if_read(conn, buf, MG_TCP_RECV_BUFFER_SIZE)) > 0) {
DBG(("%p %d bytes <- %d (SSL)", conn, n, conn->sock));
mg_if_recv_tcp_cb(conn, buf, n, 1 /* own */);
buf = NULL;
if (conn->flags & MG_F_CLOSE_IMMEDIATELY) break;
/* buf has been freed, we need a new one. */
buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
if (buf == NULL) break;
}
MG_FREE(buf);
if (n < 0 && n != MG_SSL_WANT_READ) conn->flags |= MG_F_CLOSE_IMMEDIATELY;
} else {
MG_FREE(buf);
mg_ssl_begin(conn);
return;
}
} else
#endif
{
n = (int) MG_RECV_FUNC(conn->sock, buf,
recv_avail_size(conn, MG_TCP_RECV_BUFFER_SIZE), 0);
DBG(("%p %d bytes (PLAIN) <- %d", conn, n, conn->sock));
if (n > 0) {
mg_if_recv_tcp_cb(conn, buf, n, 1 /* own */);
} else {
MG_FREE(buf);
}
if (n == 0) {
/* Orderly shutdown of the socket, try flushing output. */
conn->flags |= MG_F_SEND_AND_CLOSE;
} else if (mg_is_error(n)) {
conn->flags |= MG_F_CLOSE_IMMEDIATELY;
}
}
}
static int mg_recvfrom(struct mg_connection *nc, union socket_address *sa,
socklen_t *sa_len, char **buf) {
int n;
*buf = (char *) MG_MALLOC(MG_UDP_RECV_BUFFER_SIZE);
if (*buf == NULL) {
DBG(("Out of memory"));
return -ENOMEM;
}
n = recvfrom(nc->sock, *buf, MG_UDP_RECV_BUFFER_SIZE, 0, &sa->sa, sa_len);
if (n <= 0) {
DBG(("%p recvfrom: %s", nc, strerror(mg_get_errno())));
MG_FREE(*buf);
}
return n;
}
static void mg_handle_udp_read(struct mg_connection *nc) {
char *buf = NULL;
union socket_address sa;
socklen_t sa_len = sizeof(sa);
int n = mg_recvfrom(nc, &sa, &sa_len, &buf);
DBG(("%p %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr),
ntohs(nc->sa.sin.sin_port)));
mg_if_recv_udp_cb(nc, buf, n, &sa, sa_len);
}
#if MG_ENABLE_SSL
static void mg_ssl_begin(struct mg_connection *nc) {
int server_side = (nc->listener != NULL);
enum mg_ssl_if_result res = mg_ssl_if_handshake(nc);
DBG(("%p %d res %d", nc, server_side, res));
if (res == MG_SSL_OK) {
nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
nc->flags &= ~(MG_F_WANT_READ | MG_F_WANT_WRITE);
if (server_side) {
union socket_address sa;
socklen_t sa_len = sizeof(sa);
(void) getpeername(nc->sock, &sa.sa, &sa_len);
mg_if_accept_tcp_cb(nc, &sa, sa_len);
} else {
mg_if_connect_cb(nc, 0);
}
} else if (res != MG_SSL_WANT_READ && res != MG_SSL_WANT_WRITE) {
if (!server_side) {
mg_if_connect_cb(nc, res);
}
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
}
#endif /* MG_ENABLE_SSL */
#define _MG_F_FD_CAN_READ 1
#define _MG_F_FD_CAN_WRITE 1 << 1
#define _MG_F_FD_ERROR 1 << 2
void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
int worth_logging =
fd_flags != 0 || (nc->flags & (MG_F_WANT_READ | MG_F_WANT_WRITE));
if (worth_logging) {
DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock,
fd_flags, nc->flags, (int) nc->recv_mbuf.len,
(int) nc->send_mbuf.len));
}
if (nc->flags & MG_F_CONNECTING) {
if (fd_flags != 0) {
int err = 0;
#if !defined(MG_ESP8266)
if (!(nc->flags & MG_F_UDP)) {
socklen_t len = sizeof(err);
int ret =
getsockopt(nc->sock, SOL_SOCKET, SO_ERROR, (char *) &err, &len);
if (ret != 0) {
err = 1;
} else if (err == EAGAIN || err == EWOULDBLOCK) {
err = 0;
}
}
#else
/*
* On ESP8266 we use blocking connect.
*/
err = nc->err;
#endif
#if MG_ENABLE_SSL
if ((nc->flags & MG_F_SSL) && err == 0) {
mg_ssl_begin(nc);
} else {
mg_if_connect_cb(nc, err);
}
#else
mg_if_connect_cb(nc, err);
#endif
} else if (nc->err != 0) {
mg_if_connect_cb(nc, nc->err);
}
}
if (fd_flags & _MG_F_FD_CAN_READ) {
if (nc->flags & MG_F_UDP) {
mg_handle_udp_read(nc);
} else {
if (nc->flags & MG_F_LISTENING) {
/*
* We're not looping here, and accepting just one connection at
* a time. The reason is that eCos does not respect non-blocking
* flag on a listening socket and hangs in a loop.
*/
mg_accept_conn(nc);
} else {
mg_handle_tcp_read(nc);
}
}
}
if (!(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
if ((fd_flags & _MG_F_FD_CAN_WRITE) && nc->send_mbuf.len > 0) {
mg_write_to_socket(nc);
}
mg_if_poll(nc, (time_t) now);
mg_if_timer(nc, now);
}
if (worth_logging) {
DBG(("%p after fd=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
(int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
}
}
#if MG_ENABLE_BROADCAST
static void mg_mgr_handle_ctl_sock(struct mg_mgr *mgr) {
struct ctl_msg ctl_msg;
int len =
(int) MG_RECV_FUNC(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
size_t dummy = MG_SEND_FUNC(mgr->ctl[1], ctl_msg.message, 1, 0);
DBG(("read %d from ctl socket", len));
(void) dummy; /* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25509 */
if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
struct mg_connection *nc;
for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
ctl_msg.callback(nc, MG_EV_POLL,
ctl_msg.message MG_UD_ARG(nc->user_data));
}
}
}
#endif
/* Associate a socket to a connection. */
void mg_socket_if_sock_set(struct mg_connection *nc, sock_t sock) {
mg_set_non_blocking_mode(sock);
mg_set_close_on_exec(sock);
nc->sock = sock;
DBG(("%p %d", nc, sock));
}
void mg_socket_if_init(struct mg_iface *iface) {
(void) iface;
DBG(("%p using select()", iface->mgr));
#if MG_ENABLE_BROADCAST
do {
mg_socketpair(iface->mgr->ctl, SOCK_DGRAM);
} while (iface->mgr->ctl[0] == INVALID_SOCKET);
#endif
}
void mg_socket_if_free(struct mg_iface *iface) {
(void) iface;
}
void mg_socket_if_add_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_socket_if_remove_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
if (sock != INVALID_SOCKET
#ifdef __unix__
&& sock < (sock_t) FD_SETSIZE
#endif
) {
FD_SET(sock, set);
if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
*max_fd = sock;
}
}
}
time_t mg_socket_if_poll(struct mg_iface *iface, int timeout_ms) {
struct mg_mgr *mgr = iface->mgr;
double now = mg_time();
double min_timer;
struct mg_connection *nc, *tmp;
struct timeval tv;
fd_set read_set, write_set, err_set;
sock_t max_fd = INVALID_SOCKET;
int num_fds, num_ev, num_timers = 0;
#ifdef __unix__
int try_dup = 1;
#endif
FD_ZERO(&read_set);
FD_ZERO(&write_set);
FD_ZERO(&err_set);
#if MG_ENABLE_BROADCAST
mg_add_to_set(mgr->ctl[1], &read_set, &max_fd);
#endif
/*
* Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
* e.g. timer-only "connections".
*/
min_timer = 0;
for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
tmp = nc->next;
if (nc->sock != INVALID_SOCKET) {
num_fds++;
#ifdef __unix__
/* A hack to make sure all our file descriptos fit into FD_SETSIZE. */
if (nc->sock >= (sock_t) FD_SETSIZE && try_dup) {
int new_sock = dup(nc->sock);
if (new_sock >= 0 && new_sock < (sock_t) FD_SETSIZE) {
closesocket(nc->sock);
DBG(("new sock %d -> %d", nc->sock, new_sock));
nc->sock = new_sock;
} else {
try_dup = 0;
}
}
#endif
if (!(nc->flags & MG_F_WANT_WRITE) &&
nc->recv_mbuf.len < nc->recv_mbuf_limit &&
(!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
mg_add_to_set(nc->sock, &read_set, &max_fd);
}
if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
(nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
mg_add_to_set(nc->sock, &write_set, &max_fd);
mg_add_to_set(nc->sock, &err_set, &max_fd);
}
}
if (nc->ev_timer_time > 0) {
if (num_timers == 0 || nc->ev_timer_time < min_timer) {
min_timer = nc->ev_timer_time;
}
num_timers++;
}
}
/*
* If there is a timer to be fired earlier than the requested timeout,
* adjust the timeout.
*/
if (num_timers > 0) {
double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
if (timer_timeout_ms < timeout_ms) {
timeout_ms = (int) timer_timeout_ms;
}
}
if (timeout_ms < 0) timeout_ms = 0;
tv.tv_sec = timeout_ms / 1000;
tv.tv_usec = (timeout_ms % 1000) * 1000;
num_ev = select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
now = mg_time();
#if 0
DBG(("select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev, num_fds,
timeout_ms));
#endif
#if MG_ENABLE_BROADCAST
if (num_ev > 0 && mgr->ctl[1] != INVALID_SOCKET &&
FD_ISSET(mgr->ctl[1], &read_set)) {
mg_mgr_handle_ctl_sock(mgr);
}
#endif
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
int fd_flags = 0;
if (nc->sock != INVALID_SOCKET) {
if (num_ev > 0) {
fd_flags = (FD_ISSET(nc->sock, &read_set) &&
(!(nc->flags & MG_F_UDP) || nc->listener == NULL)
? _MG_F_FD_CAN_READ
: 0) |
(FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) |
(FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
}
#if MG_LWIP
/* With LWIP socket emulation layer, we don't get write events for UDP */
if ((nc->flags & MG_F_UDP) && nc->listener == NULL) {
fd_flags |= _MG_F_FD_CAN_WRITE;
}
#endif
}
tmp = nc->next;
mg_mgr_handle_conn(nc, fd_flags, now);
}
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
tmp = nc->next;
if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
(nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
mg_close_conn(nc);
}
}
return (time_t) now;
}
#if MG_ENABLE_BROADCAST
int mg_socketpair(sock_t sp[2], int sock_type) {
union socket_address sa;
sock_t sock;
socklen_t len = sizeof(sa.sin);
int ret = 0;
sock = sp[0] = sp[1] = INVALID_SOCKET;
(void) memset(&sa, 0, sizeof(sa));
sa.sin.sin_family = AF_INET;
sa.sin.sin_port = htons(0);
sa.sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
if ((sock = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
} else if (bind(sock, &sa.sa, len) != 0) {
} else if (sock_type == SOCK_STREAM && listen(sock, 1) != 0) {
} else if (getsockname(sock, &sa.sa, &len) != 0) {
} else if ((sp[0] = socket(AF_INET, sock_type, 0)) == INVALID_SOCKET) {
} else if (connect(sp[0], &sa.sa, len) != 0) {
} else if (sock_type == SOCK_DGRAM &&
(getsockname(sp[0], &sa.sa, &len) != 0 ||
connect(sock, &sa.sa, len) != 0)) {
} else if ((sp[1] = (sock_type == SOCK_DGRAM ? sock
: accept(sock, &sa.sa, &len))) ==
INVALID_SOCKET) {
} else {
mg_set_close_on_exec(sp[0]);
mg_set_close_on_exec(sp[1]);
if (sock_type == SOCK_STREAM) closesocket(sock);
ret = 1;
}
if (!ret) {
if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
if (sock != INVALID_SOCKET) closesocket(sock);
sock = sp[0] = sp[1] = INVALID_SOCKET;
}
return ret;
}
#endif /* MG_ENABLE_BROADCAST */
static void mg_sock_get_addr(sock_t sock, int remote,
union socket_address *sa) {
socklen_t slen = sizeof(*sa);
memset(sa, 0, slen);
if (remote) {
getpeername(sock, &sa->sa, &slen);
} else {
getsockname(sock, &sa->sa, &slen);
}
}
void mg_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
union socket_address sa;
mg_sock_get_addr(sock, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
mg_sock_addr_to_str(&sa, buf, len, flags);
}
void mg_socket_if_get_conn_addr(struct mg_connection *nc, int remote,
union socket_address *sa) {
mg_sock_get_addr(nc->sock, remote, sa);
}
/* clang-format off */
#define MG_SOCKET_IFACE_VTABLE \
{ \
mg_socket_if_init, \
mg_socket_if_free, \
mg_socket_if_add_conn, \
mg_socket_if_remove_conn, \
mg_socket_if_poll, \
mg_socket_if_listen_tcp, \
mg_socket_if_listen_udp, \
mg_socket_if_connect_tcp, \
mg_socket_if_connect_udp, \
mg_socket_if_tcp_send, \
mg_socket_if_udp_send, \
mg_socket_if_recved, \
mg_socket_if_create_conn, \
mg_socket_if_destroy_conn, \
mg_socket_if_sock_set, \
mg_socket_if_get_conn_addr, \
}
/* clang-format on */
const struct mg_iface_vtable mg_socket_iface_vtable = MG_SOCKET_IFACE_VTABLE;
#if MG_NET_IF == MG_NET_IF_SOCKET
const struct mg_iface_vtable mg_default_iface_vtable = MG_SOCKET_IFACE_VTABLE;
#endif
#endif /* MG_ENABLE_NET_IF_SOCKET */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/net_if_tun.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_TUN
/* Amalgamated: #include "common/cs_dbg.h" */
/* Amalgamated: #include "common/cs_time.h" */
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/net_if_tun.h" */
/* Amalgamated: #include "mongoose/src/tun.h" */
/* Amalgamated: #include "mongoose/src/util.h" */
#define MG_TCP_RECV_BUFFER_SIZE 1024
#define MG_UDP_RECV_BUFFER_SIZE 1500
void mg_tun_if_connect_tcp(struct mg_connection *nc,
const union socket_address *sa) {
(void) nc;
(void) sa;
}
void mg_tun_if_connect_udp(struct mg_connection *nc) {
(void) nc;
}
int mg_tun_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
(void) nc;
(void) sa;
return 0;
}
int mg_tun_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
(void) nc;
(void) sa;
return -1;
}
void mg_tun_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
struct mg_tun_client *client = (struct mg_tun_client *) nc->iface->data;
uint32_t stream_id = (uint32_t)(uintptr_t) nc->mgr_data;
struct mg_str msg = {(char *) buf, len};
#if MG_ENABLE_HEXDUMP
char hex[512];
mg_hexdump(buf, len, hex, sizeof(hex));
LOG(LL_DEBUG, ("sending to stream %zu:\n%s", stream_id, hex));
#endif
mg_tun_send_frame(client->disp, stream_id, MG_TUN_DATA_FRAME, 0, msg);
}
void mg_tun_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) {
(void) nc;
(void) buf;
(void) len;
}
void mg_tun_if_recved(struct mg_connection *nc, size_t len) {
(void) nc;
(void) len;
}
int mg_tun_if_create_conn(struct mg_connection *nc) {
(void) nc;
return 1;
}
void mg_tun_if_destroy_conn(struct mg_connection *nc) {
struct mg_tun_client *client = (struct mg_tun_client *) nc->iface->data;
if (nc->flags & MG_F_LISTENING) {
mg_tun_destroy_client(client);
} else if (client->disp) {
uint32_t stream_id = (uint32_t)(uintptr_t) nc->mgr_data;
struct mg_str msg = {NULL, 0};
LOG(LL_DEBUG, ("closing %zu:", stream_id));
mg_tun_send_frame(client->disp, stream_id, MG_TUN_DATA_FRAME,
MG_TUN_F_END_STREAM, msg);
}
}
/* Associate a socket to a connection. */
void mg_tun_if_sock_set(struct mg_connection *nc, sock_t sock) {
(void) nc;
(void) sock;
}
void mg_tun_if_init(struct mg_iface *iface) {
(void) iface;
}
void mg_tun_if_free(struct mg_iface *iface) {
(void) iface;
}
void mg_tun_if_add_conn(struct mg_connection *nc) {
nc->sock = INVALID_SOCKET;
}
void mg_tun_if_remove_conn(struct mg_connection *nc) {
(void) nc;
}
time_t mg_tun_if_poll(struct mg_iface *iface, int timeout_ms) {
(void) iface;
(void) timeout_ms;
return (time_t) cs_time();
}
void mg_tun_if_get_conn_addr(struct mg_connection *nc, int remote,
union socket_address *sa) {
(void) nc;
(void) remote;
(void) sa;
}
struct mg_connection *mg_tun_if_find_conn(struct mg_tun_client *client,
uint32_t stream_id) {
struct mg_connection *nc = NULL;
for (nc = client->mgr->active_connections; nc != NULL; nc = nc->next) {
if (nc->iface != client->iface || (nc->flags & MG_F_LISTENING)) {
continue;
}
if (stream_id == (uint32_t)(uintptr_t) nc->mgr_data) {
return nc;
}
}
if (stream_id > client->last_stream_id) {
/* create a new connection */
LOG(LL_DEBUG, ("new stream 0x%lx, accepting", stream_id));
nc = mg_if_accept_new_conn(client->listener);
nc->mgr_data = (void *) (uintptr_t) stream_id;
client->last_stream_id = stream_id;
} else {
LOG(LL_DEBUG, ("Ignoring stream 0x%lx (last_stream_id 0x%lx)", stream_id,
client->last_stream_id));
}
return nc;
}
/* clang-format off */
#define MG_TUN_IFACE_VTABLE \
{ \
mg_tun_if_init, \
mg_tun_if_free, \
mg_tun_if_add_conn, \
mg_tun_if_remove_conn, \
mg_tun_if_poll, \
mg_tun_if_listen_tcp, \
mg_tun_if_listen_udp, \
mg_tun_if_connect_tcp, \
mg_tun_if_connect_udp, \
mg_tun_if_tcp_send, \
mg_tun_if_udp_send, \
mg_tun_if_recved, \
mg_tun_if_create_conn, \
mg_tun_if_destroy_conn, \
mg_tun_if_sock_set, \
mg_tun_if_get_conn_addr, \
}
/* clang-format on */
const struct mg_iface_vtable mg_tun_iface_vtable = MG_TUN_IFACE_VTABLE;
#endif /* MG_ENABLE_TUN */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/ssl_if_openssl.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL
#ifdef __APPLE__
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
#include <openssl/ssl.h>
struct mg_ssl_if_ctx {
SSL *ssl;
SSL_CTX *ssl_ctx;
struct mbuf psk;
size_t identity_len;
};
void mg_ssl_if_init() {
SSL_library_init();
}
enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
struct mg_connection *lc) {
struct mg_ssl_if_ctx *ctx =
(struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data;
nc->ssl_if_data = ctx;
if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR;
ctx->ssl_ctx = lc_ctx->ssl_ctx;
if ((ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
return MG_SSL_ERROR;
}
return MG_SSL_OK;
}
static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert,
const char *key, const char **err_msg);
static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert);
static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl);
static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
const char *identity,
const char *key_str);
enum mg_ssl_if_result mg_ssl_if_conn_init(
struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
const char **err_msg) {
struct mg_ssl_if_ctx *ctx =
(struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""),
(params->key ? params->key : ""),
(params->ca_cert ? params->ca_cert : "")));
if (ctx == NULL) {
MG_SET_PTRPTR(err_msg, "Out of memory");
return MG_SSL_ERROR;
}
nc->ssl_if_data = ctx;
if (nc->flags & MG_F_LISTENING) {
ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
} else {
ctx->ssl_ctx = SSL_CTX_new(SSLv23_client_method());
}
if (ctx->ssl_ctx == NULL) {
MG_SET_PTRPTR(err_msg, "Failed to create SSL context");
return MG_SSL_ERROR;
}
if (params->cert != NULL &&
mg_use_cert(ctx->ssl_ctx, params->cert, params->key, err_msg) !=
MG_SSL_OK) {
return MG_SSL_ERROR;
}
if (params->ca_cert != NULL &&
mg_use_ca_cert(ctx->ssl_ctx, params->ca_cert) != MG_SSL_OK) {
MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert");
return MG_SSL_ERROR;
}
if (params->server_name != NULL) {
#ifdef KR_VERSION
SSL_CTX_kr_set_verify_name(ctx->ssl_ctx, params->server_name);
#else
/* TODO(rojer): Implement server name verification on OpenSSL. */
#endif
}
if (mg_set_cipher_list(ctx->ssl_ctx, params->cipher_suites) != MG_SSL_OK) {
MG_SET_PTRPTR(err_msg, "Invalid cipher suite list");
return MG_SSL_ERROR;
}
mbuf_init(&ctx->psk, 0);
if (mg_ssl_if_ossl_set_psk(ctx, params->psk_identity, params->psk_key) !=
MG_SSL_OK) {
MG_SET_PTRPTR(err_msg, "Invalid PSK settings");
return MG_SSL_ERROR;
}
if (!(nc->flags & MG_F_LISTENING) &&
(ctx->ssl = SSL_new(ctx->ssl_ctx)) == NULL) {
MG_SET_PTRPTR(err_msg, "Failed to create SSL session");
return MG_SSL_ERROR;
}
nc->flags |= MG_F_SSL;
return MG_SSL_OK;
}
static enum mg_ssl_if_result mg_ssl_if_ssl_err(struct mg_connection *nc,
int res) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
int err = SSL_get_error(ctx->ssl, res);
if (err == SSL_ERROR_WANT_READ) return MG_SSL_WANT_READ;
if (err == SSL_ERROR_WANT_WRITE) return MG_SSL_WANT_WRITE;
DBG(("%p %p SSL error: %d %d", nc, ctx->ssl_ctx, res, err));
nc->err = err;
return MG_SSL_ERROR;
}
enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
int server_side = (nc->listener != NULL);
int res;
/* If descriptor is not yet set, do it now. */
if (SSL_get_fd(ctx->ssl) < 0) {
if (SSL_set_fd(ctx->ssl, nc->sock) != 1) return MG_SSL_ERROR;
}
res = server_side ? SSL_accept(ctx->ssl) : SSL_connect(ctx->ssl);
if (res != 1) return mg_ssl_if_ssl_err(nc, res);
return MG_SSL_OK;
}
int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
int n = SSL_read(ctx->ssl, buf, buf_size);
DBG(("%p %d -> %d", nc, (int) buf_size, n));
if (n < 0) return mg_ssl_if_ssl_err(nc, n);
if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return n;
}
int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
int n = SSL_write(ctx->ssl, data, len);
DBG(("%p %d -> %d", nc, (int) len, n));
if (n <= 0) return mg_ssl_if_ssl_err(nc, n);
return n;
}
void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
if (ctx == NULL) return;
SSL_shutdown(ctx->ssl);
}
void mg_ssl_if_conn_free(struct mg_connection *nc) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
if (ctx == NULL) return;
nc->ssl_if_data = NULL;
if (ctx->ssl != NULL) SSL_free(ctx->ssl);
if (ctx->ssl_ctx != NULL && nc->listener == NULL) SSL_CTX_free(ctx->ssl_ctx);
mbuf_free(&ctx->psk);
memset(ctx, 0, sizeof(*ctx));
MG_FREE(ctx);
}
/*
* Cipher suite options used for TLS negotiation.
* https://wiki.mozilla.org/Security/Server_Side_TLS#Recommended_configurations
*/
static const char mg_s_cipher_list[] =
#if defined(MG_SSL_CRYPTO_MODERN)
"ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:"
"ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:"
"DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
"ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
"ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
"ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
"DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
"DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:"
"!aNULL:!eNULL:!EXPORT:!DES:!RC4:!3DES:!MD5:!PSK"
#elif defined(MG_SSL_CRYPTO_OLD)
"ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
"ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
"DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
"ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
"ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
"ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
"DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
"DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:ECDHE-RSA-DES-CBC3-SHA:"
"ECDHE-ECDSA-DES-CBC3-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
"AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:DES-CBC3-SHA:"
"HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
"!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
#else /* Default - intermediate. */
"ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:"
"ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:"
"DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:"
"ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:"
"ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:"
"ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:"
"DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:"
"DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:"
"AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:AES:CAMELLIA:"
"DES-CBC3-SHA:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:"
"!EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
#endif
;
/*
* Default DH params for PFS cipher negotiation. This is a 2048-bit group.
* Will be used if none are provided by the user in the certificate file.
*/
#if !MG_DISABLE_PFS && !defined(KR_VERSION)
static const char mg_s_default_dh_params[] =
"\
-----BEGIN DH PARAMETERS-----\n\
MIIBCAKCAQEAlvbgD/qh9znWIlGFcV0zdltD7rq8FeShIqIhkQ0C7hYFThrBvF2E\n\
Z9bmgaP+sfQwGpVlv9mtaWjvERbu6mEG7JTkgmVUJrUt/wiRzwTaCXBqZkdUO8Tq\n\
+E6VOEQAilstG90ikN1Tfo+K6+X68XkRUIlgawBTKuvKVwBhuvlqTGerOtnXWnrt\n\
ym//hd3cd5PBYGBix0i7oR4xdghvfR2WLVu0LgdThTBb6XP7gLd19cQ1JuBtAajZ\n\
wMuPn7qlUkEFDIkAZy59/Hue/H2Q2vU/JsvVhHWCQBL4F1ofEAt50il6ZxR1QfFK\n\
9VGKDC4oOgm9DlxwwBoC2FjqmvQlqVV3kwIBAg==\n\
-----END DH PARAMETERS-----\n";
#endif
static enum mg_ssl_if_result mg_use_ca_cert(SSL_CTX *ctx, const char *cert) {
if (cert == NULL || strcmp(cert, "*") == 0) {
return MG_SSL_OK;
}
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? MG_SSL_OK
: MG_SSL_ERROR;
}
static enum mg_ssl_if_result mg_use_cert(SSL_CTX *ctx, const char *cert,
const char *key,
const char **err_msg) {
if (key == NULL) key = cert;
if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') {
return MG_SSL_OK;
} else if (SSL_CTX_use_certificate_file(ctx, cert, 1) == 0) {
MG_SET_PTRPTR(err_msg, "Invalid SSL cert");
return MG_SSL_ERROR;
} else if (SSL_CTX_use_PrivateKey_file(ctx, key, 1) == 0) {
MG_SET_PTRPTR(err_msg, "Invalid SSL key");
return MG_SSL_ERROR;
} else if (SSL_CTX_use_certificate_chain_file(ctx, cert) == 0) {
MG_SET_PTRPTR(err_msg, "Invalid CA bundle");
return MG_SSL_ERROR;
} else {
SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
#if !MG_DISABLE_PFS && !defined(KR_VERSION)
BIO *bio = NULL;
DH *dh = NULL;
/* Try to read DH parameters from the cert/key file. */
bio = BIO_new_file(cert, "r");
if (bio != NULL) {
dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
BIO_free(bio);
}
/*
* If there are no DH params in the file, fall back to hard-coded ones.
* Not ideal, but better than nothing.
*/
if (dh == NULL) {
bio = BIO_new_mem_buf((void *) mg_s_default_dh_params, -1);
dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
BIO_free(bio);
}
if (dh != NULL) {
SSL_CTX_set_tmp_dh(ctx, dh);
SSL_CTX_set_options(ctx, SSL_OP_SINGLE_DH_USE);
DH_free(dh);
}
#if OPENSSL_VERSION_NUMBER > 0x10002000L
SSL_CTX_set_ecdh_auto(ctx, 1);
#endif
#endif
}
return MG_SSL_OK;
}
static enum mg_ssl_if_result mg_set_cipher_list(SSL_CTX *ctx, const char *cl) {
return (SSL_CTX_set_cipher_list(ctx, cl ? cl : mg_s_cipher_list) == 1
? MG_SSL_OK
: MG_SSL_ERROR);
}
#ifndef KR_VERSION
static unsigned int mg_ssl_if_ossl_psk_cb(SSL *ssl, const char *hint,
char *identity,
unsigned int max_identity_len,
unsigned char *psk,
unsigned int max_psk_len) {
struct mg_ssl_if_ctx *ctx =
(struct mg_ssl_if_ctx *) ssl->ctx->msg_callback_arg;
size_t key_len = ctx->psk.len - ctx->identity_len - 1;
DBG(("hint: '%s'", (hint ? hint : "")));
if (ctx->identity_len + 1 > max_identity_len) {
DBG(("identity too long"));
return 0;
}
if (key_len > max_psk_len) {
DBG(("key too long"));
return 0;
}
memcpy(identity, ctx->psk.buf, ctx->identity_len + 1);
memcpy(psk, ctx->psk.buf + ctx->identity_len + 1, key_len);
(void) ssl;
return key_len;
}
static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
const char *identity,
const char *key_str) {
unsigned char key[32];
size_t key_len;
size_t i = 0;
if (identity == NULL && key_str == NULL) return MG_SSL_OK;
if (identity == NULL || key_str == NULL) return MG_SSL_ERROR;
key_len = strlen(key_str);
if (key_len != 32 && key_len != 64) return MG_SSL_ERROR;
memset(key, 0, sizeof(key));
key_len = 0;
for (i = 0; key_str[i] != '\0'; i++) {
unsigned char c;
char hc = tolower((int) key_str[i]);
if (hc >= '0' && hc <= '9') {
c = hc - '0';
} else if (hc >= 'a' && hc <= 'f') {
c = hc - 'a' + 0xa;
} else {
return MG_SSL_ERROR;
}
key_len = i / 2;
key[key_len] <<= 4;
key[key_len] |= c;
}
key_len++;
DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len));
ctx->identity_len = strlen(identity);
mbuf_append(&ctx->psk, identity, ctx->identity_len + 1);
mbuf_append(&ctx->psk, key, key_len);
SSL_CTX_set_psk_client_callback(ctx->ssl_ctx, mg_ssl_if_ossl_psk_cb);
/* Hack: there is no field for us to keep this, so we use msg_callback_arg */
ctx->ssl_ctx->msg_callback_arg = ctx;
return MG_SSL_OK;
}
#else
static enum mg_ssl_if_result mg_ssl_if_ossl_set_psk(struct mg_ssl_if_ctx *ctx,
const char *identity,
const char *key_str) {
(void) ctx;
(void) identity;
(void) key_str;
/* Krypton does not support PSK. */
return MG_SSL_ERROR;
}
#endif /* defined(KR_VERSION) */
const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
const char *ca_cert) {
const char *err_msg = NULL;
struct mg_ssl_if_conn_params params;
memset(¶ms, 0, sizeof(params));
params.cert = cert;
params.ca_cert = ca_cert;
if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) {
return err_msg;
}
return NULL;
}
#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_OPENSSL */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/ssl_if_mbedtls.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS
#include <mbedtls/debug.h>
#include <mbedtls/ecp.h>
#include <mbedtls/platform.h>
#include <mbedtls/ssl.h>
#include <mbedtls/x509_crt.h>
static void mg_ssl_mbed_log(void *ctx, int level, const char *file, int line,
const char *str) {
enum cs_log_level cs_level;
switch (level) {
case 1:
cs_level = LL_ERROR;
break;
case 2:
case 3:
cs_level = LL_DEBUG;
break;
default:
cs_level = LL_VERBOSE_DEBUG;
}
/* mbedTLS passes strings with \n at the end, strip it. */
LOG(cs_level, ("%p %.*s", ctx, (int) (strlen(str) - 1), str));
(void) file;
(void) line;
}
struct mg_ssl_if_ctx {
mbedtls_ssl_config *conf;
mbedtls_ssl_context *ssl;
mbedtls_x509_crt *cert;
mbedtls_pk_context *key;
mbedtls_x509_crt *ca_cert;
struct mbuf cipher_suites;
};
/* Must be provided by the platform. ctx is struct mg_connection. */
extern int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len);
void mg_ssl_if_init() {
}
enum mg_ssl_if_result mg_ssl_if_conn_accept(struct mg_connection *nc,
struct mg_connection *lc) {
struct mg_ssl_if_ctx *ctx =
(struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
struct mg_ssl_if_ctx *lc_ctx = (struct mg_ssl_if_ctx *) lc->ssl_if_data;
nc->ssl_if_data = ctx;
if (ctx == NULL || lc_ctx == NULL) return MG_SSL_ERROR;
ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl));
if (mbedtls_ssl_setup(ctx->ssl, lc_ctx->conf) != 0) {
return MG_SSL_ERROR;
}
return MG_SSL_OK;
}
static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx,
const char *cert, const char *key,
const char **err_msg);
static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx,
const char *cert);
static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx,
const char *ciphers);
static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx,
const char *identity,
const char *key);
enum mg_ssl_if_result mg_ssl_if_conn_init(
struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
const char **err_msg) {
struct mg_ssl_if_ctx *ctx =
(struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
DBG(("%p %s,%s,%s", nc, (params->cert ? params->cert : ""),
(params->key ? params->key : ""),
(params->ca_cert ? params->ca_cert : "")));
if (ctx == NULL) {
MG_SET_PTRPTR(err_msg, "Out of memory");
return MG_SSL_ERROR;
}
nc->ssl_if_data = ctx;
ctx->conf = (mbedtls_ssl_config *) MG_CALLOC(1, sizeof(*ctx->conf));
mbuf_init(&ctx->cipher_suites, 0);
mbedtls_ssl_config_init(ctx->conf);
mbedtls_ssl_conf_dbg(ctx->conf, mg_ssl_mbed_log, nc);
if (mbedtls_ssl_config_defaults(
ctx->conf, (nc->flags & MG_F_LISTENING ? MBEDTLS_SSL_IS_SERVER
: MBEDTLS_SSL_IS_CLIENT),
MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT) != 0) {
MG_SET_PTRPTR(err_msg, "Failed to init SSL config");
return MG_SSL_ERROR;
}
/* TLS 1.2 and up */
mbedtls_ssl_conf_min_version(ctx->conf, MBEDTLS_SSL_MAJOR_VERSION_3,
MBEDTLS_SSL_MINOR_VERSION_3);
mbedtls_ssl_conf_rng(ctx->conf, mg_ssl_if_mbed_random, nc);
if (params->cert != NULL &&
mg_use_cert(ctx, params->cert, params->key, err_msg) != MG_SSL_OK) {
return MG_SSL_ERROR;
}
if (params->ca_cert != NULL &&
mg_use_ca_cert(ctx, params->ca_cert) != MG_SSL_OK) {
MG_SET_PTRPTR(err_msg, "Invalid SSL CA cert");
return MG_SSL_ERROR;
}
if (mg_set_cipher_list(ctx, params->cipher_suites) != MG_SSL_OK) {
MG_SET_PTRPTR(err_msg, "Invalid cipher suite list");
return MG_SSL_ERROR;
}
if (mg_ssl_if_mbed_set_psk(ctx, params->psk_identity, params->psk_key) !=
MG_SSL_OK) {
MG_SET_PTRPTR(err_msg, "Invalid PSK settings");
return MG_SSL_ERROR;
}
if (!(nc->flags & MG_F_LISTENING)) {
ctx->ssl = (mbedtls_ssl_context *) MG_CALLOC(1, sizeof(*ctx->ssl));
mbedtls_ssl_init(ctx->ssl);
if (mbedtls_ssl_setup(ctx->ssl, ctx->conf) != 0) {
MG_SET_PTRPTR(err_msg, "Failed to create SSL session");
return MG_SSL_ERROR;
}
if (params->server_name != NULL &&
mbedtls_ssl_set_hostname(ctx->ssl, params->server_name) != 0) {
return MG_SSL_ERROR;
}
}
#ifdef MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
if (mbedtls_ssl_conf_max_frag_len(ctx->conf,
#if MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 512
MBEDTLS_SSL_MAX_FRAG_LEN_512
#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 1024
MBEDTLS_SSL_MAX_FRAG_LEN_1024
#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 2048
MBEDTLS_SSL_MAX_FRAG_LEN_2048
#elif MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN == 4096
MBEDTLS_SSL_MAX_FRAG_LEN_4096
#else
#error Invalid MG_SSL_IF_MBEDTLS_MAX_FRAG_LEN
#endif
) != 0) {
return MG_SSL_ERROR;
}
#endif
nc->flags |= MG_F_SSL;
return MG_SSL_OK;
}
#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len);
int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len);
#else
static int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len) {
struct mg_connection *nc = (struct mg_connection *) ctx;
int n = (int) MG_SEND_FUNC(nc->sock, buf, len, 0);
LOG(LL_DEBUG, ("%p %d -> %d", nc, (int) len, n));
if (n >= 0) return n;
n = mg_get_errno();
return ((n == EAGAIN || n == EINPROGRESS) ? MBEDTLS_ERR_SSL_WANT_WRITE : -1);
}
static int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len) {
struct mg_connection *nc = (struct mg_connection *) ctx;
int n = (int) MG_RECV_FUNC(nc->sock, buf, len, 0);
LOG(LL_DEBUG, ("%p %d <- %d", nc, (int) len, n));
if (n >= 0) return n;
n = mg_get_errno();
return ((n == EAGAIN || n == EINPROGRESS) ? MBEDTLS_ERR_SSL_WANT_READ : -1);
}
#endif
static enum mg_ssl_if_result mg_ssl_if_mbed_err(struct mg_connection *nc,
int ret) {
if (ret == MBEDTLS_ERR_SSL_WANT_READ) return MG_SSL_WANT_READ;
if (ret == MBEDTLS_ERR_SSL_WANT_WRITE) return MG_SSL_WANT_WRITE;
if (ret !=
MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) { /* CLOSE_NOTIFY = Normal shutdown */
LOG(LL_ERROR, ("%p SSL error: %d", nc, ret));
}
nc->err = ret;
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return MG_SSL_ERROR;
}
static void mg_ssl_if_mbed_free_certs_and_keys(struct mg_ssl_if_ctx *ctx) {
if (ctx->cert != NULL) {
mbedtls_x509_crt_free(ctx->cert);
MG_FREE(ctx->cert);
ctx->cert = NULL;
mbedtls_pk_free(ctx->key);
MG_FREE(ctx->key);
ctx->key = NULL;
}
if (ctx->ca_cert != NULL) {
mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
mbedtls_x509_crt_free(ctx->ca_cert);
MG_FREE(ctx->ca_cert);
ctx->ca_cert = NULL;
}
}
enum mg_ssl_if_result mg_ssl_if_handshake(struct mg_connection *nc) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
int err;
/* If bio is not yet set, do it now. */
if (ctx->ssl->p_bio == NULL) {
mbedtls_ssl_set_bio(ctx->ssl, nc, ssl_socket_send, ssl_socket_recv, NULL);
}
err = mbedtls_ssl_handshake(ctx->ssl);
if (err != 0) return mg_ssl_if_mbed_err(nc, err);
#ifdef MG_SSL_IF_MBEDTLS_FREE_CERTS
/*
* Free the peer certificate, we don't need it after handshake.
* Note that this effectively disables renegotiation.
*/
mbedtls_x509_crt_free(ctx->ssl->session->peer_cert);
mbedtls_free(ctx->ssl->session->peer_cert);
ctx->ssl->session->peer_cert = NULL;
/* On a client connection we can also free our own and CA certs. */
if (nc->listener == NULL) {
if (ctx->conf->key_cert != NULL) {
/* Note that this assumes one key_cert entry, which matches our init. */
MG_FREE(ctx->conf->key_cert);
ctx->conf->key_cert = NULL;
}
mbedtls_ssl_conf_ca_chain(ctx->conf, NULL, NULL);
mg_ssl_if_mbed_free_certs_and_keys(ctx);
}
#endif
return MG_SSL_OK;
}
int mg_ssl_if_read(struct mg_connection *nc, void *buf, size_t buf_size) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
int n = mbedtls_ssl_read(ctx->ssl, (unsigned char *) buf, buf_size);
DBG(("%p %d -> %d", nc, (int) buf_size, n));
if (n < 0) return mg_ssl_if_mbed_err(nc, n);
if (n == 0) nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return n;
}
int mg_ssl_if_write(struct mg_connection *nc, const void *data, size_t len) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
int n = mbedtls_ssl_write(ctx->ssl, (const unsigned char *) data, len);
DBG(("%p %d -> %d", nc, (int) len, n));
if (n < 0) return mg_ssl_if_mbed_err(nc, n);
return n;
}
void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
if (ctx == NULL) return;
mbedtls_ssl_close_notify(ctx->ssl);
}
void mg_ssl_if_conn_free(struct mg_connection *nc) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
if (ctx == NULL) return;
nc->ssl_if_data = NULL;
if (ctx->ssl != NULL) {
mbedtls_ssl_free(ctx->ssl);
MG_FREE(ctx->ssl);
}
mg_ssl_if_mbed_free_certs_and_keys(ctx);
if (ctx->conf != NULL) {
mbedtls_ssl_config_free(ctx->conf);
MG_FREE(ctx->conf);
}
mbuf_free(&ctx->cipher_suites);
memset(ctx, 0, sizeof(*ctx));
MG_FREE(ctx);
}
static enum mg_ssl_if_result mg_use_ca_cert(struct mg_ssl_if_ctx *ctx,
const char *ca_cert) {
if (ca_cert == NULL || strcmp(ca_cert, "*") == 0) {
return MG_SSL_OK;
}
ctx->ca_cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->ca_cert));
mbedtls_x509_crt_init(ctx->ca_cert);
if (mbedtls_x509_crt_parse_file(ctx->ca_cert, ca_cert) != 0) {
return MG_SSL_ERROR;
}
mbedtls_ssl_conf_ca_chain(ctx->conf, ctx->ca_cert, NULL);
mbedtls_ssl_conf_authmode(ctx->conf, MBEDTLS_SSL_VERIFY_REQUIRED);
return MG_SSL_OK;
}
static enum mg_ssl_if_result mg_use_cert(struct mg_ssl_if_ctx *ctx,
const char *cert, const char *key,
const char **err_msg) {
if (key == NULL) key = cert;
if (cert == NULL || cert[0] == '\0' || key == NULL || key[0] == '\0') {
return MG_SSL_OK;
}
ctx->cert = (mbedtls_x509_crt *) MG_CALLOC(1, sizeof(*ctx->cert));
mbedtls_x509_crt_init(ctx->cert);
ctx->key = (mbedtls_pk_context *) MG_CALLOC(1, sizeof(*ctx->key));
mbedtls_pk_init(ctx->key);
if (mbedtls_x509_crt_parse_file(ctx->cert, cert) != 0) {
MG_SET_PTRPTR(err_msg, "Invalid SSL cert");
return MG_SSL_ERROR;
}
if (mbedtls_pk_parse_keyfile(ctx->key, key, NULL) != 0) {
MG_SET_PTRPTR(err_msg, "Invalid SSL key");
return MG_SSL_ERROR;
}
if (mbedtls_ssl_conf_own_cert(ctx->conf, ctx->cert, ctx->key) != 0) {
MG_SET_PTRPTR(err_msg, "Invalid SSL key or cert");
return MG_SSL_ERROR;
}
return MG_SSL_OK;
}
static const int mg_s_cipher_list[] = {
MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256,
MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256,
MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA, 0};
/*
* Ciphers can be specified as a colon-separated list of cipher suite names.
* These can be found in
* https://github.com/ARMmbed/mbedtls/blob/development/library/ssl_ciphersuites.c#L267
* E.g.: TLS-ECDHE-ECDSA-WITH-AES-128-GCM-SHA256:TLS-DHE-RSA-WITH-AES-256-CCM
*/
static enum mg_ssl_if_result mg_set_cipher_list(struct mg_ssl_if_ctx *ctx,
const char *ciphers) {
if (ciphers != NULL) {
int l, id;
const char *s = ciphers, *e;
char tmp[50];
while (s != NULL) {
e = strchr(s, ':');
l = (e != NULL ? (e - s) : (int) strlen(s));
strncpy(tmp, s, l);
tmp[l] = '\0';
id = mbedtls_ssl_get_ciphersuite_id(tmp);
DBG(("%s -> %04x", tmp, id));
if (id != 0) {
mbuf_append(&ctx->cipher_suites, &id, sizeof(id));
}
s = (e != NULL ? e + 1 : NULL);
}
if (ctx->cipher_suites.len == 0) return MG_SSL_ERROR;
id = 0;
mbuf_append(&ctx->cipher_suites, &id, sizeof(id));
mbuf_trim(&ctx->cipher_suites);
mbedtls_ssl_conf_ciphersuites(ctx->conf,
(const int *) ctx->cipher_suites.buf);
} else {
mbedtls_ssl_conf_ciphersuites(ctx->conf, mg_s_cipher_list);
}
return MG_SSL_OK;
}
static enum mg_ssl_if_result mg_ssl_if_mbed_set_psk(struct mg_ssl_if_ctx *ctx,
const char *identity,
const char *key_str) {
unsigned char key[32];
size_t key_len;
if (identity == NULL && key_str == NULL) return MG_SSL_OK;
if (identity == NULL || key_str == NULL) return MG_SSL_ERROR;
key_len = strlen(key_str);
if (key_len != 32 && key_len != 64) return MG_SSL_ERROR;
size_t i = 0;
memset(key, 0, sizeof(key));
key_len = 0;
for (i = 0; key_str[i] != '\0'; i++) {
unsigned char c;
char hc = tolower((int) key_str[i]);
if (hc >= '0' && hc <= '9') {
c = hc - '0';
} else if (hc >= 'a' && hc <= 'f') {
c = hc - 'a' + 0xa;
} else {
return MG_SSL_ERROR;
}
key_len = i / 2;
key[key_len] <<= 4;
key[key_len] |= c;
}
key_len++;
DBG(("identity = '%s', key = (%u)", identity, (unsigned int) key_len));
/* mbedTLS makes copies of psk and identity. */
if (mbedtls_ssl_conf_psk(ctx->conf, (const unsigned char *) key, key_len,
(const unsigned char *) identity,
strlen(identity)) != 0) {
return MG_SSL_ERROR;
}
return MG_SSL_OK;
}
const char *mg_set_ssl(struct mg_connection *nc, const char *cert,
const char *ca_cert) {
const char *err_msg = NULL;
struct mg_ssl_if_conn_params params;
memset(¶ms, 0, sizeof(params));
params.cert = cert;
params.ca_cert = ca_cert;
if (mg_ssl_if_conn_init(nc, ¶ms, &err_msg) != MG_SSL_OK) {
return err_msg;
}
return NULL;
}
/* Lazy RNG. Warning: it would be a bad idea to do this in production! */
#ifdef MG_SSL_MBED_DUMMY_RANDOM
int mg_ssl_if_mbed_random(void *ctx, unsigned char *buf, size_t len) {
(void) ctx;
while (len--) *buf++ = rand();
return 0;
}
#endif
#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_MBEDTLS */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/uri.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/uri.h" */
/*
* scan string until `sep`, keeping track of component boundaries in `res`.
*
* `p` will point to the char after the separator or it will be `end`.
*/
static void parse_uri_component(const char **p, const char *end, char sep,
struct mg_str *res) {
res->p = *p;
for (; *p < end; (*p)++) {
if (**p == sep) {
break;
}
}
res->len = (*p) - res->p;
if (*p < end) (*p)++;
}
int mg_parse_uri(struct mg_str uri, struct mg_str *scheme,
struct mg_str *user_info, struct mg_str *host,
unsigned int *port, struct mg_str *path, struct mg_str *query,
struct mg_str *fragment) {
struct mg_str rscheme = {0, 0}, ruser_info = {0, 0}, rhost = {0, 0},
rpath = {0, 0}, rquery = {0, 0}, rfragment = {0, 0};
unsigned int rport = 0;
enum {
P_START,
P_SCHEME_OR_PORT,
P_USER_INFO,
P_HOST,
P_PORT,
P_REST
} state = P_START;
const char *p = uri.p, *end = p + uri.len;
while (p < end) {
switch (state) {
case P_START:
/*
* expecting on of:
* - `scheme://xxxx`
* - `xxxx:port`
* - `xxxx/path`
*/
for (; p < end; p++) {
if (*p == ':') {
state = P_SCHEME_OR_PORT;
break;
} else if (*p == '/') {
state = P_REST;
break;
}
}
if (state == P_START || state == P_REST) {
rhost.p = uri.p;
rhost.len = p - uri.p;
}
break;
case P_SCHEME_OR_PORT:
if (end - p >= 3 && strncmp(p, "://", 3) == 0) {
rscheme.p = uri.p;
rscheme.len = p - uri.p;
state = P_USER_INFO;
p += 2; /* point to last separator char */
} else {
rhost.p = uri.p;
rhost.len = p - uri.p;
state = P_PORT;
}
break;
case P_USER_INFO:
p++;
ruser_info.p = p;
for (; p < end; p++) {
if (*p == '@') {
state = P_HOST;
break;
} else if (*p == '/') {
break;
}
}
if (p == end || *p == '/') {
/* backtrack and parse as host */
state = P_HOST;
p = ruser_info.p;
}
ruser_info.len = p - ruser_info.p;
break;
case P_HOST:
if (*p == '@') p++;
rhost.p = p;
for (; p < end; p++) {
if (*p == ':') {
state = P_PORT;
break;
} else if (*p == '/') {
state = P_REST;
break;
}
}
rhost.len = p - rhost.p;
break;
case P_PORT:
p++;
for (; p < end; p++) {
if (*p == '/') {
state = P_REST;
break;
}
rport *= 10;
rport += *p - '0';
}
break;
case P_REST:
/* `p` points to separator. `path` includes the separator */
parse_uri_component(&p, end, '?', &rpath);
parse_uri_component(&p, end, '#', &rquery);
parse_uri_component(&p, end, '\0', &rfragment);
break;
}
}
if (scheme != 0) *scheme = rscheme;
if (user_info != 0) *user_info = ruser_info;
if (host != 0) *host = rhost;
if (port != 0) *port = rport;
if (path != 0) *path = rpath;
if (query != 0) *query = rquery;
if (fragment != 0) *fragment = rfragment;
return 0;
}
/* Normalize the URI path. Remove/resolve "." and "..". */
int mg_normalize_uri_path(const struct mg_str *in, struct mg_str *out) {
const char *s = in->p, *se = s + in->len;
char *cp = (char *) out->p, *d;
if (in->len == 0 || *s != '/') {
out->len = 0;
return 0;
}
d = cp;
while (s < se) {
const char *next = s;
struct mg_str component;
parse_uri_component(&next, se, '/', &component);
if (mg_vcmp(&component, ".") == 0) {
/* Yum. */
} else if (mg_vcmp(&component, "..") == 0) {
/* Backtrack to previous slash. */
if (d > cp + 1 && *(d - 1) == '/') d--;
while (d > cp && *(d - 1) != '/') d--;
} else {
memmove(d, s, next - s);
d += next - s;
}
s = next;
}
if (d == cp) *d++ = '/';
out->p = cp;
out->len = d - cp;
return 1;
}
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/http.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_HTTP
/* Amalgamated: #include "common/md5.h" */
/* Amalgamated: #include "common/sha1.h" */
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/util.h" */
static const char *mg_version_header = "Mongoose/" MG_VERSION;
enum mg_http_proto_data_type { DATA_NONE, DATA_FILE, DATA_PUT };
struct mg_http_proto_data_file {
FILE *fp; /* Opened file. */
int64_t cl; /* Content-Length. How many bytes to send. */
int64_t sent; /* How many bytes have been already sent. */
int keepalive; /* Keep connection open after sending. */
enum mg_http_proto_data_type type;
};
#if MG_ENABLE_HTTP_CGI
struct mg_http_proto_data_cgi {
struct mg_connection *cgi_nc;
};
#endif
struct mg_http_proto_data_chuncked {
int64_t body_len; /* How many bytes of chunked body was reassembled. */
};
struct mg_http_endpoint {
struct mg_http_endpoint *next;
const char *name;
size_t name_len;
mg_event_handler_t handler;
#if MG_ENABLE_CALLBACK_USERDATA
void *user_data;
#endif
};
enum mg_http_multipart_stream_state {
MPS_BEGIN,
MPS_WAITING_FOR_BOUNDARY,
MPS_WAITING_FOR_CHUNK,
MPS_GOT_CHUNK,
MPS_GOT_BOUNDARY,
MPS_FINALIZE,
MPS_FINISHED
};
struct mg_http_multipart_stream {
const char *boundary;
int boundary_len;
const char *var_name;
const char *file_name;
void *user_data;
int prev_io_len;
enum mg_http_multipart_stream_state state;
int processing_part;
};
struct mg_reverse_proxy_data {
struct mg_connection *linked_conn;
};
struct mg_http_proto_data {
#if MG_ENABLE_FILESYSTEM
struct mg_http_proto_data_file file;
#endif
#if MG_ENABLE_HTTP_CGI
struct mg_http_proto_data_cgi cgi;
#endif
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
struct mg_http_multipart_stream mp_stream;
#endif
struct mg_http_proto_data_chuncked chunk;
struct mg_http_endpoint *endpoints;
mg_event_handler_t endpoint_handler;
struct mg_reverse_proxy_data reverse_proxy_data;
};
static void mg_http_conn_destructor(void *proto_data);
struct mg_connection *mg_connect_http_base(
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
struct mg_connect_opts opts, const char *schema, const char *schema_ssl,
const char *url, const char **path, char **user, char **pass, char **addr);
static struct mg_http_proto_data *mg_http_get_proto_data(
struct mg_connection *c) {
if (c->proto_data == NULL) {
c->proto_data = MG_CALLOC(1, sizeof(struct mg_http_proto_data));
c->proto_data_destructor = mg_http_conn_destructor;
}
return (struct mg_http_proto_data *) c->proto_data;
}
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
static void mg_http_free_proto_data_mp_stream(
struct mg_http_multipart_stream *mp) {
MG_FREE((void *) mp->boundary);
MG_FREE((void *) mp->var_name);
MG_FREE((void *) mp->file_name);
memset(mp, 0, sizeof(*mp));
}
#endif
#if MG_ENABLE_FILESYSTEM
static void mg_http_free_proto_data_file(struct mg_http_proto_data_file *d) {
if (d != NULL) {
if (d->fp != NULL) {
fclose(d->fp);
}
memset(d, 0, sizeof(struct mg_http_proto_data_file));
}
}
#endif
static void mg_http_free_proto_data_endpoints(struct mg_http_endpoint **ep) {
struct mg_http_endpoint *current = *ep;
while (current != NULL) {
struct mg_http_endpoint *tmp = current->next;
MG_FREE((void *) current->name);
MG_FREE(current);
current = tmp;
}
ep = NULL;
}
static void mg_http_free_reverse_proxy_data(struct mg_reverse_proxy_data *rpd) {
if (rpd->linked_conn != NULL) {
/*
* Connection has linked one, we have to unlink & close it
* since _this_ connection is going to die and
* it doesn't make sense to keep another one
*/
struct mg_http_proto_data *pd = mg_http_get_proto_data(rpd->linked_conn);
if (pd->reverse_proxy_data.linked_conn != NULL) {
pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
pd->reverse_proxy_data.linked_conn = NULL;
}
rpd->linked_conn = NULL;
}
}
static void mg_http_conn_destructor(void *proto_data) {
struct mg_http_proto_data *pd = (struct mg_http_proto_data *) proto_data;
#if MG_ENABLE_FILESYSTEM
mg_http_free_proto_data_file(&pd->file);
#endif
#if MG_ENABLE_HTTP_CGI
mg_http_free_proto_data_cgi(&pd->cgi);
#endif
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
mg_http_free_proto_data_mp_stream(&pd->mp_stream);
#endif
mg_http_free_proto_data_endpoints(&pd->endpoints);
mg_http_free_reverse_proxy_data(&pd->reverse_proxy_data);
MG_FREE(proto_data);
}
#if MG_ENABLE_FILESYSTEM
#define MIME_ENTRY(_ext, _type) \
{ _ext, sizeof(_ext) - 1, _type }
static const struct {
const char *extension;
size_t ext_len;
const char *mime_type;
} mg_static_builtin_mime_types[] = {
MIME_ENTRY("html", "text/html"),
MIME_ENTRY("html", "text/html"),
MIME_ENTRY("htm", "text/html"),
MIME_ENTRY("shtm", "text/html"),
MIME_ENTRY("shtml", "text/html"),
MIME_ENTRY("css", "text/css"),
MIME_ENTRY("js", "application/x-javascript"),
MIME_ENTRY("ico", "image/x-icon"),
MIME_ENTRY("gif", "image/gif"),
MIME_ENTRY("jpg", "image/jpeg"),
MIME_ENTRY("jpeg", "image/jpeg"),
MIME_ENTRY("png", "image/png"),
MIME_ENTRY("svg", "image/svg+xml"),
MIME_ENTRY("txt", "text/plain"),
MIME_ENTRY("torrent", "application/x-bittorrent"),
MIME_ENTRY("wav", "audio/x-wav"),
MIME_ENTRY("mp3", "audio/x-mp3"),
MIME_ENTRY("mid", "audio/mid"),
MIME_ENTRY("m3u", "audio/x-mpegurl"),
MIME_ENTRY("ogg", "application/ogg"),
MIME_ENTRY("ram", "audio/x-pn-realaudio"),
MIME_ENTRY("xml", "text/xml"),
MIME_ENTRY("ttf", "application/x-font-ttf"),
MIME_ENTRY("json", "application/json"),
MIME_ENTRY("xslt", "application/xml"),
MIME_ENTRY("xsl", "application/xml"),
MIME_ENTRY("ra", "audio/x-pn-realaudio"),
MIME_ENTRY("doc", "application/msword"),
MIME_ENTRY("exe", "application/octet-stream"),
MIME_ENTRY("zip", "application/x-zip-compressed"),
MIME_ENTRY("xls", "application/excel"),
MIME_ENTRY("tgz", "application/x-tar-gz"),
MIME_ENTRY("tar", "application/x-tar"),
MIME_ENTRY("gz", "application/x-gunzip"),
MIME_ENTRY("arj", "application/x-arj-compressed"),
MIME_ENTRY("rar", "application/x-rar-compressed"),
MIME_ENTRY("rtf", "application/rtf"),
MIME_ENTRY("pdf", "application/pdf"),
MIME_ENTRY("swf", "application/x-shockwave-flash"),
MIME_ENTRY("mpg", "video/mpeg"),
MIME_ENTRY("webm", "video/webm"),
MIME_ENTRY("mpeg", "video/mpeg"),
MIME_ENTRY("mov", "video/quicktime"),
MIME_ENTRY("mp4", "video/mp4"),
MIME_ENTRY("m4v", "video/x-m4v"),
MIME_ENTRY("asf", "video/x-ms-asf"),
MIME_ENTRY("avi", "video/x-msvideo"),
MIME_ENTRY("bmp", "image/bmp"),
{NULL, 0, NULL}};
static struct mg_str mg_get_mime_type(const char *path, const char *dflt,
const struct mg_serve_http_opts *opts) {
const char *ext, *overrides;
size_t i, path_len;
struct mg_str r, k, v;
path_len = strlen(path);
overrides = opts->custom_mime_types;
while ((overrides = mg_next_comma_list_entry(overrides, &k, &v)) != NULL) {
ext = path + (path_len - k.len);
if (path_len > k.len && mg_vcasecmp(&k, ext) == 0) {
return v;
}
}
for (i = 0; mg_static_builtin_mime_types[i].extension != NULL; i++) {
ext = path + (path_len - mg_static_builtin_mime_types[i].ext_len);
if (path_len > mg_static_builtin_mime_types[i].ext_len && ext[-1] == '.' &&
mg_casecmp(ext, mg_static_builtin_mime_types[i].extension) == 0) {
r.p = mg_static_builtin_mime_types[i].mime_type;
r.len = strlen(r.p);
return r;
}
}
r.p = dflt;
r.len = strlen(r.p);
return r;
}
#endif
/*
* Check whether full request is buffered. Return:
* -1 if request is malformed
* 0 if request is not yet fully buffered
* >0 actual request length, including last \r\n\r\n
*/
static int mg_http_get_request_len(const char *s, int buf_len) {
const unsigned char *buf = (unsigned char *) s;
int i;
for (i = 0; i < buf_len; i++) {
if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
return -1;
} else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
return i + 2;
} else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
buf[i + 2] == '\n') {
return i + 3;
}
}
return 0;
}
static const char *mg_http_parse_headers(const char *s, const char *end,
int len, struct http_message *req) {
int i = 0;
while (i < (int) ARRAY_SIZE(req->header_names) - 1) {
struct mg_str *k = &req->header_names[i], *v = &req->header_values[i];
s = mg_skip(s, end, ": ", k);
s = mg_skip(s, end, "\r\n", v);
while (v->len > 0 && v->p[v->len - 1] == ' ') {
v->len--; /* Trim trailing spaces in header value */
}
/*
* If header value is empty - skip it and go to next (if any).
* NOTE: Do not add it to headers_values because such addition changes API
* behaviour
*/
if (k->len != 0 && v->len == 0) {
continue;
}
if (k->len == 0 || v->len == 0) {
k->p = v->p = NULL;
k->len = v->len = 0;
break;
}
if (!mg_ncasecmp(k->p, "Content-Length", 14)) {
req->body.len = (size_t) to64(v->p);
req->message.len = len + req->body.len;
}
i++;
}
return s;
}
int mg_parse_http(const char *s, int n, struct http_message *hm, int is_req) {
const char *end, *qs;
int len = mg_http_get_request_len(s, n);
if (len <= 0) return len;
memset(hm, 0, sizeof(*hm));
hm->message.p = s;
hm->body.p = s + len;
hm->message.len = hm->body.len = (size_t) ~0;
end = s + len;
/* Request is fully buffered. Skip leading whitespaces. */
while (s < end && isspace(*(unsigned char *) s)) s++;
if (is_req) {
/* Parse request line: method, URI, proto */
s = mg_skip(s, end, " ", &hm->method);
s = mg_skip(s, end, " ", &hm->uri);
s = mg_skip(s, end, "\r\n", &hm->proto);
if (hm->uri.p <= hm->method.p || hm->proto.p <= hm->uri.p) return -1;
/* If URI contains '?' character, initialize query_string */
if ((qs = (char *) memchr(hm->uri.p, '?', hm->uri.len)) != NULL) {
hm->query_string.p = qs + 1;
hm->query_string.len = &hm->uri.p[hm->uri.len] - (qs + 1);
hm->uri.len = qs - hm->uri.p;
}
} else {
s = mg_skip(s, end, " ", &hm->proto);
if (end - s < 4 || s[3] != ' ') return -1;
hm->resp_code = atoi(s);
if (hm->resp_code < 100 || hm->resp_code >= 600) return -1;
s += 4;
s = mg_skip(s, end, "\r\n", &hm->resp_status_msg);
}
s = mg_http_parse_headers(s, end, len, hm);
/*
* mg_parse_http() is used to parse both HTTP requests and HTTP
* responses. If HTTP response does not have Content-Length set, then
* body is read until socket is closed, i.e. body.len is infinite (~0).
*
* For HTTP requests though, according to
* http://tools.ietf.org/html/rfc7231#section-8.1.3,
* only POST and PUT methods have defined body semantics.
* Therefore, if Content-Length is not specified and methods are
* not one of PUT or POST, set body length to 0.
*
* So,
* if it is HTTP request, and Content-Length is not set,
* and method is not (PUT or POST) then reset body length to zero.
*/
if (hm->body.len == (size_t) ~0 && is_req &&
mg_vcasecmp(&hm->method, "PUT") != 0 &&
mg_vcasecmp(&hm->method, "POST") != 0) {
hm->body.len = 0;
hm->message.len = len;
}
return len;
}
struct mg_str *mg_get_http_header(struct http_message *hm, const char *name) {
size_t i, len = strlen(name);
for (i = 0; hm->header_names[i].len > 0; i++) {
struct mg_str *h = &hm->header_names[i], *v = &hm->header_values[i];
if (h->p != NULL && h->len == len && !mg_ncasecmp(h->p, name, len))
return v;
}
return NULL;
}
#if MG_ENABLE_FILESYSTEM
static void mg_http_transfer_file_data(struct mg_connection *nc) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
char buf[MG_MAX_HTTP_SEND_MBUF];
size_t n = 0, to_read = 0, left = (size_t)(pd->file.cl - pd->file.sent);
if (pd->file.type == DATA_FILE) {
struct mbuf *io = &nc->send_mbuf;
if (io->len < sizeof(buf)) {
to_read = sizeof(buf) - io->len;
}
if (left > 0 && to_read > left) {
to_read = left;
}
if (to_read == 0) {
/* Rate limiting. send_mbuf is too full, wait until it's drained. */
} else if (pd->file.sent < pd->file.cl &&
(n = mg_fread(buf, 1, to_read, pd->file.fp)) > 0) {
mg_send(nc, buf, n);
pd->file.sent += n;
} else {
if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
mg_http_free_proto_data_file(&pd->file);
}
} else if (pd->file.type == DATA_PUT) {
struct mbuf *io = &nc->recv_mbuf;
size_t to_write = left <= 0 ? 0 : left < io->len ? (size_t) left : io->len;
size_t n = mg_fwrite(io->buf, 1, to_write, pd->file.fp);
if (n > 0) {
mbuf_remove(io, n);
pd->file.sent += n;
}
if (n == 0 || pd->file.sent >= pd->file.cl) {
if (!pd->file.keepalive) nc->flags |= MG_F_SEND_AND_CLOSE;
mg_http_free_proto_data_file(&pd->file);
}
}
#if MG_ENABLE_HTTP_CGI
else if (pd->cgi.cgi_nc != NULL) {
/* This is POST data that needs to be forwarded to the CGI process */
if (pd->cgi.cgi_nc != NULL) {
mg_forward(nc, pd->cgi.cgi_nc);
} else {
nc->flags |= MG_F_SEND_AND_CLOSE;
}
}
#endif
}
#endif /* MG_ENABLE_FILESYSTEM */
/*
* Parse chunked-encoded buffer. Return 0 if the buffer is not encoded, or
* if it's incomplete. If the chunk is fully buffered, return total number of
* bytes in a chunk, and store data in `data`, `data_len`.
*/
static size_t mg_http_parse_chunk(char *buf, size_t len, char **chunk_data,
size_t *chunk_len) {
unsigned char *s = (unsigned char *) buf;
size_t n = 0; /* scanned chunk length */
size_t i = 0; /* index in s */
/* Scan chunk length. That should be a hexadecimal number. */
while (i < len && isxdigit(s[i])) {
n *= 16;
n += (s[i] >= '0' && s[i] <= '9') ? s[i] - '0' : tolower(s[i]) - 'a' + 10;
i++;
}
/* Skip new line */
if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
return 0;
}
i += 2;
/* Record where the data is */
*chunk_data = (char *) s + i;
*chunk_len = n;
/* Skip data */
i += n;
/* Skip new line */
if (i == 0 || i + 2 > len || s[i] != '\r' || s[i + 1] != '\n') {
return 0;
}
return i + 2;
}
MG_INTERNAL size_t mg_handle_chunked(struct mg_connection *nc,
struct http_message *hm, char *buf,
size_t blen) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
char *data;
size_t i, n, data_len, body_len, zero_chunk_received = 0;
/* Find out piece of received data that is not yet reassembled */
body_len = (size_t) pd->chunk.body_len;
assert(blen >= body_len);
/* Traverse all fully buffered chunks */
for (i = body_len;
(n = mg_http_parse_chunk(buf + i, blen - i, &data, &data_len)) > 0;
i += n) {
/* Collapse chunk data to the rest of HTTP body */
memmove(buf + body_len, data, data_len);
body_len += data_len;
hm->body.len = body_len;
if (data_len == 0) {
zero_chunk_received = 1;
i += n;
break;
}
}
if (i > body_len) {
/* Shift unparsed content to the parsed body */
assert(i <= blen);
memmove(buf + body_len, buf + i, blen - i);
memset(buf + body_len + blen - i, 0, i - body_len);
nc->recv_mbuf.len -= i - body_len;
pd->chunk.body_len = body_len;
/* Send MG_EV_HTTP_CHUNK event */
nc->flags &= ~MG_F_DELETE_CHUNK;
mg_call(nc, nc->handler, nc->user_data, MG_EV_HTTP_CHUNK, hm);
/* Delete processed data if user set MG_F_DELETE_CHUNK flag */
if (nc->flags & MG_F_DELETE_CHUNK) {
memset(buf, 0, body_len);
memmove(buf, buf + body_len, blen - i);
nc->recv_mbuf.len -= body_len;
hm->body.len = 0;
pd->chunk.body_len = 0;
}
if (zero_chunk_received) {
/* Total message size is len(body) + len(headers) */
hm->message.len =
(size_t) pd->chunk.body_len + blen - i + (hm->body.p - hm->message.p);
}
}
return body_len;
}
struct mg_http_endpoint *mg_http_get_endpoint_handler(struct mg_connection *nc,
struct mg_str *uri_path) {
struct mg_http_proto_data *pd;
struct mg_http_endpoint *ret = NULL;
int matched, matched_max = 0;
struct mg_http_endpoint *ep;
if (nc == NULL) {
return NULL;
}
pd = mg_http_get_proto_data(nc);
ep = pd->endpoints;
while (ep != NULL) {
const struct mg_str name_s = {ep->name, ep->name_len};
if ((matched = mg_match_prefix_n(name_s, *uri_path)) != -1) {
if (matched > matched_max) {
/* Looking for the longest suitable handler */
ret = ep;
matched_max = matched;
}
}
ep = ep->next;
}
return ret;
}
static void mg_http_call_endpoint_handler(struct mg_connection *nc, int ev,
struct http_message *hm) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
void *user_data = nc->user_data;
if (ev == MG_EV_HTTP_REQUEST) {
struct mg_http_endpoint *ep =
mg_http_get_endpoint_handler(nc->listener, &hm->uri);
if (ep != NULL) {
pd->endpoint_handler = ep->handler;
#if MG_ENABLE_CALLBACK_USERDATA
user_data = ep->user_data;
#endif
}
}
mg_call(nc, pd->endpoint_handler ? pd->endpoint_handler : nc->handler,
user_data, ev, hm);
}
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
static void mg_http_multipart_continue(struct mg_connection *nc);
static void mg_http_multipart_begin(struct mg_connection *nc,
struct http_message *hm, int req_len);
#endif
/*
* lx106 compiler has a bug (TODO(mkm) report and insert tracking bug here)
* If a big structure is declared in a big function, lx106 gcc will make it
* even bigger (round up to 4k, from 700 bytes of actual size).
*/
#ifdef __xtensa__
static void mg_http_handler2(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data),
struct http_message *hm) __attribute__((noinline));
void mg_http_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct http_message hm;
mg_http_handler2(nc, ev, ev_data MG_UD_ARG(user_data), &hm);
}
static void mg_http_handler2(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data),
struct http_message *hm) {
#else /* !__XTENSA__ */
void mg_http_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct http_message shm;
struct http_message *hm = &shm;
#endif /* __XTENSA__ */
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
struct mbuf *io = &nc->recv_mbuf;
int req_len;
const int is_req = (nc->listener != NULL);
#if MG_ENABLE_HTTP_WEBSOCKET
struct mg_str *vec;
#endif
if (ev == MG_EV_CLOSE) {
#if MG_ENABLE_HTTP_CGI
/* Close associated CGI forwarder connection */
if (pd->cgi.cgi_nc != NULL) {
pd->cgi.cgi_nc->user_data = NULL;
pd->cgi.cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
#endif
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
if (pd->mp_stream.boundary != NULL) {
/*
* Multipart message is in progress, but connection is closed.
* Finish part and request with an error flag.
*/
struct mg_http_multipart_part mp;
memset(&mp, 0, sizeof(mp));
mp.status = -1;
mp.var_name = pd->mp_stream.var_name;
mp.file_name = pd->mp_stream.file_name;
mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
nc->user_data, MG_EV_HTTP_PART_END, &mp);
mp.var_name = NULL;
mp.file_name = NULL;
mg_call(nc, (pd->endpoint_handler ? pd->endpoint_handler : nc->handler),
nc->user_data, MG_EV_HTTP_MULTIPART_REQUEST_END, &mp);
} else
#endif
if (io->len > 0 && mg_parse_http(io->buf, io->len, hm, is_req) > 0) {
/*
* For HTTP messages without Content-Length, always send HTTP message
* before MG_EV_CLOSE message.
*/
int ev2 = is_req ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
hm->message.len = io->len;
hm->body.len = io->buf + io->len - hm->body.p;
mg_http_call_endpoint_handler(nc, ev2, hm);
}
}
#if MG_ENABLE_FILESYSTEM
if (pd->file.fp != NULL) {
mg_http_transfer_file_data(nc);
}
#endif
mg_call(nc, nc->handler, nc->user_data, ev, ev_data);
if (ev == MG_EV_RECV) {
struct mg_str *s;
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
if (pd->mp_stream.boundary != NULL) {
mg_http_multipart_continue(nc);
return;
}
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
req_len = mg_parse_http(io->buf, io->len, hm, is_req);
if (req_len > 0 &&
(s = mg_get_http_header(hm, "Transfer-Encoding")) != NULL &&
mg_vcasecmp(s, "chunked") == 0) {
mg_handle_chunked(nc, hm, io->buf + req_len, io->len - req_len);
}
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
if (req_len > 0 && (s = mg_get_http_header(hm, "Content-Type")) != NULL &&
s->len >= 9 && strncmp(s->p, "multipart", 9) == 0) {
mg_http_multipart_begin(nc, hm, req_len);
mg_http_multipart_continue(nc);
return;
}
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
/* TODO(alashkin): refactor this ifelseifelseifelseifelse */
if ((req_len < 0 ||
(req_len == 0 && io->len >= MG_MAX_HTTP_REQUEST_SIZE))) {
DBG(("invalid request"));
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
} else if (req_len == 0) {
/* Do nothing, request is not yet fully buffered */
}
#if MG_ENABLE_HTTP_WEBSOCKET
else if (nc->listener == NULL &&
mg_get_http_header(hm, "Sec-WebSocket-Accept")) {
/* We're websocket client, got handshake response from server. */
/* TODO(lsm): check the validity of accept Sec-WebSocket-Accept */
mbuf_remove(io, req_len);
nc->proto_handler = mg_ws_handler;
nc->flags |= MG_F_IS_WEBSOCKET;
mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE,
NULL);
mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data));
} else if (nc->listener != NULL &&
(vec = mg_get_http_header(hm, "Sec-WebSocket-Key")) != NULL) {
struct mg_http_endpoint *ep;
/* This is a websocket request. Switch protocol handlers. */
mbuf_remove(io, req_len);
nc->proto_handler = mg_ws_handler;
nc->flags |= MG_F_IS_WEBSOCKET;
/*
* If we have a handler set up with mg_register_http_endpoint(),
* deliver subsequent websocket events to this handler after the
* protocol switch.
*/
ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
if (ep != NULL) {
nc->handler = ep->handler;
#if MG_ENABLE_CALLBACK_USERDATA
nc->user_data = ep->user_data;
#endif
}
/* Send handshake */
mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_REQUEST,
hm);
if (!(nc->flags & (MG_F_CLOSE_IMMEDIATELY | MG_F_SEND_AND_CLOSE))) {
if (nc->send_mbuf.len == 0) {
mg_ws_handshake(nc, vec);
}
mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_HANDSHAKE_DONE,
NULL);
mg_ws_handler(nc, MG_EV_RECV, ev_data MG_UD_ARG(user_data));
}
}
#endif /* MG_ENABLE_HTTP_WEBSOCKET */
else if (hm->message.len <= io->len) {
int trigger_ev = nc->listener ? MG_EV_HTTP_REQUEST : MG_EV_HTTP_REPLY;
char addr[32];
mg_sock_addr_to_str(&nc->sa, addr, sizeof(addr),
MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
DBG(("%p %s %.*s %.*s", nc, addr, (int) hm->method.len, hm->method.p,
(int) hm->uri.len, hm->uri.p));
/* Whole HTTP message is fully buffered, call event handler */
#if MG_ENABLE_JAVASCRIPT
v7_val_t v1, v2, headers, req, args, res;
struct v7 *v7 = nc->mgr->v7;
const char *ev_name = trigger_ev == MG_EV_HTTP_REPLY ? "onsnd" : "onrcv";
int i, js_callback_handled_request = 0;
if (v7 != NULL) {
/* Lookup JS callback */
v1 = v7_get(v7, v7_get_global(v7), "Http", ~0);
v2 = v7_get(v7, v1, ev_name, ~0);
/* Create callback params. TODO(lsm): own/disown those */
args = v7_mk_array(v7);
req = v7_mk_object(v7);
headers = v7_mk_object(v7);
/* Populate request object */
v7_set(v7, req, "method", ~0,
v7_mk_string(v7, hm->method.p, hm->method.len, 1));
v7_set(v7, req, "uri", ~0, v7_mk_string(v7, hm->uri.p, hm->uri.len, 1));
v7_set(v7, req, "body", ~0,
v7_mk_string(v7, hm->body.p, hm->body.len, 1));
v7_set(v7, req, "headers", ~0, headers);
for (i = 0; hm->header_names[i].len > 0; i++) {
const struct mg_str *name = &hm->header_names[i];
const struct mg_str *value = &hm->header_values[i];
v7_set(v7, headers, name->p, name->len,
v7_mk_string(v7, value->p, value->len, 1));
}
/* Invoke callback. TODO(lsm): report errors */
v7_array_push(v7, args, v7_mk_foreign(v7, nc));
v7_array_push(v7, args, req);
if (v7_apply(v7, v2, V7_UNDEFINED, args, &res) == V7_OK &&
v7_is_truthy(v7, res)) {
js_callback_handled_request++;
}
}
/* If JS callback returns true, stop request processing */
if (js_callback_handled_request) {
nc->flags |= MG_F_SEND_AND_CLOSE;
} else {
mg_http_call_endpoint_handler(nc, trigger_ev, hm);
}
#else
mg_http_call_endpoint_handler(nc, trigger_ev, hm);
#endif
mbuf_remove(io, hm->message.len);
}
}
(void) pd;
}
static size_t mg_get_line_len(const char *buf, size_t buf_len) {
size_t len = 0;
while (len < buf_len && buf[len] != '\n') len++;
return len == buf_len ? 0 : len + 1;
}
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
static void mg_http_multipart_begin(struct mg_connection *nc,
struct http_message *hm, int req_len) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
struct mg_str *ct;
struct mbuf *io = &nc->recv_mbuf;
void *user_data = nc->user_data;
char boundary[100];
int boundary_len;
ct = mg_get_http_header(hm, "Content-Type");
if (ct == NULL) {
/* We need more data - or it isn't multipart mesage */
goto exit_mp;
}
/* Content-type should start with "multipart" */
if (ct->len < 9 || strncmp(ct->p, "multipart", 9) != 0) {
goto exit_mp;
}
boundary_len =
mg_http_parse_header(ct, "boundary", boundary, sizeof(boundary));
if (boundary_len == 0) {
/*
* Content type is multipart, but there is no boundary,
* probably malformed request
*/
nc->flags = MG_F_CLOSE_IMMEDIATELY;
DBG(("invalid request"));
goto exit_mp;
}
/* If we reach this place - that is multipart request */
if (pd->mp_stream.boundary != NULL) {
/*
* Another streaming request was in progress,
* looks like protocol error
*/
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
} else {
struct mg_http_endpoint *ep = NULL;
pd->mp_stream.state = MPS_BEGIN;
pd->mp_stream.boundary = strdup(boundary);
pd->mp_stream.boundary_len = strlen(boundary);
pd->mp_stream.var_name = pd->mp_stream.file_name = NULL;
pd->endpoint_handler = nc->handler;
ep = mg_http_get_endpoint_handler(nc->listener, &hm->uri);
if (ep != NULL) {
pd->endpoint_handler = ep->handler;
#if MG_ENABLE_CALLBACK_USERDATA
user_data = ep->user_data;
#endif
}
mg_call(nc, pd->endpoint_handler, user_data, MG_EV_HTTP_MULTIPART_REQUEST,
hm);
mbuf_remove(io, req_len);
}
exit_mp:
;
}
#define CONTENT_DISPOSITION "Content-Disposition: "
static void mg_http_multipart_call_handler(struct mg_connection *c, int ev,
const char *data, size_t data_len) {
struct mg_http_multipart_part mp;
struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
memset(&mp, 0, sizeof(mp));
mp.var_name = pd->mp_stream.var_name;
mp.file_name = pd->mp_stream.file_name;
mp.user_data = pd->mp_stream.user_data;
mp.data.p = data;
mp.data.len = data_len;
mg_call(c, pd->endpoint_handler, c->user_data, ev, &mp);
pd->mp_stream.user_data = mp.user_data;
}
static int mg_http_multipart_got_chunk(struct mg_connection *c) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
struct mbuf *io = &c->recv_mbuf;
mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf,
pd->mp_stream.prev_io_len);
mbuf_remove(io, pd->mp_stream.prev_io_len);
pd->mp_stream.prev_io_len = 0;
pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
return 0;
}
static int mg_http_multipart_finalize(struct mg_connection *c) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
MG_FREE((void *) pd->mp_stream.file_name);
pd->mp_stream.file_name = NULL;
MG_FREE((void *) pd->mp_stream.var_name);
pd->mp_stream.var_name = NULL;
mg_http_multipart_call_handler(c, MG_EV_HTTP_MULTIPART_REQUEST_END, NULL, 0);
mg_http_free_proto_data_mp_stream(&pd->mp_stream);
pd->mp_stream.state = MPS_FINISHED;
return 1;
}
static int mg_http_multipart_wait_for_boundary(struct mg_connection *c) {
const char *boundary;
struct mbuf *io = &c->recv_mbuf;
struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
if (pd->mp_stream.boundary == NULL) {
pd->mp_stream.state = MPS_FINALIZE;
DBG(("Invalid request: boundary not initilaized"));
return 0;
}
if ((int) io->len < pd->mp_stream.boundary_len + 2) {
return 0;
}
boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
if (boundary != NULL) {
const char *boundary_end = (boundary + pd->mp_stream.boundary_len);
if (io->len - (boundary_end - io->buf) < 4) {
return 0;
}
if (strncmp(boundary_end, "--\r\n", 4) == 0) {
pd->mp_stream.state = MPS_FINALIZE;
mbuf_remove(io, (boundary_end - io->buf) + 4);
} else {
pd->mp_stream.state = MPS_GOT_BOUNDARY;
}
} else {
return 0;
}
return 1;
}
static int mg_http_multipart_process_boundary(struct mg_connection *c) {
int data_size;
const char *boundary, *block_begin;
struct mbuf *io = &c->recv_mbuf;
struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
char file_name[100], var_name[100];
int line_len;
boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
block_begin = boundary + pd->mp_stream.boundary_len + 2;
data_size = io->len - (block_begin - io->buf);
while (data_size > 0 &&
(line_len = mg_get_line_len(block_begin, data_size)) != 0) {
if (line_len > (int) sizeof(CONTENT_DISPOSITION) &&
mg_ncasecmp(block_begin, CONTENT_DISPOSITION,
sizeof(CONTENT_DISPOSITION) - 1) == 0) {
struct mg_str header;
header.p = block_begin + sizeof(CONTENT_DISPOSITION) - 1;
header.len = line_len - sizeof(CONTENT_DISPOSITION) - 1;
mg_http_parse_header(&header, "name", var_name, sizeof(var_name) - 2);
mg_http_parse_header(&header, "filename", file_name,
sizeof(file_name) - 2);
block_begin += line_len;
data_size -= line_len;
continue;
}
if (line_len == 2 && mg_ncasecmp(block_begin, "\r\n", 2) == 0) {
mbuf_remove(io, block_begin - io->buf + 2);
if (pd->mp_stream.processing_part != 0) {
mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_END, NULL, 0);
}
MG_FREE((void *) pd->mp_stream.file_name);
pd->mp_stream.file_name = strdup(file_name);
MG_FREE((void *) pd->mp_stream.var_name);
pd->mp_stream.var_name = strdup(var_name);
mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_BEGIN, NULL, 0);
pd->mp_stream.state = MPS_WAITING_FOR_CHUNK;
pd->mp_stream.processing_part++;
return 1;
}
block_begin += line_len;
}
pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
return 0;
}
static int mg_http_multipart_continue_wait_for_chunk(struct mg_connection *c) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
struct mbuf *io = &c->recv_mbuf;
const char *boundary;
if ((int) io->len < pd->mp_stream.boundary_len + 6 /* \r\n, --, -- */) {
return 0;
}
boundary = c_strnstr(io->buf, pd->mp_stream.boundary, io->len);
if (boundary == NULL && pd->mp_stream.prev_io_len == 0) {
pd->mp_stream.prev_io_len = io->len;
return 0;
} else if (boundary == NULL &&
(int) io->len >
pd->mp_stream.prev_io_len + pd->mp_stream.boundary_len + 4) {
pd->mp_stream.state = MPS_GOT_CHUNK;
return 1;
} else if (boundary != NULL) {
int data_size = (boundary - io->buf - 4);
mg_http_multipart_call_handler(c, MG_EV_HTTP_PART_DATA, io->buf, data_size);
mbuf_remove(io, (boundary - io->buf));
pd->mp_stream.prev_io_len = 0;
pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
return 1;
} else {
return 0;
}
}
static void mg_http_multipart_continue(struct mg_connection *c) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(c);
while (1) {
switch (pd->mp_stream.state) {
case MPS_BEGIN: {
pd->mp_stream.state = MPS_WAITING_FOR_BOUNDARY;
break;
}
case MPS_WAITING_FOR_BOUNDARY: {
if (mg_http_multipart_wait_for_boundary(c) == 0) {
return;
}
break;
}
case MPS_GOT_BOUNDARY: {
if (mg_http_multipart_process_boundary(c) == 0) {
return;
}
break;
}
case MPS_WAITING_FOR_CHUNK: {
if (mg_http_multipart_continue_wait_for_chunk(c) == 0) {
return;
}
break;
}
case MPS_GOT_CHUNK: {
if (mg_http_multipart_got_chunk(c) == 0) {
return;
}
break;
}
case MPS_FINALIZE: {
if (mg_http_multipart_finalize(c) == 0) {
return;
}
break;
}
case MPS_FINISHED: {
mbuf_remove(&c->recv_mbuf, c->recv_mbuf.len);
return;
}
}
}
}
struct file_upload_state {
char *lfn;
size_t num_recd;
FILE *fp;
};
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
void mg_set_protocol_http_websocket(struct mg_connection *nc) {
nc->proto_handler = mg_http_handler;
}
const char *mg_status_message(int status_code) {
switch (status_code) {
case 206:
return "Partial Content";
case 301:
return "Moved";
case 302:
return "Found";
case 400:
return "Bad Request";
case 401:
return "Unauthorized";
case 403:
return "Forbidden";
case 404:
return "Not Found";
case 416:
return "Requested Range Not Satisfiable";
case 418:
return "I'm a teapot";
case 500:
return "Internal Server Error";
case 502:
return "Bad Gateway";
case 503:
return "Service Unavailable";
#if MG_ENABLE_EXTRA_ERRORS_DESC
case 100:
return "Continue";
case 101:
return "Switching Protocols";
case 102:
return "Processing";
case 200:
return "OK";
case 201:
return "Created";
case 202:
return "Accepted";
case 203:
return "Non-Authoritative Information";
case 204:
return "No Content";
case 205:
return "Reset Content";
case 207:
return "Multi-Status";
case 208:
return "Already Reported";
case 226:
return "IM Used";
case 300:
return "Multiple Choices";
case 303:
return "See Other";
case 304:
return "Not Modified";
case 305:
return "Use Proxy";
case 306:
return "Switch Proxy";
case 307:
return "Temporary Redirect";
case 308:
return "Permanent Redirect";
case 402:
return "Payment Required";
case 405:
return "Method Not Allowed";
case 406:
return "Not Acceptable";
case 407:
return "Proxy Authentication Required";
case 408:
return "Request Timeout";
case 409:
return "Conflict";
case 410:
return "Gone";
case 411:
return "Length Required";
case 412:
return "Precondition Failed";
case 413:
return "Payload Too Large";
case 414:
return "URI Too Long";
case 415:
return "Unsupported Media Type";
case 417:
return "Expectation Failed";
case 422:
return "Unprocessable Entity";
case 423:
return "Locked";
case 424:
return "Failed Dependency";
case 426:
return "Upgrade Required";
case 428:
return "Precondition Required";
case 429:
return "Too Many Requests";
case 431:
return "Request Header Fields Too Large";
case 451:
return "Unavailable For Legal Reasons";
case 501:
return "Not Implemented";
case 504:
return "Gateway Timeout";
case 505:
return "HTTP Version Not Supported";
case 506:
return "Variant Also Negotiates";
case 507:
return "Insufficient Storage";
case 508:
return "Loop Detected";
case 510:
return "Not Extended";
case 511:
return "Network Authentication Required";
#endif /* MG_ENABLE_EXTRA_ERRORS_DESC */
default:
return "OK";
}
}
void mg_send_response_line_s(struct mg_connection *nc, int status_code,
const struct mg_str extra_headers) {
mg_printf(nc, "HTTP/1.1 %d %s\r\nServer: %s\r\n", status_code,
mg_status_message(status_code), mg_version_header);
if (extra_headers.len > 0) {
mg_printf(nc, "%.*s\r\n", (int) extra_headers.len, extra_headers.p);
}
}
void mg_send_response_line(struct mg_connection *nc, int status_code,
const char *extra_headers) {
mg_send_response_line_s(nc, status_code, mg_mk_str(extra_headers));
}
void mg_http_send_redirect(struct mg_connection *nc, int status_code,
const struct mg_str location,
const struct mg_str extra_headers) {
char bbody[100], *pbody = bbody;
int bl = mg_asprintf(&pbody, sizeof(bbody),
"<p>Moved <a href='%.*s'>here</a>.\r\n",
(int) location.len, location.p);
char bhead[150], *phead = bhead;
mg_asprintf(&phead, sizeof(bhead),
"Location: %.*s\r\n"
"Content-Type: text/html\r\n"
"Content-Length: %d\r\n"
"Cache-Control: no-cache\r\n"
"%.*s%s",
(int) location.len, location.p, bl, (int) extra_headers.len,
extra_headers.p, (extra_headers.len > 0 ? "\r\n" : ""));
mg_send_response_line(nc, status_code, phead);
if (phead != bhead) MG_FREE(phead);
mg_send(nc, pbody, bl);
if (pbody != bbody) MG_FREE(pbody);
}
void mg_send_head(struct mg_connection *c, int status_code,
int64_t content_length, const char *extra_headers) {
mg_send_response_line(c, status_code, extra_headers);
if (content_length < 0) {
mg_printf(c, "%s", "Transfer-Encoding: chunked\r\n");
} else {
mg_printf(c, "Content-Length: %" INT64_FMT "\r\n", content_length);
}
mg_send(c, "\r\n", 2);
}
void mg_http_send_error(struct mg_connection *nc, int code,
const char *reason) {
if (!reason) reason = mg_status_message(code);
LOG(LL_DEBUG, ("%p %d %s", nc, code, reason));
mg_send_head(nc, code, strlen(reason),
"Content-Type: text/plain\r\nConnection: close");
mg_send(nc, reason, strlen(reason));
nc->flags |= MG_F_SEND_AND_CLOSE;
}
#if MG_ENABLE_FILESYSTEM
static void mg_http_construct_etag(char *buf, size_t buf_len,
const cs_stat_t *st) {
snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long) st->st_mtime,
(int64_t) st->st_size);
}
#ifndef WINCE
static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
}
#else
/* Look wince_lib.c for WindowsCE implementation */
static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t);
#endif
static int mg_http_parse_range_header(const struct mg_str *header, int64_t *a,
int64_t *b) {
/*
* There is no snscanf. Headers are not guaranteed to be NUL-terminated,
* so we have this. Ugh.
*/
int result;
char *p = (char *) MG_MALLOC(header->len + 1);
if (p == NULL) return 0;
memcpy(p, header->p, header->len);
p[header->len] = '\0';
result = sscanf(p, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
MG_FREE(p);
return result;
}
void mg_http_serve_file(struct mg_connection *nc, struct http_message *hm,
const char *path, const struct mg_str mime_type,
const struct mg_str extra_headers) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
cs_stat_t st;
LOG(LL_DEBUG, ("%p [%s] %.*s", nc, path, (int) mime_type.len, mime_type.p));
if (mg_stat(path, &st) != 0 || (pd->file.fp = mg_fopen(path, "rb")) == NULL) {
int code, err = mg_get_errno();
switch (err) {
case EACCES:
code = 403;
break;
case ENOENT:
code = 404;
break;
default:
code = 500;
};
mg_http_send_error(nc, code, "Open failed");
} else {
char etag[50], current_time[50], last_modified[50], range[70];
time_t t = (time_t) mg_time();
int64_t r1 = 0, r2 = 0, cl = st.st_size;
struct mg_str *range_hdr = mg_get_http_header(hm, "Range");
int n, status_code = 200;
/* Handle Range header */
range[0] = '\0';
if (range_hdr != NULL &&
(n = mg_http_parse_range_header(range_hdr, &r1, &r2)) > 0 && r1 >= 0 &&
r2 >= 0) {
/* If range is specified like "400-", set second limit to content len */
if (n == 1) {
r2 = cl - 1;
}
if (r1 > r2 || r2 >= cl) {
status_code = 416;
cl = 0;
snprintf(range, sizeof(range),
"Content-Range: bytes */%" INT64_FMT "\r\n",
(int64_t) st.st_size);
} else {
status_code = 206;
cl = r2 - r1 + 1;
snprintf(range, sizeof(range), "Content-Range: bytes %" INT64_FMT
"-%" INT64_FMT "/%" INT64_FMT "\r\n",
r1, r1 + cl - 1, (int64_t) st.st_size);
#if _FILE_OFFSET_BITS == 64 || _POSIX_C_SOURCE >= 200112L || \
_XOPEN_SOURCE >= 600
fseeko(pd->file.fp, r1, SEEK_SET);
#else
fseek(pd->file.fp, (long) r1, SEEK_SET);
#endif
}
}
#if !MG_DISABLE_HTTP_KEEP_ALIVE
{
struct mg_str *conn_hdr = mg_get_http_header(hm, "Connection");
if (conn_hdr != NULL) {
pd->file.keepalive = (mg_vcasecmp(conn_hdr, "keep-alive") == 0);
} else {
pd->file.keepalive = (mg_vcmp(&hm->proto, "HTTP/1.1") == 0);
}
}
#endif
mg_http_construct_etag(etag, sizeof(etag), &st);
mg_gmt_time_string(current_time, sizeof(current_time), &t);
mg_gmt_time_string(last_modified, sizeof(last_modified), &st.st_mtime);
/*
* Content length casted to size_t because:
* 1) that's the maximum buffer size anyway
* 2) ESP8266 RTOS SDK newlib vprintf cannot contain a 64bit arg at non-last
* position
* TODO(mkm): fix ESP8266 RTOS SDK
*/
mg_send_response_line_s(nc, status_code, extra_headers);
mg_printf(nc,
"Date: %s\r\n"
"Last-Modified: %s\r\n"
"Accept-Ranges: bytes\r\n"
"Content-Type: %.*s\r\n"
"Connection: %s\r\n"
"Content-Length: %" SIZE_T_FMT
"\r\n"
"%sEtag: %s\r\n\r\n",
current_time, last_modified, (int) mime_type.len, mime_type.p,
(pd->file.keepalive ? "keep-alive" : "close"), (size_t) cl, range,
etag);
pd->file.cl = cl;
pd->file.type = DATA_FILE;
mg_http_transfer_file_data(nc);
}
}
static void mg_http_serve_file2(struct mg_connection *nc, const char *path,
struct http_message *hm,
struct mg_serve_http_opts *opts) {
#if MG_ENABLE_HTTP_SSI
if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) > 0) {
mg_handle_ssi_request(nc, hm, path, opts);
return;
}
#endif
mg_http_serve_file(nc, hm, path, mg_get_mime_type(path, "text/plain", opts),
mg_mk_str(opts->extra_headers));
}
#endif
int mg_url_decode(const char *src, int src_len, char *dst, int dst_len,
int is_form_url_encoded) {
int i, j, a, b;
#define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
if (src[i] == '%') {
if (i < src_len - 2 && isxdigit(*(const unsigned char *) (src + i + 1)) &&
isxdigit(*(const unsigned char *) (src + i + 2))) {
a = tolower(*(const unsigned char *) (src + i + 1));
b = tolower(*(const unsigned char *) (src + i + 2));
dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
i += 2;
} else {
return -1;
}
} else if (is_form_url_encoded && src[i] == '+') {
dst[j] = ' ';
} else {
dst[j] = src[i];
}
}
dst[j] = '\0'; /* Null-terminate the destination */
return i >= src_len ? j : -1;
}
int mg_get_http_var(const struct mg_str *buf, const char *name, char *dst,
size_t dst_len) {
const char *p, *e, *s;
size_t name_len;
int len;
/*
* According to the documentation function returns negative
* value in case of error. For debug purposes it returns:
* -1 - src is wrong (NUUL)
* -2 - dst is wrong (NULL)
* -3 - failed to decode url or dst is to small
*/
if (dst == NULL || dst_len == 0) {
len = -2;
} else if (buf->p == NULL || name == NULL || buf->len == 0) {
len = -1;
dst[0] = '\0';
} else {
name_len = strlen(name);
e = buf->p + buf->len;
len = 0;
dst[0] = '\0';
for (p = buf->p; p + name_len < e; p++) {
if ((p == buf->p || p[-1] == '&') && p[name_len] == '=' &&
!mg_ncasecmp(name, p, name_len)) {
p += name_len + 1;
s = (const char *) memchr(p, '&', (size_t)(e - p));
if (s == NULL) {
s = e;
}
len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
/* -1 means: failed to decode or dst is too small */
if (len == -1) {
len = -3;
}
break;
}
}
}
return len;
}
void mg_send_http_chunk(struct mg_connection *nc, const char *buf, size_t len) {
char chunk_size[50];
int n;
n = snprintf(chunk_size, sizeof(chunk_size), "%lX\r\n", (unsigned long) len);
mg_send(nc, chunk_size, n);
mg_send(nc, buf, len);
mg_send(nc, "\r\n", 2);
}
void mg_printf_http_chunk(struct mg_connection *nc, const char *fmt, ...) {
char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
int len;
va_list ap;
va_start(ap, fmt);
len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
va_end(ap);
if (len >= 0) {
mg_send_http_chunk(nc, buf, len);
}
/* LCOV_EXCL_START */
if (buf != mem && buf != NULL) {
MG_FREE(buf);
}
/* LCOV_EXCL_STOP */
}
void mg_printf_html_escape(struct mg_connection *nc, const char *fmt, ...) {
char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
int i, j, len;
va_list ap;
va_start(ap, fmt);
len = mg_avprintf(&buf, sizeof(mem), fmt, ap);
va_end(ap);
if (len >= 0) {
for (i = j = 0; i < len; i++) {
if (buf[i] == '<' || buf[i] == '>') {
mg_send(nc, buf + j, i - j);
mg_send(nc, buf[i] == '<' ? "<" : ">", 4);
j = i + 1;
}
}
mg_send(nc, buf + j, i - j);
}
/* LCOV_EXCL_START */
if (buf != mem && buf != NULL) {
MG_FREE(buf);
}
/* LCOV_EXCL_STOP */
}
int mg_http_parse_header(struct mg_str *hdr, const char *var_name, char *buf,
size_t buf_size) {
int ch = ' ', ch1 = ',', len = 0, n = strlen(var_name);
const char *p, *end = hdr ? hdr->p + hdr->len : NULL, *s = NULL;
if (buf != NULL && buf_size > 0) buf[0] = '\0';
if (hdr == NULL) return 0;
/* Find where variable starts */
for (s = hdr->p; s != NULL && s + n < end; s++) {
if ((s == hdr->p || s[-1] == ch || s[-1] == ch1 || s[-1] == ';') &&
s[n] == '=' && !strncmp(s, var_name, n))
break;
}
if (s != NULL && &s[n + 1] < end) {
s += n + 1;
if (*s == '"' || *s == '\'') {
ch = ch1 = *s++;
}
p = s;
while (p < end && p[0] != ch && p[0] != ch1 && len < (int) buf_size) {
if (ch != ' ' && p[0] == '\\' && p[1] == ch) p++;
buf[len++] = *p++;
}
if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
len = 0;
} else {
if (len > 0 && s[len - 1] == ',') len--;
if (len > 0 && s[len - 1] == ';') len--;
buf[len] = '\0';
}
}
return len;
}
int mg_get_http_basic_auth(struct http_message *hm, char *user, size_t user_len,
char *pass, size_t pass_len) {
struct mg_str *hdr = mg_get_http_header(hm, "Authorization");
if (hdr == NULL) return -1;
return mg_parse_http_basic_auth(hdr, user, user_len, pass, pass_len);
}
int mg_parse_http_basic_auth(struct mg_str *hdr, char *user, size_t user_len,
char *pass, size_t pass_len) {
char *buf = NULL;
char fmt[64];
int res = 0;
if (mg_strncmp(*hdr, mg_mk_str("Basic "), 6) != 0) return -1;
buf = (char *) MG_MALLOC(hdr->len);
cs_base64_decode((unsigned char *) hdr->p + 6, hdr->len, buf, NULL);
/* e.g. "%123[^:]:%321[^\n]" */
snprintf(fmt, sizeof(fmt), "%%%" SIZE_T_FMT "[^:]:%%%" SIZE_T_FMT "[^\n]",
user_len - 1, pass_len - 1);
if (sscanf(buf, fmt, user, pass) == 0) {
res = -1;
}
MG_FREE(buf);
return res;
}
#if MG_ENABLE_FILESYSTEM
static int mg_is_file_hidden(const char *path,
const struct mg_serve_http_opts *opts,
int exclude_specials) {
const char *p1 = opts->per_directory_auth_file;
const char *p2 = opts->hidden_file_pattern;
/* Strip directory path from the file name */
const char *pdir = strrchr(path, DIRSEP);
if (pdir != NULL) {
path = pdir + 1;
}
return (exclude_specials && (!strcmp(path, ".") || !strcmp(path, ".."))) ||
(p1 != NULL &&
mg_match_prefix(p1, strlen(p1), path) == (int) strlen(p1)) ||
(p2 != NULL && mg_match_prefix(p2, strlen(p2), path) > 0);
}
#if !MG_DISABLE_HTTP_DIGEST_AUTH
static void mg_mkmd5resp(const char *method, size_t method_len, const char *uri,
size_t uri_len, const char *ha1, size_t ha1_len,
const char *nonce, size_t nonce_len, const char *nc,
size_t nc_len, const char *cnonce, size_t cnonce_len,
const char *qop, size_t qop_len, char *resp) {
static const char colon[] = ":";
static const size_t one = 1;
char ha2[33];
cs_md5(ha2, method, method_len, colon, one, uri, uri_len, NULL);
cs_md5(resp, ha1, ha1_len, colon, one, nonce, nonce_len, colon, one, nc,
nc_len, colon, one, cnonce, cnonce_len, colon, one, qop, qop_len,
colon, one, ha2, sizeof(ha2) - 1, NULL);
}
int mg_http_create_digest_auth_header(char *buf, size_t buf_len,
const char *method, const char *uri,
const char *auth_domain, const char *user,
const char *passwd) {
static const char colon[] = ":", qop[] = "auth";
static const size_t one = 1;
char ha1[33], resp[33], cnonce[40];
snprintf(cnonce, sizeof(cnonce), "%x", (unsigned int) mg_time());
cs_md5(ha1, user, (size_t) strlen(user), colon, one, auth_domain,
(size_t) strlen(auth_domain), colon, one, passwd,
(size_t) strlen(passwd), NULL);
mg_mkmd5resp(method, strlen(method), uri, strlen(uri), ha1, sizeof(ha1) - 1,
cnonce, strlen(cnonce), "1", one, cnonce, strlen(cnonce), qop,
sizeof(qop) - 1, resp);
return snprintf(buf, buf_len,
"Authorization: Digest username=\"%s\","
"realm=\"%s\",uri=\"%s\",qop=%s,nc=1,cnonce=%s,"
"nonce=%s,response=%s\r\n",
user, auth_domain, uri, qop, cnonce, cnonce, resp);
}
/*
* Check for authentication timeout.
* Clients send time stamp encoded in nonce. Make sure it is not too old,
* to prevent replay attacks.
* Assumption: nonce is a hexadecimal number of seconds since 1970.
*/
static int mg_check_nonce(const char *nonce) {
unsigned long now = (unsigned long) mg_time();
unsigned long val = (unsigned long) strtoul(nonce, NULL, 16);
return now < val || now - val < 3600;
}
int mg_http_check_digest_auth(struct http_message *hm, const char *auth_domain,
FILE *fp) {
struct mg_str *hdr;
char buf[128], f_user[sizeof(buf)], f_ha1[sizeof(buf)], f_domain[sizeof(buf)];
char user[50], cnonce[33], response[40], uri[200], qop[20], nc[20], nonce[30];
char expected_response[33];
/* Parse "Authorization:" header, fail fast on parse error */
if (hm == NULL || fp == NULL ||
(hdr = mg_get_http_header(hm, "Authorization")) == NULL ||
mg_http_parse_header(hdr, "username", user, sizeof(user)) == 0 ||
mg_http_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce)) == 0 ||
mg_http_parse_header(hdr, "response", response, sizeof(response)) == 0 ||
mg_http_parse_header(hdr, "uri", uri, sizeof(uri)) == 0 ||
mg_http_parse_header(hdr, "qop", qop, sizeof(qop)) == 0 ||
mg_http_parse_header(hdr, "nc", nc, sizeof(nc)) == 0 ||
mg_http_parse_header(hdr, "nonce", nonce, sizeof(nonce)) == 0 ||
mg_check_nonce(nonce) == 0) {
return 0;
}
/*
* Read passwords file line by line. If should have htdigest format,
* i.e. each line should be a colon-separated sequence:
* USER_NAME:DOMAIN_NAME:HA1_HASH_OF_USER_DOMAIN_AND_PASSWORD
*/
while (fgets(buf, sizeof(buf), fp) != NULL) {
if (sscanf(buf, "%[^:]:%[^:]:%s", f_user, f_domain, f_ha1) == 3 &&
strcmp(user, f_user) == 0 &&
/* NOTE(lsm): due to a bug in MSIE, we do not compare URIs */
strcmp(auth_domain, f_domain) == 0) {
/* User and domain matched, check the password */
mg_mkmd5resp(
hm->method.p, hm->method.len, hm->uri.p,
hm->uri.len + (hm->query_string.len ? hm->query_string.len + 1 : 0),
f_ha1, strlen(f_ha1), nonce, strlen(nonce), nc, strlen(nc), cnonce,
strlen(cnonce), qop, strlen(qop), expected_response);
return mg_casecmp(response, expected_response) == 0;
}
}
/* None of the entries in the passwords file matched - return failure */
return 0;
}
static int mg_is_authorized(struct http_message *hm, const char *path,
int is_directory, const char *domain,
const char *passwords_file,
int is_global_pass_file) {
char buf[MG_MAX_PATH];
const char *p;
FILE *fp;
int authorized = 1;
if (domain != NULL && passwords_file != NULL) {
if (is_global_pass_file) {
fp = mg_fopen(passwords_file, "r");
} else if (is_directory) {
snprintf(buf, sizeof(buf), "%s%c%s", path, DIRSEP, passwords_file);
fp = mg_fopen(buf, "r");
} else {
p = strrchr(path, DIRSEP);
if (p == NULL) p = path;
snprintf(buf, sizeof(buf), "%.*s%c%s", (int) (p - path), path, DIRSEP,
passwords_file);
fp = mg_fopen(buf, "r");
}
if (fp != NULL) {
authorized = mg_http_check_digest_auth(hm, domain, fp);
fclose(fp);
}
}
LOG(LL_DEBUG, ("%s '%s' %d %d", path, passwords_file ? passwords_file : "",
is_global_pass_file, authorized));
return authorized;
}
#else
static int mg_is_authorized(struct http_message *hm, const char *path,
int is_directory, const char *domain,
const char *passwords_file,
int is_global_pass_file) {
(void) hm;
(void) path;
(void) is_directory;
(void) domain;
(void) passwords_file;
(void) is_global_pass_file;
return 1;
}
#endif
#if MG_ENABLE_DIRECTORY_LISTING
static size_t mg_url_encode(const char *src, size_t s_len, char *dst,
size_t dst_len) {
static const char *dont_escape = "._-$,;~()/";
static const char *hex = "0123456789abcdef";
size_t i = 0, j = 0;
for (i = j = 0; dst_len > 0 && i < s_len && j + 2 < dst_len - 1; i++, j++) {
if (isalnum(*(const unsigned char *) (src + i)) ||
strchr(dont_escape, *(const unsigned char *) (src + i)) != NULL) {
dst[j] = src[i];
} else if (j + 3 < dst_len) {
dst[j] = '%';
dst[j + 1] = hex[(*(const unsigned char *) (src + i)) >> 4];
dst[j + 2] = hex[(*(const unsigned char *) (src + i)) & 0xf];
j += 2;
}
}
dst[j] = '\0';
return j;
}
static void mg_escape(const char *src, char *dst, size_t dst_len) {
size_t n = 0;
while (*src != '\0' && n + 5 < dst_len) {
unsigned char ch = *(unsigned char *) src++;
if (ch == '<') {
n += snprintf(dst + n, dst_len - n, "%s", "<");
} else {
dst[n++] = ch;
}
}
dst[n] = '\0';
}
static void mg_print_dir_entry(struct mg_connection *nc, const char *file_name,
cs_stat_t *stp) {
char size[64], mod[64], href[MAX_PATH_SIZE * 3], path[MAX_PATH_SIZE];
int64_t fsize = stp->st_size;
int is_dir = S_ISDIR(stp->st_mode);
const char *slash = is_dir ? "/" : "";
if (is_dir) {
snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
} else {
/*
* We use (double) cast below because MSVC 6 compiler cannot
* convert unsigned __int64 to double.
*/
if (fsize < 1024) {
snprintf(size, sizeof(size), "%d", (int) fsize);
} else if (fsize < 0x100000) {
snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
} else if (fsize < 0x40000000) {
snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
} else {
snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
}
}
strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&stp->st_mtime));
mg_escape(file_name, path, sizeof(path));
mg_url_encode(file_name, strlen(file_name), href, sizeof(href));
mg_printf_http_chunk(nc,
"<tr><td><a href=\"%s%s\">%s%s</a></td>"
"<td>%s</td><td name=%" INT64_FMT ">%s</td></tr>\n",
href, slash, path, slash, mod, is_dir ? -1 : fsize,
size);
}
static void mg_scan_directory(struct mg_connection *nc, const char *dir,
const struct mg_serve_http_opts *opts,
void (*func)(struct mg_connection *, const char *,
cs_stat_t *)) {
char path[MAX_PATH_SIZE];
cs_stat_t st;
struct dirent *dp;
DIR *dirp;
LOG(LL_DEBUG, ("%p [%s]", nc, dir));
if ((dirp = (opendir(dir))) != NULL) {
while ((dp = readdir(dirp)) != NULL) {
/* Do not show current dir and hidden files */
if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
continue;
}
snprintf(path, sizeof(path), "%s/%s", dir, dp->d_name);
if (mg_stat(path, &st) == 0) {
func(nc, (const char *) dp->d_name, &st);
}
}
closedir(dirp);
} else {
LOG(LL_DEBUG, ("%p opendir(%s) -> %d", nc, dir, mg_get_errno()));
}
}
static void mg_send_directory_listing(struct mg_connection *nc, const char *dir,
struct http_message *hm,
struct mg_serve_http_opts *opts) {
static const char *sort_js_code =
"<script>function srt(tb, sc, so, d) {"
"var tr = Array.prototype.slice.call(tb.rows, 0),"
"tr = tr.sort(function (a, b) { var c1 = a.cells[sc], c2 = b.cells[sc],"
"n1 = c1.getAttribute('name'), n2 = c2.getAttribute('name'), "
"t1 = a.cells[2].getAttribute('name'), "
"t2 = b.cells[2].getAttribute('name'); "
"return so * (t1 < 0 && t2 >= 0 ? -1 : t2 < 0 && t1 >= 0 ? 1 : "
"n1 ? parseInt(n2) - parseInt(n1) : "
"c1.textContent.trim().localeCompare(c2.textContent.trim())); });";
static const char *sort_js_code2 =
"for (var i = 0; i < tr.length; i++) tb.appendChild(tr[i]); "
"if (!d) window.location.hash = ('sc=' + sc + '&so=' + so); "
"};"
"window.onload = function() {"
"var tb = document.getElementById('tb');"
"var m = /sc=([012]).so=(1|-1)/.exec(window.location.hash) || [0, 2, 1];"
"var sc = m[1], so = m[2]; document.onclick = function(ev) { "
"var c = ev.target.rel; if (c) {if (c == sc) so *= -1; srt(tb, c, so); "
"sc = c; ev.preventDefault();}};"
"srt(tb, sc, so, true);"
"}"
"</script>";
mg_send_response_line(nc, 200, opts->extra_headers);
mg_printf(nc, "%s: %s\r\n%s: %s\r\n\r\n", "Transfer-Encoding", "chunked",
"Content-Type", "text/html; charset=utf-8");
mg_printf_http_chunk(
nc,
"<html><head><title>Index of %.*s</title>%s%s"
"<style>th,td {text-align: left; padding-right: 1em; "
"font-family: monospace; }</style></head>\n"
"<body><h1>Index of %.*s</h1>\n<table cellpadding=0><thead>"
"<tr><th><a href=# rel=0>Name</a></th><th>"
"<a href=# rel=1>Modified</a</th>"
"<th><a href=# rel=2>Size</a></th></tr>"
"<tr><td colspan=3><hr></td></tr>\n"
"</thead>\n"
"<tbody id=tb>",
(int) hm->uri.len, hm->uri.p, sort_js_code, sort_js_code2,
(int) hm->uri.len, hm->uri.p);
mg_scan_directory(nc, dir, opts, mg_print_dir_entry);
mg_printf_http_chunk(nc,
"</tbody><tr><td colspan=3><hr></td></tr>\n"
"</table>\n"
"<address>%s</address>\n"
"</body></html>",
mg_version_header);
mg_send_http_chunk(nc, "", 0);
/* TODO(rojer): Remove when cesanta/dev/issues/197 is fixed. */
nc->flags |= MG_F_SEND_AND_CLOSE;
}
#endif /* MG_ENABLE_DIRECTORY_LISTING */
/*
* Given a directory path, find one of the files specified in the
* comma-separated list of index files `list`.
* First found index file wins. If an index file is found, then gets
* appended to the `path`, stat-ed, and result of `stat()` passed to `stp`.
* If index file is not found, then `path` and `stp` remain unchanged.
*/
MG_INTERNAL void mg_find_index_file(const char *path, const char *list,
char **index_file, cs_stat_t *stp) {
struct mg_str vec;
size_t path_len = strlen(path);
int found = 0;
*index_file = NULL;
/* Traverse index files list. For each entry, append it to the given */
/* path and see if the file exists. If it exists, break the loop */
while ((list = mg_next_comma_list_entry(list, &vec, NULL)) != NULL) {
cs_stat_t st;
size_t len = path_len + 1 + vec.len + 1;
*index_file = (char *) MG_REALLOC(*index_file, len);
if (*index_file == NULL) break;
snprintf(*index_file, len, "%s%c%.*s", path, DIRSEP, (int) vec.len, vec.p);
/* Does it exist? Is it a file? */
if (mg_stat(*index_file, &st) == 0 && S_ISREG(st.st_mode)) {
/* Yes it does, break the loop */
*stp = st;
found = 1;
break;
}
}
if (!found) {
MG_FREE(*index_file);
*index_file = NULL;
}
LOG(LL_DEBUG, ("[%s] [%s]", path, (*index_file ? *index_file : "")));
}
#if MG_ENABLE_HTTP_URL_REWRITES
static int mg_http_send_port_based_redirect(
struct mg_connection *c, struct http_message *hm,
const struct mg_serve_http_opts *opts) {
const char *rewrites = opts->url_rewrites;
struct mg_str a, b;
char local_port[20] = {'%'};
mg_conn_addr_to_str(c, local_port + 1, sizeof(local_port) - 1,
MG_SOCK_STRINGIFY_PORT);
while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
if (mg_vcmp(&a, local_port) == 0) {
mg_send_response_line(c, 301, NULL);
mg_printf(c, "Content-Length: 0\r\nLocation: %.*s%.*s\r\n\r\n",
(int) b.len, b.p, (int) (hm->proto.p - hm->uri.p - 1),
hm->uri.p);
return 1;
}
}
return 0;
}
static void mg_reverse_proxy_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct http_message *hm = (struct http_message *) ev_data;
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
if (pd == NULL || pd->reverse_proxy_data.linked_conn == NULL) {
DBG(("%p: upstream closed", nc));
return;
}
switch (ev) {
case MG_EV_CONNECT:
if (*(int *) ev_data != 0) {
mg_http_send_error(pd->reverse_proxy_data.linked_conn, 502, NULL);
}
break;
/* TODO(mkm): handle streaming */
case MG_EV_HTTP_REPLY:
mg_send(pd->reverse_proxy_data.linked_conn, hm->message.p,
hm->message.len);
pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
break;
case MG_EV_CLOSE:
pd->reverse_proxy_data.linked_conn->flags |= MG_F_SEND_AND_CLOSE;
break;
}
#if MG_ENABLE_CALLBACK_USERDATA
(void) user_data;
#endif
}
void mg_http_reverse_proxy(struct mg_connection *nc,
const struct http_message *hm, struct mg_str mount,
struct mg_str upstream) {
struct mg_connection *be;
char burl[256], *purl = burl;
char *addr = NULL;
const char *path = NULL;
int i;
const char *error;
struct mg_connect_opts opts;
memset(&opts, 0, sizeof(opts));
opts.error_string = &error;
mg_asprintf(&purl, sizeof(burl), "%.*s%.*s", (int) upstream.len, upstream.p,
(int) (hm->uri.len - mount.len), hm->uri.p + mount.len);
be = mg_connect_http_base(nc->mgr, MG_CB(mg_reverse_proxy_handler, NULL),
opts, "http://", "https://", purl, &path,
NULL /* user */, NULL /* pass */, &addr);
LOG(LL_DEBUG, ("Proxying %.*s to %s (rule: %.*s)", (int) hm->uri.len,
hm->uri.p, purl, (int) mount.len, mount.p));
if (be == NULL) {
LOG(LL_ERROR, ("Error connecting to %s: %s", purl, error));
mg_http_send_error(nc, 502, NULL);
goto cleanup;
}
/* link connections to each other, they must live and die together */
mg_http_get_proto_data(be)->reverse_proxy_data.linked_conn = nc;
mg_http_get_proto_data(nc)->reverse_proxy_data.linked_conn = be;
/* send request upstream */
mg_printf(be, "%.*s %s HTTP/1.1\r\n", (int) hm->method.len, hm->method.p,
path);
mg_printf(be, "Host: %s\r\n", addr);
for (i = 0; i < MG_MAX_HTTP_HEADERS && hm->header_names[i].len > 0; i++) {
struct mg_str hn = hm->header_names[i];
struct mg_str hv = hm->header_values[i];
/* we rewrite the host header */
if (mg_vcasecmp(&hn, "Host") == 0) continue;
/*
* Don't pass chunked transfer encoding to the client because hm->body is
* already dechunked when we arrive here.
*/
if (mg_vcasecmp(&hn, "Transfer-encoding") == 0 &&
mg_vcasecmp(&hv, "chunked") == 0) {
mg_printf(be, "Content-Length: %" SIZE_T_FMT "\r\n", hm->body.len);
continue;
}
/* We don't support proxying Expect: 100-continue. */
if (mg_vcasecmp(&hn, "Expect") == 0 &&
mg_vcasecmp(&hv, "100-continue") == 0) {
continue;
}
mg_printf(be, "%.*s: %.*s\r\n", (int) hn.len, hn.p, (int) hv.len, hv.p);
}
mg_send(be, "\r\n", 2);
mg_send(be, hm->body.p, hm->body.len);
cleanup:
if (purl != burl) MG_FREE(purl);
}
static int mg_http_handle_forwarding(struct mg_connection *nc,
struct http_message *hm,
const struct mg_serve_http_opts *opts) {
const char *rewrites = opts->url_rewrites;
struct mg_str a, b;
struct mg_str p1 = MG_MK_STR("http://"), p2 = MG_MK_STR("https://");
while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
if (mg_strncmp(a, hm->uri, a.len) == 0) {
if (mg_strncmp(b, p1, p1.len) == 0 || mg_strncmp(b, p2, p2.len) == 0) {
mg_http_reverse_proxy(nc, hm, a, b);
return 1;
}
}
}
return 0;
}
#endif
MG_INTERNAL int mg_uri_to_local_path(struct http_message *hm,
const struct mg_serve_http_opts *opts,
char **local_path,
struct mg_str *remainder) {
int ok = 1;
const char *cp = hm->uri.p, *cp_end = hm->uri.p + hm->uri.len;
struct mg_str root = {NULL, 0};
const char *file_uri_start = cp;
*local_path = NULL;
remainder->p = NULL;
remainder->len = 0;
{ /* 1. Determine which root to use. */
#if MG_ENABLE_HTTP_URL_REWRITES
const char *rewrites = opts->url_rewrites;
#else
const char *rewrites = "";
#endif
struct mg_str *hh = mg_get_http_header(hm, "Host");
struct mg_str a, b;
/* Check rewrites first. */
while ((rewrites = mg_next_comma_list_entry(rewrites, &a, &b)) != NULL) {
if (a.len > 1 && a.p[0] == '@') {
/* Host rewrite. */
if (hh != NULL && hh->len == a.len - 1 &&
mg_ncasecmp(a.p + 1, hh->p, a.len - 1) == 0) {
root = b;
break;
}
} else {
/* Regular rewrite, URI=directory */
int match_len = mg_match_prefix_n(a, hm->uri);
if (match_len > 0) {
file_uri_start = hm->uri.p + match_len;
if (*file_uri_start == '/' || file_uri_start == cp_end) {
/* Match ended at component boundary, ok. */
} else if (*(file_uri_start - 1) == '/') {
/* Pattern ends with '/', backtrack. */
file_uri_start--;
} else {
/* No match: must fall on the component boundary. */
continue;
}
root = b;
break;
}
}
}
/* If no rewrite rules matched, use DAV or regular document root. */
if (root.p == NULL) {
#if MG_ENABLE_HTTP_WEBDAV
if (opts->dav_document_root != NULL && mg_is_dav_request(&hm->method)) {
root.p = opts->dav_document_root;
root.len = strlen(opts->dav_document_root);
} else
#endif
{
root.p = opts->document_root;
root.len = strlen(opts->document_root);
}
}
assert(root.p != NULL && root.len > 0);
}
{ /* 2. Find where in the canonical URI path the local path ends. */
const char *u = file_uri_start + 1;
char *lp = (char *) MG_MALLOC(root.len + hm->uri.len + 1);
char *lp_end = lp + root.len + hm->uri.len + 1;
char *p = lp, *ps;
int exists = 1;
if (lp == NULL) {
ok = 0;
goto out;
}
memcpy(p, root.p, root.len);
p += root.len;
if (*(p - 1) == DIRSEP) p--;
*p = '\0';
ps = p;
/* Chop off URI path components one by one and build local path. */
while (u <= cp_end) {
const char *next = u;
struct mg_str component;
if (exists) {
cs_stat_t st;
exists = (mg_stat(lp, &st) == 0);
if (exists && S_ISREG(st.st_mode)) {
/* We found the terminal, the rest of the URI (if any) is path_info.
*/
if (*(u - 1) == '/') u--;
break;
}
}
if (u >= cp_end) break;
parse_uri_component((const char **) &next, cp_end, '/', &component);
if (component.len > 0) {
int len;
memmove(p + 1, component.p, component.len);
len = mg_url_decode(p + 1, component.len, p + 1, lp_end - p - 1, 0);
if (len <= 0) {
ok = 0;
break;
}
component.p = p + 1;
component.len = len;
if (mg_vcmp(&component, ".") == 0) {
/* Yum. */
} else if (mg_vcmp(&component, "..") == 0) {
while (p > ps && *p != DIRSEP) p--;
*p = '\0';
} else {
size_t i;
#ifdef _WIN32
/* On Windows, make sure it's valid Unicode (no funny stuff). */
wchar_t buf[MG_MAX_PATH * 2];
if (to_wchar(component.p, buf, MG_MAX_PATH) == 0) {
DBG(("[%.*s] smells funny", (int) component.len, component.p));
ok = 0;
break;
}
#endif
*p++ = DIRSEP;
/* No NULs and DIRSEPs in the component (percent-encoded). */
for (i = 0; i < component.len; i++, p++) {
if (*p == '\0' || *p == DIRSEP
#ifdef _WIN32
/* On Windows, "/" is also accepted, so check for that too. */
||
*p == '/'
#endif
) {
ok = 0;
break;
}
}
}
}
u = next;
}
if (ok) {
*local_path = lp;
if (u > cp_end) u = cp_end;
remainder->p = u;
remainder->len = cp_end - u;
} else {
MG_FREE(lp);
}
}
out:
LOG(LL_DEBUG,
("'%.*s' -> '%s' + '%.*s'", (int) hm->uri.len, hm->uri.p,
*local_path ? *local_path : "", (int) remainder->len, remainder->p));
return ok;
}
static int mg_get_month_index(const char *s) {
static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
size_t i;
for (i = 0; i < ARRAY_SIZE(month_names); i++)
if (!strcmp(s, month_names[i])) return (int) i;
return -1;
}
static int mg_num_leap_years(int year) {
return year / 4 - year / 100 + year / 400;
}
/* Parse UTC date-time string, and return the corresponding time_t value. */
MG_INTERNAL time_t mg_parse_date_string(const char *datetime) {
static const unsigned short days_before_month[] = {
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
char month_str[32];
int second, minute, hour, day, month, year, leap_days, days;
time_t result = (time_t) 0;
if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour,
&minute, &second) == 6) ||
(sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour,
&minute, &second) == 6) ||
(sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year,
&hour, &minute, &second) == 6) ||
(sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour,
&minute, &second) == 6)) &&
year > 1970 && (month = mg_get_month_index(month_str)) != -1) {
leap_days = mg_num_leap_years(year) - mg_num_leap_years(1970);
year -= 1970;
days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
}
return result;
}
MG_INTERNAL int mg_is_not_modified(struct http_message *hm, cs_stat_t *st) {
struct mg_str *hdr;
if ((hdr = mg_get_http_header(hm, "If-None-Match")) != NULL) {
char etag[64];
mg_http_construct_etag(etag, sizeof(etag), st);
return mg_vcasecmp(hdr, etag) == 0;
} else if ((hdr = mg_get_http_header(hm, "If-Modified-Since")) != NULL) {
return st->st_mtime <= mg_parse_date_string(hdr->p);
} else {
return 0;
}
}
static void mg_http_send_digest_auth_request(struct mg_connection *c,
const char *domain) {
mg_printf(c,
"HTTP/1.1 401 Unauthorized\r\n"
"WWW-Authenticate: Digest qop=\"auth\", "
"realm=\"%s\", nonce=\"%lu\"\r\n"
"Content-Length: 0\r\n\r\n",
domain, (unsigned long) mg_time());
}
static void mg_http_send_options(struct mg_connection *nc) {
mg_printf(nc, "%s",
"HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, CONNECT, OPTIONS"
#if MG_ENABLE_HTTP_WEBDAV
", MKCOL, PUT, DELETE, PROPFIND, MOVE\r\nDAV: 1,2"
#endif
"\r\n\r\n");
nc->flags |= MG_F_SEND_AND_CLOSE;
}
static int mg_is_creation_request(const struct http_message *hm) {
return mg_vcmp(&hm->method, "MKCOL") == 0 || mg_vcmp(&hm->method, "PUT") == 0;
}
MG_INTERNAL void mg_send_http_file(struct mg_connection *nc, char *path,
const struct mg_str *path_info,
struct http_message *hm,
struct mg_serve_http_opts *opts) {
int exists, is_directory, is_cgi;
#if MG_ENABLE_HTTP_WEBDAV
int is_dav = mg_is_dav_request(&hm->method);
#else
int is_dav = 0;
#endif
char *index_file = NULL;
cs_stat_t st;
exists = (mg_stat(path, &st) == 0);
is_directory = exists && S_ISDIR(st.st_mode);
if (is_directory)
mg_find_index_file(path, opts->index_files, &index_file, &st);
is_cgi =
(mg_match_prefix(opts->cgi_file_pattern, strlen(opts->cgi_file_pattern),
index_file ? index_file : path) > 0);
LOG(LL_DEBUG,
("%p %.*s [%s] exists=%d is_dir=%d is_dav=%d is_cgi=%d index=%s", nc,
(int) hm->method.len, hm->method.p, path, exists, is_directory, is_dav,
is_cgi, index_file ? index_file : ""));
if (is_directory && hm->uri.p[hm->uri.len - 1] != '/' && !is_dav) {
mg_printf(nc,
"HTTP/1.1 301 Moved\r\nLocation: %.*s/\r\n"
"Content-Length: 0\r\n\r\n",
(int) hm->uri.len, hm->uri.p);
MG_FREE(index_file);
return;
}
/* If we have path_info, the only way to handle it is CGI. */
if (path_info->len > 0 && !is_cgi) {
mg_http_send_error(nc, 501, NULL);
MG_FREE(index_file);
return;
}
if (is_dav && opts->dav_document_root == NULL) {
mg_http_send_error(nc, 501, NULL);
} else if (!mg_is_authorized(hm, path, is_directory, opts->auth_domain,
opts->global_auth_file, 1) ||
!mg_is_authorized(hm, path, is_directory, opts->auth_domain,
opts->per_directory_auth_file, 0)) {
mg_http_send_digest_auth_request(nc, opts->auth_domain);
} else if (is_cgi) {
#if MG_ENABLE_HTTP_CGI
mg_handle_cgi(nc, index_file ? index_file : path, path_info, hm, opts);
#else
mg_http_send_error(nc, 501, NULL);
#endif /* MG_ENABLE_HTTP_CGI */
} else if ((!exists ||
mg_is_file_hidden(path, opts, 0 /* specials are ok */)) &&
!mg_is_creation_request(hm)) {
mg_http_send_error(nc, 404, NULL);
#if MG_ENABLE_HTTP_WEBDAV
} else if (!mg_vcmp(&hm->method, "PROPFIND")) {
mg_handle_propfind(nc, path, &st, hm, opts);
#if !MG_DISABLE_DAV_AUTH
} else if (is_dav &&
(opts->dav_auth_file == NULL ||
(strcmp(opts->dav_auth_file, "-") != 0 &&
!mg_is_authorized(hm, path, is_directory, opts->auth_domain,
opts->dav_auth_file, 1)))) {
mg_http_send_digest_auth_request(nc, opts->auth_domain);
#endif
} else if (!mg_vcmp(&hm->method, "MKCOL")) {
mg_handle_mkcol(nc, path, hm);
} else if (!mg_vcmp(&hm->method, "DELETE")) {
mg_handle_delete(nc, opts, path);
} else if (!mg_vcmp(&hm->method, "PUT")) {
mg_handle_put(nc, path, hm);
} else if (!mg_vcmp(&hm->method, "MOVE")) {
mg_handle_move(nc, opts, path, hm);
#if MG_ENABLE_FAKE_DAVLOCK
} else if (!mg_vcmp(&hm->method, "LOCK")) {
mg_handle_lock(nc, path);
#endif
#endif /* MG_ENABLE_HTTP_WEBDAV */
} else if (!mg_vcmp(&hm->method, "OPTIONS")) {
mg_http_send_options(nc);
} else if (is_directory && index_file == NULL) {
#if MG_ENABLE_DIRECTORY_LISTING
if (strcmp(opts->enable_directory_listing, "yes") == 0) {
mg_send_directory_listing(nc, path, hm, opts);
} else {
mg_http_send_error(nc, 403, NULL);
}
#else
mg_http_send_error(nc, 501, NULL);
#endif
} else if (mg_is_not_modified(hm, &st)) {
mg_http_send_error(nc, 304, "Not Modified");
} else {
mg_http_serve_file2(nc, index_file ? index_file : path, hm, opts);
}
MG_FREE(index_file);
}
void mg_serve_http(struct mg_connection *nc, struct http_message *hm,
struct mg_serve_http_opts opts) {
char *path = NULL;
struct mg_str *hdr, path_info;
uint32_t remote_ip = ntohl(*(uint32_t *) &nc->sa.sin.sin_addr);
if (mg_check_ip_acl(opts.ip_acl, remote_ip) != 1) {
/* Not allowed to connect */
mg_http_send_error(nc, 403, NULL);
nc->flags |= MG_F_SEND_AND_CLOSE;
return;
}
#if MG_ENABLE_HTTP_URL_REWRITES
if (mg_http_handle_forwarding(nc, hm, &opts)) {
return;
}
if (mg_http_send_port_based_redirect(nc, hm, &opts)) {
return;
}
#endif
if (opts.document_root == NULL) {
opts.document_root = ".";
}
if (opts.per_directory_auth_file == NULL) {
opts.per_directory_auth_file = ".htpasswd";
}
if (opts.enable_directory_listing == NULL) {
opts.enable_directory_listing = "yes";
}
if (opts.cgi_file_pattern == NULL) {
opts.cgi_file_pattern = "**.cgi$|**.php$";
}
if (opts.ssi_pattern == NULL) {
opts.ssi_pattern = "**.shtml$|**.shtm$";
}
if (opts.index_files == NULL) {
opts.index_files = "index.html,index.htm,index.shtml,index.cgi,index.php";
}
/* Normalize path - resolve "." and ".." (in-place). */
if (!mg_normalize_uri_path(&hm->uri, &hm->uri)) {
mg_http_send_error(nc, 400, NULL);
return;
}
if (mg_uri_to_local_path(hm, &opts, &path, &path_info) == 0) {
mg_http_send_error(nc, 404, NULL);
return;
}
mg_send_http_file(nc, path, &path_info, hm, &opts);
MG_FREE(path);
path = NULL;
/* Close connection for non-keep-alive requests */
if (mg_vcmp(&hm->proto, "HTTP/1.1") != 0 ||
((hdr = mg_get_http_header(hm, "Connection")) != NULL &&
mg_vcmp(hdr, "keep-alive") != 0)) {
#if 0
nc->flags |= MG_F_SEND_AND_CLOSE;
#endif
}
}
#if MG_ENABLE_HTTP_STREAMING_MULTIPART
void mg_file_upload_handler(struct mg_connection *nc, int ev, void *ev_data,
mg_fu_fname_fn local_name_fn
MG_UD_ARG(void *user_data)) {
switch (ev) {
case MG_EV_HTTP_PART_BEGIN: {
struct mg_http_multipart_part *mp =
(struct mg_http_multipart_part *) ev_data;
struct file_upload_state *fus =
(struct file_upload_state *) MG_CALLOC(1, sizeof(*fus));
struct mg_str lfn = local_name_fn(nc, mg_mk_str(mp->file_name));
mp->user_data = NULL;
if (lfn.p == NULL || lfn.len == 0) {
LOG(LL_ERROR, ("%p Not allowed to upload %s", nc, mp->file_name));
mg_printf(nc,
"HTTP/1.1 403 Not Allowed\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"
"Not allowed to upload %s\r\n",
mp->file_name);
nc->flags |= MG_F_SEND_AND_CLOSE;
return;
}
fus->lfn = (char *) MG_MALLOC(lfn.len + 1);
memcpy(fus->lfn, lfn.p, lfn.len);
fus->lfn[lfn.len] = '\0';
if (lfn.p != mp->file_name) MG_FREE((char *) lfn.p);
LOG(LL_DEBUG,
("%p Receiving file %s -> %s", nc, mp->file_name, fus->lfn));
fus->fp = mg_fopen(fus->lfn, "w");
if (fus->fp == NULL) {
mg_printf(nc,
"HTTP/1.1 500 Internal Server Error\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n");
LOG(LL_ERROR, ("Failed to open %s: %d\n", fus->lfn, mg_get_errno()));
mg_printf(nc, "Failed to open %s: %d\n", fus->lfn, mg_get_errno());
/* Do not close the connection just yet, discard remainder of the data.
* This is because at the time of writing some browsers (Chrome) fail to
* render response before all the data is sent. */
}
mp->user_data = (void *) fus;
break;
}
case MG_EV_HTTP_PART_DATA: {
struct mg_http_multipart_part *mp =
(struct mg_http_multipart_part *) ev_data;
struct file_upload_state *fus =
(struct file_upload_state *) mp->user_data;
if (fus == NULL || fus->fp == NULL) break;
if (mg_fwrite(mp->data.p, 1, mp->data.len, fus->fp) != mp->data.len) {
LOG(LL_ERROR, ("Failed to write to %s: %d, wrote %d", fus->lfn,
mg_get_errno(), (int) fus->num_recd));
if (mg_get_errno() == ENOSPC
#ifdef SPIFFS_ERR_FULL
|| mg_get_errno() == SPIFFS_ERR_FULL
#endif
) {
mg_printf(nc,
"HTTP/1.1 413 Payload Too Large\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n");
mg_printf(nc, "Failed to write to %s: no space left; wrote %d\r\n",
fus->lfn, (int) fus->num_recd);
} else {
mg_printf(nc,
"HTTP/1.1 500 Internal Server Error\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n");
mg_printf(nc, "Failed to write to %s: %d, wrote %d", mp->file_name,
mg_get_errno(), (int) fus->num_recd);
}
fclose(fus->fp);
remove(fus->lfn);
fus->fp = NULL;
/* Do not close the connection just yet, discard remainder of the data.
* This is because at the time of writing some browsers (Chrome) fail to
* render response before all the data is sent. */
return;
}
fus->num_recd += mp->data.len;
LOG(LL_DEBUG, ("%p rec'd %d bytes, %d total", nc, (int) mp->data.len,
(int) fus->num_recd));
break;
}
case MG_EV_HTTP_PART_END: {
struct mg_http_multipart_part *mp =
(struct mg_http_multipart_part *) ev_data;
struct file_upload_state *fus =
(struct file_upload_state *) mp->user_data;
if (fus == NULL) break;
if (mp->status >= 0 && fus->fp != NULL) {
LOG(LL_DEBUG, ("%p Uploaded %s (%s), %d bytes", nc, mp->file_name,
fus->lfn, (int) fus->num_recd));
mg_printf(nc,
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n\r\n"
"Ok, %s - %d bytes.\r\n",
mp->file_name, (int) fus->num_recd);
} else {
LOG(LL_ERROR, ("Failed to store %s (%s)", mp->file_name, fus->lfn));
/*
* mp->status < 0 means connection was terminated, so no reason to send
* HTTP reply
*/
}
if (fus->fp != NULL) fclose(fus->fp);
MG_FREE(fus->lfn);
MG_FREE(fus);
mp->user_data = NULL;
nc->flags |= MG_F_SEND_AND_CLOSE;
break;
}
}
#if MG_ENABLE_CALLBACK_USERDATA
(void) user_data;
#endif
}
#endif /* MG_ENABLE_HTTP_STREAMING_MULTIPART */
#endif /* MG_ENABLE_FILESYSTEM */
/* returns 0 on success, -1 on error */
MG_INTERNAL int mg_http_common_url_parse(const char *url, const char *schema,
const char *schema_tls, int *use_ssl,
char **user, char **pass, char **addr,
int *port_i, const char **path) {
int addr_len = 0;
int auth_sep_pos = -1;
int user_sep_pos = -1;
int port_pos = -1;
(void) user;
(void) pass;
if (strncmp(url, schema, strlen(schema)) == 0) {
url += strlen(schema);
} else if (strncmp(url, schema_tls, strlen(schema_tls)) == 0) {
url += strlen(schema_tls);
*use_ssl = 1;
#if !MG_ENABLE_SSL
return -1; /* SSL is not enabled, cannot do HTTPS URLs */
#endif
}
while (*url != '\0') {
*addr = (char *) MG_REALLOC(*addr, addr_len + 6 /* space for port too. */);
if (*addr == NULL) {
DBG(("OOM"));
return -1;
}
if (*url == '/') {
break;
}
if (*url == '@') {
auth_sep_pos = addr_len;
user_sep_pos = port_pos;
port_pos = -1;
}
if (*url == ':') port_pos = addr_len;
(*addr)[addr_len++] = *url;
(*addr)[addr_len] = '\0';
url++;
}
if (addr_len == 0) goto cleanup;
if (port_pos < 0) {
*port_i = addr_len;
addr_len += sprintf(*addr + addr_len, ":%d", *use_ssl ? 443 : 80);
} else {
*port_i = -1;
}
if (*path == NULL) *path = url;
if (**path == '\0') *path = "/";
if (user != NULL && pass != NULL) {
if (auth_sep_pos == -1) {
*user = NULL;
*pass = NULL;
} else {
/* user is from 0 to user_sep_pos */
*user = (char *) MG_MALLOC(user_sep_pos + 1);
memcpy(*user, *addr, user_sep_pos);
(*user)[user_sep_pos] = '\0';
/* pass is from user_sep_pos + 1 to auth_sep_pos */
*pass = (char *) MG_MALLOC(auth_sep_pos - user_sep_pos - 1 + 1);
memcpy(*pass, *addr + user_sep_pos + 1, auth_sep_pos - user_sep_pos - 1);
(*pass)[auth_sep_pos - user_sep_pos - 1] = '\0';
/* move address proper to the front */
memmove(*addr, *addr + auth_sep_pos + 1, addr_len - auth_sep_pos);
}
}
DBG(("%s %s", *addr, *path));
return 0;
cleanup:
MG_FREE(*addr);
return -1;
}
struct mg_connection *mg_connect_http_base(
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
struct mg_connect_opts opts, const char *schema, const char *schema_ssl,
const char *url, const char **path, char **user, char **pass, char **addr) {
struct mg_connection *nc = NULL;
int port_i = -1;
int use_ssl = 0;
if (mg_http_common_url_parse(url, schema, schema_ssl, &use_ssl, user, pass,
addr, &port_i, path) < 0) {
MG_SET_PTRPTR(opts.error_string, "cannot parse url");
return NULL;
}
LOG(LL_DEBUG, ("%s use_ssl? %d", url, use_ssl));
if (use_ssl) {
#if MG_ENABLE_SSL
/*
* Schema requires SSL, but no SSL parameters were provided in opts.
* In order to maintain backward compatibility, use a faux-SSL with no
* verification.
*/
if (opts.ssl_ca_cert == NULL) {
opts.ssl_ca_cert = "*";
}
#else
MG_SET_PTRPTR(opts.error_string, "ssl is disabled");
if (user != NULL) MG_FREE(*user);
if (pass != NULL) MG_FREE(*pass);
MG_FREE(*addr);
return NULL;
#endif
}
if ((nc = mg_connect_opt(mgr, *addr, MG_CB(ev_handler, user_data), opts)) !=
NULL) {
mg_set_protocol_http_websocket(nc);
/* If the port was addred by us, restore the original host. */
if (port_i >= 0) (*addr)[port_i] = '\0';
}
return nc;
}
struct mg_connection *mg_connect_http_opt(
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
struct mg_connect_opts opts, const char *url, const char *extra_headers,
const char *post_data) {
char *user = NULL, *pass = NULL, *addr = NULL;
const char *path = NULL;
struct mbuf auth;
struct mg_connection *nc =
mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "http://",
"https://", url, &path, &user, &pass, &addr);
if (nc == NULL) {
return NULL;
}
mbuf_init(&auth, 0);
if (user != NULL) {
mg_basic_auth_header(user, pass, &auth);
}
if (post_data == NULL) post_data = "";
if (extra_headers == NULL) extra_headers = "";
mg_printf(nc, "%s %s HTTP/1.1\r\nHost: %s\r\nContent-Length: %" SIZE_T_FMT
"\r\n%.*s%s\r\n%s",
post_data[0] == '\0' ? "GET" : "POST", path, addr,
strlen(post_data), (int) auth.len,
(auth.buf == NULL ? "" : auth.buf), extra_headers, post_data);
mbuf_free(&auth);
MG_FREE(user);
MG_FREE(pass);
MG_FREE(addr);
return nc;
}
struct mg_connection *mg_connect_http(
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
const char *url, const char *extra_headers, const char *post_data) {
struct mg_connect_opts opts;
memset(&opts, 0, sizeof(opts));
return mg_connect_http_opt(mgr, MG_CB(ev_handler, user_data), opts, url,
extra_headers, post_data);
}
size_t mg_parse_multipart(const char *buf, size_t buf_len, char *var_name,
size_t var_name_len, char *file_name,
size_t file_name_len, const char **data,
size_t *data_len) {
static const char cd[] = "Content-Disposition: ";
size_t hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
if (buf == NULL || buf_len <= 0) return 0;
if ((hl = mg_http_get_request_len(buf, buf_len)) <= 0) return 0;
if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
/* Get boundary length */
bl = mg_get_line_len(buf, buf_len);
/* Loop through headers, fetch variable name and file name */
var_name[0] = file_name[0] = '\0';
for (n = bl; (ll = mg_get_line_len(buf + n, hl - n)) > 0; n += ll) {
if (mg_ncasecmp(cd, buf + n, cdl) == 0) {
struct mg_str header;
header.p = buf + n + cdl;
header.len = ll - (cdl + 2);
mg_http_parse_header(&header, "name", var_name, var_name_len);
mg_http_parse_header(&header, "filename", file_name, file_name_len);
}
}
/* Scan through the body, search for terminating boundary */
for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
if (buf[pos] == '-' && !strncmp(buf, &buf[pos], bl - 2)) {
if (data_len != NULL) *data_len = (pos - 2) - hl;
if (data != NULL) *data = buf + hl;
return pos;
}
}
return 0;
}
void mg_register_http_endpoint(struct mg_connection *nc, const char *uri_path,
MG_CB(mg_event_handler_t handler,
void *user_data)) {
struct mg_http_proto_data *pd = NULL;
struct mg_http_endpoint *new_ep = NULL;
if (nc == NULL) return;
new_ep = (struct mg_http_endpoint *) MG_CALLOC(1, sizeof(*new_ep));
if (new_ep == NULL) return;
pd = mg_http_get_proto_data(nc);
new_ep->name = strdup(uri_path);
new_ep->name_len = strlen(new_ep->name);
new_ep->handler = handler;
#if MG_ENABLE_CALLBACK_USERDATA
new_ep->user_data = user_data;
#endif
new_ep->next = pd->endpoints;
pd->endpoints = new_ep;
}
#endif /* MG_ENABLE_HTTP */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/http_cgi.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI
#ifndef MG_MAX_CGI_ENVIR_VARS
#define MG_MAX_CGI_ENVIR_VARS 64
#endif
#ifndef MG_ENV_EXPORT_TO_CGI
#define MG_ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
#endif
/*
* This structure helps to create an environment for the spawned CGI program.
* Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
* last element must be NULL.
* However, on Windows there is a requirement that all these VARIABLE=VALUE\0
* strings must reside in a contiguous buffer. The end of the buffer is
* marked by two '\0' characters.
* We satisfy both worlds: we create an envp array (which is vars), all
* entries are actually pointers inside buf.
*/
struct mg_cgi_env_block {
struct mg_connection *nc;
char buf[MG_CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
const char *vars[MG_MAX_CGI_ENVIR_VARS]; /* char *envp[] */
int len; /* Space taken */
int nvars; /* Number of variables in envp[] */
};
#ifdef _WIN32
struct mg_threadparam {
sock_t s;
HANDLE hPipe;
};
static int mg_wait_until_ready(sock_t sock, int for_read) {
fd_set set;
FD_ZERO(&set);
FD_SET(sock, &set);
return select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0) == 1;
}
static void *mg_push_to_stdin(void *arg) {
struct mg_threadparam *tp = (struct mg_threadparam *) arg;
int n, sent, stop = 0;
DWORD k;
char buf[BUFSIZ];
while (!stop && mg_wait_until_ready(tp->s, 1) &&
(n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
for (sent = 0; !stop && sent < n; sent += k) {
if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
}
}
DBG(("%s", "FORWARED EVERYTHING TO CGI"));
CloseHandle(tp->hPipe);
MG_FREE(tp);
return NULL;
}
static void *mg_pull_from_stdout(void *arg) {
struct mg_threadparam *tp = (struct mg_threadparam *) arg;
int k = 0, stop = 0;
DWORD n, sent;
char buf[BUFSIZ];
while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
for (sent = 0; !stop && sent < n; sent += k) {
if (mg_wait_until_ready(tp->s, 0) &&
(k = send(tp->s, buf + sent, n - sent, 0)) <= 0)
stop = 1;
}
}
DBG(("%s", "EOF FROM CGI"));
CloseHandle(tp->hPipe);
shutdown(tp->s, 2); // Without this, IO thread may get truncated data
closesocket(tp->s);
MG_FREE(tp);
return NULL;
}
static void mg_spawn_stdio_thread(sock_t sock, HANDLE hPipe,
void *(*func)(void *)) {
struct mg_threadparam *tp = (struct mg_threadparam *) MG_MALLOC(sizeof(*tp));
if (tp != NULL) {
tp->s = sock;
tp->hPipe = hPipe;
mg_start_thread(func, tp);
}
}
static void mg_abs_path(const char *utf8_path, char *abs_path, size_t len) {
wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
}
static int mg_start_process(const char *interp, const char *cmd,
const char *env, const char *envp[],
const char *dir, sock_t sock) {
STARTUPINFOW si;
PROCESS_INFORMATION pi;
HANDLE a[2], b[2], me = GetCurrentProcess();
wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
char buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
buf4[MAX_PATH_SIZE], cmdline[MAX_PATH_SIZE];
DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
FILE *fp;
memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
CreatePipe(&a[0], &a[1], NULL, 0);
CreatePipe(&b[0], &b[1], NULL, 0);
DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
if (interp == NULL && (fp = mg_fopen(cmd, "r")) != NULL) {
buf[0] = buf[1] = '\0';
fgets(buf, sizeof(buf), fp);
buf[sizeof(buf) - 1] = '\0';
if (buf[0] == '#' && buf[1] == '!') {
interp = buf + 2;
/* Trim leading spaces: https://github.com/cesanta/mongoose/issues/489 */
while (*interp != '\0' && isspace(*(unsigned char *) interp)) {
interp++;
}
}
fclose(fp);
}
snprintf(buf, sizeof(buf), "%s/%s", dir, cmd);
mg_abs_path(buf, buf2, ARRAY_SIZE(buf2));
mg_abs_path(dir, buf5, ARRAY_SIZE(buf5));
to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
if (interp != NULL) {
mg_abs_path(interp, buf4, ARRAY_SIZE(buf4));
snprintf(cmdline, sizeof(cmdline), "%s \"%s\"", buf4, buf2);
} else {
snprintf(cmdline, sizeof(cmdline), "\"%s\"", buf2);
}
to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
(void *) env, full_dir, &si, &pi) != 0) {
mg_spawn_stdio_thread(sock, a[1], mg_push_to_stdin);
mg_spawn_stdio_thread(sock, b[0], mg_pull_from_stdout);
CloseHandle(si.hStdOutput);
CloseHandle(si.hStdInput);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
} else {
CloseHandle(a[1]);
CloseHandle(b[0]);
closesocket(sock);
}
DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
/* Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE */
(void) envp;
return (pi.hProcess != NULL);
}
#else
static int mg_start_process(const char *interp, const char *cmd,
const char *env, const char *envp[],
const char *dir, sock_t sock) {
char buf[500];
pid_t pid = fork();
(void) env;
if (pid == 0) {
/*
* In Linux `chdir` declared with `warn_unused_result` attribute
* To shutup compiler we have yo use result in some way
*/
int tmp = chdir(dir);
(void) tmp;
(void) dup2(sock, 0);
(void) dup2(sock, 1);
closesocket(sock);
/*
* After exec, all signal handlers are restored to their default values,
* with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
* implementation, SIGCHLD's handler will leave unchanged after exec
* if it was set to be ignored. Restore it to default action.
*/
signal(SIGCHLD, SIG_DFL);
if (interp == NULL) {
execle(cmd, cmd, (char *) 0, envp); /* (char *) 0 to squash warning */
} else {
execle(interp, interp, cmd, (char *) 0, envp);
}
snprintf(buf, sizeof(buf),
"Status: 500\r\n\r\n"
"500 Server Error: %s%s%s: %s",
interp == NULL ? "" : interp, interp == NULL ? "" : " ", cmd,
strerror(errno));
send(1, buf, strlen(buf), 0);
_exit(EXIT_FAILURE); /* exec call failed */
}
return (pid != 0);
}
#endif /* _WIN32 */
/*
* Append VARIABLE=VALUE\0 string to the buffer, and add a respective
* pointer into the vars array.
*/
static char *mg_addenv(struct mg_cgi_env_block *block, const char *fmt, ...) {
int n, space;
char *added = block->buf + block->len;
va_list ap;
/* Calculate how much space is left in the buffer */
space = sizeof(block->buf) - (block->len + 2);
if (space > 0) {
/* Copy VARIABLE=VALUE\0 string into the free space */
va_start(ap, fmt);
n = vsnprintf(added, (size_t) space, fmt, ap);
va_end(ap);
/* Make sure we do not overflow buffer and the envp array */
if (n > 0 && n + 1 < space &&
block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
/* Append a pointer to the added string into the envp array */
block->vars[block->nvars++] = added;
/* Bump up used length counter. Include \0 terminator */
block->len += n + 1;
}
}
return added;
}
static void mg_addenv2(struct mg_cgi_env_block *blk, const char *name) {
const char *s;
if ((s = getenv(name)) != NULL) mg_addenv(blk, "%s=%s", name, s);
}
static void mg_prepare_cgi_environment(struct mg_connection *nc,
const char *prog,
const struct mg_str *path_info,
const struct http_message *hm,
const struct mg_serve_http_opts *opts,
struct mg_cgi_env_block *blk) {
const char *s;
struct mg_str *h;
char *p;
size_t i;
char buf[100];
blk->len = blk->nvars = 0;
blk->nc = nc;
if ((s = getenv("SERVER_NAME")) != NULL) {
mg_addenv(blk, "SERVER_NAME=%s", s);
} else {
mg_sock_to_str(nc->sock, buf, sizeof(buf), 3);
mg_addenv(blk, "SERVER_NAME=%s", buf);
}
mg_addenv(blk, "SERVER_ROOT=%s", opts->document_root);
mg_addenv(blk, "DOCUMENT_ROOT=%s", opts->document_root);
mg_addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MG_VERSION);
/* Prepare the environment block */
mg_addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
mg_addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
mg_addenv(blk, "%s", "REDIRECT_STATUS=200"); /* For PHP */
mg_addenv(blk, "REQUEST_METHOD=%.*s", (int) hm->method.len, hm->method.p);
mg_addenv(blk, "REQUEST_URI=%.*s%s%.*s", (int) hm->uri.len, hm->uri.p,
hm->query_string.len == 0 ? "" : "?", (int) hm->query_string.len,
hm->query_string.p);
mg_conn_addr_to_str(nc, buf, sizeof(buf),
MG_SOCK_STRINGIFY_REMOTE | MG_SOCK_STRINGIFY_IP);
mg_addenv(blk, "REMOTE_ADDR=%s", buf);
mg_conn_addr_to_str(nc, buf, sizeof(buf), MG_SOCK_STRINGIFY_PORT);
mg_addenv(blk, "SERVER_PORT=%s", buf);
s = hm->uri.p + hm->uri.len - path_info->len - 1;
if (*s == '/') {
const char *base_name = strrchr(prog, DIRSEP);
mg_addenv(blk, "SCRIPT_NAME=%.*s/%s", (int) (s - hm->uri.p), hm->uri.p,
(base_name != NULL ? base_name + 1 : prog));
} else {
mg_addenv(blk, "SCRIPT_NAME=%.*s", (int) (s - hm->uri.p + 1), hm->uri.p);
}
mg_addenv(blk, "SCRIPT_FILENAME=%s", prog);
if (path_info != NULL && path_info->len > 0) {
mg_addenv(blk, "PATH_INFO=%.*s", (int) path_info->len, path_info->p);
/* Not really translated... */
mg_addenv(blk, "PATH_TRANSLATED=%.*s", (int) path_info->len, path_info->p);
}
#if MG_ENABLE_SSL
mg_addenv(blk, "HTTPS=%s", (nc->flags & MG_F_SSL ? "on" : "off"));
#else
mg_addenv(blk, "HTTPS=off");
#endif
if ((h = mg_get_http_header((struct http_message *) hm, "Content-Type")) !=
NULL) {
mg_addenv(blk, "CONTENT_TYPE=%.*s", (int) h->len, h->p);
}
if (hm->query_string.len > 0) {
mg_addenv(blk, "QUERY_STRING=%.*s", (int) hm->query_string.len,
hm->query_string.p);
}
if ((h = mg_get_http_header((struct http_message *) hm, "Content-Length")) !=
NULL) {
mg_addenv(blk, "CONTENT_LENGTH=%.*s", (int) h->len, h->p);
}
mg_addenv2(blk, "PATH");
mg_addenv2(blk, "TMP");
mg_addenv2(blk, "TEMP");
mg_addenv2(blk, "TMPDIR");
mg_addenv2(blk, "PERLLIB");
mg_addenv2(blk, MG_ENV_EXPORT_TO_CGI);
#ifdef _WIN32
mg_addenv2(blk, "COMSPEC");
mg_addenv2(blk, "SYSTEMROOT");
mg_addenv2(blk, "SystemDrive");
mg_addenv2(blk, "ProgramFiles");
mg_addenv2(blk, "ProgramFiles(x86)");
mg_addenv2(blk, "CommonProgramFiles(x86)");
#else
mg_addenv2(blk, "LD_LIBRARY_PATH");
#endif /* _WIN32 */
/* Add all headers as HTTP_* variables */
for (i = 0; hm->header_names[i].len > 0; i++) {
p = mg_addenv(blk, "HTTP_%.*s=%.*s", (int) hm->header_names[i].len,
hm->header_names[i].p, (int) hm->header_values[i].len,
hm->header_values[i].p);
/* Convert variable name into uppercase, and change - to _ */
for (; *p != '=' && *p != '\0'; p++) {
if (*p == '-') *p = '_';
*p = (char) toupper(*(unsigned char *) p);
}
}
blk->vars[blk->nvars++] = NULL;
blk->buf[blk->len++] = '\0';
}
static void mg_cgi_ev_handler(struct mg_connection *cgi_nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
#if !MG_ENABLE_CALLBACK_USERDATA
void *user_data = cgi_nc->user_data;
#endif
struct mg_connection *nc = (struct mg_connection *) user_data;
(void) ev_data;
if (nc == NULL) {
cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return;
}
switch (ev) {
case MG_EV_RECV:
/*
* CGI script does not output reply line, like "HTTP/1.1 CODE XXXXX\n"
* It outputs headers, then body. Headers might include "Status"
* header, which changes CODE, and it might include "Location" header
* which changes CODE to 302.
*
* Therefore we do not send the output from the CGI script to the user
* until all CGI headers are received.
*
* Here we parse the output from the CGI script, and if all headers has
* been received, send appropriate reply line, and forward all
* received headers to the client.
*/
if (nc->flags & MG_F_USER_1) {
struct mbuf *io = &cgi_nc->recv_mbuf;
int len = mg_http_get_request_len(io->buf, io->len);
if (len == 0) break;
if (len < 0 || io->len > MG_MAX_HTTP_REQUEST_SIZE) {
cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
mg_http_send_error(nc, 500, "Bad headers");
} else {
struct http_message hm;
struct mg_str *h;
mg_http_parse_headers(io->buf, io->buf + io->len, io->len, &hm);
if (mg_get_http_header(&hm, "Location") != NULL) {
mg_printf(nc, "%s", "HTTP/1.1 302 Moved\r\n");
} else if ((h = mg_get_http_header(&hm, "Status")) != NULL) {
mg_printf(nc, "HTTP/1.1 %.*s\r\n", (int) h->len, h->p);
} else {
mg_printf(nc, "%s", "HTTP/1.1 200 OK\r\n");
}
}
nc->flags &= ~MG_F_USER_1;
}
if (!(nc->flags & MG_F_USER_1)) {
mg_forward(cgi_nc, nc);
}
break;
case MG_EV_CLOSE:
mg_http_free_proto_data_cgi(&mg_http_get_proto_data(nc)->cgi);
nc->flags |= MG_F_SEND_AND_CLOSE;
break;
}
}
MG_INTERNAL void mg_handle_cgi(struct mg_connection *nc, const char *prog,
const struct mg_str *path_info,
const struct http_message *hm,
const struct mg_serve_http_opts *opts) {
struct mg_cgi_env_block blk;
char dir[MAX_PATH_SIZE];
const char *p;
sock_t fds[2];
DBG(("%p [%s]", nc, prog));
mg_prepare_cgi_environment(nc, prog, path_info, hm, opts, &blk);
/*
* CGI must be executed in its own directory. 'dir' must point to the
* directory containing executable program, 'p' must point to the
* executable program name relative to 'dir'.
*/
if ((p = strrchr(prog, DIRSEP)) == NULL) {
snprintf(dir, sizeof(dir), "%s", ".");
} else {
snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
prog = p + 1;
}
/*
* Try to create socketpair in a loop until success. mg_socketpair()
* can be interrupted by a signal and fail.
* TODO(lsm): use sigaction to restart interrupted syscall
*/
do {
mg_socketpair(fds, SOCK_STREAM);
} while (fds[0] == INVALID_SOCKET);
if (mg_start_process(opts->cgi_interpreter, prog, blk.buf, blk.vars, dir,
fds[1]) != 0) {
size_t n = nc->recv_mbuf.len - (hm->message.len - hm->body.len);
struct mg_connection *cgi_nc =
mg_add_sock(nc->mgr, fds[0], mg_cgi_ev_handler MG_UD_ARG(nc));
struct mg_http_proto_data *cgi_pd = mg_http_get_proto_data(nc);
cgi_pd->cgi.cgi_nc = cgi_nc;
#if !MG_ENABLE_CALLBACK_USERDATA
cgi_pd->cgi.cgi_nc->user_data = nc;
#endif
nc->flags |= MG_F_USER_1;
/* Push POST data to the CGI */
if (n > 0 && n < nc->recv_mbuf.len) {
mg_send(cgi_pd->cgi.cgi_nc, hm->body.p, n);
}
mbuf_remove(&nc->recv_mbuf, nc->recv_mbuf.len);
} else {
closesocket(fds[0]);
mg_http_send_error(nc, 500, "CGI failure");
}
#ifndef _WIN32
closesocket(fds[1]); /* On Windows, CGI stdio thread closes that socket */
#endif
}
MG_INTERNAL void mg_http_free_proto_data_cgi(struct mg_http_proto_data_cgi *d) {
if (d != NULL) {
if (d->cgi_nc != NULL) d->cgi_nc->flags |= MG_F_CLOSE_IMMEDIATELY;
memset(d, 0, sizeof(struct mg_http_proto_data_cgi));
}
}
#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_CGI */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/http_ssi.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_SSI && MG_ENABLE_FILESYSTEM
static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
const char *path, FILE *fp, int include_level,
const struct mg_serve_http_opts *opts);
static void mg_send_file_data(struct mg_connection *nc, FILE *fp) {
char buf[BUFSIZ];
size_t n;
while ((n = mg_fread(buf, 1, sizeof(buf), fp)) > 0) {
mg_send(nc, buf, n);
}
}
static void mg_do_ssi_include(struct mg_connection *nc, struct http_message *hm,
const char *ssi, char *tag, int include_level,
const struct mg_serve_http_opts *opts) {
char file_name[BUFSIZ], path[MAX_PATH_SIZE], *p;
FILE *fp;
/*
* sscanf() is safe here, since send_ssi_file() also uses buffer
* of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
*/
if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
/* File name is relative to the webserver root */
snprintf(path, sizeof(path), "%s/%s", opts->document_root, file_name);
} else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
/*
* File name is relative to the webserver working directory
* or it is absolute system path
*/
snprintf(path, sizeof(path), "%s", file_name);
} else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
/* File name is relative to the currect document */
snprintf(path, sizeof(path), "%s", ssi);
if ((p = strrchr(path, DIRSEP)) != NULL) {
p[1] = '\0';
}
snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s", file_name);
} else {
mg_printf(nc, "Bad SSI #include: [%s]", tag);
return;
}
if ((fp = mg_fopen(path, "rb")) == NULL) {
mg_printf(nc, "SSI include error: mg_fopen(%s): %s", path,
strerror(mg_get_errno()));
} else {
mg_set_close_on_exec((sock_t) fileno(fp));
if (mg_match_prefix(opts->ssi_pattern, strlen(opts->ssi_pattern), path) >
0) {
mg_send_ssi_file(nc, hm, path, fp, include_level + 1, opts);
} else {
mg_send_file_data(nc, fp);
}
fclose(fp);
}
}
#if MG_ENABLE_HTTP_SSI_EXEC
static void do_ssi_exec(struct mg_connection *nc, char *tag) {
char cmd[BUFSIZ];
FILE *fp;
if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
mg_printf(nc, "Bad SSI #exec: [%s]", tag);
} else if ((fp = popen(cmd, "r")) == NULL) {
mg_printf(nc, "Cannot SSI #exec: [%s]: %s", cmd, strerror(mg_get_errno()));
} else {
mg_send_file_data(nc, fp);
pclose(fp);
}
}
#endif /* MG_ENABLE_HTTP_SSI_EXEC */
/*
* SSI directive has the following format:
* <!--#directive parameter=value parameter=value -->
*/
static void mg_send_ssi_file(struct mg_connection *nc, struct http_message *hm,
const char *path, FILE *fp, int include_level,
const struct mg_serve_http_opts *opts) {
static const struct mg_str btag = MG_MK_STR("<!--#");
static const struct mg_str d_include = MG_MK_STR("include");
static const struct mg_str d_call = MG_MK_STR("call");
#if MG_ENABLE_HTTP_SSI_EXEC
static const struct mg_str d_exec = MG_MK_STR("exec");
#endif
char buf[BUFSIZ], *p = buf + btag.len; /* p points to SSI directive */
int ch, len, in_ssi_tag;
if (include_level > 10) {
mg_printf(nc, "SSI #include level is too deep (%s)", path);
return;
}
in_ssi_tag = len = 0;
while ((ch = fgetc(fp)) != EOF) {
if (in_ssi_tag && ch == '>' && buf[len - 1] == '-' && buf[len - 2] == '-') {
size_t i = len - 2;
in_ssi_tag = 0;
/* Trim closing --> */
buf[i--] = '\0';
while (i > 0 && buf[i] == ' ') {
buf[i--] = '\0';
}
/* Handle known SSI directives */
if (strncmp(p, d_include.p, d_include.len) == 0) {
mg_do_ssi_include(nc, hm, path, p + d_include.len + 1, include_level,
opts);
} else if (strncmp(p, d_call.p, d_call.len) == 0) {
struct mg_ssi_call_ctx cctx;
memset(&cctx, 0, sizeof(cctx));
cctx.req = hm;
cctx.file = mg_mk_str(path);
cctx.arg = mg_mk_str(p + d_call.len + 1);
mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL,
(void *) cctx.arg.p); /* NUL added above */
mg_call(nc, NULL, nc->user_data, MG_EV_SSI_CALL_CTX, &cctx);
#if MG_ENABLE_HTTP_SSI_EXEC
} else if (strncmp(p, d_exec.p, d_exec.len) == 0) {
do_ssi_exec(nc, p + d_exec.len + 1);
#endif
} else {
/* Silently ignore unknown SSI directive. */
}
len = 0;
} else if (ch == '<') {
in_ssi_tag = 1;
if (len > 0) {
mg_send(nc, buf, (size_t) len);
}
len = 0;
buf[len++] = ch & 0xff;
} else if (in_ssi_tag) {
if (len == (int) btag.len && strncmp(buf, btag.p, btag.len) != 0) {
/* Not an SSI tag */
in_ssi_tag = 0;
} else if (len == (int) sizeof(buf) - 2) {
mg_printf(nc, "%s: SSI tag is too large", path);
len = 0;
}
buf[len++] = ch & 0xff;
} else {
buf[len++] = ch & 0xff;
if (len == (int) sizeof(buf)) {
mg_send(nc, buf, (size_t) len);
len = 0;
}
}
}
/* Send the rest of buffered data */
if (len > 0) {
mg_send(nc, buf, (size_t) len);
}
}
MG_INTERNAL void mg_handle_ssi_request(struct mg_connection *nc,
struct http_message *hm,
const char *path,
const struct mg_serve_http_opts *opts) {
FILE *fp;
struct mg_str mime_type;
DBG(("%p %s", nc, path));
if ((fp = mg_fopen(path, "rb")) == NULL) {
mg_http_send_error(nc, 404, NULL);
} else {
mg_set_close_on_exec((sock_t) fileno(fp));
mime_type = mg_get_mime_type(path, "text/plain", opts);
mg_send_response_line(nc, 200, opts->extra_headers);
mg_printf(nc,
"Content-Type: %.*s\r\n"
"Connection: close\r\n\r\n",
(int) mime_type.len, mime_type.p);
mg_send_ssi_file(nc, hm, path, fp, 0, opts);
fclose(fp);
nc->flags |= MG_F_SEND_AND_CLOSE;
}
}
#endif /* MG_ENABLE_HTTP_SSI && MG_ENABLE_HTTP && MG_ENABLE_FILESYSTEM */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/http_webdav.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV
MG_INTERNAL int mg_is_dav_request(const struct mg_str *s) {
static const char *methods[] = {
"PUT",
"DELETE",
"MKCOL",
"PROPFIND",
"MOVE"
#if MG_ENABLE_FAKE_DAVLOCK
,
"LOCK",
"UNLOCK"
#endif
};
size_t i;
for (i = 0; i < ARRAY_SIZE(methods); i++) {
if (mg_vcmp(s, methods[i]) == 0) {
return 1;
}
}
return 0;
}
static int mg_mkdir(const char *path, uint32_t mode) {
#ifndef _WIN32
return mkdir(path, mode);
#else
(void) mode;
return _mkdir(path);
#endif
}
static void mg_print_props(struct mg_connection *nc, const char *name,
cs_stat_t *stp) {
char mtime[64], buf[MAX_PATH_SIZE * 3];
time_t t = stp->st_mtime; /* store in local variable for NDK compile */
mg_gmt_time_string(mtime, sizeof(mtime), &t);
mg_url_encode(name, strlen(name), buf, sizeof(buf));
mg_printf(nc,
"<d:response>"
"<d:href>%s</d:href>"
"<d:propstat>"
"<d:prop>"
"<d:resourcetype>%s</d:resourcetype>"
"<d:getcontentlength>%" INT64_FMT
"</d:getcontentlength>"
"<d:getlastmodified>%s</d:getlastmodified>"
"</d:prop>"
"<d:status>HTTP/1.1 200 OK</d:status>"
"</d:propstat>"
"</d:response>\n",
buf, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
(int64_t) stp->st_size, mtime);
}
MG_INTERNAL void mg_handle_propfind(struct mg_connection *nc, const char *path,
cs_stat_t *stp, struct http_message *hm,
struct mg_serve_http_opts *opts) {
static const char header[] =
"HTTP/1.1 207 Multi-Status\r\n"
"Connection: close\r\n"
"Content-Type: text/xml; charset=utf-8\r\n\r\n"
"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<d:multistatus xmlns:d='DAV:'>\n";
static const char footer[] = "</d:multistatus>\n";
const struct mg_str *depth = mg_get_http_header(hm, "Depth");
/* Print properties for the requested resource itself */
if (S_ISDIR(stp->st_mode) &&
strcmp(opts->enable_directory_listing, "yes") != 0) {
mg_printf(nc, "%s", "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
} else {
char uri[MAX_PATH_SIZE];
mg_send(nc, header, sizeof(header) - 1);
snprintf(uri, sizeof(uri), "%.*s", (int) hm->uri.len, hm->uri.p);
mg_print_props(nc, uri, stp);
if (S_ISDIR(stp->st_mode) && (depth == NULL || mg_vcmp(depth, "0") != 0)) {
mg_scan_directory(nc, path, opts, mg_print_props);
}
mg_send(nc, footer, sizeof(footer) - 1);
nc->flags |= MG_F_SEND_AND_CLOSE;
}
}
#if MG_ENABLE_FAKE_DAVLOCK
/*
* Windows explorer (probably there are another WebDav clients like it)
* requires LOCK support in webdav. W/out this, it still works, but fails
* to save file: shows error message and offers "Save As".
* "Save as" works, but this message is very annoying.
* This is fake lock, which doesn't lock something, just returns LOCK token,
* UNLOCK always answers "OK".
* With this fake LOCK Windows Explorer looks happy and saves file.
* NOTE: that is not DAV LOCK imlementation, it is just a way to shut up
* Windows native DAV client. This is why FAKE LOCK is not enabed by default
*/
MG_INTERNAL void mg_handle_lock(struct mg_connection *nc, const char *path) {
static const char *reply =
"HTTP/1.1 207 Multi-Status\r\n"
"Connection: close\r\n"
"Content-Type: text/xml; charset=utf-8\r\n\r\n"
"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<d:multistatus xmlns:d='DAV:'>\n"
"<D:lockdiscovery>\n"
"<D:activelock>\n"
"<D:locktoken>\n"
"<D:href>\n"
"opaquelocktoken:%s%u"
"</D:href>"
"</D:locktoken>"
"</D:activelock>\n"
"</D:lockdiscovery>"
"</d:multistatus>\n";
mg_printf(nc, reply, path, (unsigned int) mg_time());
nc->flags |= MG_F_SEND_AND_CLOSE;
}
#endif
MG_INTERNAL void mg_handle_mkcol(struct mg_connection *nc, const char *path,
struct http_message *hm) {
int status_code = 500;
if (hm->body.len != (size_t) ~0 && hm->body.len > 0) {
status_code = 415;
} else if (!mg_mkdir(path, 0755)) {
status_code = 201;
} else if (errno == EEXIST) {
status_code = 405;
} else if (errno == EACCES) {
status_code = 403;
} else if (errno == ENOENT) {
status_code = 409;
} else {
status_code = 500;
}
mg_http_send_error(nc, status_code, NULL);
}
static int mg_remove_directory(const struct mg_serve_http_opts *opts,
const char *dir) {
char path[MAX_PATH_SIZE];
struct dirent *dp;
cs_stat_t st;
DIR *dirp;
if ((dirp = opendir(dir)) == NULL) return 0;
while ((dp = readdir(dirp)) != NULL) {
if (mg_is_file_hidden((const char *) dp->d_name, opts, 1)) {
continue;
}
snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
mg_stat(path, &st);
if (S_ISDIR(st.st_mode)) {
mg_remove_directory(opts, path);
} else {
remove(path);
}
}
closedir(dirp);
rmdir(dir);
return 1;
}
MG_INTERNAL void mg_handle_move(struct mg_connection *c,
const struct mg_serve_http_opts *opts,
const char *path, struct http_message *hm) {
const struct mg_str *dest = mg_get_http_header(hm, "Destination");
if (dest == NULL) {
mg_http_send_error(c, 411, NULL);
} else {
const char *p = (char *) memchr(dest->p, '/', dest->len);
if (p != NULL && p[1] == '/' &&
(p = (char *) memchr(p + 2, '/', dest->p + dest->len - p)) != NULL) {
char buf[MAX_PATH_SIZE];
snprintf(buf, sizeof(buf), "%s%.*s", opts->dav_document_root,
(int) (dest->p + dest->len - p), p);
if (rename(path, buf) == 0) {
mg_http_send_error(c, 200, NULL);
} else {
mg_http_send_error(c, 418, NULL);
}
} else {
mg_http_send_error(c, 500, NULL);
}
}
}
MG_INTERNAL void mg_handle_delete(struct mg_connection *nc,
const struct mg_serve_http_opts *opts,
const char *path) {
cs_stat_t st;
if (mg_stat(path, &st) != 0) {
mg_http_send_error(nc, 404, NULL);
} else if (S_ISDIR(st.st_mode)) {
mg_remove_directory(opts, path);
mg_http_send_error(nc, 204, NULL);
} else if (remove(path) == 0) {
mg_http_send_error(nc, 204, NULL);
} else {
mg_http_send_error(nc, 423, NULL);
}
}
/* Return -1 on error, 1 on success. */
static int mg_create_itermediate_directories(const char *path) {
const char *s;
/* Create intermediate directories if they do not exist */
for (s = path + 1; *s != '\0'; s++) {
if (*s == '/') {
char buf[MAX_PATH_SIZE];
cs_stat_t st;
snprintf(buf, sizeof(buf), "%.*s", (int) (s - path), path);
buf[sizeof(buf) - 1] = '\0';
if (mg_stat(buf, &st) != 0 && mg_mkdir(buf, 0755) != 0) {
return -1;
}
}
}
return 1;
}
MG_INTERNAL void mg_handle_put(struct mg_connection *nc, const char *path,
struct http_message *hm) {
struct mg_http_proto_data *pd = mg_http_get_proto_data(nc);
cs_stat_t st;
const struct mg_str *cl_hdr = mg_get_http_header(hm, "Content-Length");
int rc, status_code = mg_stat(path, &st) == 0 ? 200 : 201;
mg_http_free_proto_data_file(&pd->file);
if ((rc = mg_create_itermediate_directories(path)) == 0) {
mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
} else if (rc == -1) {
mg_http_send_error(nc, 500, NULL);
} else if (cl_hdr == NULL) {
mg_http_send_error(nc, 411, NULL);
} else if ((pd->file.fp = mg_fopen(path, "w+b")) == NULL) {
mg_http_send_error(nc, 500, NULL);
} else {
const struct mg_str *range_hdr = mg_get_http_header(hm, "Content-Range");
int64_t r1 = 0, r2 = 0;
pd->file.type = DATA_PUT;
mg_set_close_on_exec((sock_t) fileno(pd->file.fp));
pd->file.cl = to64(cl_hdr->p);
if (range_hdr != NULL &&
mg_http_parse_range_header(range_hdr, &r1, &r2) > 0) {
status_code = 206;
fseeko(pd->file.fp, r1, SEEK_SET);
pd->file.cl = r2 > r1 ? r2 - r1 + 1 : pd->file.cl - r1;
}
mg_printf(nc, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n", status_code);
/* Remove HTTP request from the mbuf, leave only payload */
mbuf_remove(&nc->recv_mbuf, hm->message.len - hm->body.len);
mg_http_transfer_file_data(nc);
}
}
#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBDAV */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/http_websocket.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET
#ifndef MG_WEBSOCKET_PING_INTERVAL_SECONDS
#define MG_WEBSOCKET_PING_INTERVAL_SECONDS 5
#endif
#define MG_WS_NO_HOST_HEADER_MAGIC ((char *) 0x1)
static int mg_is_ws_fragment(unsigned char flags) {
return (flags & 0x80) == 0 || (flags & 0x0f) == 0;
}
static int mg_is_ws_first_fragment(unsigned char flags) {
return (flags & 0x80) == 0 && (flags & 0x0f) != 0;
}
static void mg_handle_incoming_websocket_frame(struct mg_connection *nc,
struct websocket_message *wsm) {
if (wsm->flags & 0x8) {
mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_CONTROL_FRAME, wsm);
} else {
mg_call(nc, nc->handler, nc->user_data, MG_EV_WEBSOCKET_FRAME, wsm);
}
}
static int mg_deliver_websocket_data(struct mg_connection *nc) {
/* Using unsigned char *, cause of integer arithmetic below */
uint64_t i, data_len = 0, frame_len = 0, buf_len = nc->recv_mbuf.len, len,
mask_len = 0, header_len = 0;
unsigned char *p = (unsigned char *) nc->recv_mbuf.buf, *buf = p,
*e = p + buf_len;
unsigned *sizep = (unsigned *) &p[1]; /* Size ptr for defragmented frames */
int ok, reass = buf_len > 0 && mg_is_ws_fragment(p[0]) &&
!(nc->flags & MG_F_WEBSOCKET_NO_DEFRAG);
/* If that's a continuation frame that must be reassembled, handle it */
if (reass && !mg_is_ws_first_fragment(p[0]) &&
buf_len >= 1 + sizeof(*sizep) && buf_len >= 1 + sizeof(*sizep) + *sizep) {
buf += 1 + sizeof(*sizep) + *sizep;
buf_len -= 1 + sizeof(*sizep) + *sizep;
}
if (buf_len >= 2) {
len = buf[1] & 127;
mask_len = buf[1] & 128 ? 4 : 0;
if (len < 126 && buf_len >= mask_len) {
data_len = len;
header_len = 2 + mask_len;
} else if (len == 126 && buf_len >= 4 + mask_len) {
header_len = 4 + mask_len;
data_len = ntohs(*(uint16_t *) &buf[2]);
} else if (buf_len >= 10 + mask_len) {
header_len = 10 + mask_len;
data_len = (((uint64_t) ntohl(*(uint32_t *) &buf[2])) << 32) +
ntohl(*(uint32_t *) &buf[6]);
}
}
frame_len = header_len + data_len;
ok = frame_len > 0 && frame_len <= buf_len;
if (ok) {
struct websocket_message wsm;
wsm.size = (size_t) data_len;
wsm.data = buf + header_len;
wsm.flags = buf[0];
/* Apply mask if necessary */
if (mask_len > 0) {
for (i = 0; i < data_len; i++) {
buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4];
}
}
if (reass) {
/* On first fragmented frame, nullify size */
if (mg_is_ws_first_fragment(wsm.flags)) {
mbuf_resize(&nc->recv_mbuf, nc->recv_mbuf.size + sizeof(*sizep));
p[0] &= ~0x0f; /* Next frames will be treated as continuation */
buf = p + 1 + sizeof(*sizep);
*sizep = 0; /* TODO(lsm): fix. this can stomp over frame data */
}
/* Append this frame to the reassembled buffer */
memmove(buf, wsm.data, e - wsm.data);
(*sizep) += wsm.size;
nc->recv_mbuf.len -= wsm.data - buf;
/* On last fragmented frame - call user handler and remove data */
if (wsm.flags & 0x80) {
wsm.data = p + 1 + sizeof(*sizep);
wsm.size = *sizep;
mg_handle_incoming_websocket_frame(nc, &wsm);
mbuf_remove(&nc->recv_mbuf, 1 + sizeof(*sizep) + *sizep);
}
} else {
/* TODO(lsm): properly handle OOB control frames during defragmentation */
mg_handle_incoming_websocket_frame(nc, &wsm);
mbuf_remove(&nc->recv_mbuf, (size_t) frame_len); /* Cleanup frame */
}
/* If the frame is not reassembled - client closes and close too */
if (!reass && (buf[0] & 0x0f) == WEBSOCKET_OP_CLOSE) {
nc->flags |= MG_F_SEND_AND_CLOSE;
}
}
return ok;
}
struct ws_mask_ctx {
size_t pos; /* zero means unmasked */
uint32_t mask;
};
static uint32_t mg_ws_random_mask(void) {
uint32_t mask;
/*
* The spec requires WS client to generate hard to
* guess mask keys. From RFC6455, Section 5.3:
*
* The unpredictability of the masking key is essential to prevent
* authors of malicious applications from selecting the bytes that appear on
* the wire.
*
* Hence this feature is essential when the actual end user of this API
* is untrusted code that wouldn't have access to a lower level net API
* anyway (e.g. web browsers). Hence this feature is low prio for most
* mongoose use cases and thus can be disabled, e.g. when porting to a platform
* that lacks rand().
*/
#if MG_DISABLE_WS_RANDOM_MASK
mask = 0xefbeadde; /* generated with a random number generator, I swear */
#else
if (sizeof(long) >= 4) {
mask = (uint32_t) rand();
} else if (sizeof(long) == 2) {
mask = (uint32_t) rand() << 16 | (uint32_t) rand();
}
#endif
return mask;
}
static void mg_send_ws_header(struct mg_connection *nc, int op, size_t len,
struct ws_mask_ctx *ctx) {
int header_len;
unsigned char header[10];
header[0] = (op & WEBSOCKET_DONT_FIN ? 0x0 : 0x80) + (op & 0x0f);
if (len < 126) {
header[1] = (unsigned char) len;
header_len = 2;
} else if (len < 65535) {
uint16_t tmp = htons((uint16_t) len);
header[1] = 126;
memcpy(&header[2], &tmp, sizeof(tmp));
header_len = 4;
} else {
uint32_t tmp;
header[1] = 127;
tmp = htonl((uint32_t)((uint64_t) len >> 32));
memcpy(&header[2], &tmp, sizeof(tmp));
tmp = htonl((uint32_t)(len & 0xffffffff));
memcpy(&header[6], &tmp, sizeof(tmp));
header_len = 10;
}
/* client connections enable masking */
if (nc->listener == NULL) {
header[1] |= 1 << 7; /* set masking flag */
mg_send(nc, header, header_len);
ctx->mask = mg_ws_random_mask();
mg_send(nc, &ctx->mask, sizeof(ctx->mask));
ctx->pos = nc->send_mbuf.len;
} else {
mg_send(nc, header, header_len);
ctx->pos = 0;
}
}
static void mg_ws_mask_frame(struct mbuf *mbuf, struct ws_mask_ctx *ctx) {
size_t i;
if (ctx->pos == 0) return;
for (i = 0; i < (mbuf->len - ctx->pos); i++) {
mbuf->buf[ctx->pos + i] ^= ((char *) &ctx->mask)[i % 4];
}
}
void mg_send_websocket_frame(struct mg_connection *nc, int op, const void *data,
size_t len) {
struct ws_mask_ctx ctx;
DBG(("%p %d %d", nc, op, (int) len));
mg_send_ws_header(nc, op, len, &ctx);
mg_send(nc, data, len);
mg_ws_mask_frame(&nc->send_mbuf, &ctx);
if (op == WEBSOCKET_OP_CLOSE) {
nc->flags |= MG_F_SEND_AND_CLOSE;
}
}
void mg_send_websocket_framev(struct mg_connection *nc, int op,
const struct mg_str *strv, int strvcnt) {
struct ws_mask_ctx ctx;
int i;
int len = 0;
for (i = 0; i < strvcnt; i++) {
len += strv[i].len;
}
mg_send_ws_header(nc, op, len, &ctx);
for (i = 0; i < strvcnt; i++) {
mg_send(nc, strv[i].p, strv[i].len);
}
mg_ws_mask_frame(&nc->send_mbuf, &ctx);
if (op == WEBSOCKET_OP_CLOSE) {
nc->flags |= MG_F_SEND_AND_CLOSE;
}
}
void mg_printf_websocket_frame(struct mg_connection *nc, int op,
const char *fmt, ...) {
char mem[MG_VPRINTF_BUFFER_SIZE], *buf = mem;
va_list ap;
int len;
va_start(ap, fmt);
if ((len = mg_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
mg_send_websocket_frame(nc, op, buf, len);
}
va_end(ap);
if (buf != mem && buf != NULL) {
MG_FREE(buf);
}
}
MG_INTERNAL void mg_ws_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
mg_call(nc, nc->handler, nc->user_data, ev, ev_data);
switch (ev) {
case MG_EV_RECV:
do {
} while (mg_deliver_websocket_data(nc));
break;
case MG_EV_POLL:
/* Ping idle websocket connections */
{
time_t now = *(time_t *) ev_data;
if (nc->flags & MG_F_IS_WEBSOCKET &&
now > nc->last_io_time + MG_WEBSOCKET_PING_INTERVAL_SECONDS) {
mg_send_websocket_frame(nc, WEBSOCKET_OP_PING, "", 0);
}
}
break;
default:
break;
}
#if MG_ENABLE_CALLBACK_USERDATA
(void) user_data;
#endif
}
#ifndef MG_EXT_SHA1
static void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
const size_t *msg_lens, uint8_t *digest) {
size_t i;
cs_sha1_ctx sha_ctx;
cs_sha1_init(&sha_ctx);
for (i = 0; i < num_msgs; i++) {
cs_sha1_update(&sha_ctx, msgs[i], msg_lens[i]);
}
cs_sha1_final(digest, &sha_ctx);
}
#else
extern void mg_hash_sha1_v(size_t num_msgs, const uint8_t *msgs[],
const size_t *msg_lens, uint8_t *digest);
#endif
MG_INTERNAL void mg_ws_handshake(struct mg_connection *nc,
const struct mg_str *key) {
static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
const uint8_t *msgs[2] = {(const uint8_t *) key->p, (const uint8_t *) magic};
const size_t msg_lens[2] = {key->len, 36};
unsigned char sha[20];
char b64_sha[30];
mg_hash_sha1_v(2, msgs, msg_lens, sha);
mg_base64_encode(sha, sizeof(sha), b64_sha);
mg_printf(nc, "%s%s%s",
"HTTP/1.1 101 Switching Protocols\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Accept: ",
b64_sha, "\r\n\r\n");
DBG(("%p %.*s %s", nc, (int) key->len, key->p, b64_sha));
}
void mg_send_websocket_handshake2(struct mg_connection *nc, const char *path,
const char *host, const char *protocol,
const char *extra_headers) {
mg_send_websocket_handshake3(nc, path, host, protocol, extra_headers, NULL,
NULL);
}
void mg_send_websocket_handshake3(struct mg_connection *nc, const char *path,
const char *host, const char *protocol,
const char *extra_headers, const char *user,
const char *pass) {
struct mbuf auth;
char key[25];
uint32_t nonce[4];
nonce[0] = mg_ws_random_mask();
nonce[1] = mg_ws_random_mask();
nonce[2] = mg_ws_random_mask();
nonce[3] = mg_ws_random_mask();
mg_base64_encode((unsigned char *) &nonce, sizeof(nonce), key);
mbuf_init(&auth, 0);
if (user != NULL) {
mg_basic_auth_header(user, pass, &auth);
}
/*
* NOTE: the (auth.buf == NULL ? "" : auth.buf) is because cc3200 libc is
* broken: it doesn't like zero length to be passed to %.*s
* i.e. sprintf("f%.*so", (int)0, NULL), yields `f\0o`.
* because it handles NULL specially (and incorrectly).
*/
mg_printf(nc,
"GET %s HTTP/1.1\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"%.*s"
"Sec-WebSocket-Version: 13\r\n"
"Sec-WebSocket-Key: %s\r\n",
path, (int) auth.len, (auth.buf == NULL ? "" : auth.buf), key);
/* TODO(mkm): take default hostname from http proto data if host == NULL */
if (host != MG_WS_NO_HOST_HEADER_MAGIC) {
mg_printf(nc, "Host: %s\r\n", host);
}
if (protocol != NULL) {
mg_printf(nc, "Sec-WebSocket-Protocol: %s\r\n", protocol);
}
if (extra_headers != NULL) {
mg_printf(nc, "%s", extra_headers);
}
mg_printf(nc, "\r\n");
mbuf_free(&auth);
}
void mg_send_websocket_handshake(struct mg_connection *nc, const char *path,
const char *extra_headers) {
mg_send_websocket_handshake2(nc, path, MG_WS_NO_HOST_HEADER_MAGIC, NULL,
extra_headers);
}
struct mg_connection *mg_connect_ws_opt(
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
struct mg_connect_opts opts, const char *url, const char *protocol,
const char *extra_headers) {
char *user = NULL, *pass = NULL, *addr = NULL;
const char *path = NULL;
struct mg_connection *nc =
mg_connect_http_base(mgr, MG_CB(ev_handler, user_data), opts, "ws://",
"wss://", url, &path, &user, &pass, &addr);
if (nc != NULL) {
mg_send_websocket_handshake3(nc, path, addr, protocol, extra_headers, user,
pass);
}
MG_FREE(addr);
MG_FREE(user);
MG_FREE(pass);
return nc;
}
struct mg_connection *mg_connect_ws(
struct mg_mgr *mgr, MG_CB(mg_event_handler_t ev_handler, void *user_data),
const char *url, const char *protocol, const char *extra_headers) {
struct mg_connect_opts opts;
memset(&opts, 0, sizeof(opts));
return mg_connect_ws_opt(mgr, MG_CB(ev_handler, user_data), opts, url,
protocol, extra_headers);
}
#endif /* MG_ENABLE_HTTP && MG_ENABLE_HTTP_WEBSOCKET */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/util.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
/* Amalgamated: #include "common/base64.h" */
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/util.h" */
/* For platforms with limited libc */
#ifndef MAX
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#endif
const char *mg_skip(const char *s, const char *end, const char *delims,
struct mg_str *v) {
v->p = s;
while (s < end && strchr(delims, *(unsigned char *) s) == NULL) s++;
v->len = s - v->p;
while (s < end && strchr(delims, *(unsigned char *) s) != NULL) s++;
return s;
}
static int lowercase(const char *s) {
return tolower(*(const unsigned char *) s);
}
#if MG_ENABLE_FILESYSTEM && !defined(MG_USER_FILE_FUNCTIONS)
int mg_stat(const char *path, cs_stat_t *st) {
#ifdef _WIN32
wchar_t wpath[MAX_PATH_SIZE];
to_wchar(path, wpath, ARRAY_SIZE(wpath));
DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
return _wstati64(wpath, st);
#else
return stat(path, st);
#endif
}
FILE *mg_fopen(const char *path, const char *mode) {
#ifdef _WIN32
wchar_t wpath[MAX_PATH_SIZE], wmode[10];
to_wchar(path, wpath, ARRAY_SIZE(wpath));
to_wchar(mode, wmode, ARRAY_SIZE(wmode));
return _wfopen(wpath, wmode);
#else
return fopen(path, mode);
#endif
}
int mg_open(const char *path, int flag, int mode) { /* LCOV_EXCL_LINE */
#if defined(_WIN32) && !defined(WINCE)
wchar_t wpath[MAX_PATH_SIZE];
to_wchar(path, wpath, ARRAY_SIZE(wpath));
return _wopen(wpath, flag, mode);
#else
return open(path, flag, mode); /* LCOV_EXCL_LINE */
#endif
}
size_t mg_fread(void *ptr, size_t size, size_t count, FILE *f) {
return fread(ptr, size, count, f);
}
size_t mg_fwrite(const void *ptr, size_t size, size_t count, FILE *f) {
return fwrite(ptr, size, count, f);
}
#endif
void mg_base64_encode(const unsigned char *src, int src_len, char *dst) {
cs_base64_encode(src, src_len, dst);
}
int mg_base64_decode(const unsigned char *s, int len, char *dst) {
return cs_base64_decode(s, len, dst, NULL);
}
#if MG_ENABLE_THREADS
void *mg_start_thread(void *(*f)(void *), void *p) {
#ifdef WINCE
return (void *) CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0, NULL);
#elif defined(_WIN32)
return (void *) _beginthread((void(__cdecl *) (void *) ) f, 0, p);
#else
pthread_t thread_id = (pthread_t) 0;
pthread_attr_t attr;
(void) pthread_attr_init(&attr);
(void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
#if defined(MG_STACK_SIZE) && MG_STACK_SIZE > 1
(void) pthread_attr_setstacksize(&attr, MG_STACK_SIZE);
#endif
pthread_create(&thread_id, &attr, f, p);
pthread_attr_destroy(&attr);
return (void *) thread_id;
#endif
}
#endif /* MG_ENABLE_THREADS */
/* Set close-on-exec bit for a given socket. */
void mg_set_close_on_exec(sock_t sock) {
#if defined(_WIN32) && !defined(WINCE)
(void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
#elif defined(__unix__)
fcntl(sock, F_SETFD, FD_CLOEXEC);
#else
(void) sock;
#endif
}
void mg_sock_addr_to_str(const union socket_address *sa, char *buf, size_t len,
int flags) {
int is_v6;
if (buf == NULL || len <= 0) return;
memset(buf, 0, len);
#if MG_ENABLE_IPV6
is_v6 = sa->sa.sa_family == AF_INET6;
#else
is_v6 = 0;
#endif
if (flags & MG_SOCK_STRINGIFY_IP) {
#if MG_ENABLE_IPV6
const void *addr = NULL;
char *start = buf;
socklen_t capacity = len;
if (!is_v6) {
addr = &sa->sin.sin_addr;
} else {
addr = (void *) &sa->sin6.sin6_addr;
if (flags & MG_SOCK_STRINGIFY_PORT) {
*buf = '[';
start++;
capacity--;
}
}
if (inet_ntop(sa->sa.sa_family, addr, start, capacity) == NULL) {
goto cleanup;
}
#elif defined(_WIN32) || MG_LWIP || (MG_NET_IF == MG_NET_IF_PIC32)
/* Only Windoze Vista (and newer) have inet_ntop() */
char *addr_str = inet_ntoa(sa->sin.sin_addr);
if (addr_str != NULL) {
strncpy(buf, inet_ntoa(sa->sin.sin_addr), len - 1);
} else {
goto cleanup;
}
#else
if (inet_ntop(AF_INET, (void *) &sa->sin.sin_addr, buf, len - 1) == NULL) {
goto cleanup;
}
#endif
}
if (flags & MG_SOCK_STRINGIFY_PORT) {
int port = ntohs(sa->sin.sin_port);
if (flags & MG_SOCK_STRINGIFY_IP) {
int buf_len = strlen(buf);
snprintf(buf + buf_len, len - (buf_len + 1), "%s:%d", (is_v6 ? "]" : ""),
port);
} else {
snprintf(buf, len, "%d", port);
}
}
return;
cleanup:
*buf = '\0';
}
void mg_conn_addr_to_str(struct mg_connection *nc, char *buf, size_t len,
int flags) {
union socket_address sa;
memset(&sa, 0, sizeof(sa));
mg_if_get_conn_addr(nc, flags & MG_SOCK_STRINGIFY_REMOTE, &sa);
mg_sock_addr_to_str(&sa, buf, len, flags);
}
#if MG_ENABLE_HEXDUMP
static int mg_hexdump_n(const void *buf, int len, char *dst, int dst_len,
int offset) {
const unsigned char *p = (const unsigned char *) buf;
char ascii[17] = "";
int i, idx, n = 0;
for (i = 0; i < len; i++) {
idx = i % 16;
if (idx == 0) {
if (i > 0) n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii);
n += snprintf(dst + n, MAX(dst_len - n, 0), "%04x ", i + offset);
}
if (dst_len - n < 0) {
return n;
}
n += snprintf(dst + n, MAX(dst_len - n, 0), " %02x", p[i]);
ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
ascii[idx + 1] = '\0';
}
while (i++ % 16) n += snprintf(dst + n, MAX(dst_len - n, 0), "%s", " ");
n += snprintf(dst + n, MAX(dst_len - n, 0), " %s\n", ascii);
return n;
}
int mg_hexdump(const void *buf, int len, char *dst, int dst_len) {
return mg_hexdump_n(buf, len, dst, dst_len, 0);
}
void mg_hexdumpf(FILE *fp, const void *buf, int len) {
char tmp[80];
int offset = 0, n;
while (len > 0) {
n = (len < 16 ? len : 16);
mg_hexdump_n(((const char *) buf) + offset, n, tmp, sizeof(tmp), offset);
fputs(tmp, fp);
offset += n;
len -= n;
}
}
void mg_hexdump_connection(struct mg_connection *nc, const char *path,
const void *buf, int num_bytes, int ev) {
FILE *fp = NULL;
char *hexbuf, src[60], dst[60];
int buf_size = num_bytes * 5 + 100;
if (strcmp(path, "-") == 0) {
fp = stdout;
} else if (strcmp(path, "--") == 0) {
fp = stderr;
#if MG_ENABLE_FILESYSTEM
} else {
fp = mg_fopen(path, "a");
#endif
}
if (fp == NULL) return;
mg_conn_addr_to_str(nc, src, sizeof(src),
MG_SOCK_STRINGIFY_IP | MG_SOCK_STRINGIFY_PORT);
mg_conn_addr_to_str(nc, dst, sizeof(dst), MG_SOCK_STRINGIFY_IP |
MG_SOCK_STRINGIFY_PORT |
MG_SOCK_STRINGIFY_REMOTE);
fprintf(
fp, "%lu %p %s %s %s %d\n", (unsigned long) mg_time(), (void *) nc, src,
ev == MG_EV_RECV ? "<-" : ev == MG_EV_SEND
? "->"
: ev == MG_EV_ACCEPT
? "<A"
: ev == MG_EV_CONNECT ? "C>" : "XX",
dst, num_bytes);
if (num_bytes > 0 && (hexbuf = (char *) MG_MALLOC(buf_size)) != NULL) {
mg_hexdump(buf, num_bytes, hexbuf, buf_size);
fprintf(fp, "%s", hexbuf);
MG_FREE(hexbuf);
}
if (fp != stdin && fp != stdout) fclose(fp);
}
#endif
int mg_is_big_endian(void) {
static const int n = 1;
/* TODO(mkm) use compiletime check with 4-byte char literal */
return ((char *) &n)[0] == 0;
}
const char *mg_next_comma_list_entry(const char *list, struct mg_str *val,
struct mg_str *eq_val) {
if (list == NULL || *list == '\0') {
/* End of the list */
list = NULL;
} else {
val->p = list;
if ((list = strchr(val->p, ',')) != NULL) {
/* Comma found. Store length and shift the list ptr */
val->len = list - val->p;
list++;
} else {
/* This value is the last one */
list = val->p + strlen(val->p);
val->len = list - val->p;
}
if (eq_val != NULL) {
/* Value has form "x=y", adjust pointers and lengths */
/* so that val points to "x", and eq_val points to "y". */
eq_val->len = 0;
eq_val->p = (const char *) memchr(val->p, '=', val->len);
if (eq_val->p != NULL) {
eq_val->p++; /* Skip over '=' character */
eq_val->len = val->p + val->len - eq_val->p;
val->len = (eq_val->p - val->p) - 1;
}
}
}
return list;
}
int mg_match_prefix_n(const struct mg_str pattern, const struct mg_str str) {
const char *or_str;
size_t len, i = 0, j = 0;
int res;
if ((or_str = (const char *) memchr(pattern.p, '|', pattern.len)) != NULL) {
struct mg_str pstr = {pattern.p, (size_t)(or_str - pattern.p)};
res = mg_match_prefix_n(pstr, str);
if (res > 0) return res;
pstr.p = or_str + 1;
pstr.len = (pattern.p + pattern.len) - (or_str + 1);
return mg_match_prefix_n(pstr, str);
}
for (; i < pattern.len; i++, j++) {
if (pattern.p[i] == '?' && j != str.len) {
continue;
} else if (pattern.p[i] == '$') {
return j == str.len ? (int) j : -1;
} else if (pattern.p[i] == '*') {
i++;
if (pattern.p[i] == '*') {
i++;
len = str.len - j;
} else {
len = 0;
while (j + len != str.len && str.p[j + len] != '/') {
len++;
}
}
if (i == pattern.len) {
return j + len;
}
do {
const struct mg_str pstr = {pattern.p + i, pattern.len - i};
const struct mg_str sstr = {str.p + j + len, str.len - j - len};
res = mg_match_prefix_n(pstr, sstr);
} while (res == -1 && len-- > 0);
return res == -1 ? -1 : (int) (j + res + len);
} else if (lowercase(&pattern.p[i]) != lowercase(&str.p[j])) {
return -1;
}
}
return j;
}
int mg_match_prefix(const char *pattern, int pattern_len, const char *str) {
const struct mg_str pstr = {pattern, (size_t) pattern_len};
return mg_match_prefix_n(pstr, mg_mk_str(str));
}
DO_NOT_WARN_UNUSED MG_INTERNAL int mg_get_errno(void) {
#ifndef WINCE
return errno;
#else
/* TODO(alashkin): translate error codes? */
return GetLastError();
#endif
}
void mg_mbuf_append_base64_putc(char ch, void *user_data) {
struct mbuf *mbuf = (struct mbuf *) user_data;
mbuf_append(mbuf, &ch, sizeof(ch));
}
void mg_mbuf_append_base64(struct mbuf *mbuf, const void *data, size_t len) {
struct cs_base64_ctx ctx;
cs_base64_init(&ctx, mg_mbuf_append_base64_putc, mbuf);
cs_base64_update(&ctx, (const char *) data, len);
cs_base64_finish(&ctx);
}
void mg_basic_auth_header(const char *user, const char *pass,
struct mbuf *buf) {
const char *header_prefix = "Authorization: Basic ";
const char *header_suffix = "\r\n";
struct cs_base64_ctx ctx;
cs_base64_init(&ctx, mg_mbuf_append_base64_putc, buf);
mbuf_append(buf, header_prefix, strlen(header_prefix));
cs_base64_update(&ctx, user, strlen(user));
if (pass != NULL) {
cs_base64_update(&ctx, ":", 1);
cs_base64_update(&ctx, pass, strlen(pass));
}
cs_base64_finish(&ctx);
mbuf_append(buf, header_suffix, strlen(header_suffix));
}
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mqtt.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_MQTT
#include <string.h>
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/mqtt.h" */
static uint16_t getu16(const char *p) {
const uint8_t *up = (const uint8_t *) p;
return (up[0] << 8) + up[1];
}
static const char *scanto(const char *p, struct mg_str *s) {
s->len = getu16(p);
s->p = p + 2;
return s->p + s->len;
}
MG_INTERNAL int parse_mqtt(struct mbuf *io, struct mg_mqtt_message *mm) {
uint8_t header;
size_t len = 0;
int cmd;
const char *p = &io->buf[1], *end;
if (io->len < 2) return -1;
header = io->buf[0];
cmd = header >> 4;
/* decode mqtt variable length */
do {
len += (*p & 127) << 7 * (p - &io->buf[1]);
} while ((*p++ & 128) != 0 && ((size_t)(p - io->buf) <= io->len));
end = p + len;
if (end > io->buf + io->len + 1) {
return -1;
}
mm->cmd = cmd;
mm->qos = MG_MQTT_GET_QOS(header);
switch (cmd) {
case MG_MQTT_CMD_CONNECT: {
p = scanto(p, &mm->protocol_name);
mm->protocol_version = *(uint8_t *) p++;
mm->connect_flags = *(uint8_t *) p++;
mm->keep_alive_timer = getu16(p);
p += 2;
if (p < end) p = scanto(p, &mm->client_id);
if (p < end && (mm->connect_flags & MG_MQTT_HAS_WILL))
p = scanto(p, &mm->will_topic);
if (p < end && (mm->connect_flags & MG_MQTT_HAS_WILL))
p = scanto(p, &mm->will_message);
if (p < end && (mm->connect_flags & MG_MQTT_HAS_USER_NAME))
p = scanto(p, &mm->user_name);
if (p < end && (mm->connect_flags & MG_MQTT_HAS_PASSWORD))
p = scanto(p, &mm->password);
LOG(LL_DEBUG,
("%d %2x %d proto [%.*s] client_id [%.*s] will_topic [%.*s] "
"will_msg [%.*s] user_name [%.*s] password [%.*s]",
len, (int) mm->connect_flags, (int) mm->keep_alive_timer,
(int) mm->protocol_name.len, mm->protocol_name.p,
(int) mm->client_id.len, mm->client_id.p, (int) mm->will_topic.len,
mm->will_topic.p, (int) mm->will_message.len, mm->will_message.p,
(int) mm->user_name.len, mm->user_name.p, (int) mm->password.len,
mm->password.p));
break;
}
case MG_MQTT_CMD_CONNACK:
mm->connack_ret_code = p[1];
break;
case MG_MQTT_CMD_PUBACK:
case MG_MQTT_CMD_PUBREC:
case MG_MQTT_CMD_PUBREL:
case MG_MQTT_CMD_PUBCOMP:
case MG_MQTT_CMD_SUBACK:
mm->message_id = getu16(p);
break;
case MG_MQTT_CMD_PUBLISH: {
p = scanto(p, &mm->topic);
if (mm->qos > 0) {
mm->message_id = getu16(p);
p += 2;
}
mm->payload.p = p;
mm->payload.len = end - p;
break;
}
case MG_MQTT_CMD_SUBSCRIBE:
mm->message_id = getu16(p);
p += 2;
/*
* topic expressions are left in the payload and can be parsed with
* `mg_mqtt_next_subscribe_topic`
*/
mm->payload.p = p;
mm->payload.len = end - p;
break;
default:
/* Unhandled command */
break;
}
return end - io->buf;
}
static void mqtt_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
int len;
struct mbuf *io = &nc->recv_mbuf;
struct mg_mqtt_message mm;
memset(&mm, 0, sizeof(mm));
nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
switch (ev) {
case MG_EV_RECV:
len = parse_mqtt(io, &mm);
if (len == -1) break; /* not fully buffered */
nc->handler(nc, MG_MQTT_EVENT_BASE + mm.cmd, &mm MG_UD_ARG(user_data));
mbuf_remove(io, len);
break;
}
}
static void mg_mqtt_proto_data_destructor(void *proto_data) {
MG_FREE(proto_data);
}
int mg_mqtt_match_topic_expression(struct mg_str exp, struct mg_str topic) {
/* TODO(mkm): implement real matching */
if (memchr(exp.p, '#', exp.len)) {
/* exp `foo/#` will become `foo/` */
exp.len -= 1;
/*
* topic should be longer than the expression: e.g. topic `foo/bar` does
* match `foo/#`, but neither `foo` nor `foo/` do.
*/
if (topic.len <= exp.len) {
return 0;
}
/* Truncate topic so that it'll pass the next length check */
topic.len = exp.len;
}
if (topic.len != exp.len) {
return 0;
}
return strncmp(topic.p, exp.p, exp.len) == 0;
}
int mg_mqtt_vmatch_topic_expression(const char *exp, struct mg_str topic) {
return mg_mqtt_match_topic_expression(mg_mk_str(exp), topic);
}
void mg_set_protocol_mqtt(struct mg_connection *nc) {
nc->proto_handler = mqtt_handler;
nc->proto_data = MG_CALLOC(1, sizeof(struct mg_mqtt_proto_data));
nc->proto_data_destructor = mg_mqtt_proto_data_destructor;
}
void mg_send_mqtt_handshake(struct mg_connection *nc, const char *client_id) {
static struct mg_send_mqtt_handshake_opts opts;
mg_send_mqtt_handshake_opt(nc, client_id, opts);
}
void mg_send_mqtt_handshake_opt(struct mg_connection *nc, const char *client_id,
struct mg_send_mqtt_handshake_opts opts) {
uint8_t header = MG_MQTT_CMD_CONNECT << 4;
uint8_t rem_len;
uint16_t keep_alive;
uint16_t len;
struct mg_mqtt_proto_data *pd = (struct mg_mqtt_proto_data *) nc->proto_data;
/*
* 9: version_header(len, magic_string, version_number), 1: flags, 2:
* keep-alive timer,
* 2: client_identifier_len, n: client_id
*/
rem_len = 9 + 1 + 2 + 2 + (uint8_t) strlen(client_id);
if (opts.user_name != NULL) {
opts.flags |= MG_MQTT_HAS_USER_NAME;
rem_len += (uint8_t) strlen(opts.user_name) + 2;
}
if (opts.password != NULL) {
opts.flags |= MG_MQTT_HAS_PASSWORD;
rem_len += (uint8_t) strlen(opts.password) + 2;
}
if (opts.will_topic != NULL && opts.will_message != NULL) {
opts.flags |= MG_MQTT_HAS_WILL;
rem_len += (uint8_t) strlen(opts.will_topic) + 2;
rem_len += (uint8_t) strlen(opts.will_message) + 2;
}
mg_send(nc, &header, 1);
mg_send(nc, &rem_len, 1);
mg_send(nc, "\00\06MQIsdp\03", 9);
mg_send(nc, &opts.flags, 1);
if (opts.keep_alive == 0) {
opts.keep_alive = 60;
}
keep_alive = htons(opts.keep_alive);
mg_send(nc, &keep_alive, 2);
len = htons((uint16_t) strlen(client_id));
mg_send(nc, &len, 2);
mg_send(nc, client_id, strlen(client_id));
if (opts.flags & MG_MQTT_HAS_WILL) {
len = htons((uint16_t) strlen(opts.will_topic));
mg_send(nc, &len, 2);
mg_send(nc, opts.will_topic, strlen(opts.will_topic));
len = htons((uint16_t) strlen(opts.will_message));
mg_send(nc, &len, 2);
mg_send(nc, opts.will_message, strlen(opts.will_message));
}
if (opts.flags & MG_MQTT_HAS_USER_NAME) {
len = htons((uint16_t) strlen(opts.user_name));
mg_send(nc, &len, 2);
mg_send(nc, opts.user_name, strlen(opts.user_name));
}
if (opts.flags & MG_MQTT_HAS_PASSWORD) {
len = htons((uint16_t) strlen(opts.password));
mg_send(nc, &len, 2);
mg_send(nc, opts.password, strlen(opts.password));
}
if (pd != NULL) {
pd->keep_alive = opts.keep_alive;
}
}
static void mg_mqtt_prepend_header(struct mg_connection *nc, uint8_t cmd,
uint8_t flags, size_t len) {
size_t off = nc->send_mbuf.len - len;
uint8_t header = cmd << 4 | (uint8_t) flags;
uint8_t buf[1 + sizeof(size_t)];
uint8_t *vlen = &buf[1];
assert(nc->send_mbuf.len >= len);
buf[0] = header;
/* mqtt variable length encoding */
do {
*vlen = len % 0x80;
len /= 0x80;
if (len > 0) *vlen |= 0x80;
vlen++;
} while (len > 0);
mbuf_insert(&nc->send_mbuf, off, buf, vlen - buf);
}
void mg_mqtt_publish(struct mg_connection *nc, const char *topic,
uint16_t message_id, int flags, const void *data,
size_t len) {
size_t old_len = nc->send_mbuf.len;
uint16_t topic_len = htons((uint16_t) strlen(topic));
uint16_t message_id_net = htons(message_id);
mg_send(nc, &topic_len, 2);
mg_send(nc, topic, strlen(topic));
if (MG_MQTT_GET_QOS(flags) > 0) {
mg_send(nc, &message_id_net, 2);
}
mg_send(nc, data, len);
mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PUBLISH, flags,
nc->send_mbuf.len - old_len);
}
void mg_mqtt_subscribe(struct mg_connection *nc,
const struct mg_mqtt_topic_expression *topics,
size_t topics_len, uint16_t message_id) {
size_t old_len = nc->send_mbuf.len;
uint16_t message_id_n = htons(message_id);
size_t i;
mg_send(nc, (char *) &message_id_n, 2);
for (i = 0; i < topics_len; i++) {
uint16_t topic_len_n = htons((uint16_t) strlen(topics[i].topic));
mg_send(nc, &topic_len_n, 2);
mg_send(nc, topics[i].topic, strlen(topics[i].topic));
mg_send(nc, &topics[i].qos, 1);
}
mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBSCRIBE, MG_MQTT_QOS(1),
nc->send_mbuf.len - old_len);
}
int mg_mqtt_next_subscribe_topic(struct mg_mqtt_message *msg,
struct mg_str *topic, uint8_t *qos, int pos) {
unsigned char *buf = (unsigned char *) msg->payload.p + pos;
if ((size_t) pos >= msg->payload.len) {
return -1;
}
topic->len = buf[0] << 8 | buf[1];
topic->p = (char *) buf + 2;
*qos = buf[2 + topic->len];
return pos + 2 + topic->len + 1;
}
void mg_mqtt_unsubscribe(struct mg_connection *nc, char **topics,
size_t topics_len, uint16_t message_id) {
size_t old_len = nc->send_mbuf.len;
uint16_t message_id_n = htons(message_id);
size_t i;
mg_send(nc, (char *) &message_id_n, 2);
for (i = 0; i < topics_len; i++) {
uint16_t topic_len_n = htons((uint16_t) strlen(topics[i]));
mg_send(nc, &topic_len_n, 2);
mg_send(nc, topics[i], strlen(topics[i]));
}
mg_mqtt_prepend_header(nc, MG_MQTT_CMD_UNSUBSCRIBE, MG_MQTT_QOS(1),
nc->send_mbuf.len - old_len);
}
void mg_mqtt_connack(struct mg_connection *nc, uint8_t return_code) {
uint8_t unused = 0;
mg_send(nc, &unused, 1);
mg_send(nc, &return_code, 1);
mg_mqtt_prepend_header(nc, MG_MQTT_CMD_CONNACK, 0, 2);
}
/*
* Sends a command which contains only a `message_id` and a QoS level of 1.
*
* Helper function.
*/
static void mg_send_mqtt_short_command(struct mg_connection *nc, uint8_t cmd,
uint16_t message_id) {
uint16_t message_id_net = htons(message_id);
uint8_t flags = (cmd == MG_MQTT_CMD_PUBREL ? 2 : 0);
mg_send(nc, &message_id_net, 2);
mg_mqtt_prepend_header(nc, cmd, flags, 2 /* len */);
}
void mg_mqtt_puback(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBACK, message_id);
}
void mg_mqtt_pubrec(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREC, message_id);
}
void mg_mqtt_pubrel(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBREL, message_id);
}
void mg_mqtt_pubcomp(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_PUBCOMP, message_id);
}
void mg_mqtt_suback(struct mg_connection *nc, uint8_t *qoss, size_t qoss_len,
uint16_t message_id) {
size_t i;
uint16_t message_id_net = htons(message_id);
mg_send(nc, &message_id_net, 2);
for (i = 0; i < qoss_len; i++) {
mg_send(nc, &qoss[i], 1);
}
mg_mqtt_prepend_header(nc, MG_MQTT_CMD_SUBACK, MG_MQTT_QOS(1), 2 + qoss_len);
}
void mg_mqtt_unsuback(struct mg_connection *nc, uint16_t message_id) {
mg_send_mqtt_short_command(nc, MG_MQTT_CMD_UNSUBACK, message_id);
}
void mg_mqtt_ping(struct mg_connection *nc) {
mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGREQ, 0, 0);
}
void mg_mqtt_pong(struct mg_connection *nc) {
mg_mqtt_prepend_header(nc, MG_MQTT_CMD_PINGRESP, 0, 0);
}
void mg_mqtt_disconnect(struct mg_connection *nc) {
mg_mqtt_prepend_header(nc, MG_MQTT_CMD_DISCONNECT, 0, 0);
}
#endif /* MG_ENABLE_MQTT */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/mqtt_server.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/mqtt-server.h" */
#if MG_ENABLE_MQTT_BROKER
static void mg_mqtt_session_init(struct mg_mqtt_broker *brk,
struct mg_mqtt_session *s,
struct mg_connection *nc) {
s->brk = brk;
s->subscriptions = NULL;
s->num_subscriptions = 0;
s->nc = nc;
}
static void mg_mqtt_add_session(struct mg_mqtt_session *s) {
LIST_INSERT_HEAD(&s->brk->sessions, s, link);
}
static void mg_mqtt_remove_session(struct mg_mqtt_session *s) {
LIST_REMOVE(s, link);
}
static void mg_mqtt_destroy_session(struct mg_mqtt_session *s) {
size_t i;
for (i = 0; i < s->num_subscriptions; i++) {
MG_FREE((void *) s->subscriptions[i].topic);
}
MG_FREE(s->subscriptions);
MG_FREE(s);
}
static void mg_mqtt_close_session(struct mg_mqtt_session *s) {
mg_mqtt_remove_session(s);
mg_mqtt_destroy_session(s);
}
void mg_mqtt_broker_init(struct mg_mqtt_broker *brk, void *user_data) {
LIST_INIT(&brk->sessions);
brk->user_data = user_data;
}
static void mg_mqtt_broker_handle_connect(struct mg_mqtt_broker *brk,
struct mg_connection *nc) {
struct mg_mqtt_session *s =
(struct mg_mqtt_session *) MG_CALLOC(1, sizeof *s);
if (s == NULL) {
/* LCOV_EXCL_START */
mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE);
return;
/* LCOV_EXCL_STOP */
}
/* TODO(mkm): check header (magic and version) */
mg_mqtt_session_init(brk, s, nc);
s->user_data = nc->user_data;
nc->user_data = s;
mg_mqtt_add_session(s);
mg_mqtt_connack(nc, MG_EV_MQTT_CONNACK_ACCEPTED);
}
static void mg_mqtt_broker_handle_subscribe(struct mg_connection *nc,
struct mg_mqtt_message *msg) {
struct mg_mqtt_session *ss = (struct mg_mqtt_session *) nc->user_data;
uint8_t qoss[512];
size_t qoss_len = 0;
struct mg_str topic;
uint8_t qos;
int pos;
struct mg_mqtt_topic_expression *te;
for (pos = 0;
(pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;) {
qoss[qoss_len++] = qos;
}
ss->subscriptions = (struct mg_mqtt_topic_expression *) MG_REALLOC(
ss->subscriptions, sizeof(*ss->subscriptions) * qoss_len);
for (pos = 0;
(pos = mg_mqtt_next_subscribe_topic(msg, &topic, &qos, pos)) != -1;
ss->num_subscriptions++) {
te = &ss->subscriptions[ss->num_subscriptions];
te->topic = (char *) MG_MALLOC(topic.len + 1);
te->qos = qos;
strncpy((char *) te->topic, topic.p, topic.len + 1);
}
mg_mqtt_suback(nc, qoss, qoss_len, msg->message_id);
}
static void mg_mqtt_broker_handle_publish(struct mg_mqtt_broker *brk,
struct mg_mqtt_message *msg) {
struct mg_mqtt_session *s;
size_t i;
for (s = mg_mqtt_next(brk, NULL); s != NULL; s = mg_mqtt_next(brk, s)) {
for (i = 0; i < s->num_subscriptions; i++) {
if (mg_mqtt_vmatch_topic_expression(s->subscriptions[i].topic,
msg->topic)) {
char buf[100], *p = buf;
mg_asprintf(&p, sizeof(buf), "%.*s", (int) msg->topic.len,
msg->topic.p);
if (p == NULL) {
return;
}
mg_mqtt_publish(s->nc, p, 0, 0, msg->payload.p, msg->payload.len);
if (p != buf) {
MG_FREE(p);
}
break;
}
}
}
}
void mg_mqtt_broker(struct mg_connection *nc, int ev, void *data) {
struct mg_mqtt_message *msg = (struct mg_mqtt_message *) data;
struct mg_mqtt_broker *brk;
if (nc->listener) {
brk = (struct mg_mqtt_broker *) nc->listener->user_data;
} else {
brk = (struct mg_mqtt_broker *) nc->user_data;
}
switch (ev) {
case MG_EV_ACCEPT:
mg_set_protocol_mqtt(nc);
nc->user_data = NULL; /* Clear up the inherited pointer to broker */
break;
case MG_EV_MQTT_CONNECT:
mg_mqtt_broker_handle_connect(brk, nc);
break;
case MG_EV_MQTT_SUBSCRIBE:
mg_mqtt_broker_handle_subscribe(nc, msg);
break;
case MG_EV_MQTT_PUBLISH:
mg_mqtt_broker_handle_publish(brk, msg);
break;
case MG_EV_CLOSE:
if (nc->listener && nc->user_data != NULL) {
mg_mqtt_close_session((struct mg_mqtt_session *) nc->user_data);
}
break;
}
}
struct mg_mqtt_session *mg_mqtt_next(struct mg_mqtt_broker *brk,
struct mg_mqtt_session *s) {
return s == NULL ? LIST_FIRST(&brk->sessions) : LIST_NEXT(s, link);
}
#endif /* MG_ENABLE_MQTT_BROKER */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/dns.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_DNS
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/dns.h" */
static int mg_dns_tid = 0xa0;
struct mg_dns_header {
uint16_t transaction_id;
uint16_t flags;
uint16_t num_questions;
uint16_t num_answers;
uint16_t num_authority_prs;
uint16_t num_other_prs;
};
struct mg_dns_resource_record *mg_dns_next_record(
struct mg_dns_message *msg, int query,
struct mg_dns_resource_record *prev) {
struct mg_dns_resource_record *rr;
for (rr = (prev == NULL ? msg->answers : prev + 1);
rr - msg->answers < msg->num_answers; rr++) {
if (rr->rtype == query) {
return rr;
}
}
return NULL;
}
int mg_dns_parse_record_data(struct mg_dns_message *msg,
struct mg_dns_resource_record *rr, void *data,
size_t data_len) {
switch (rr->rtype) {
case MG_DNS_A_RECORD:
if (data_len < sizeof(struct in_addr)) {
return -1;
}
if (rr->rdata.p + data_len > msg->pkt.p + msg->pkt.len) {
return -1;
}
memcpy(data, rr->rdata.p, data_len);
return 0;
#if MG_ENABLE_IPV6
case MG_DNS_AAAA_RECORD:
if (data_len < sizeof(struct in6_addr)) {
return -1; /* LCOV_EXCL_LINE */
}
memcpy(data, rr->rdata.p, data_len);
return 0;
#endif
case MG_DNS_CNAME_RECORD:
mg_dns_uncompress_name(msg, &rr->rdata, (char *) data, data_len);
return 0;
}
return -1;
}
int mg_dns_insert_header(struct mbuf *io, size_t pos,
struct mg_dns_message *msg) {
struct mg_dns_header header;
memset(&header, 0, sizeof(header));
header.transaction_id = msg->transaction_id;
header.flags = htons(msg->flags);
header.num_questions = htons(msg->num_questions);
header.num_answers = htons(msg->num_answers);
return mbuf_insert(io, pos, &header, sizeof(header));
}
int mg_dns_copy_questions(struct mbuf *io, struct mg_dns_message *msg) {
unsigned char *begin, *end;
struct mg_dns_resource_record *last_q;
if (msg->num_questions <= 0) return 0;
begin = (unsigned char *) msg->pkt.p + sizeof(struct mg_dns_header);
last_q = &msg->questions[msg->num_questions - 1];
end = (unsigned char *) last_q->name.p + last_q->name.len + 4;
return mbuf_append(io, begin, end - begin);
}
int mg_dns_encode_name(struct mbuf *io, const char *name, size_t len) {
const char *s;
unsigned char n;
size_t pos = io->len;
do {
if ((s = strchr(name, '.')) == NULL) {
s = name + len;
}
if (s - name > 127) {
return -1; /* TODO(mkm) cover */
}
n = s - name; /* chunk length */
mbuf_append(io, &n, 1); /* send length */
mbuf_append(io, name, n);
if (*s == '.') {
n++;
}
name += n;
len -= n;
} while (*s != '\0');
mbuf_append(io, "\0", 1); /* Mark end of host name */
return io->len - pos;
}
int mg_dns_encode_record(struct mbuf *io, struct mg_dns_resource_record *rr,
const char *name, size_t nlen, const void *rdata,
size_t rlen) {
size_t pos = io->len;
uint16_t u16;
uint32_t u32;
if (rr->kind == MG_DNS_INVALID_RECORD) {
return -1; /* LCOV_EXCL_LINE */
}
if (mg_dns_encode_name(io, name, nlen) == -1) {
return -1;
}
u16 = htons(rr->rtype);
mbuf_append(io, &u16, 2);
u16 = htons(rr->rclass);
mbuf_append(io, &u16, 2);
if (rr->kind == MG_DNS_ANSWER) {
u32 = htonl(rr->ttl);
mbuf_append(io, &u32, 4);
if (rr->rtype == MG_DNS_CNAME_RECORD) {
int clen;
/* fill size after encoding */
size_t off = io->len;
mbuf_append(io, &u16, 2);
if ((clen = mg_dns_encode_name(io, (const char *) rdata, rlen)) == -1) {
return -1;
}
u16 = clen;
io->buf[off] = u16 >> 8;
io->buf[off + 1] = u16 & 0xff;
} else {
u16 = htons((uint16_t) rlen);
mbuf_append(io, &u16, 2);
mbuf_append(io, rdata, rlen);
}
}
return io->len - pos;
}
void mg_send_dns_query(struct mg_connection *nc, const char *name,
int query_type) {
struct mg_dns_message *msg =
(struct mg_dns_message *) MG_CALLOC(1, sizeof(*msg));
struct mbuf pkt;
struct mg_dns_resource_record *rr = &msg->questions[0];
DBG(("%s %d", name, query_type));
mbuf_init(&pkt, 64 /* Start small, it'll grow as needed. */);
msg->transaction_id = ++mg_dns_tid;
msg->flags = 0x100;
msg->num_questions = 1;
mg_dns_insert_header(&pkt, 0, msg);
rr->rtype = query_type;
rr->rclass = 1; /* Class: inet */
rr->kind = MG_DNS_QUESTION;
if (mg_dns_encode_record(&pkt, rr, name, strlen(name), NULL, 0) == -1) {
/* TODO(mkm): return an error code */
goto cleanup; /* LCOV_EXCL_LINE */
}
/* TCP DNS requires messages to be prefixed with len */
if (!(nc->flags & MG_F_UDP)) {
uint16_t len = htons((uint16_t) pkt.len);
mbuf_insert(&pkt, 0, &len, 2);
}
mg_send(nc, pkt.buf, pkt.len);
mbuf_free(&pkt);
cleanup:
MG_FREE(msg);
}
static unsigned char *mg_parse_dns_resource_record(
unsigned char *data, unsigned char *end, struct mg_dns_resource_record *rr,
int reply) {
unsigned char *name = data;
int chunk_len, data_len;
while (data < end && (chunk_len = *data)) {
if (((unsigned char *) data)[0] & 0xc0) {
data += 1;
break;
}
data += chunk_len + 1;
}
if (data > end - 5) {
return NULL;
}
rr->name.p = (char *) name;
rr->name.len = data - name + 1;
data++;
rr->rtype = data[0] << 8 | data[1];
data += 2;
rr->rclass = data[0] << 8 | data[1];
data += 2;
rr->kind = reply ? MG_DNS_ANSWER : MG_DNS_QUESTION;
if (reply) {
if (data >= end - 6) {
return NULL;
}
rr->ttl = (uint32_t) data[0] << 24 | (uint32_t) data[1] << 16 |
data[2] << 8 | data[3];
data += 4;
data_len = *data << 8 | *(data + 1);
data += 2;
rr->rdata.p = (char *) data;
rr->rdata.len = data_len;
data += data_len;
}
return data;
}
int mg_parse_dns(const char *buf, int len, struct mg_dns_message *msg) {
struct mg_dns_header *header = (struct mg_dns_header *) buf;
unsigned char *data = (unsigned char *) buf + sizeof(*header);
unsigned char *end = (unsigned char *) buf + len;
int i;
memset(msg, 0, sizeof(*msg));
msg->pkt.p = buf;
msg->pkt.len = len;
if (len < (int) sizeof(*header)) return -1;
msg->transaction_id = header->transaction_id;
msg->flags = ntohs(header->flags);
msg->num_questions = ntohs(header->num_questions);
if (msg->num_questions > (int) ARRAY_SIZE(msg->questions)) {
msg->num_questions = (int) ARRAY_SIZE(msg->questions);
}
msg->num_answers = ntohs(header->num_answers);
if (msg->num_answers > (int) ARRAY_SIZE(msg->answers)) {
msg->num_answers = (int) ARRAY_SIZE(msg->answers);
}
for (i = 0; i < msg->num_questions; i++) {
data = mg_parse_dns_resource_record(data, end, &msg->questions[i], 0);
if (data == NULL) return -1;
}
for (i = 0; i < msg->num_answers; i++) {
data = mg_parse_dns_resource_record(data, end, &msg->answers[i], 1);
if (data == NULL) return -1;
}
return 0;
}
size_t mg_dns_uncompress_name(struct mg_dns_message *msg, struct mg_str *name,
char *dst, int dst_len) {
int chunk_len;
char *old_dst = dst;
const unsigned char *data = (unsigned char *) name->p;
const unsigned char *end = (unsigned char *) msg->pkt.p + msg->pkt.len;
if (data >= end) {
return 0;
}
while ((chunk_len = *data++)) {
int leeway = dst_len - (dst - old_dst);
if (data >= end) {
return 0;
}
if (chunk_len & 0xc0) {
uint16_t off = (data[-1] & (~0xc0)) << 8 | data[0];
if (off >= msg->pkt.len) {
return 0;
}
data = (unsigned char *) msg->pkt.p + off;
continue;
}
if (chunk_len > leeway) {
chunk_len = leeway;
}
if (data + chunk_len >= end) {
return 0;
}
memcpy(dst, data, chunk_len);
data += chunk_len;
dst += chunk_len;
leeway -= chunk_len;
if (leeway == 0) {
return dst - old_dst;
}
*dst++ = '.';
}
if (dst != old_dst) {
*--dst = 0;
}
return dst - old_dst;
}
static void dns_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct mbuf *io = &nc->recv_mbuf;
struct mg_dns_message msg;
/* Pass low-level events to the user handler */
nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
switch (ev) {
case MG_EV_RECV:
if (!(nc->flags & MG_F_UDP)) {
mbuf_remove(&nc->recv_mbuf, 2);
}
if (mg_parse_dns(nc->recv_mbuf.buf, nc->recv_mbuf.len, &msg) == -1) {
/* reply + recursion allowed + format error */
memset(&msg, 0, sizeof(msg));
msg.flags = 0x8081;
mg_dns_insert_header(io, 0, &msg);
if (!(nc->flags & MG_F_UDP)) {
uint16_t len = htons((uint16_t) io->len);
mbuf_insert(io, 0, &len, 2);
}
mg_send(nc, io->buf, io->len);
} else {
/* Call user handler with parsed message */
nc->handler(nc, MG_DNS_MESSAGE, &msg MG_UD_ARG(user_data));
}
mbuf_remove(io, io->len);
break;
}
}
void mg_set_protocol_dns(struct mg_connection *nc) {
nc->proto_handler = dns_handler;
}
#endif /* MG_ENABLE_DNS */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/dns_server.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_DNS_SERVER
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/dns-server.h" */
struct mg_dns_reply mg_dns_create_reply(struct mbuf *io,
struct mg_dns_message *msg) {
struct mg_dns_reply rep;
rep.msg = msg;
rep.io = io;
rep.start = io->len;
/* reply + recursion allowed */
msg->flags |= 0x8080;
mg_dns_copy_questions(io, msg);
msg->num_answers = 0;
return rep;
}
void mg_dns_send_reply(struct mg_connection *nc, struct mg_dns_reply *r) {
size_t sent = r->io->len - r->start;
mg_dns_insert_header(r->io, r->start, r->msg);
if (!(nc->flags & MG_F_UDP)) {
uint16_t len = htons((uint16_t) sent);
mbuf_insert(r->io, r->start, &len, 2);
}
if (&nc->send_mbuf != r->io) {
mg_send(nc, r->io->buf + r->start, r->io->len - r->start);
r->io->len = r->start;
}
}
int mg_dns_reply_record(struct mg_dns_reply *reply,
struct mg_dns_resource_record *question,
const char *name, int rtype, int ttl, const void *rdata,
size_t rdata_len) {
struct mg_dns_message *msg = (struct mg_dns_message *) reply->msg;
char rname[512];
struct mg_dns_resource_record *ans = &msg->answers[msg->num_answers];
if (msg->num_answers >= MG_MAX_DNS_ANSWERS) {
return -1; /* LCOV_EXCL_LINE */
}
if (name == NULL) {
name = rname;
rname[511] = 0;
mg_dns_uncompress_name(msg, &question->name, rname, sizeof(rname) - 1);
}
*ans = *question;
ans->kind = MG_DNS_ANSWER;
ans->rtype = rtype;
ans->ttl = ttl;
if (mg_dns_encode_record(reply->io, ans, name, strlen(name), rdata,
rdata_len) == -1) {
return -1; /* LCOV_EXCL_LINE */
};
msg->num_answers++;
return 0;
}
#endif /* MG_ENABLE_DNS_SERVER */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/resolv.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_ASYNC_RESOLVER
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/resolv.h" */
#ifndef MG_DEFAULT_NAMESERVER
#define MG_DEFAULT_NAMESERVER "8.8.8.8"
#endif
struct mg_resolve_async_request {
char name[1024];
int query;
mg_resolve_callback_t callback;
void *data;
time_t timeout;
int max_retries;
enum mg_resolve_err err;
/* state */
time_t last_time;
int retries;
};
/*
* Find what nameserver to use.
*
* Return 0 if OK, -1 if error
*/
static int mg_get_ip_address_of_nameserver(char *name, size_t name_len) {
int ret = -1;
#ifdef _WIN32
int i;
LONG err;
HKEY hKey, hSub;
wchar_t subkey[512], value[128],
*key = L"SYSTEM\\ControlSet001\\Services\\Tcpip\\Parameters\\Interfaces";
if ((err = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key, 0, KEY_READ, &hKey)) !=
ERROR_SUCCESS) {
fprintf(stderr, "cannot open reg key %S: %ld\n", key, err);
ret = -1;
} else {
for (ret = -1, i = 0; 1; i++) {
DWORD subkey_size = sizeof(subkey), type, len = sizeof(value);
if (RegEnumKeyExW(hKey, i, subkey, &subkey_size, NULL, NULL, NULL,
NULL) != ERROR_SUCCESS) {
break;
}
if (RegOpenKeyExW(hKey, subkey, 0, KEY_READ, &hSub) == ERROR_SUCCESS &&
(RegQueryValueExW(hSub, L"NameServer", 0, &type, (void *) value,
&len) == ERROR_SUCCESS ||
RegQueryValueExW(hSub, L"DhcpNameServer", 0, &type, (void *) value,
&len) == ERROR_SUCCESS)) {
/*
* See https://github.com/cesanta/mongoose/issues/176
* The value taken from the registry can be empty, a single
* IP address, or multiple IP addresses separated by comma.
* If it's empty, check the next interface.
* If it's multiple IP addresses, take the first one.
*/
wchar_t *comma = wcschr(value, ',');
if (value[0] == '\0') {
continue;
}
if (comma != NULL) {
*comma = '\0';
}
/* %S will convert wchar_t -> char */
snprintf(name, name_len, "%S", value);
ret = 0;
RegCloseKey(hSub);
break;
}
}
RegCloseKey(hKey);
}
#elif MG_ENABLE_FILESYSTEM
FILE *fp;
char line[512];
if ((fp = mg_fopen("/etc/resolv.conf", "r")) == NULL) {
ret = -1;
} else {
/* Try to figure out what nameserver to use */
for (ret = -1; fgets(line, sizeof(line), fp) != NULL;) {
unsigned int a, b, c, d;
if (sscanf(line, "nameserver %u.%u.%u.%u", &a, &b, &c, &d) == 4) {
snprintf(name, name_len, "%u.%u.%u.%u", a, b, c, d);
ret = 0;
break;
}
}
(void) fclose(fp);
}
#else
snprintf(name, name_len, "%s", MG_DEFAULT_NAMESERVER);
#endif /* _WIN32 */
return ret;
}
int mg_resolve_from_hosts_file(const char *name, union socket_address *usa) {
#if MG_ENABLE_FILESYSTEM
/* TODO(mkm) cache /etc/hosts */
FILE *fp;
char line[1024];
char *p;
char alias[256];
unsigned int a, b, c, d;
int len = 0;
if ((fp = mg_fopen("/etc/hosts", "r")) == NULL) {
return -1;
}
for (; fgets(line, sizeof(line), fp) != NULL;) {
if (line[0] == '#') continue;
if (sscanf(line, "%u.%u.%u.%u%n", &a, &b, &c, &d, &len) == 0) {
/* TODO(mkm): handle ipv6 */
continue;
}
for (p = line + len; sscanf(p, "%s%n", alias, &len) == 1; p += len) {
if (strcmp(alias, name) == 0) {
usa->sin.sin_addr.s_addr = htonl(a << 24 | b << 16 | c << 8 | d);
fclose(fp);
return 0;
}
}
}
fclose(fp);
#else
(void) name;
(void) usa;
#endif
return -1;
}
static void mg_resolve_async_eh(struct mg_connection *nc, int ev,
void *data MG_UD_ARG(void *user_data)) {
time_t now = (time_t) mg_time();
struct mg_resolve_async_request *req;
struct mg_dns_message *msg;
int first = 0;
#if !MG_ENABLE_CALLBACK_USERDATA
void *user_data = nc->user_data;
#endif
if (ev != MG_EV_POLL) DBG(("ev=%d user_data=%p", ev, user_data));
req = (struct mg_resolve_async_request *) user_data;
if (req == NULL) {
return;
}
switch (ev) {
case MG_EV_CONNECT:
/* don't depend on timer not being at epoch for sending out first req */
first = 1;
/* fallthrough */
case MG_EV_POLL:
if (req->retries > req->max_retries) {
req->err = MG_RESOLVE_EXCEEDED_RETRY_COUNT;
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
break;
}
if (first || now - req->last_time >= req->timeout) {
mg_send_dns_query(nc, req->name, req->query);
req->last_time = now;
req->retries++;
}
break;
case MG_EV_RECV:
msg = (struct mg_dns_message *) MG_MALLOC(sizeof(*msg));
if (mg_parse_dns(nc->recv_mbuf.buf, *(int *) data, msg) == 0 &&
msg->num_answers > 0) {
req->callback(msg, req->data, MG_RESOLVE_OK);
nc->user_data = NULL;
MG_FREE(req);
} else {
req->err = MG_RESOLVE_NO_ANSWERS;
}
MG_FREE(msg);
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
break;
case MG_EV_SEND:
/*
* If a send error occurs, prevent closing of the connection by the core.
* We will retry after timeout.
*/
nc->flags &= ~MG_F_CLOSE_IMMEDIATELY;
mbuf_remove(&nc->send_mbuf, nc->send_mbuf.len);
break;
case MG_EV_TIMER:
req->err = MG_RESOLVE_TIMEOUT;
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
break;
case MG_EV_CLOSE:
/* If we got here with request still not done, fire an error callback. */
if (req != NULL) {
req->callback(NULL, req->data, req->err);
nc->user_data = NULL;
MG_FREE(req);
}
break;
}
}
int mg_resolve_async(struct mg_mgr *mgr, const char *name, int query,
mg_resolve_callback_t cb, void *data) {
struct mg_resolve_async_opts opts;
memset(&opts, 0, sizeof(opts));
return mg_resolve_async_opt(mgr, name, query, cb, data, opts);
}
int mg_resolve_async_opt(struct mg_mgr *mgr, const char *name, int query,
mg_resolve_callback_t cb, void *data,
struct mg_resolve_async_opts opts) {
struct mg_resolve_async_request *req;
struct mg_connection *dns_nc;
const char *nameserver = opts.nameserver;
char dns_server_buff[17], nameserver_url[26];
if (nameserver == NULL) {
nameserver = mgr->nameserver;
}
DBG(("%s %d %p", name, query, opts.dns_conn));
/* resolve with DNS */
req = (struct mg_resolve_async_request *) MG_CALLOC(1, sizeof(*req));
if (req == NULL) {
return -1;
}
strncpy(req->name, name, sizeof(req->name));
req->query = query;
req->callback = cb;
req->data = data;
/* TODO(mkm): parse defaults out of resolve.conf */
req->max_retries = opts.max_retries ? opts.max_retries : 2;
req->timeout = opts.timeout ? opts.timeout : 5;
/* Lazily initialize dns server */
if (nameserver == NULL) {
if (mg_get_ip_address_of_nameserver(dns_server_buff,
sizeof(dns_server_buff)) != -1) {
nameserver = dns_server_buff;
} else {
nameserver = MG_DEFAULT_NAMESERVER;
}
}
snprintf(nameserver_url, sizeof(nameserver_url), "udp://%s:53", nameserver);
dns_nc = mg_connect(mgr, nameserver_url, MG_CB(mg_resolve_async_eh, NULL));
if (dns_nc == NULL) {
MG_FREE(req);
return -1;
}
dns_nc->user_data = req;
if (opts.dns_conn != NULL) {
*opts.dns_conn = dns_nc;
}
return 0;
}
void mg_set_nameserver(struct mg_mgr *mgr, const char *nameserver) {
MG_FREE((char *) mgr->nameserver);
if (nameserver != NULL) {
mgr->nameserver = strdup(nameserver);
}
}
#endif /* MG_ENABLE_ASYNC_RESOLVER */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/coap.c"
#endif
/*
* Copyright (c) 2015 Cesanta Software Limited
* All rights reserved
* This software is dual-licensed: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation. For the terms of this
* license, see <http://www.gnu.org/licenses/>.
*
* You are free to use this software under the terms of the GNU General
* Public License, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* Alternatively, you can license this software under a commercial
* license, as set out in <https://www.cesanta.com/license>.
*/
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/coap.h" */
#if MG_ENABLE_COAP
void mg_coap_free_options(struct mg_coap_message *cm) {
while (cm->options != NULL) {
struct mg_coap_option *next = cm->options->next;
MG_FREE(cm->options);
cm->options = next;
}
}
struct mg_coap_option *mg_coap_add_option(struct mg_coap_message *cm,
uint32_t number, char *value,
size_t len) {
struct mg_coap_option *new_option =
(struct mg_coap_option *) MG_CALLOC(1, sizeof(*new_option));
new_option->number = number;
new_option->value.p = value;
new_option->value.len = len;
if (cm->options == NULL) {
cm->options = cm->optiomg_tail = new_option;
} else {
/*
* A very simple attention to help clients to compose options:
* CoAP wants to see options ASC ordered.
* Could be change by using sort in coap_compose
*/
if (cm->optiomg_tail->number <= new_option->number) {
/* if option is already ordered just add it */
cm->optiomg_tail = cm->optiomg_tail->next = new_option;
} else {
/* looking for appropriate position */
struct mg_coap_option *current_opt = cm->options;
struct mg_coap_option *prev_opt = 0;
while (current_opt != NULL) {
if (current_opt->number > new_option->number) {
break;
}
prev_opt = current_opt;
current_opt = current_opt->next;
}
if (prev_opt != NULL) {
prev_opt->next = new_option;
new_option->next = current_opt;
} else {
/* insert new_option to the beginning */
new_option->next = cm->options;
cm->options = new_option;
}
}
}
return new_option;
}
/*
* Fills CoAP header in mg_coap_message.
*
* Helper function.
*/
static char *coap_parse_header(char *ptr, struct mbuf *io,
struct mg_coap_message *cm) {
if (io->len < sizeof(uint32_t)) {
cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
return NULL;
}
/*
* Version (Ver): 2-bit unsigned integer. Indicates the CoAP version
* number. Implementations of this specification MUST set this field
* to 1 (01 binary). Other values are reserved for future versions.
* Messages with unknown version numbers MUST be silently ignored.
*/
if (((uint8_t) *ptr >> 6) != 1) {
cm->flags |= MG_COAP_IGNORE;
return NULL;
}
/*
* Type (T): 2-bit unsigned integer. Indicates if this message is of
* type Confirmable (0), Non-confirmable (1), Acknowledgement (2), or
* Reset (3).
*/
cm->msg_type = ((uint8_t) *ptr & 0x30) >> 4;
cm->flags |= MG_COAP_MSG_TYPE_FIELD;
/*
* Token Length (TKL): 4-bit unsigned integer. Indicates the length of
* the variable-length Token field (0-8 bytes). Lengths 9-15 are
* reserved, MUST NOT be sent, and MUST be processed as a message
* format error.
*/
cm->token.len = *ptr & 0x0F;
if (cm->token.len > 8) {
cm->flags |= MG_COAP_FORMAT_ERROR;
return NULL;
}
ptr++;
/*
* Code: 8-bit unsigned integer, split into a 3-bit class (most
* significant bits) and a 5-bit detail (least significant bits)
*/
cm->code_class = (uint8_t) *ptr >> 5;
cm->code_detail = *ptr & 0x1F;
cm->flags |= (MG_COAP_CODE_CLASS_FIELD | MG_COAP_CODE_DETAIL_FIELD);
ptr++;
/* Message ID: 16-bit unsigned integer in network byte order. */
cm->msg_id = (uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1);
cm->flags |= MG_COAP_MSG_ID_FIELD;
ptr += 2;
return ptr;
}
/*
* Fills token information in mg_coap_message.
*
* Helper function.
*/
static char *coap_get_token(char *ptr, struct mbuf *io,
struct mg_coap_message *cm) {
if (cm->token.len != 0) {
if (ptr + cm->token.len > io->buf + io->len) {
cm->flags |= MG_COAP_NOT_ENOUGH_DATA;
return NULL;
} else {
cm->token.p = ptr;
ptr += cm->token.len;
cm->flags |= MG_COAP_TOKEN_FIELD;
}
}
return ptr;
}
/*
* Returns Option Delta or Length.
*
* Helper function.
*/
static int coap_get_ext_opt(char *ptr, struct mbuf *io, uint16_t *opt_info) {
int ret = 0;
if (*opt_info == 13) {
/*
* 13: An 8-bit unsigned integer follows the initial byte and
* indicates the Option Delta/Length minus 13.
*/
if (ptr < io->buf + io->len) {
*opt_info = (uint8_t) *ptr + 13;
ret = sizeof(uint8_t);
} else {
ret = -1; /* LCOV_EXCL_LINE */
}
} else if (*opt_info == 14) {
/*
* 14: A 16-bit unsigned integer in network byte order follows the
* initial byte and indicates the Option Delta/Length minus 269.
*/
if (ptr + sizeof(uint8_t) < io->buf + io->len) {
*opt_info = ((uint8_t) *ptr << 8 | (uint8_t) * (ptr + 1)) + 269;
ret = sizeof(uint16_t);
} else {
ret = -1; /* LCOV_EXCL_LINE */
}
}
return ret;
}
/*
* Fills options in mg_coap_message.
*
* Helper function.
*
* General options format:
* +---------------+---------------+
* | Option Delta | Option Length | 1 byte
* +---------------+---------------+
* \ Option Delta (extended) \ 0-2 bytes
* +-------------------------------+
* / Option Length (extended) \ 0-2 bytes
* +-------------------------------+
* \ Option Value \ 0 or more bytes
* +-------------------------------+
*/
static char *coap_get_options(char *ptr, struct mbuf *io,
struct mg_coap_message *cm) {
uint16_t prev_opt = 0;
if (ptr == io->buf + io->len) {
/* end of packet, ok */
return NULL;
}
/* 0xFF is payload marker */
while (ptr < io->buf + io->len && (uint8_t) *ptr != 0xFF) {
uint16_t option_delta, option_lenght;
int optinfo_len;
/* Option Delta: 4-bit unsigned integer */
option_delta = ((uint8_t) *ptr & 0xF0) >> 4;
/* Option Length: 4-bit unsigned integer */
option_lenght = *ptr & 0x0F;
if (option_delta == 15 || option_lenght == 15) {
/*
* 15: Reserved for future use. If the field is set to this value,
* it MUST be processed as a message format error
*/
cm->flags |= MG_COAP_FORMAT_ERROR;
break;
}
ptr++;
/* check for extended option delta */
optinfo_len = coap_get_ext_opt(ptr, io, &option_delta);
if (optinfo_len == -1) {
cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
break; /* LCOV_EXCL_LINE */
}
ptr += optinfo_len;
/* check or extended option lenght */
optinfo_len = coap_get_ext_opt(ptr, io, &option_lenght);
if (optinfo_len == -1) {
cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
break; /* LCOV_EXCL_LINE */
}
ptr += optinfo_len;
/*
* Instead of specifying the Option Number directly, the instances MUST
* appear in order of their Option Numbers and a delta encoding is used
* between them.
*/
option_delta += prev_opt;
mg_coap_add_option(cm, option_delta, ptr, option_lenght);
prev_opt = option_delta;
if (ptr + option_lenght > io->buf + io->len) {
cm->flags |= MG_COAP_NOT_ENOUGH_DATA; /* LCOV_EXCL_LINE */
break; /* LCOV_EXCL_LINE */
}
ptr += option_lenght;
}
if ((cm->flags & MG_COAP_ERROR) != 0) {
mg_coap_free_options(cm);
return NULL;
}
cm->flags |= MG_COAP_OPTIOMG_FIELD;
if (ptr == io->buf + io->len) {
/* end of packet, ok */
return NULL;
}
ptr++;
return ptr;
}
uint32_t mg_coap_parse(struct mbuf *io, struct mg_coap_message *cm) {
char *ptr;
memset(cm, 0, sizeof(*cm));
if ((ptr = coap_parse_header(io->buf, io, cm)) == NULL) {
return cm->flags;
}
if ((ptr = coap_get_token(ptr, io, cm)) == NULL) {
return cm->flags;
}
if ((ptr = coap_get_options(ptr, io, cm)) == NULL) {
return cm->flags;
}
/* the rest is payload */
cm->payload.len = io->len - (ptr - io->buf);
if (cm->payload.len != 0) {
cm->payload.p = ptr;
cm->flags |= MG_COAP_PAYLOAD_FIELD;
}
return cm->flags;
}
/*
* Calculates extended size of given Opt Number/Length in coap message.
*
* Helper function.
*/
static size_t coap_get_ext_opt_size(uint32_t value) {
int ret = 0;
if (value >= 13 && value <= 0xFF + 13) {
ret = sizeof(uint8_t);
} else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
ret = sizeof(uint16_t);
}
return ret;
}
/*
* Splits given Opt Number/Length into base and ext values.
*
* Helper function.
*/
static int coap_split_opt(uint32_t value, uint8_t *base, uint16_t *ext) {
int ret = 0;
if (value < 13) {
*base = value;
} else if (value >= 13 && value <= 0xFF + 13) {
*base = 13;
*ext = value - 13;
ret = sizeof(uint8_t);
} else if (value > 0xFF + 13 && value <= 0xFFFF + 269) {
*base = 14;
*ext = value - 269;
ret = sizeof(uint16_t);
}
return ret;
}
/*
* Puts uint16_t (in network order) into given char stream.
*
* Helper function.
*/
static char *coap_add_uint16(char *ptr, uint16_t val) {
*ptr = val >> 8;
ptr++;
*ptr = val & 0x00FF;
ptr++;
return ptr;
}
/*
* Puts extended value of Opt Number/Length into given char stream.
*
* Helper function.
*/
static char *coap_add_opt_info(char *ptr, uint16_t val, size_t len) {
if (len == sizeof(uint8_t)) {
*ptr = (char) val;
ptr++;
} else if (len == sizeof(uint16_t)) {
ptr = coap_add_uint16(ptr, val);
}
return ptr;
}
/*
* Verifies given mg_coap_message and calculates message size for it.
*
* Helper function.
*/
static uint32_t coap_calculate_packet_size(struct mg_coap_message *cm,
size_t *len) {
struct mg_coap_option *opt;
uint32_t prev_opt_number;
*len = 4; /* header */
if (cm->msg_type > MG_COAP_MSG_MAX) {
return MG_COAP_ERROR | MG_COAP_MSG_TYPE_FIELD;
}
if (cm->token.len > 8) {
return MG_COAP_ERROR | MG_COAP_TOKEN_FIELD;
}
if (cm->code_class > 7) {
return MG_COAP_ERROR | MG_COAP_CODE_CLASS_FIELD;
}
if (cm->code_detail > 31) {
return MG_COAP_ERROR | MG_COAP_CODE_DETAIL_FIELD;
}
*len += cm->token.len;
if (cm->payload.len != 0) {
*len += cm->payload.len + 1; /* ... + 1; add payload marker */
}
opt = cm->options;
prev_opt_number = 0;
while (opt != NULL) {
*len += 1; /* basic delta/length */
*len += coap_get_ext_opt_size(opt->number - prev_opt_number);
*len += coap_get_ext_opt_size((uint32_t) opt->value.len);
/*
* Current implementation performs check if
* option_number > previous option_number and produces an error
* TODO(alashkin): write design doc with limitations
* May be resorting is more suitable solution.
*/
if ((opt->next != NULL && opt->number > opt->next->number) ||
opt->value.len > 0xFFFF + 269 ||
opt->number - prev_opt_number > 0xFFFF + 269) {
return MG_COAP_ERROR | MG_COAP_OPTIOMG_FIELD;
}
*len += opt->value.len;
prev_opt_number = opt->number;
opt = opt->next;
}
return 0;
}
uint32_t mg_coap_compose(struct mg_coap_message *cm, struct mbuf *io) {
struct mg_coap_option *opt;
uint32_t res, prev_opt_number;
size_t prev_io_len, packet_size;
char *ptr;
res = coap_calculate_packet_size(cm, &packet_size);
if (res != 0) {
return res;
}
/* saving previous lenght to handle non-empty mbuf */
prev_io_len = io->len;
mbuf_append(io, NULL, packet_size);
ptr = io->buf + prev_io_len;
/*
* since cm is verified, it is possible to use bits shift operator
* without additional zeroing of unused bits
*/
/* ver: 2 bits, msg_type: 2 bits, toklen: 4 bits */
*ptr = (1 << 6) | (cm->msg_type << 4) | (uint8_t)(cm->token.len);
ptr++;
/* code class: 3 bits, code detail: 5 bits */
*ptr = (cm->code_class << 5) | (cm->code_detail);
ptr++;
ptr = coap_add_uint16(ptr, cm->msg_id);
if (cm->token.len != 0) {
memcpy(ptr, cm->token.p, cm->token.len);
ptr += cm->token.len;
}
opt = cm->options;
prev_opt_number = 0;
while (opt != NULL) {
uint8_t delta_base = 0, length_base = 0;
uint16_t delta_ext = 0, length_ext = 0;
size_t opt_delta_len =
coap_split_opt(opt->number - prev_opt_number, &delta_base, &delta_ext);
size_t opt_lenght_len =
coap_split_opt((uint32_t) opt->value.len, &length_base, &length_ext);
*ptr = (delta_base << 4) | length_base;
ptr++;
ptr = coap_add_opt_info(ptr, delta_ext, opt_delta_len);
ptr = coap_add_opt_info(ptr, length_ext, opt_lenght_len);
if (opt->value.len != 0) {
memcpy(ptr, opt->value.p, opt->value.len);
ptr += opt->value.len;
}
prev_opt_number = opt->number;
opt = opt->next;
}
if (cm->payload.len != 0) {
*ptr = (char) -1;
ptr++;
memcpy(ptr, cm->payload.p, cm->payload.len);
}
return 0;
}
uint32_t mg_coap_send_message(struct mg_connection *nc,
struct mg_coap_message *cm) {
struct mbuf packet_out;
uint32_t compose_res;
mbuf_init(&packet_out, 0);
compose_res = mg_coap_compose(cm, &packet_out);
if (compose_res != 0) {
return compose_res; /* LCOV_EXCL_LINE */
}
mg_send(nc, packet_out.buf, (int) packet_out.len);
mbuf_free(&packet_out);
return 0;
}
uint32_t mg_coap_send_ack(struct mg_connection *nc, uint16_t msg_id) {
struct mg_coap_message cm;
memset(&cm, 0, sizeof(cm));
cm.msg_type = MG_COAP_MSG_ACK;
cm.msg_id = msg_id;
return mg_coap_send_message(nc, &cm);
}
static void coap_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct mbuf *io = &nc->recv_mbuf;
struct mg_coap_message cm;
uint32_t parse_res;
memset(&cm, 0, sizeof(cm));
nc->handler(nc, ev, ev_data MG_UD_ARG(user_data));
switch (ev) {
case MG_EV_RECV:
parse_res = mg_coap_parse(io, &cm);
if ((parse_res & MG_COAP_IGNORE) == 0) {
if ((cm.flags & MG_COAP_NOT_ENOUGH_DATA) != 0) {
/*
* Since we support UDP only
* MG_COAP_NOT_ENOUGH_DATA == MG_COAP_FORMAT_ERROR
*/
cm.flags |= MG_COAP_FORMAT_ERROR; /* LCOV_EXCL_LINE */
} /* LCOV_EXCL_LINE */
nc->handler(nc, MG_COAP_EVENT_BASE + cm.msg_type,
&cm MG_UD_ARG(user_data));
}
mg_coap_free_options(&cm);
mbuf_remove(io, io->len);
break;
}
}
/*
* Attach built-in CoAP event handler to the given connection.
*
* The user-defined event handler will receive following extra events:
*
* - MG_EV_COAP_CON
* - MG_EV_COAP_NOC
* - MG_EV_COAP_ACK
* - MG_EV_COAP_RST
*/
int mg_set_protocol_coap(struct mg_connection *nc) {
/* supports UDP only */
if ((nc->flags & MG_F_UDP) == 0) {
return -1;
}
nc->proto_handler = coap_handler;
return 0;
}
#endif /* MG_ENABLE_COAP */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/tun.c"
#endif
/*
* Copyright (c) 2014 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_TUN
/* Amalgamated: #include "common/cs_dbg.h" */
/* Amalgamated: #include "mongoose/src/http.h" */
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/net.h" */
/* Amalgamated: #include "mongoose/src/net_if_tun.h" */
/* Amalgamated: #include "mongoose/src/tun.h" */
/* Amalgamated: #include "mongoose/src/util.h" */
static void mg_tun_reconnect(struct mg_tun_client *client, int timeout);
static void mg_tun_init_client(struct mg_tun_client *client, struct mg_mgr *mgr,
struct mg_iface *iface, const char *dispatcher,
struct mg_tun_ssl_opts ssl) {
client->mgr = mgr;
client->iface = iface;
client->disp_url = dispatcher;
client->last_stream_id = 0;
client->ssl = ssl;
client->disp = NULL; /* will be set by mg_tun_reconnect */
client->listener = NULL; /* will be set by mg_do_bind */
client->reconnect = NULL; /* will be set by mg_tun_reconnect */
}
void mg_tun_log_frame(struct mg_tun_frame *frame) {
LOG(LL_DEBUG, ("Got TUN frame: type=0x%x, flags=0x%x stream_id=0x%lx, "
"len=%zu",
frame->type, frame->flags, frame->stream_id, frame->body.len));
#if MG_ENABLE_HEXDUMP
{
char hex[512];
mg_hexdump(frame->body.p, frame->body.len, hex, sizeof(hex) - 1);
hex[sizeof(hex) - 1] = '\0';
LOG(LL_DEBUG, ("body:\n%s", hex));
}
#else
LOG(LL_DEBUG, ("body: '%.*s'", (int) frame->body.len, frame->body.p));
#endif
}
static void mg_tun_close_all(struct mg_tun_client *client) {
struct mg_connection *nc;
for (nc = client->mgr->active_connections; nc != NULL; nc = nc->next) {
if (nc->iface == client->iface && !(nc->flags & MG_F_LISTENING)) {
LOG(LL_DEBUG, ("Closing tunneled connection %p", nc));
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
/* mg_close_conn(nc); */
}
}
}
static void mg_tun_client_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
#if !MG_ENABLE_CALLBACK_USERDATA
void *user_data = nc->user_data;
#else
(void) nc;
#endif
struct mg_tun_client *client = (struct mg_tun_client *) user_data;
switch (ev) {
case MG_EV_CONNECT: {
int err = *(int *) ev_data;
if (err) {
LOG(LL_ERROR, ("Cannot connect to the tunnel dispatcher: %d", err));
} else {
LOG(LL_INFO, ("Connected to the tunnel dispatcher"));
}
break;
}
case MG_EV_HTTP_REPLY: {
struct http_message *hm = (struct http_message *) ev_data;
if (hm->resp_code != 200) {
LOG(LL_ERROR,
("Tunnel dispatcher reply non-OK status code %d", hm->resp_code));
}
break;
}
case MG_EV_WEBSOCKET_HANDSHAKE_DONE: {
LOG(LL_INFO, ("Tunnel dispatcher handshake done"));
break;
}
case MG_EV_WEBSOCKET_FRAME: {
struct websocket_message *wm = (struct websocket_message *) ev_data;
struct mg_connection *tc;
struct mg_tun_frame frame;
if (mg_tun_parse_frame(wm->data, wm->size, &frame) == -1) {
LOG(LL_ERROR, ("Got invalid tun frame dropping", wm->size));
break;
}
mg_tun_log_frame(&frame);
tc = mg_tun_if_find_conn(client, frame.stream_id);
if (tc == NULL) {
if (frame.body.len > 0) {
LOG(LL_DEBUG, ("Got frame after receiving end has been closed"));
}
break;
}
if (frame.body.len > 0) {
mg_if_recv_tcp_cb(tc, (void *) frame.body.p, frame.body.len,
0 /* own */);
}
if (frame.flags & MG_TUN_F_END_STREAM) {
LOG(LL_DEBUG, ("Closing tunneled connection because got end of stream "
"from other end"));
tc->flags |= MG_F_CLOSE_IMMEDIATELY;
mg_close_conn(tc);
}
break;
}
case MG_EV_CLOSE: {
LOG(LL_DEBUG, ("Closing all tunneled connections"));
/*
* The client might have been already freed when the listening socket is
* closed.
*/
if (client != NULL) {
mg_tun_close_all(client);
client->disp = NULL;
LOG(LL_INFO, ("Dispatcher connection is no more, reconnecting"));
/* TODO(mkm): implement exp back off */
mg_tun_reconnect(client, MG_TUN_RECONNECT_INTERVAL);
}
break;
}
default:
break;
}
}
static void mg_tun_do_reconnect(struct mg_tun_client *client) {
struct mg_connection *dc;
struct mg_connect_opts opts;
memset(&opts, 0, sizeof(opts));
#if MG_ENABLE_SSL
opts.ssl_cert = client->ssl.ssl_cert;
opts.ssl_key = client->ssl.ssl_key;
opts.ssl_ca_cert = client->ssl.ssl_ca_cert;
#endif
/* HTTP/Websocket listener */
if ((dc = mg_connect_ws_opt(client->mgr, MG_CB(mg_tun_client_handler, client),
opts, client->disp_url, MG_TUN_PROTO_NAME,
NULL)) == NULL) {
LOG(LL_ERROR,
("Cannot connect to WS server on addr [%s]\n", client->disp_url));
return;
}
client->disp = dc;
#if !MG_ENABLE_CALLBACK_USERDATA
dc->user_data = client;
#endif
}
void mg_tun_reconnect_ev_handler(struct mg_connection *nc, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
#if !MG_ENABLE_CALLBACK_USERDATA
void *user_data = nc->user_data;
#else
(void) nc;
#endif
struct mg_tun_client *client = (struct mg_tun_client *) user_data;
(void) ev_data;
switch (ev) {
case MG_EV_TIMER:
if (!(client->listener->flags & MG_F_TUN_DO_NOT_RECONNECT)) {
mg_tun_do_reconnect(client);
} else {
/* Reconnecting is suppressed, we'll check again at the next poll */
mg_tun_reconnect(client, 0);
}
break;
}
}
static void mg_tun_reconnect(struct mg_tun_client *client, int timeout) {
if (client->reconnect == NULL) {
client->reconnect = mg_add_sock(client->mgr, INVALID_SOCKET,
MG_CB(mg_tun_reconnect_ev_handler, client));
#if !MG_ENABLE_CALLBACK_USERDATA
client->reconnect->user_data = client;
#endif
}
client->reconnect->ev_timer_time = mg_time() + timeout;
}
static struct mg_tun_client *mg_tun_create_client(struct mg_mgr *mgr,
const char *dispatcher,
struct mg_tun_ssl_opts ssl) {
struct mg_tun_client *client = NULL;
struct mg_iface *iface = mg_find_iface(mgr, &mg_tun_iface_vtable, NULL);
if (iface == NULL) {
LOG(LL_ERROR, ("The tun feature requires the manager to have a tun "
"interface enabled"));
return NULL;
}
client = (struct mg_tun_client *) MG_MALLOC(sizeof(*client));
mg_tun_init_client(client, mgr, iface, dispatcher, ssl);
iface->data = client;
/*
* We need to give application a chance to set MG_F_TUN_DO_NOT_RECONNECT on a
* listening connection right after mg_tun_bind_opt() returned it, so we
* should use mg_tun_reconnect() here, instead of mg_tun_do_reconnect()
*/
mg_tun_reconnect(client, 0);
return client;
}
void mg_tun_destroy_client(struct mg_tun_client *client) {
/*
* NOTE:
* `client` is NULL in case of OOM
* `client->disp` is NULL if connection failed
* `client->iface is NULL is `mg_find_iface` failed
*/
if (client != NULL && client->disp != NULL) {
/* the dispatcher connection handler will in turn close all tunnels */
client->disp->flags |= MG_F_CLOSE_IMMEDIATELY;
/* this is used as a signal to other tun handlers that the party is over */
client->disp->user_data = NULL;
}
if (client != NULL && client->reconnect != NULL) {
client->reconnect->flags |= MG_F_CLOSE_IMMEDIATELY;
}
if (client != NULL && client->iface != NULL) {
client->iface->data = NULL;
}
MG_FREE(client);
}
static struct mg_connection *mg_tun_do_bind(struct mg_tun_client *client,
MG_CB(mg_event_handler_t handler,
void *user_data),
struct mg_bind_opts opts) {
struct mg_connection *lc;
opts.iface = client->iface;
lc = mg_bind_opt(client->mgr, ":1234" /* dummy port */,
MG_CB(handler, user_data), opts);
client->listener = lc;
return lc;
}
struct mg_connection *mg_tun_bind_opt(struct mg_mgr *mgr,
const char *dispatcher,
MG_CB(mg_event_handler_t handler,
void *user_data),
struct mg_bind_opts opts) {
#if MG_ENABLE_SSL
struct mg_tun_ssl_opts ssl = {opts.ssl_cert, opts.ssl_key, opts.ssl_ca_cert};
#else
struct mg_tun_ssl_opts ssl = {0};
#endif
struct mg_tun_client *client = mg_tun_create_client(mgr, dispatcher, ssl);
if (client == NULL) {
return NULL;
}
#if MG_ENABLE_SSL
/* these options don't make sense in the local mouth of the tunnel */
opts.ssl_cert = NULL;
opts.ssl_key = NULL;
opts.ssl_ca_cert = NULL;
#endif
return mg_tun_do_bind(client, MG_CB(handler, user_data), opts);
}
int mg_tun_parse_frame(void *data, size_t len, struct mg_tun_frame *frame) {
const size_t header_size = sizeof(uint32_t) + sizeof(uint8_t) * 2;
if (len < header_size) {
return -1;
}
frame->type = *(uint8_t *) (data);
frame->flags = *(uint8_t *) ((char *) data + 1);
memcpy(&frame->stream_id, (char *) data + 2, sizeof(uint32_t));
frame->stream_id = ntohl(frame->stream_id);
frame->body.p = (char *) data + header_size;
frame->body.len = len - header_size;
return 0;
}
void mg_tun_send_frame(struct mg_connection *ws, uint32_t stream_id,
uint8_t type, uint8_t flags, struct mg_str msg) {
stream_id = htonl(stream_id);
{
struct mg_str parts[] = {
{(char *) &type, sizeof(type)},
{(char *) &flags, sizeof(flags)},
{(char *) &stream_id, sizeof(stream_id)},
{msg.p, msg.len} /* vc6 doesn't like just `msg` here */};
mg_send_websocket_framev(ws, WEBSOCKET_OP_BINARY, parts,
sizeof(parts) / sizeof(parts[0]));
}
}
#endif /* MG_ENABLE_TUN */
#ifdef MG_MODULE_LINES
#line 1 "mongoose/src/sntp.c"
#endif
/*
* Copyright (c) 2016 Cesanta Software Limited
* All rights reserved
*/
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/sntp.h" */
/* Amalgamated: #include "mongoose/src/util.h" */
#if MG_ENABLE_SNTP
#define SNTP_TIME_OFFSET 2208988800
#ifndef SNTP_TIMEOUT
#define SNTP_TIMEOUT 10
#endif
#ifndef SNTP_ATTEMPTS
#define SNTP_ATTEMPTS 3
#endif
static uint64_t mg_get_sec(uint64_t val) {
return (val & 0xFFFFFFFF00000000) >> 32;
}
static uint64_t mg_get_usec(uint64_t val) {
uint64_t tmp = (val & 0x00000000FFFFFFFF);
tmp *= 1000000;
tmp >>= 32;
return tmp;
}
static void mg_ntp_to_tv(uint64_t val, struct timeval *tv) {
uint64_t tmp;
tmp = mg_get_sec(val);
tmp -= SNTP_TIME_OFFSET;
tv->tv_sec = tmp;
tv->tv_usec = mg_get_usec(val);
}
static void mg_get_ntp_ts(const char *ntp, uint64_t *val) {
uint32_t tmp;
memcpy(&tmp, ntp, sizeof(tmp));
tmp = ntohl(tmp);
*val = (uint64_t) tmp << 32;
memcpy(&tmp, ntp + 4, sizeof(tmp));
tmp = ntohl(tmp);
*val |= tmp;
}
void mg_sntp_send_request(struct mg_connection *c) {
char buf[48] = {0};
/*
* header - 8 bit:
* LI (2 bit) - 3 (not in sync), VN (3 bit) - 4 (version),
* mode (3 bit) - 3 (client)
*/
buf[0] = (3 << 6) | (4 << 3) | 3;
/*
* Next fields should be empty in client request
* stratum, 8 bit
* poll interval, 8 bit
* rrecision, 8 bit
* root delay, 32 bit
* root dispersion, 32 bit
* ref id, 32 bit
* ref timestamp, 64 bit
* originate Timestamp, 64 bit
* receive Timestamp, 64 bit
*/
/*
* convert time to sntp format (sntp starts from 00:00:00 01.01.1900)
* according to rfc868 it is 2208988800L sec
* this information is used to correct roundtrip delay
* but if local clock is absolutely broken (and doesn't work even
* as simple timer), it is better to disable it
*/
#ifndef MG_SNMP_NO_DELAY_CORRECTION
uint32_t sec;
sec = htonl((uint32_t)(mg_time() + SNTP_TIME_OFFSET));
memcpy(&buf[40], &sec, sizeof(sec));
#endif
mg_send(c, buf, sizeof(buf));
}
#ifndef MG_SNMP_NO_DELAY_CORRECTION
static uint64_t mg_calculate_delay(uint64_t t1, uint64_t t2, uint64_t t3) {
/* roundloop delay = (T4 - T1) - (T3 - T2) */
uint64_t d1 = ((mg_time() + SNTP_TIME_OFFSET) * 1000000) -
(mg_get_sec(t1) * 1000000 + mg_get_usec(t1));
uint64_t d2 = (mg_get_sec(t3) * 1000000 + mg_get_usec(t3)) -
(mg_get_sec(t2) * 1000000 + mg_get_usec(t2));
return (d1 > d2) ? d1 - d2 : 0;
}
#endif
MG_INTERNAL int mg_sntp_parse_reply(const char *buf, int len,
struct mg_sntp_message *msg) {
uint8_t hdr;
uint64_t orig_ts_T1, recv_ts_T2, trsm_ts_T3, delay = 0;
int mode;
struct timeval tv;
(void) orig_ts_T1;
(void) recv_ts_T2;
if (len < 48) {
return -1;
}
hdr = buf[0];
if ((hdr & 0x38) >> 3 != 4) {
/* Wrong version */
return -1;
}
mode = hdr & 0x7;
if (mode != 4 && mode != 5) {
/* Not a server reply */
return -1;
}
memset(msg, 0, sizeof(*msg));
msg->kiss_of_death = (buf[1] == 0); /* Server asks to not send requests */
mg_get_ntp_ts(&buf[40], &trsm_ts_T3);
#ifndef MG_SNMP_NO_DELAY_CORRECTION
mg_get_ntp_ts(&buf[24], &orig_ts_T1);
mg_get_ntp_ts(&buf[32], &recv_ts_T2);
delay = mg_calculate_delay(orig_ts_T1, recv_ts_T2, trsm_ts_T3);
#endif
mg_ntp_to_tv(trsm_ts_T3, &tv);
msg->time = (double) tv.tv_sec + (((double) tv.tv_usec + delay) / 1000000.0);
return 0;
}
static void mg_sntp_handler(struct mg_connection *c, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
struct mbuf *io = &c->recv_mbuf;
struct mg_sntp_message msg;
c->handler(c, ev, ev_data MG_UD_ARG(user_data));
switch (ev) {
case MG_EV_RECV: {
if (mg_sntp_parse_reply(io->buf, io->len, &msg) < 0) {
DBG(("Invalid SNTP packet received (%d)", (int) io->len));
c->handler(c, MG_SNTP_MALFORMED_REPLY, NULL MG_UD_ARG(user_data));
} else {
c->handler(c, MG_SNTP_REPLY, (void *) &msg MG_UD_ARG(user_data));
}
mbuf_remove(io, io->len);
break;
}
}
}
int mg_set_protocol_sntp(struct mg_connection *c) {
if ((c->flags & MG_F_UDP) == 0) {
return -1;
}
c->proto_handler = mg_sntp_handler;
return 0;
}
struct mg_connection *mg_sntp_connect(struct mg_mgr *mgr,
MG_CB(mg_event_handler_t event_handler,
void *user_data),
const char *sntp_server_name) {
struct mg_connection *c = NULL;
char url[100], *p_url = url;
const char *proto = "", *port = "", *tmp;
/* If port is not specified, use default (123) */
tmp = strchr(sntp_server_name, ':');
if (tmp != NULL && *(tmp + 1) == '/') {
tmp = strchr(tmp + 1, ':');
}
if (tmp == NULL) {
port = ":123";
}
/* Add udp:// if needed */
if (strncmp(sntp_server_name, "udp://", 6) != 0) {
proto = "udp://";
}
mg_asprintf(&p_url, sizeof(url), "%s%s%s", proto, sntp_server_name, port);
c = mg_connect(mgr, p_url, event_handler MG_UD_ARG(user_data));
if (c == NULL) {
goto cleanup;
}
mg_set_protocol_sntp(c);
cleanup:
if (p_url != url) {
MG_FREE(p_url);
}
return c;
}
struct sntp_data {
mg_event_handler_t hander;
int count;
};
static void mg_sntp_util_ev_handler(struct mg_connection *c, int ev,
void *ev_data MG_UD_ARG(void *user_data)) {
#if !MG_ENABLE_CALLBACK_USERDATA
void *user_data = c->user_data;
#endif
struct sntp_data *sd = (struct sntp_data *) user_data;
switch (ev) {
case MG_EV_CONNECT:
if (*(int *) ev_data != 0) {
mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
break;
}
/* fallthrough */
case MG_EV_TIMER:
if (sd->count <= SNTP_ATTEMPTS) {
mg_sntp_send_request(c);
mg_set_timer(c, mg_time() + 10);
sd->count++;
} else {
mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
c->flags |= MG_F_CLOSE_IMMEDIATELY;
}
break;
case MG_SNTP_MALFORMED_REPLY:
mg_call(c, sd->hander, c->user_data, MG_SNTP_FAILED, NULL);
c->flags |= MG_F_CLOSE_IMMEDIATELY;
break;
case MG_SNTP_REPLY:
mg_call(c, sd->hander, c->user_data, MG_SNTP_REPLY, ev_data);
c->flags |= MG_F_CLOSE_IMMEDIATELY;
break;
case MG_EV_CLOSE:
MG_FREE(user_data);
c->user_data = NULL;
break;
}
}
struct mg_connection *mg_sntp_get_time(struct mg_mgr *mgr,
mg_event_handler_t event_handler,
const char *sntp_server_name) {
struct mg_connection *c;
struct sntp_data *sd = (struct sntp_data *) MG_CALLOC(1, sizeof(*sd));
if (sd == NULL) {
return NULL;
}
c = mg_sntp_connect(mgr, MG_CB(mg_sntp_util_ev_handler, sd),
sntp_server_name);
if (c == NULL) {
MG_FREE(sd);
return NULL;
}
sd->hander = event_handler;
#if !MG_ENABLE_CALLBACK_USERDATA
c->user_data = sd;
#endif
return c;
}
#endif /* MG_ENABLE_SNTP */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/cc3200/cc3200_libc.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if CS_PLATFORM == CS_P_CC3200
/* Amalgamated: #include "common/mg_mem.h" */
#include <stdio.h>
#include <string.h>
#ifndef __TI_COMPILER_VERSION__
#include <reent.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#endif
#include <inc/hw_types.h>
#include <inc/hw_memmap.h>
#include <driverlib/prcm.h>
#include <driverlib/rom.h>
#include <driverlib/rom_map.h>
#include <driverlib/uart.h>
#include <driverlib/utils.h>
#define CONSOLE_UART UARTA0_BASE
#ifdef __TI_COMPILER_VERSION__
int asprintf(char **strp, const char *fmt, ...) {
va_list ap;
int len;
*strp = MG_MALLOC(BUFSIZ);
if (*strp == NULL) return -1;
va_start(ap, fmt);
len = vsnprintf(*strp, BUFSIZ, fmt, ap);
va_end(ap);
if (len > 0) {
*strp = MG_REALLOC(*strp, len + 1);
if (*strp == NULL) return -1;
}
if (len >= BUFSIZ) {
va_start(ap, fmt);
len = vsnprintf(*strp, len + 1, fmt, ap);
va_end(ap);
}
return len;
}
#if MG_TI_NO_HOST_INTERFACE
time_t HOSTtime() {
struct timeval tp;
gettimeofday(&tp, NULL);
return tp.tv_sec;
}
#endif
#endif /* __TI_COMPILER_VERSION__ */
#ifndef __TI_COMPILER_VERSION__
int _gettimeofday_r(struct _reent *r, struct timeval *tp, void *tzp) {
#else
int gettimeofday(struct timeval *tp, void *tzp) {
#endif
unsigned long long r1 = 0, r2;
/* Achieve two consecutive reads of the same value. */
do {
r2 = r1;
r1 = PRCMSlowClkCtrFastGet();
} while (r1 != r2);
/* This is a 32768 Hz counter. */
tp->tv_sec = (r1 >> 15);
/* 1/32768-th of a second is 30.517578125 microseconds, approx. 31,
* but we round down so it doesn't overflow at 32767 */
tp->tv_usec = (r1 & 0x7FFF) * 30;
return 0;
}
void fprint_str(FILE *fp, const char *str) {
while (*str != '\0') {
if (*str == '\n') MAP_UARTCharPut(CONSOLE_UART, '\r');
MAP_UARTCharPut(CONSOLE_UART, *str++);
}
}
void _exit(int status) {
fprint_str(stderr, "_exit\n");
/* cause an unaligned access exception, that will drop you into gdb */
*(int *) 1 = status;
while (1)
; /* avoid gcc warning because stdlib abort() has noreturn attribute */
}
void _not_implemented(const char *what) {
fprint_str(stderr, what);
fprint_str(stderr, " is not implemented\n");
_exit(42);
}
int _kill(int pid, int sig) {
(void) pid;
(void) sig;
_not_implemented("_kill");
return -1;
}
int _getpid() {
fprint_str(stderr, "_getpid is not implemented\n");
return 42;
}
int _isatty(int fd) {
/* 0, 1 and 2 are TTYs. */
return fd < 2;
}
#endif /* CS_PLATFORM == CS_P_CC3200 */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/msp432/msp432_libc.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if CS_PLATFORM == CS_P_MSP432
#include <ti/sysbios/BIOS.h>
#include <ti/sysbios/knl/Clock.h>
int gettimeofday(struct timeval *tp, void *tzp) {
uint32_t ticks = Clock_getTicks();
tp->tv_sec = ticks / 1000;
tp->tv_usec = (ticks % 1000) * 1000;
return 0;
}
#endif /* CS_PLATFORM == CS_P_MSP432 */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/nrf5/nrf5_libc.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if (CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52) && \
defined(__ARMCC_VERSION)
int gettimeofday(struct timeval *tp, void *tzp) {
/* TODO */
tp->tv_sec = 0;
tp->tv_usec = 0;
return 0;
}
#endif
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/simplelink/sl_fs_slfs.h"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_
#if defined(MG_FS_SLFS)
#include <stdio.h>
#ifndef __TI_COMPILER_VERSION__
#include <unistd.h>
#include <sys/stat.h>
#endif
#define MAX_OPEN_SLFS_FILES 8
/* Indirect libc interface - same functions, different names. */
int fs_slfs_open(const char *pathname, int flags, mode_t mode);
int fs_slfs_close(int fd);
ssize_t fs_slfs_read(int fd, void *buf, size_t count);
ssize_t fs_slfs_write(int fd, const void *buf, size_t count);
int fs_slfs_stat(const char *pathname, struct stat *s);
int fs_slfs_fstat(int fd, struct stat *s);
off_t fs_slfs_lseek(int fd, off_t offset, int whence);
int fs_slfs_unlink(const char *filename);
int fs_slfs_rename(const char *from, const char *to);
void fs_slfs_set_new_file_size(const char *name, size_t size);
#endif /* defined(MG_FS_SLFS) */
#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_FS_SLFS_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/simplelink/sl_fs_slfs.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
/* Standard libc interface to TI SimpleLink FS. */
#if defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS)
/* Amalgamated: #include "common/platforms/simplelink/sl_fs_slfs.h" */
#include <errno.h>
#if CS_PLATFORM == CS_P_CC3200
#include <inc/hw_types.h>
#endif
#include <simplelink/include/simplelink.h>
#include <simplelink/include/fs.h>
/* Amalgamated: #include "common/cs_dbg.h" */
/* Amalgamated: #include "common/mg_mem.h" */
/* From sl_fs.c */
extern int set_errno(int e);
static const char *drop_dir(const char *fname, bool *is_slfs);
/*
* With SLFS, you have to pre-declare max file size. Yes. Really.
* 64K should be enough for everyone. Right?
*/
#ifndef FS_SLFS_MAX_FILE_SIZE
#define FS_SLFS_MAX_FILE_SIZE (64 * 1024)
#endif
struct sl_file_size_hint {
char *name;
size_t size;
};
struct sl_fd_info {
_i32 fh;
_off_t pos;
size_t size;
};
static struct sl_fd_info s_sl_fds[MAX_OPEN_SLFS_FILES];
static struct sl_file_size_hint s_sl_file_size_hints[MAX_OPEN_SLFS_FILES];
static int sl_fs_to_errno(_i32 r) {
DBG(("SL error: %d", (int) r));
switch (r) {
case SL_FS_OK:
return 0;
case SL_FS_FILE_NAME_EXIST:
return EEXIST;
case SL_FS_WRONG_FILE_NAME:
return EINVAL;
case SL_FS_ERR_NO_AVAILABLE_NV_INDEX:
case SL_FS_ERR_NO_AVAILABLE_BLOCKS:
return ENOSPC;
case SL_FS_ERR_FAILED_TO_ALLOCATE_MEM:
return ENOMEM;
case SL_FS_ERR_FILE_NOT_EXISTS:
return ENOENT;
case SL_FS_ERR_NOT_SUPPORTED:
return ENOTSUP;
}
return ENXIO;
}
int fs_slfs_open(const char *pathname, int flags, mode_t mode) {
int fd;
for (fd = 0; fd < MAX_OPEN_SLFS_FILES; fd++) {
if (s_sl_fds[fd].fh <= 0) break;
}
if (fd >= MAX_OPEN_SLFS_FILES) return set_errno(ENOMEM);
struct sl_fd_info *fi = &s_sl_fds[fd];
/*
* Apply path manipulations again, in case we got here directly
* (via TI libc's "add_device").
*/
pathname = drop_dir(pathname, NULL);
_u32 am = 0;
fi->size = (size_t) -1;
int rw = (flags & 3);
if (rw == O_RDONLY) {
SlFsFileInfo_t sl_fi;
_i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
if (r == SL_FS_OK) {
fi->size = sl_fi.FileLen;
}
am = FS_MODE_OPEN_READ;
} else {
if (!(flags & O_TRUNC) || (flags & O_APPEND)) {
// FailFS files cannot be opened for append and will be truncated
// when opened for write.
return set_errno(ENOTSUP);
}
if (flags & O_CREAT) {
size_t i, size = FS_SLFS_MAX_FILE_SIZE;
for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
if (s_sl_file_size_hints[i].name != NULL &&
strcmp(s_sl_file_size_hints[i].name, pathname) == 0) {
size = s_sl_file_size_hints[i].size;
MG_FREE(s_sl_file_size_hints[i].name);
s_sl_file_size_hints[i].name = NULL;
break;
}
}
DBG(("creating %s with max size %d", pathname, (int) size));
am = FS_MODE_OPEN_CREATE(size, 0);
} else {
am = FS_MODE_OPEN_WRITE;
}
}
_i32 r = sl_FsOpen((_u8 *) pathname, am, NULL, &fi->fh);
DBG(("sl_FsOpen(%s, 0x%x) = %d, %d", pathname, (int) am, (int) r,
(int) fi->fh));
if (r == SL_FS_OK) {
fi->pos = 0;
r = fd;
} else {
fi->fh = -1;
r = set_errno(sl_fs_to_errno(r));
}
return r;
}
int fs_slfs_close(int fd) {
struct sl_fd_info *fi = &s_sl_fds[fd];
if (fi->fh <= 0) return set_errno(EBADF);
_i32 r = sl_FsClose(fi->fh, NULL, NULL, 0);
DBG(("sl_FsClose(%d) = %d", (int) fi->fh, (int) r));
s_sl_fds[fd].fh = -1;
return set_errno(sl_fs_to_errno(r));
}
ssize_t fs_slfs_read(int fd, void *buf, size_t count) {
struct sl_fd_info *fi = &s_sl_fds[fd];
if (fi->fh <= 0) return set_errno(EBADF);
/* Simulate EOF. sl_FsRead @ file_size return SL_FS_ERR_OFFSET_OUT_OF_RANGE.
*/
if (fi->pos == fi->size) return 0;
_i32 r = sl_FsRead(fi->fh, fi->pos, buf, count);
DBG(("sl_FsRead(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
(int) r));
if (r >= 0) {
fi->pos += r;
return r;
}
return set_errno(sl_fs_to_errno(r));
}
ssize_t fs_slfs_write(int fd, const void *buf, size_t count) {
struct sl_fd_info *fi = &s_sl_fds[fd];
if (fi->fh <= 0) return set_errno(EBADF);
_i32 r = sl_FsWrite(fi->fh, fi->pos, (_u8 *) buf, count);
DBG(("sl_FsWrite(%d, %d, %d) = %d", (int) fi->fh, (int) fi->pos, (int) count,
(int) r));
if (r >= 0) {
fi->pos += r;
return r;
}
return set_errno(sl_fs_to_errno(r));
}
int fs_slfs_stat(const char *pathname, struct stat *s) {
SlFsFileInfo_t sl_fi;
/*
* Apply path manipulations again, in case we got here directly
* (via TI libc's "add_device").
*/
pathname = drop_dir(pathname, NULL);
_i32 r = sl_FsGetInfo((const _u8 *) pathname, 0, &sl_fi);
if (r == SL_FS_OK) {
s->st_mode = S_IFREG | 0666;
s->st_nlink = 1;
s->st_size = sl_fi.FileLen;
return 0;
}
return set_errno(sl_fs_to_errno(r));
}
int fs_slfs_fstat(int fd, struct stat *s) {
struct sl_fd_info *fi = &s_sl_fds[fd];
if (fi->fh <= 0) return set_errno(EBADF);
s->st_mode = 0666;
s->st_mode = S_IFREG | 0666;
s->st_nlink = 1;
s->st_size = fi->size;
return 0;
}
off_t fs_slfs_lseek(int fd, off_t offset, int whence) {
if (s_sl_fds[fd].fh <= 0) return set_errno(EBADF);
switch (whence) {
case SEEK_SET:
s_sl_fds[fd].pos = offset;
break;
case SEEK_CUR:
s_sl_fds[fd].pos += offset;
break;
case SEEK_END:
return set_errno(ENOTSUP);
}
return 0;
}
int fs_slfs_unlink(const char *pathname) {
/*
* Apply path manipulations again, in case we got here directly
* (via TI libc's "add_device").
*/
pathname = drop_dir(pathname, NULL);
return set_errno(sl_fs_to_errno(sl_FsDel((const _u8 *) pathname, 0)));
}
int fs_slfs_rename(const char *from, const char *to) {
return set_errno(ENOTSUP);
}
void fs_slfs_set_new_file_size(const char *name, size_t size) {
int i;
for (i = 0; i < MAX_OPEN_SLFS_FILES; i++) {
if (s_sl_file_size_hints[i].name == NULL) {
DBG(("File size hint: %s %d", name, (int) size));
s_sl_file_size_hints[i].name = strdup(name);
s_sl_file_size_hints[i].size = size;
break;
}
}
}
#endif /* defined(MG_FS_SLFS) || defined(CC3200_FS_SLFS) */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/simplelink/sl_fs.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_NET_IF == MG_NET_IF_SIMPLELINK && \
(defined(MG_FS_SLFS) || defined(MG_FS_SPIFFS))
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __TI_COMPILER_VERSION__
#include <file.h>
#endif
/* Amalgamated: #include "common/cs_dbg.h" */
/* Amalgamated: #include "common/platform.h" */
#ifdef CC3200_FS_SPIFFS
/* Amalgamated: #include "cc3200_fs_spiffs.h" */
#endif
#ifdef MG_FS_SLFS
/* Amalgamated: #include "sl_fs_slfs.h" */
#endif
#define NUM_SYS_FDS 3
#define SPIFFS_FD_BASE 10
#define SLFS_FD_BASE 100
#ifndef MG_UART_CHAR_PUT
#if CS_PLATFORM == CS_P_CC3200
#include <inc/hw_types.h>
#include <inc/hw_memmap.h>
#include <driverlib/rom.h>
#include <driverlib/rom_map.h>
#include <driverlib/uart.h>
#define MG_UART_CHAR_PUT(fd, c) MAP_UARTCharPut(UARTA0_BASE, c);
#else
#define MG_UART_CHAR_PUT(fd, c)
#endif /* CS_PLATFORM == CS_P_CC3200 */
#endif /* !MG_UART_CHAR_PUT */
int set_errno(int e) {
errno = e;
return (e == 0 ? 0 : -1);
}
static const char *drop_dir(const char *fname, bool *is_slfs) {
if (is_slfs != NULL) {
*is_slfs = (strncmp(fname, "SL:", 3) == 0);
if (*is_slfs) fname += 3;
}
/* Drop "./", if any */
if (fname[0] == '.' && fname[1] == '/') {
fname += 2;
}
/*
* Drop / if it is the only one in the path.
* This allows use of /pretend/directories but serves /file.txt as normal.
*/
if (fname[0] == '/' && strchr(fname + 1, '/') == NULL) {
fname++;
}
return fname;
}
enum fd_type {
FD_INVALID,
FD_SYS,
#ifdef CC3200_FS_SPIFFS
FD_SPIFFS,
#endif
#ifdef MG_FS_SLFS
FD_SLFS
#endif
};
static int fd_type(int fd) {
if (fd >= 0 && fd < NUM_SYS_FDS) return FD_SYS;
#ifdef CC3200_FS_SPIFFS
if (fd >= SPIFFS_FD_BASE && fd < SPIFFS_FD_BASE + MAX_OPEN_SPIFFS_FILES) {
return FD_SPIFFS;
}
#endif
#ifdef MG_FS_SLFS
if (fd >= SLFS_FD_BASE && fd < SLFS_FD_BASE + MAX_OPEN_SLFS_FILES) {
return FD_SLFS;
}
#endif
return FD_INVALID;
}
#if MG_TI_NO_HOST_INTERFACE
int open(const char *pathname, unsigned flags, int mode) {
#else
int _open(const char *pathname, int flags, mode_t mode) {
#endif
int fd = -1;
bool is_sl;
const char *fname = drop_dir(pathname, &is_sl);
if (is_sl) {
#ifdef MG_FS_SLFS
fd = fs_slfs_open(fname, flags, mode);
if (fd >= 0) fd += SLFS_FD_BASE;
#endif
} else {
#ifdef CC3200_FS_SPIFFS
fd = fs_spiffs_open(fname, flags, mode);
if (fd >= 0) fd += SPIFFS_FD_BASE;
#endif
}
LOG(LL_DEBUG,
("open(%s, 0x%x) = %d, fname = %s", pathname, flags, fd, fname));
return fd;
}
int _stat(const char *pathname, struct stat *st) {
int res = -1;
bool is_sl;
const char *fname = drop_dir(pathname, &is_sl);
memset(st, 0, sizeof(*st));
/* Simulate statting the root directory. */
if (fname[0] == '\0' || strcmp(fname, ".") == 0) {
st->st_ino = 0;
st->st_mode = S_IFDIR | 0777;
st->st_nlink = 1;
st->st_size = 0;
return 0;
}
if (is_sl) {
#ifdef MG_FS_SLFS
res = fs_slfs_stat(fname, st);
#endif
} else {
#ifdef CC3200_FS_SPIFFS
res = fs_spiffs_stat(fname, st);
#endif
}
LOG(LL_DEBUG, ("stat(%s) = %d; fname = %s", pathname, res, fname));
return res;
}
#if MG_TI_NO_HOST_INTERFACE
int close(int fd) {
#else
int _close(int fd) {
#endif
int r = -1;
switch (fd_type(fd)) {
case FD_INVALID:
r = set_errno(EBADF);
break;
case FD_SYS:
r = set_errno(EACCES);
break;
#ifdef CC3200_FS_SPIFFS
case FD_SPIFFS:
r = fs_spiffs_close(fd - SPIFFS_FD_BASE);
break;
#endif
#ifdef MG_FS_SLFS
case FD_SLFS:
r = fs_slfs_close(fd - SLFS_FD_BASE);
break;
#endif
}
DBG(("close(%d) = %d", fd, r));
return r;
}
#if MG_TI_NO_HOST_INTERFACE
off_t lseek(int fd, off_t offset, int whence) {
#else
off_t _lseek(int fd, off_t offset, int whence) {
#endif
int r = -1;
switch (fd_type(fd)) {
case FD_INVALID:
r = set_errno(EBADF);
break;
case FD_SYS:
r = set_errno(ESPIPE);
break;
#ifdef CC3200_FS_SPIFFS
case FD_SPIFFS:
r = fs_spiffs_lseek(fd - SPIFFS_FD_BASE, offset, whence);
break;
#endif
#ifdef MG_FS_SLFS
case FD_SLFS:
r = fs_slfs_lseek(fd - SLFS_FD_BASE, offset, whence);
break;
#endif
}
DBG(("lseek(%d, %d, %d) = %d", fd, (int) offset, whence, r));
return r;
}
int _fstat(int fd, struct stat *s) {
int r = -1;
memset(s, 0, sizeof(*s));
switch (fd_type(fd)) {
case FD_INVALID:
r = set_errno(EBADF);
break;
case FD_SYS: {
/* Create barely passable stats for STD{IN,OUT,ERR}. */
memset(s, 0, sizeof(*s));
s->st_ino = fd;
s->st_mode = S_IFCHR | 0666;
r = 0;
break;
}
#ifdef CC3200_FS_SPIFFS
case FD_SPIFFS:
r = fs_spiffs_fstat(fd - SPIFFS_FD_BASE, s);
break;
#endif
#ifdef MG_FS_SLFS
case FD_SLFS:
r = fs_slfs_fstat(fd - SLFS_FD_BASE, s);
break;
#endif
}
DBG(("fstat(%d) = %d", fd, r));
return r;
}
#if MG_TI_NO_HOST_INTERFACE
int read(int fd, char *buf, unsigned count) {
#else
ssize_t _read(int fd, void *buf, size_t count) {
#endif
int r = -1;
switch (fd_type(fd)) {
case FD_INVALID:
r = set_errno(EBADF);
break;
case FD_SYS: {
if (fd != 0) {
r = set_errno(EACCES);
break;
}
/* Should we allow reading from stdin = uart? */
r = set_errno(ENOTSUP);
break;
}
#ifdef CC3200_FS_SPIFFS
case FD_SPIFFS:
r = fs_spiffs_read(fd - SPIFFS_FD_BASE, buf, count);
break;
#endif
#ifdef MG_FS_SLFS
case FD_SLFS:
r = fs_slfs_read(fd - SLFS_FD_BASE, buf, count);
break;
#endif
}
DBG(("read(%d, %u) = %d", fd, count, r));
return r;
}
#if MG_TI_NO_HOST_INTERFACE
int write(int fd, const char *buf, unsigned count) {
#else
ssize_t _write(int fd, const void *buf, size_t count) {
#endif
int r = -1;
size_t i = 0;
switch (fd_type(fd)) {
case FD_INVALID:
r = set_errno(EBADF);
break;
case FD_SYS: {
if (fd == 0) {
r = set_errno(EACCES);
break;
}
for (i = 0; i < count; i++) {
const char c = ((const char *) buf)[i];
if (c == '\n') MG_UART_CHAR_PUT(fd, '\r');
MG_UART_CHAR_PUT(fd, c);
}
r = count;
break;
}
#ifdef CC3200_FS_SPIFFS
case FD_SPIFFS:
r = fs_spiffs_write(fd - SPIFFS_FD_BASE, buf, count);
break;
#endif
#ifdef MG_FS_SLFS
case FD_SLFS:
r = fs_slfs_write(fd - SLFS_FD_BASE, buf, count);
break;
#endif
}
return r;
}
/*
* On Newlib we override rename directly too, because the default
* implementation using _link and _unlink doesn't work for us.
*/
#if MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION)
int rename(const char *frompath, const char *topath) {
int r = -1;
bool is_sl_from, is_sl_to;
const char *from = drop_dir(frompath, &is_sl_from);
const char *to = drop_dir(topath, &is_sl_to);
if (is_sl_from || is_sl_to) {
set_errno(ENOTSUP);
} else {
#ifdef CC3200_FS_SPIFFS
r = fs_spiffs_rename(from, to);
#endif
}
DBG(("rename(%s, %s) = %d", from, to, r));
return r;
}
#endif /* MG_TI_NO_HOST_INTERFACE || defined(_NEWLIB_VERSION) */
#if MG_TI_NO_HOST_INTERFACE
int unlink(const char *pathname) {
#else
int _unlink(const char *pathname) {
#endif
int r = -1;
bool is_sl;
const char *fname = drop_dir(pathname, &is_sl);
if (is_sl) {
#ifdef MG_FS_SLFS
r = fs_slfs_unlink(fname);
#endif
} else {
#ifdef CC3200_FS_SPIFFS
r = fs_spiffs_unlink(fname);
#endif
}
DBG(("unlink(%s) = %d, fname = %s", pathname, r, fname));
return r;
}
#ifdef CC3200_FS_SPIFFS /* FailFS does not support listing files. */
DIR *opendir(const char *dir_name) {
DIR *r = NULL;
bool is_sl;
drop_dir(dir_name, &is_sl);
if (is_sl) {
r = NULL;
set_errno(ENOTSUP);
} else {
r = fs_spiffs_opendir(dir_name);
}
DBG(("opendir(%s) = %p", dir_name, r));
return r;
}
struct dirent *readdir(DIR *dir) {
struct dirent *res = fs_spiffs_readdir(dir);
DBG(("readdir(%p) = %p", dir, res));
return res;
}
int closedir(DIR *dir) {
int res = fs_spiffs_closedir(dir);
DBG(("closedir(%p) = %d", dir, res));
return res;
}
int rmdir(const char *path) {
return fs_spiffs_rmdir(path);
}
int mkdir(const char *path, mode_t mode) {
(void) path;
(void) mode;
/* for spiffs supports only root dir, which comes from mongoose as '.' */
return (strlen(path) == 1 && *path == '.') ? 0 : ENOTDIR;
}
#endif
int sl_fs_init(void) {
int ret = 1;
#ifdef __TI_COMPILER_VERSION__
#ifdef MG_FS_SLFS
#pragma diag_push
#pragma diag_suppress 169 /* Nothing we can do about the prototype mismatch. \
*/
ret = (add_device("SL", _MSA, fs_slfs_open, fs_slfs_close, fs_slfs_read,
fs_slfs_write, fs_slfs_lseek, fs_slfs_unlink,
fs_slfs_rename) == 0);
#pragma diag_pop
#endif
#endif
return ret;
}
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && (defined(MG_FS_SLFS) || \
defined(MG_FS_SPIFFS)) */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/simplelink/sl_socket.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_NET_IF == MG_NET_IF_SIMPLELINK
#include <errno.h>
#include <stdio.h>
/* Amalgamated: #include "common/platform.h" */
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
int res;
struct in_addr *in = (struct in_addr *) src;
if (af != AF_INET) {
errno = EAFNOSUPPORT;
return NULL;
}
res = snprintf(dst, size, "%lu.%lu.%lu.%lu", SL_IPV4_BYTE(in->s_addr, 0),
SL_IPV4_BYTE(in->s_addr, 1), SL_IPV4_BYTE(in->s_addr, 2),
SL_IPV4_BYTE(in->s_addr, 3));
return res > 0 ? dst : NULL;
}
char *inet_ntoa(struct in_addr n) {
static char a[16];
return (char *) inet_ntop(AF_INET, &n, a, sizeof(a));
}
int inet_pton(int af, const char *src, void *dst) {
uint32_t a0, a1, a2, a3;
uint8_t *db = (uint8_t *) dst;
if (af != AF_INET) {
errno = EAFNOSUPPORT;
return 0;
}
if (sscanf(src, "%lu.%lu.%lu.%lu", &a0, &a1, &a2, &a3) != 4) {
return 0;
}
*db = a3;
*(db + 1) = a2;
*(db + 2) = a1;
*(db + 3) = a0;
return 1;
}
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/simplelink/sl_mg_task.c"
#endif
#if MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI)
/* Amalgamated: #include "mg_task.h" */
#include <oslib/osi.h>
enum mg_q_msg_type {
MG_Q_MSG_CB,
};
struct mg_q_msg {
enum mg_q_msg_type type;
void (*cb)(struct mg_mgr *mgr, void *arg);
void *arg;
};
static OsiMsgQ_t s_mg_q;
static void mg_task(void *arg);
bool mg_start_task(int priority, int stack_size, mg_init_cb mg_init) {
if (osi_MsgQCreate(&s_mg_q, "MG", sizeof(struct mg_q_msg), 16) != OSI_OK) {
return false;
}
if (osi_TaskCreate(mg_task, (const signed char *) "MG", stack_size,
(void *) mg_init, priority, NULL) != OSI_OK) {
return false;
}
return true;
}
static void mg_task(void *arg) {
struct mg_mgr mgr;
mg_init_cb mg_init = (mg_init_cb) arg;
mg_mgr_init(&mgr, NULL);
mg_init(&mgr);
while (1) {
struct mg_q_msg msg;
mg_mgr_poll(&mgr, 1);
if (osi_MsgQRead(&s_mg_q, &msg, 1) != OSI_OK) continue;
switch (msg.type) {
case MG_Q_MSG_CB: {
msg.cb(&mgr, msg.arg);
}
}
}
}
void mg_run_in_task(void (*cb)(struct mg_mgr *mgr, void *arg), void *cb_arg) {
struct mg_q_msg msg = {MG_Q_MSG_CB, cb, cb_arg};
osi_MsgQWrite(&s_mg_q, &msg, OSI_NO_WAIT);
}
#endif /* MG_NET_IF == MG_NET_IF_SIMPLELINK && !defined(MG_SIMPLELINK_NO_OSI) \
*/
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/simplelink/sl_net_if.h"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#ifndef CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
#define CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_
/* Amalgamated: #include "mongoose/src/net_if.h" */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#ifndef MG_ENABLE_NET_IF_SIMPLELINK
#define MG_ENABLE_NET_IF_SIMPLELINK MG_NET_IF == MG_NET_IF_SIMPLELINK
#endif
extern const struct mg_iface_vtable mg_simplelink_iface_vtable;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_COMMON_PLATFORMS_SIMPLELINK_SL_NET_IF_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/simplelink/sl_net_if.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
/* Amalgamated: #include "common/platforms/simplelink/sl_net_if.h" */
#if MG_ENABLE_NET_IF_SIMPLELINK
/* Amalgamated: #include "mongoose/src/internal.h" */
/* Amalgamated: #include "mongoose/src/util.h" */
#define MG_TCP_RECV_BUFFER_SIZE 1024
#define MG_UDP_RECV_BUFFER_SIZE 1500
static sock_t mg_open_listening_socket(union socket_address *sa, int type,
int proto);
int sl_set_ssl_opts(struct mg_connection *nc);
void mg_set_non_blocking_mode(sock_t sock) {
SlSockNonblocking_t opt;
opt.NonblockingEnabled = 1;
sl_SetSockOpt(sock, SL_SOL_SOCKET, SL_SO_NONBLOCKING, &opt, sizeof(opt));
}
static int mg_is_error(int n) {
return (n < 0 && n != SL_EALREADY && n != SL_EAGAIN);
}
void mg_sl_if_connect_tcp(struct mg_connection *nc,
const union socket_address *sa) {
int proto = 0;
if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
sock_t sock = sl_Socket(AF_INET, SOCK_STREAM, proto);
if (sock < 0) {
nc->err = sock;
goto out;
}
mg_sock_set(nc, sock);
#if MG_ENABLE_SSL
nc->err = sl_set_ssl_opts(nc);
if (nc->err != 0) goto out;
#endif
nc->err = sl_Connect(sock, &sa->sa, sizeof(sa->sin));
out:
DBG(("%p to %s:%d sock %d %d err %d", nc, inet_ntoa(sa->sin.sin_addr),
ntohs(sa->sin.sin_port), nc->sock, proto, nc->err));
}
void mg_sl_if_connect_udp(struct mg_connection *nc) {
sock_t sock = sl_Socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
nc->err = sock;
return;
}
mg_sock_set(nc, sock);
nc->err = 0;
}
int mg_sl_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
int proto = 0;
if (nc->flags & MG_F_SSL) proto = SL_SEC_SOCKET;
sock_t sock = mg_open_listening_socket(sa, SOCK_STREAM, proto);
if (sock < 0) return sock;
mg_sock_set(nc, sock);
#if MG_ENABLE_SSL
return sl_set_ssl_opts(nc);
#else
return 0;
#endif
}
int mg_sl_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
sock_t sock = mg_open_listening_socket(sa, SOCK_DGRAM, 0);
if (sock == INVALID_SOCKET) return (errno ? errno : 1);
mg_sock_set(nc, sock);
return 0;
}
void mg_sl_if_tcp_send(struct mg_connection *nc, const void *buf, size_t len) {
mbuf_append(&nc->send_mbuf, buf, len);
}
void mg_sl_if_udp_send(struct mg_connection *nc, const void *buf, size_t len) {
mbuf_append(&nc->send_mbuf, buf, len);
}
void mg_sl_if_recved(struct mg_connection *nc, size_t len) {
(void) nc;
(void) len;
}
int mg_sl_if_create_conn(struct mg_connection *nc) {
(void) nc;
return 1;
}
void mg_sl_if_destroy_conn(struct mg_connection *nc) {
if (nc->sock == INVALID_SOCKET) return;
/* For UDP, only close outgoing sockets or listeners. */
if (!(nc->flags & MG_F_UDP) || nc->listener == NULL) {
sl_Close(nc->sock);
}
nc->sock = INVALID_SOCKET;
}
static int mg_accept_conn(struct mg_connection *lc) {
struct mg_connection *nc;
union socket_address sa;
socklen_t sa_len = sizeof(sa);
sock_t sock = sl_Accept(lc->sock, &sa.sa, &sa_len);
if (sock < 0) {
DBG(("%p: failed to accept: %d", lc, sock));
return 0;
}
nc = mg_if_accept_new_conn(lc);
if (nc == NULL) {
sl_Close(sock);
return 0;
}
DBG(("%p conn from %s:%d", nc, inet_ntoa(sa.sin.sin_addr),
ntohs(sa.sin.sin_port)));
mg_sock_set(nc, sock);
if (nc->flags & MG_F_SSL) nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
mg_if_accept_tcp_cb(nc, &sa, sa_len);
return 1;
}
/* 'sa' must be an initialized address to bind to */
static sock_t mg_open_listening_socket(union socket_address *sa, int type,
int proto) {
int r;
socklen_t sa_len =
(sa->sa.sa_family == AF_INET) ? sizeof(sa->sin) : sizeof(sa->sin6);
sock_t sock = sl_Socket(sa->sa.sa_family, type, proto);
if (sock < 0) return sock;
if ((r = sl_Bind(sock, &sa->sa, sa_len)) < 0) {
sl_Close(sock);
return r;
}
if (type != SOCK_DGRAM && (r = sl_Listen(sock, SOMAXCONN)) < 0) {
sl_Close(sock);
return r;
}
mg_set_non_blocking_mode(sock);
return sock;
}
static void mg_write_to_socket(struct mg_connection *nc) {
struct mbuf *io = &nc->send_mbuf;
int n = 0;
if (nc->flags & MG_F_UDP) {
n = sl_SendTo(nc->sock, io->buf, io->len, 0, &nc->sa.sa,
sizeof(nc->sa.sin));
DBG(("%p %d %d %d %s:%hu", nc, nc->sock, n, errno,
inet_ntoa(nc->sa.sin.sin_addr), ntohs(nc->sa.sin.sin_port)));
} else {
n = (int) sl_Send(nc->sock, io->buf, io->len, 0);
DBG(("%p %d bytes -> %d", nc, n, nc->sock));
}
if (n > 0) {
mbuf_remove(io, n);
mg_if_sent_cb(nc, n);
} else if (n < 0 && mg_is_error(n)) {
/* Something went wrong, drop the connection. */
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
}
MG_INTERNAL size_t recv_avail_size(struct mg_connection *conn, size_t max) {
size_t avail;
if (conn->recv_mbuf_limit < conn->recv_mbuf.len) return 0;
avail = conn->recv_mbuf_limit - conn->recv_mbuf.len;
return avail > max ? max : avail;
}
static void mg_handle_tcp_read(struct mg_connection *conn) {
int n = 0;
char *buf = (char *) MG_MALLOC(MG_TCP_RECV_BUFFER_SIZE);
if (buf == NULL) {
DBG(("OOM"));
return;
}
n = (int) sl_Recv(conn->sock, buf,
recv_avail_size(conn, MG_TCP_RECV_BUFFER_SIZE), 0);
DBG(("%p %d bytes <- %d", conn, n, conn->sock));
if (n > 0) {
mg_if_recv_tcp_cb(conn, buf, n, 1 /* own */);
} else {
MG_FREE(buf);
}
if (n == 0) {
/* Orderly shutdown of the socket, try flushing output. */
conn->flags |= MG_F_SEND_AND_CLOSE;
} else if (mg_is_error(n)) {
conn->flags |= MG_F_CLOSE_IMMEDIATELY;
}
}
static void mg_handle_udp_read(struct mg_connection *nc) {
char *buf = (char *) MG_MALLOC(MG_UDP_RECV_BUFFER_SIZE);
if (buf == NULL) return;
union socket_address sa;
socklen_t sa_len = sizeof(sa);
int n = sl_RecvFrom(nc->sock, buf, MG_UDP_RECV_BUFFER_SIZE, 0,
(SlSockAddr_t *) &sa, &sa_len);
DBG(("%p %d bytes from %s:%d", nc, n, inet_ntoa(nc->sa.sin.sin_addr),
ntohs(nc->sa.sin.sin_port)));
if (n > 0) {
mg_if_recv_udp_cb(nc, buf, n, &sa, sa_len);
} else {
MG_FREE(buf);
}
}
#define _MG_F_FD_CAN_READ 1
#define _MG_F_FD_CAN_WRITE 1 << 1
#define _MG_F_FD_ERROR 1 << 2
void mg_mgr_handle_conn(struct mg_connection *nc, int fd_flags, double now) {
DBG(("%p fd=%d fd_flags=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock,
fd_flags, nc->flags, (int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
if (nc->flags & MG_F_CONNECTING) {
if (nc->flags & MG_F_UDP || nc->err != SL_EALREADY) {
mg_if_connect_cb(nc, nc->err);
} else {
/* In SimpleLink, to get status of non-blocking connect() we need to wait
* until socket is writable and repeat the call to sl_Connect again,
* which will now return the real status. */
if (fd_flags & _MG_F_FD_CAN_WRITE) {
nc->err = sl_Connect(nc->sock, &nc->sa.sa, sizeof(nc->sa.sin));
DBG(("%p conn res=%d", nc, nc->err));
if (nc->err == SL_ESECSNOVERIFY ||
/* TODO(rojer): Provide API to set the date for verification. */
nc->err == SL_ESECDATEERROR) {
nc->err = 0;
}
if (nc->flags & MG_F_SSL && nc->err == 0) {
nc->flags |= MG_F_SSL_HANDSHAKE_DONE;
}
mg_if_connect_cb(nc, nc->err);
}
}
/* Ignore read/write in further processing, we've handled it. */
fd_flags &= ~(_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE);
}
if (fd_flags & _MG_F_FD_CAN_READ) {
if (nc->flags & MG_F_UDP) {
mg_handle_udp_read(nc);
} else {
if (nc->flags & MG_F_LISTENING) {
mg_accept_conn(nc);
} else {
mg_handle_tcp_read(nc);
}
}
}
if (!(nc->flags & MG_F_CLOSE_IMMEDIATELY)) {
if ((fd_flags & _MG_F_FD_CAN_WRITE) && nc->send_mbuf.len > 0) {
mg_write_to_socket(nc);
}
if (!(fd_flags & (_MG_F_FD_CAN_READ | _MG_F_FD_CAN_WRITE))) {
mg_if_poll(nc, now);
}
mg_if_timer(nc, now);
}
DBG(("%p after fd=%d nc_flags=%lu rmbl=%d smbl=%d", nc, nc->sock, nc->flags,
(int) nc->recv_mbuf.len, (int) nc->send_mbuf.len));
}
/* Associate a socket to a connection. */
void mg_sl_if_sock_set(struct mg_connection *nc, sock_t sock) {
mg_set_non_blocking_mode(sock);
nc->sock = sock;
DBG(("%p %d", nc, sock));
}
void mg_sl_if_init(struct mg_iface *iface) {
(void) iface;
DBG(("%p using sl_Select()", iface->mgr));
}
void mg_sl_if_free(struct mg_iface *iface) {
(void) iface;
}
void mg_sl_if_add_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_sl_if_remove_conn(struct mg_connection *nc) {
(void) nc;
}
time_t mg_sl_if_poll(struct mg_iface *iface, int timeout_ms) {
struct mg_mgr *mgr = iface->mgr;
double now = mg_time();
double min_timer;
struct mg_connection *nc, *tmp;
struct SlTimeval_t tv;
SlFdSet_t read_set, write_set, err_set;
sock_t max_fd = INVALID_SOCKET;
int num_fds, num_ev = 0, num_timers = 0;
SL_FD_ZERO(&read_set);
SL_FD_ZERO(&write_set);
SL_FD_ZERO(&err_set);
/*
* Note: it is ok to have connections with sock == INVALID_SOCKET in the list,
* e.g. timer-only "connections".
*/
min_timer = 0;
for (nc = mgr->active_connections, num_fds = 0; nc != NULL; nc = tmp) {
tmp = nc->next;
if (nc->sock != INVALID_SOCKET) {
num_fds++;
if (!(nc->flags & MG_F_WANT_WRITE) &&
nc->recv_mbuf.len < nc->recv_mbuf_limit &&
(!(nc->flags & MG_F_UDP) || nc->listener == NULL)) {
SL_FD_SET(nc->sock, &read_set);
if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
}
if (((nc->flags & MG_F_CONNECTING) && !(nc->flags & MG_F_WANT_READ)) ||
(nc->send_mbuf.len > 0 && !(nc->flags & MG_F_CONNECTING))) {
SL_FD_SET(nc->sock, &write_set);
SL_FD_SET(nc->sock, &err_set);
if (max_fd == INVALID_SOCKET || nc->sock > max_fd) max_fd = nc->sock;
}
}
if (nc->ev_timer_time > 0) {
if (num_timers == 0 || nc->ev_timer_time < min_timer) {
min_timer = nc->ev_timer_time;
}
num_timers++;
}
}
/*
* If there is a timer to be fired earlier than the requested timeout,
* adjust the timeout.
*/
if (num_timers > 0) {
double timer_timeout_ms = (min_timer - mg_time()) * 1000 + 1 /* rounding */;
if (timer_timeout_ms < timeout_ms) {
timeout_ms = timer_timeout_ms;
}
}
if (timeout_ms < 0) timeout_ms = 0;
tv.tv_sec = timeout_ms / 1000;
tv.tv_usec = (timeout_ms % 1000) * 1000;
if (num_fds > 0) {
num_ev = sl_Select((int) max_fd + 1, &read_set, &write_set, &err_set, &tv);
}
now = mg_time();
DBG(("sl_Select @ %ld num_ev=%d of %d, timeout=%d", (long) now, num_ev,
num_fds, timeout_ms));
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
int fd_flags = 0;
if (nc->sock != INVALID_SOCKET) {
if (num_ev > 0) {
fd_flags =
(SL_FD_ISSET(nc->sock, &read_set) &&
(!(nc->flags & MG_F_UDP) || nc->listener == NULL)
? _MG_F_FD_CAN_READ
: 0) |
(SL_FD_ISSET(nc->sock, &write_set) ? _MG_F_FD_CAN_WRITE : 0) |
(SL_FD_ISSET(nc->sock, &err_set) ? _MG_F_FD_ERROR : 0);
}
/* SimpleLink does not report UDP sockets as writable. */
if (nc->flags & MG_F_UDP && nc->send_mbuf.len > 0) {
fd_flags |= _MG_F_FD_CAN_WRITE;
}
}
tmp = nc->next;
mg_mgr_handle_conn(nc, fd_flags, now);
}
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
tmp = nc->next;
if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
(nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
mg_close_conn(nc);
}
}
return now;
}
void mg_sl_if_get_conn_addr(struct mg_connection *nc, int remote,
union socket_address *sa) {
/* SimpleLink does not provide a way to get socket's peer address after
* accept or connect. Address should have been preserved in the connection,
* so we do our best here by using it. */
if (remote) memcpy(sa, &nc->sa, sizeof(*sa));
}
void sl_restart_cb(struct mg_mgr *mgr) {
/*
* SimpleLink has been restarted, meaning all sockets have been invalidated.
* We try our best - we'll restart the listeners, but for outgoing
* connections we have no option but to terminate.
*/
struct mg_connection *nc;
for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
if (nc->sock == INVALID_SOCKET) continue; /* Could be a timer */
if (nc->flags & MG_F_LISTENING) {
DBG(("restarting %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
ntohs(nc->sa.sin.sin_port)));
int res = (nc->flags & MG_F_UDP ? mg_sl_if_listen_udp(nc, &nc->sa)
: mg_sl_if_listen_tcp(nc, &nc->sa));
if (res == 0) continue;
/* Well, we tried and failed. Fall through to closing. */
}
nc->sock = INVALID_SOCKET;
DBG(("terminating %p %s:%d", nc, inet_ntoa(nc->sa.sin.sin_addr),
ntohs(nc->sa.sin.sin_port)));
/* TODO(rojer): Outgoing UDP? */
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
}
}
/* clang-format off */
#define MG_SL_IFACE_VTABLE \
{ \
mg_sl_if_init, \
mg_sl_if_free, \
mg_sl_if_add_conn, \
mg_sl_if_remove_conn, \
mg_sl_if_poll, \
mg_sl_if_listen_tcp, \
mg_sl_if_listen_udp, \
mg_sl_if_connect_tcp, \
mg_sl_if_connect_udp, \
mg_sl_if_tcp_send, \
mg_sl_if_udp_send, \
mg_sl_if_recved, \
mg_sl_if_create_conn, \
mg_sl_if_destroy_conn, \
mg_sl_if_sock_set, \
mg_sl_if_get_conn_addr, \
}
/* clang-format on */
const struct mg_iface_vtable mg_simplelink_iface_vtable = MG_SL_IFACE_VTABLE;
#if MG_NET_IF == MG_NET_IF_SIMPLELINK
const struct mg_iface_vtable mg_default_iface_vtable = MG_SL_IFACE_VTABLE;
#endif
#endif /* MG_ENABLE_NET_IF_SIMPLELINK */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/simplelink/sl_ssl_if.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK
/* Amalgamated: #include "common/mg_mem.h" */
struct mg_ssl_if_ctx {
char *ssl_cert;
char *ssl_key;
char *ssl_ca_cert;
char *ssl_server_name;
};
void mg_ssl_if_init() {
}
enum mg_ssl_if_result mg_ssl_if_conn_init(
struct mg_connection *nc, const struct mg_ssl_if_conn_params *params,
const char **err_msg) {
struct mg_ssl_if_ctx *ctx =
(struct mg_ssl_if_ctx *) MG_CALLOC(1, sizeof(*ctx));
if (ctx == NULL) {
MG_SET_PTRPTR(err_msg, "Out of memory");
return MG_SSL_ERROR;
}
nc->ssl_if_data = ctx;
if (params->cert != NULL || params->key != NULL) {
if (params->cert != NULL && params->key != NULL) {
ctx->ssl_cert = strdup(params->cert);
ctx->ssl_key = strdup(params->key);
} else {
MG_SET_PTRPTR(err_msg, "Both cert and key are required.");
return MG_SSL_ERROR;
}
}
if (params->ca_cert != NULL && strcmp(params->ca_cert, "*") != 0) {
ctx->ssl_ca_cert = strdup(params->ca_cert);
}
/* TODO(rojer): cipher_suites. */
if (params->server_name != NULL) {
ctx->ssl_server_name = strdup(params->server_name);
}
return MG_SSL_OK;
}
void mg_ssl_if_conn_close_notify(struct mg_connection *nc) {
/* Nothing to do */
(void) nc;
}
void mg_ssl_if_conn_free(struct mg_connection *nc) {
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
if (ctx == NULL) return;
nc->ssl_if_data = NULL;
MG_FREE(ctx->ssl_cert);
MG_FREE(ctx->ssl_key);
MG_FREE(ctx->ssl_ca_cert);
MG_FREE(ctx->ssl_server_name);
memset(ctx, 0, sizeof(*ctx));
MG_FREE(ctx);
}
bool pem_to_der(const char *pem_file, const char *der_file) {
bool ret = false;
FILE *pf = NULL, *df = NULL;
bool writing = false;
pf = fopen(pem_file, "r");
if (pf == NULL) goto clean;
remove(der_file);
fs_slfs_set_new_file_size(der_file + 3, 2048);
df = fopen(der_file, "w");
if (df == NULL) goto clean;
while (1) {
char pem_buf[70];
char der_buf[48];
if (!fgets(pem_buf, sizeof(pem_buf), pf)) break;
if (writing) {
if (strstr(pem_buf, "-----END ") != NULL) {
ret = true;
break;
}
int l = 0;
while (!isspace((unsigned int) pem_buf[l])) l++;
int der_len = 0;
cs_base64_decode((const unsigned char *) pem_buf, sizeof(pem_buf),
der_buf, &der_len);
if (der_len <= 0) break;
if (fwrite(der_buf, 1, der_len, df) != der_len) break;
} else if (strstr(pem_buf, "-----BEGIN ") != NULL) {
writing = true;
}
}
clean:
if (pf != NULL) fclose(pf);
if (df != NULL) {
fclose(df);
if (!ret) remove(der_file);
}
return ret;
}
#if MG_ENABLE_FILESYSTEM && defined(MG_FS_SLFS)
/* If the file's extension is .pem, convert it to DER format and put on SLFS. */
static char *sl_pem2der(const char *pem_file) {
const char *pem_ext = strstr(pem_file, ".pem");
if (pem_ext == NULL || *(pem_ext + 4) != '\0') {
return strdup(pem_file);
}
char *der_file = NULL;
/* DER file must be located on SLFS, add prefix. */
int l = mg_asprintf(&der_file, 0, "SL:%.*s.der", (int) (pem_ext - pem_file),
pem_file);
if (der_file == NULL) return NULL;
bool result = false;
cs_stat_t st;
if (mg_stat(der_file, &st) != 0) {
result = pem_to_der(pem_file, der_file);
LOG(LL_DEBUG, ("%s -> %s = %d", pem_file, der_file, result));
} else {
/* File exists, assume it's already been converted. */
result = true;
}
if (result) {
/* Strip the SL: prefix we added since NWP does not expect it. */
memmove(der_file, der_file + 3, l - 2 /* including \0 */);
} else {
MG_FREE(der_file);
der_file = NULL;
}
return der_file;
}
#else
static char *sl_pem2der(const char *pem_file) {
return strdup(pem_file);
}
#endif
int sl_set_ssl_opts(struct mg_connection *nc) {
int err;
struct mg_ssl_if_ctx *ctx = (struct mg_ssl_if_ctx *) nc->ssl_if_data;
DBG(("%p ssl ctx: %p", nc, ctx));
if (ctx != NULL) {
DBG(("%p %s,%s,%s,%s", nc, (ctx->ssl_cert ? ctx->ssl_cert : "-"),
(ctx->ssl_key ? ctx->ssl_cert : "-"),
(ctx->ssl_ca_cert ? ctx->ssl_ca_cert : "-"),
(ctx->ssl_server_name ? ctx->ssl_server_name : "-")));
if (ctx->ssl_cert != NULL && ctx->ssl_key != NULL) {
char *ssl_cert = sl_pem2der(ctx->ssl_cert);
char *ssl_key = sl_pem2der(ctx->ssl_key);
if (ssl_cert != NULL && ssl_key != NULL) {
err = sl_SetSockOpt(nc->sock, SL_SOL_SOCKET,
SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME, ssl_cert,
strlen(ssl_cert));
LOG(LL_INFO, ("CERTIFICATE_FILE_NAME %s -> %d", ssl_cert, err));
err = sl_SetSockOpt(nc->sock, SL_SOL_SOCKET,
SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME, ssl_key,
strlen(ssl_key));
LOG(LL_INFO, ("PRIVATE_KEY_FILE_NAME %s -> %d", ssl_key, err));
} else {
err = -1;
}
MG_FREE(ssl_cert);
MG_FREE(ssl_key);
if (err != 0) return err;
}
if (ctx->ssl_ca_cert != NULL) {
if (ctx->ssl_ca_cert[0] != '\0') {
char *ssl_ca_cert = sl_pem2der(ctx->ssl_ca_cert);
if (ssl_ca_cert != NULL) {
err = sl_SetSockOpt(nc->sock, SL_SOL_SOCKET,
SL_SO_SECURE_FILES_CA_FILE_NAME, ssl_ca_cert,
strlen(ssl_ca_cert));
LOG(LL_INFO, ("CA_FILE_NAME %s -> %d", ssl_ca_cert, err));
} else {
err = -1;
}
MG_FREE(ssl_ca_cert);
if (err != 0) return err;
}
}
if (ctx->ssl_server_name != NULL) {
err = sl_SetSockOpt(nc->sock, SL_SOL_SOCKET,
SO_SECURE_DOMAIN_NAME_VERIFICATION,
ctx->ssl_server_name, strlen(ctx->ssl_server_name));
DBG(("DOMAIN_NAME_VERIFICATION %s -> %d", ctx->ssl_server_name, err));
/* Domain name verificationw as added in a NWP service pack, older
* versions return SL_ENOPROTOOPT. There isn't much we can do about it,
* so we ignore the error. */
if (err != 0 && err != SL_ENOPROTOOPT) return err;
}
}
return 0;
}
#endif /* MG_ENABLE_SSL && MG_SSL_IF == MG_SSL_IF_SIMPLELINK */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/lwip/mg_lwip_net_if.h"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#ifndef CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
#define CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_
#ifndef MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
#define MG_ENABLE_NET_IF_LWIP_LOW_LEVEL MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
#endif
#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
#include <stdint.h>
extern const struct mg_iface_vtable mg_lwip_iface_vtable;
struct mg_lwip_conn_state {
struct mg_connection *nc;
struct mg_connection *lc;
union {
struct tcp_pcb *tcp;
struct udp_pcb *udp;
} pcb;
err_t err;
size_t num_sent; /* Number of acknowledged bytes to be reported to the core */
struct pbuf *rx_chain; /* Chain of incoming data segments. */
size_t rx_offset; /* Offset within the first pbuf (if partially consumed) */
/* Last SSL write size, for retries. */
int last_ssl_write_size;
/* Whether MG_SIG_RECV is already pending for this connection */
int recv_pending;
};
enum mg_sig_type {
MG_SIG_CONNECT_RESULT = 1,
MG_SIG_RECV = 2,
MG_SIG_SENT_CB = 3,
MG_SIG_CLOSE_CONN = 4,
MG_SIG_TOMBSTONE = 5,
MG_SIG_ACCEPT = 6,
};
void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc);
/* To be implemented by the platform. */
void mg_lwip_mgr_schedule_poll(struct mg_mgr *mgr);
#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
#endif /* CS_COMMON_PLATFORMS_LWIP_MG_NET_IF_LWIP_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/lwip/mg_lwip_net_if.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_NET_IF_LWIP_LOW_LEVEL
/* Amalgamated: #include "common/mg_mem.h" */
#include <lwip/pbuf.h>
#include <lwip/tcp.h>
#if CS_PLATFORM != CS_P_STM32
#include <lwip/tcp_impl.h>
#endif
#include <lwip/udp.h>
/* Amalgamated: #include "common/cs_dbg.h" */
/*
* Depending on whether Mongoose is compiled with ipv6 support, use right
* lwip functions
*/
#if MG_ENABLE_IPV6
#define TCP_NEW tcp_new_ip6
#define TCP_BIND tcp_bind_ip6
#define UDP_BIND udp_bind_ip6
#define IPADDR_NTOA(x) ip6addr_ntoa((const ip6_addr_t *)(x))
#define SET_ADDR(dst, src) \
memcpy((dst)->sin6.sin6_addr.s6_addr, (src)->ip6.addr, \
sizeof((dst)->sin6.sin6_addr.s6_addr))
#else
#define TCP_NEW tcp_new
#define TCP_BIND tcp_bind
#define UDP_BIND udp_bind
#define IPADDR_NTOA ipaddr_ntoa
#define SET_ADDR(dst, src) (dst)->sin.sin_addr.s_addr = GET_IPV4(src)
#endif
/*
* If lwip is compiled with ipv6 support, then API changes even for ipv4
*/
#if !defined(LWIP_IPV6) || !LWIP_IPV6
#define GET_IPV4(ipX_addr) ((ipX_addr)->addr)
#else
#define GET_IPV4(ipX_addr) ((ipX_addr)->ip4.addr)
#endif
void mg_lwip_ssl_do_hs(struct mg_connection *nc);
void mg_lwip_ssl_send(struct mg_connection *nc);
void mg_lwip_ssl_recv(struct mg_connection *nc);
void mg_lwip_if_init(struct mg_iface *iface);
void mg_lwip_if_free(struct mg_iface *iface);
void mg_lwip_if_add_conn(struct mg_connection *nc);
void mg_lwip_if_remove_conn(struct mg_connection *nc);
time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms);
#ifdef RTOS_SDK
extern void mgos_lock();
extern void mgos_unlock();
#else
#define mgos_lock()
#define mgos_unlock()
#endif
static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p);
#if LWIP_TCP_KEEPALIVE
void mg_lwip_set_keepalive_params(struct mg_connection *nc, int idle,
int interval, int count) {
if (nc->sock == INVALID_SOCKET || nc->flags & MG_F_UDP) {
return;
}
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct tcp_pcb *tpcb = cs->pcb.tcp;
if (idle > 0 && interval > 0 && count > 0) {
tpcb->keep_idle = idle * 1000;
tpcb->keep_intvl = interval * 1000;
tpcb->keep_cnt = count;
tpcb->so_options |= SOF_KEEPALIVE;
} else {
tpcb->so_options &= ~SOF_KEEPALIVE;
}
}
#elif !defined(MG_NO_LWIP_TCP_KEEPALIVE)
#warning LWIP TCP keepalive is disabled. Please consider enabling it.
#endif /* LWIP_TCP_KEEPALIVE */
static err_t mg_lwip_tcp_conn_cb(void *arg, struct tcp_pcb *tpcb, err_t err) {
struct mg_connection *nc = (struct mg_connection *) arg;
DBG(("%p connect to %s:%u = %d", nc, IPADDR_NTOA(ipX_2_ip(&tpcb->remote_ip)),
tpcb->remote_port, err));
if (nc == NULL) {
tcp_abort(tpcb);
return ERR_ARG;
}
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
cs->err = err;
#if LWIP_TCP_KEEPALIVE
if (err == 0) mg_lwip_set_keepalive_params(nc, 60, 10, 6);
#endif
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
return ERR_OK;
}
static void mg_lwip_tcp_error_cb(void *arg, err_t err) {
struct mg_connection *nc = (struct mg_connection *) arg;
DBG(("%p conn error %d", nc, err));
if (nc == NULL) return;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
cs->pcb.tcp = NULL; /* Has already been deallocated */
if (nc->flags & MG_F_CONNECTING) {
cs->err = err;
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
} else {
mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
}
}
static err_t mg_lwip_tcp_recv_cb(void *arg, struct tcp_pcb *tpcb,
struct pbuf *p, err_t err) {
struct mg_connection *nc = (struct mg_connection *) arg;
DBG(("%p %p %u %d", nc, tpcb, (p != NULL ? p->tot_len : 0), err));
if (p == NULL) {
if (nc != NULL) {
mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
} else {
/* Tombstoned connection, do nothing. */
}
return ERR_OK;
} else if (nc == NULL) {
tcp_abort(tpcb);
return ERR_ARG;
}
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
/*
* If we get a chain of more than one segment at once, we need to bump
* refcount on the subsequent bufs to make them independent.
*/
if (p->next != NULL) {
struct pbuf *q = p->next;
for (; q != NULL; q = q->next) pbuf_ref(q);
}
if (cs->rx_chain == NULL) {
cs->rx_offset = 0;
} else if (pbuf_clen(cs->rx_chain) >= 4) {
/* ESP SDK has a limited pool of 5 pbufs. We must not hog them all or RX
* will be completely blocked. We already have at least 4 in the chain,
* this one is, so we have to make a copy and release this one. */
struct pbuf *np = pbuf_alloc(PBUF_RAW, p->tot_len, PBUF_RAM);
if (np != NULL) {
pbuf_copy(np, p);
pbuf_free(p);
p = np;
}
}
mg_lwip_recv_common(nc, p);
return ERR_OK;
}
static void mg_lwip_handle_recv_tcp(struct mg_connection *nc) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
#if MG_ENABLE_SSL
if (nc->flags & MG_F_SSL) {
if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
mg_lwip_ssl_recv(nc);
} else {
mg_lwip_ssl_do_hs(nc);
}
return;
}
#endif
mgos_lock();
while (cs->rx_chain != NULL) {
struct pbuf *seg = cs->rx_chain;
size_t len = (seg->len - cs->rx_offset);
char *data = (char *) MG_MALLOC(len);
if (data == NULL) {
mgos_unlock();
DBG(("OOM"));
return;
}
pbuf_copy_partial(seg, data, len, cs->rx_offset);
cs->rx_offset += len;
if (cs->rx_offset == cs->rx_chain->len) {
cs->rx_chain = pbuf_dechain(cs->rx_chain);
pbuf_free(seg);
cs->rx_offset = 0;
}
mgos_unlock();
mg_if_recv_tcp_cb(nc, data, len, 1 /* own */);
mgos_lock();
}
mgos_unlock();
if (nc->send_mbuf.len > 0) {
mg_lwip_mgr_schedule_poll(nc->mgr);
}
}
static err_t mg_lwip_tcp_sent_cb(void *arg, struct tcp_pcb *tpcb,
u16_t num_sent) {
struct mg_connection *nc = (struct mg_connection *) arg;
DBG(("%p %p %u", nc, tpcb, num_sent));
if (nc == NULL) {
tcp_abort(tpcb);
return ERR_ABRT;
}
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
cs->num_sent += num_sent;
mg_lwip_post_signal(MG_SIG_SENT_CB, nc);
return ERR_OK;
}
void mg_lwip_if_connect_tcp(struct mg_connection *nc,
const union socket_address *sa) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct tcp_pcb *tpcb = TCP_NEW();
cs->pcb.tcp = tpcb;
ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
u16_t port = ntohs(sa->sin.sin_port);
tcp_arg(tpcb, nc);
tcp_err(tpcb, mg_lwip_tcp_error_cb);
tcp_sent(tpcb, mg_lwip_tcp_sent_cb);
tcp_recv(tpcb, mg_lwip_tcp_recv_cb);
cs->err = TCP_BIND(tpcb, IP_ADDR_ANY, 0 /* any port */);
DBG(("%p tcp_bind = %d", nc, cs->err));
if (cs->err != ERR_OK) {
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
return;
}
cs->err = tcp_connect(tpcb, ip, port, mg_lwip_tcp_conn_cb);
DBG(("%p tcp_connect %p = %d", nc, tpcb, cs->err));
if (cs->err != ERR_OK) {
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
return;
}
}
/*
* Lwip included in the SDKs for nRF5x chips has different type for the
* callback of `udp_recv()`
*/
#if CS_PLATFORM == CS_P_NRF51 || CS_PLATFORM == CS_P_NRF52 || \
CS_PLATFORM == CS_P_STM32
static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
const ip_addr_t *addr, u16_t port)
#else
static void mg_lwip_udp_recv_cb(void *arg, struct udp_pcb *pcb, struct pbuf *p,
ip_addr_t *addr, u16_t port)
#endif
{
struct mg_connection *nc = (struct mg_connection *) arg;
DBG(("%p %s:%u %p %u %u", nc, IPADDR_NTOA(addr), port, p, p->ref, p->len));
/* Put address in a separate pbuf and tack it onto the packet. */
struct pbuf *sap =
pbuf_alloc(PBUF_RAW, sizeof(union socket_address), PBUF_RAM);
if (sap == NULL) {
pbuf_free(p);
return;
}
union socket_address *sa = (union socket_address *) sap->payload;
sa->sin.sin_addr.s_addr = addr->addr;
sa->sin.sin_port = htons(port);
/* Logic in the recv handler requires that there be exactly one data pbuf. */
p = pbuf_coalesce(p, PBUF_RAW);
pbuf_chain(sap, p);
mg_lwip_recv_common(nc, sap);
(void) pcb;
}
static void mg_lwip_recv_common(struct mg_connection *nc, struct pbuf *p) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
mgos_lock();
if (cs->rx_chain == NULL) {
cs->rx_chain = p;
} else {
pbuf_chain(cs->rx_chain, p);
}
if (!cs->recv_pending) {
cs->recv_pending = 1;
mg_lwip_post_signal(MG_SIG_RECV, nc);
}
mgos_unlock();
}
static void mg_lwip_handle_recv_udp(struct mg_connection *nc) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
/*
* For UDP, RX chain consists of interleaved address and packet bufs:
* Address pbuf followed by exactly one data pbuf (recv_cb took care of that).
*/
while (cs->rx_chain != NULL) {
struct pbuf *sap = cs->rx_chain;
struct pbuf *p = sap->next;
cs->rx_chain = pbuf_dechain(p);
size_t data_len = p->len;
char *data = (char *) MG_MALLOC(data_len);
if (data != NULL) {
pbuf_copy_partial(p, data, data_len, 0);
pbuf_free(p);
mg_if_recv_udp_cb(nc, data, data_len,
(union socket_address *) sap->payload, sap->len);
pbuf_free(sap);
} else {
pbuf_free(p);
pbuf_free(sap);
}
}
}
void mg_lwip_if_connect_udp(struct mg_connection *nc) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct udp_pcb *upcb = udp_new();
cs->err = UDP_BIND(upcb, IP_ADDR_ANY, 0 /* any port */);
DBG(("%p udp_bind %p = %d", nc, upcb, cs->err));
if (cs->err == ERR_OK) {
udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
cs->pcb.udp = upcb;
} else {
udp_remove(upcb);
}
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
}
void mg_lwip_accept_conn(struct mg_connection *nc, struct tcp_pcb *tpcb) {
union socket_address sa;
SET_ADDR(&sa, &tpcb->remote_ip);
sa.sin.sin_port = htons(tpcb->remote_port);
mg_if_accept_tcp_cb(nc, &sa, sizeof(sa.sin));
}
void mg_lwip_handle_accept(struct mg_connection *nc) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
#if MG_ENABLE_SSL
if (cs->lc->flags & MG_F_SSL) {
if (mg_ssl_if_conn_accept(nc, cs->lc) != MG_SSL_OK) {
LOG(LL_ERROR, ("SSL error"));
tcp_close(cs->pcb.tcp);
}
} else
#endif
{
mg_lwip_accept_conn(nc, cs->pcb.tcp);
}
}
static err_t mg_lwip_accept_cb(void *arg, struct tcp_pcb *newtpcb, err_t err) {
struct mg_connection *lc = (struct mg_connection *) arg;
DBG(("%p conn %p from %s:%u", lc, newtpcb,
IPADDR_NTOA(ipX_2_ip(&newtpcb->remote_ip)), newtpcb->remote_port));
struct mg_connection *nc = mg_if_accept_new_conn(lc);
if (nc == NULL) {
tcp_abort(newtpcb);
return ERR_ABRT;
}
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
cs->lc = lc;
cs->pcb.tcp = newtpcb;
/* We need to set up callbacks before returning because data may start
* arriving immediately. */
tcp_arg(newtpcb, nc);
tcp_err(newtpcb, mg_lwip_tcp_error_cb);
tcp_sent(newtpcb, mg_lwip_tcp_sent_cb);
tcp_recv(newtpcb, mg_lwip_tcp_recv_cb);
#if LWIP_TCP_KEEPALIVE
mg_lwip_set_keepalive_params(nc, 60, 10, 6);
#endif
mg_lwip_post_signal(MG_SIG_ACCEPT, nc);
(void) err;
return ERR_OK;
}
int mg_lwip_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct tcp_pcb *tpcb = TCP_NEW();
ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
u16_t port = ntohs(sa->sin.sin_port);
cs->err = TCP_BIND(tpcb, ip, port);
DBG(("%p tcp_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err));
if (cs->err != ERR_OK) {
tcp_close(tpcb);
return -1;
}
tcp_arg(tpcb, nc);
tpcb = tcp_listen(tpcb);
cs->pcb.tcp = tpcb;
tcp_accept(tpcb, mg_lwip_accept_cb);
return 0;
}
int mg_lwip_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct udp_pcb *upcb = udp_new();
ip_addr_t *ip = (ip_addr_t *) &sa->sin.sin_addr.s_addr;
u16_t port = ntohs(sa->sin.sin_port);
cs->err = UDP_BIND(upcb, ip, port);
DBG(("%p udb_bind(%s:%u) = %d", nc, IPADDR_NTOA(ip), port, cs->err));
if (cs->err != ERR_OK) {
udp_remove(upcb);
return -1;
}
udp_recv(upcb, mg_lwip_udp_recv_cb, nc);
cs->pcb.udp = upcb;
return 0;
}
int mg_lwip_tcp_write(struct mg_connection *nc, const void *data,
uint16_t len) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct tcp_pcb *tpcb = cs->pcb.tcp;
if (tpcb == NULL) return -1;
len = MIN(tpcb->mss, MIN(len, tpcb->snd_buf));
if (len == 0) {
DBG(("%p no buf avail %u %u %u %p %p", tpcb, tpcb->acked, tpcb->snd_buf,
tpcb->snd_queuelen, tpcb->unsent, tpcb->unacked));
tcp_output(tpcb);
return 0;
}
/*
* On ESP8266 we only allow one TCP segment in flight at any given time.
* This may increase latency and reduce efficiency of tcp windowing,
* but memory is scarce and precious on that platform so we do this to
* reduce footprint.
*/
#if CS_PLATFORM == CS_P_ESP8266
if (tpcb->unacked != NULL) {
return 0;
}
if (tpcb->unsent != NULL) {
len = MIN(len, (TCP_MSS - tpcb->unsent->len));
}
#endif
err_t err = tcp_write(tpcb, data, len, TCP_WRITE_FLAG_COPY);
DBG(("%p tcp_write %u = %d", tpcb, len, err));
if (err != ERR_OK) {
/*
* We ignore ERR_MEM because memory will be freed up when the data is sent
* and we'll retry.
*/
return (err == ERR_MEM ? 0 : -1);
}
return len;
}
static void mg_lwip_send_more(struct mg_connection *nc) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (nc->sock == INVALID_SOCKET || cs->pcb.tcp == NULL) {
DBG(("%p invalid socket", nc));
return;
}
int num_written = mg_lwip_tcp_write(nc, nc->send_mbuf.buf, nc->send_mbuf.len);
DBG(("%p mg_lwip_tcp_write %u = %d", nc, nc->send_mbuf.len, num_written));
if (num_written == 0) return;
if (num_written < 0) {
mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
}
mbuf_remove(&nc->send_mbuf, num_written);
mbuf_trim(&nc->send_mbuf);
}
void mg_lwip_if_tcp_send(struct mg_connection *nc, const void *buf,
size_t len) {
mbuf_append(&nc->send_mbuf, buf, len);
mg_lwip_mgr_schedule_poll(nc->mgr);
}
void mg_lwip_if_udp_send(struct mg_connection *nc, const void *buf,
size_t len) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (nc->sock == INVALID_SOCKET || cs->pcb.udp == NULL) {
/*
* In case of UDP, this usually means, what
* async DNS resolve is still in progress and connection
* is not ready yet
*/
DBG(("%p socket is not connected", nc));
return;
}
struct udp_pcb *upcb = cs->pcb.udp;
struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, len, PBUF_RAM);
ip_addr_t *ip = (ip_addr_t *) &nc->sa.sin.sin_addr.s_addr;
u16_t port = ntohs(nc->sa.sin.sin_port);
if (p == NULL) {
DBG(("OOM"));
return;
}
memcpy(p->payload, buf, len);
cs->err = udp_sendto(upcb, p, (ip_addr_t *) ip, port);
DBG(("%p udp_sendto = %d", nc, cs->err));
pbuf_free(p);
if (cs->err != ERR_OK) {
mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
} else {
cs->num_sent += len;
mg_lwip_post_signal(MG_SIG_SENT_CB, nc);
}
}
void mg_lwip_if_recved(struct mg_connection *nc, size_t len) {
if (nc->flags & MG_F_UDP) return;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (nc->sock == INVALID_SOCKET || cs->pcb.tcp == NULL) {
DBG(("%p invalid socket", nc));
return;
}
DBG(("%p %p %u", nc, cs->pcb.tcp, len));
/* Currently SSL acknowledges data immediately.
* TODO(rojer): Find a way to propagate mg_lwip_if_recved. */
#if MG_ENABLE_SSL
if (!(nc->flags & MG_F_SSL)) {
tcp_recved(cs->pcb.tcp, len);
}
#else
tcp_recved(cs->pcb.tcp, len);
#endif
mbuf_trim(&nc->recv_mbuf);
}
int mg_lwip_if_create_conn(struct mg_connection *nc) {
struct mg_lwip_conn_state *cs =
(struct mg_lwip_conn_state *) MG_CALLOC(1, sizeof(*cs));
if (cs == NULL) return 0;
cs->nc = nc;
nc->sock = (intptr_t) cs;
return 1;
}
void mg_lwip_if_destroy_conn(struct mg_connection *nc) {
if (nc->sock == INVALID_SOCKET) return;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (!(nc->flags & MG_F_UDP)) {
struct tcp_pcb *tpcb = cs->pcb.tcp;
if (tpcb != NULL) {
tcp_arg(tpcb, NULL);
DBG(("%p tcp_close %p", nc, tpcb));
tcp_arg(tpcb, NULL);
tcp_close(tpcb);
}
while (cs->rx_chain != NULL) {
struct pbuf *seg = cs->rx_chain;
cs->rx_chain = pbuf_dechain(cs->rx_chain);
pbuf_free(seg);
}
memset(cs, 0, sizeof(*cs));
MG_FREE(cs);
} else if (nc->listener == NULL) {
/* Only close outgoing UDP pcb or listeners. */
struct udp_pcb *upcb = cs->pcb.udp;
if (upcb != NULL) {
DBG(("%p udp_remove %p", nc, upcb));
udp_remove(upcb);
}
memset(cs, 0, sizeof(*cs));
MG_FREE(cs);
}
nc->sock = INVALID_SOCKET;
}
void mg_lwip_if_get_conn_addr(struct mg_connection *nc, int remote,
union socket_address *sa) {
memset(sa, 0, sizeof(*sa));
if (nc->sock == INVALID_SOCKET) return;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (nc->flags & MG_F_UDP) {
struct udp_pcb *upcb = cs->pcb.udp;
if (remote) {
memcpy(sa, &nc->sa, sizeof(*sa));
} else {
sa->sin.sin_port = htons(upcb->local_port);
SET_ADDR(sa, &upcb->local_ip);
}
} else {
struct tcp_pcb *tpcb = cs->pcb.tcp;
if (remote) {
sa->sin.sin_port = htons(tpcb->remote_port);
SET_ADDR(sa, &tpcb->remote_ip);
} else {
sa->sin.sin_port = htons(tpcb->local_port);
SET_ADDR(sa, &tpcb->local_ip);
}
}
}
void mg_lwip_if_sock_set(struct mg_connection *nc, sock_t sock) {
nc->sock = sock;
}
/* clang-format off */
#define MG_LWIP_IFACE_VTABLE \
{ \
mg_lwip_if_init, \
mg_lwip_if_free, \
mg_lwip_if_add_conn, \
mg_lwip_if_remove_conn, \
mg_lwip_if_poll, \
mg_lwip_if_listen_tcp, \
mg_lwip_if_listen_udp, \
mg_lwip_if_connect_tcp, \
mg_lwip_if_connect_udp, \
mg_lwip_if_tcp_send, \
mg_lwip_if_udp_send, \
mg_lwip_if_recved, \
mg_lwip_if_create_conn, \
mg_lwip_if_destroy_conn, \
mg_lwip_if_sock_set, \
mg_lwip_if_get_conn_addr, \
}
/* clang-format on */
const struct mg_iface_vtable mg_lwip_iface_vtable = MG_LWIP_IFACE_VTABLE;
#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
const struct mg_iface_vtable mg_default_iface_vtable = MG_LWIP_IFACE_VTABLE;
#endif
#endif /* MG_ENABLE_NET_IF_LWIP_LOW_LEVEL */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/lwip/mg_lwip_ev_mgr.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
#ifndef MG_SIG_QUEUE_LEN
#define MG_SIG_QUEUE_LEN 32
#endif
struct mg_ev_mgr_lwip_signal {
int sig;
struct mg_connection *nc;
};
struct mg_ev_mgr_lwip_data {
struct mg_ev_mgr_lwip_signal sig_queue[MG_SIG_QUEUE_LEN];
int sig_queue_len;
int start_index;
};
void mg_lwip_post_signal(enum mg_sig_type sig, struct mg_connection *nc) {
struct mg_ev_mgr_lwip_data *md =
(struct mg_ev_mgr_lwip_data *) nc->iface->data;
mgos_lock();
if (md->sig_queue_len >= MG_SIG_QUEUE_LEN) {
mgos_unlock();
return;
}
int end_index = (md->start_index + md->sig_queue_len) % MG_SIG_QUEUE_LEN;
md->sig_queue[end_index].sig = sig;
md->sig_queue[end_index].nc = nc;
md->sig_queue_len++;
mg_lwip_mgr_schedule_poll(nc->mgr);
mgos_unlock();
}
void mg_ev_mgr_lwip_process_signals(struct mg_mgr *mgr) {
struct mg_ev_mgr_lwip_data *md =
(struct mg_ev_mgr_lwip_data *) mgr->ifaces[MG_MAIN_IFACE]->data;
while (md->sig_queue_len > 0) {
mgos_lock();
int sig = md->sig_queue[md->start_index].sig;
struct mg_connection *nc = md->sig_queue[md->start_index].nc;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
md->start_index = (md->start_index + 1) % MG_SIG_QUEUE_LEN;
md->sig_queue_len--;
mgos_unlock();
if (nc->iface == NULL || nc->mgr == NULL) continue;
switch (sig) {
case MG_SIG_CONNECT_RESULT: {
#if MG_ENABLE_SSL
if (cs->err == 0 && (nc->flags & MG_F_SSL) &&
!(nc->flags & MG_F_SSL_HANDSHAKE_DONE)) {
mg_lwip_ssl_do_hs(nc);
} else
#endif
{
mg_if_connect_cb(nc, cs->err);
}
break;
}
case MG_SIG_CLOSE_CONN: {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
mg_close_conn(nc);
break;
}
case MG_SIG_RECV: {
cs->recv_pending = 0;
if (nc->flags & MG_F_UDP) {
mg_lwip_handle_recv_udp(nc);
} else {
mg_lwip_handle_recv_tcp(nc);
}
break;
}
case MG_SIG_SENT_CB: {
if (cs->num_sent > 0) mg_if_sent_cb(nc, cs->num_sent);
cs->num_sent = 0;
if (nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE) &&
!(nc->flags & MG_F_WANT_WRITE)) {
mg_close_conn(nc);
}
break;
}
case MG_SIG_TOMBSTONE: {
break;
}
case MG_SIG_ACCEPT: {
mg_lwip_handle_accept(nc);
break;
}
}
}
}
void mg_lwip_if_init(struct mg_iface *iface) {
LOG(LL_INFO, ("%p Mongoose init"));
iface->data = MG_CALLOC(1, sizeof(struct mg_ev_mgr_lwip_data));
}
void mg_lwip_if_free(struct mg_iface *iface) {
MG_FREE(iface->data);
iface->data = NULL;
}
void mg_lwip_if_add_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_lwip_if_remove_conn(struct mg_connection *nc) {
struct mg_ev_mgr_lwip_data *md =
(struct mg_ev_mgr_lwip_data *) nc->iface->data;
/* Walk the queue and null-out further signals for this conn. */
for (int i = 0; i < MG_SIG_QUEUE_LEN; i++) {
if (md->sig_queue[i].nc == nc) {
md->sig_queue[i].sig = MG_SIG_TOMBSTONE;
}
}
}
time_t mg_lwip_if_poll(struct mg_iface *iface, int timeout_ms) {
struct mg_mgr *mgr = iface->mgr;
int n = 0;
double now = mg_time();
struct mg_connection *nc, *tmp;
double min_timer = 0;
int num_timers = 0;
#if 0
DBG(("begin poll @%u", (unsigned int) (now * 1000)));
#endif
mg_ev_mgr_lwip_process_signals(mgr);
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
tmp = nc->next;
n++;
if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
((nc->flags & MG_F_SEND_AND_CLOSE) && (nc->flags & MG_F_UDP) &&
(nc->send_mbuf.len == 0))) {
mg_close_conn(nc);
continue;
}
mg_if_poll(nc, now);
mg_if_timer(nc, now);
#if MG_ENABLE_SSL
if ((nc->flags & MG_F_SSL) && cs != NULL && cs->pcb.tcp != NULL &&
cs->pcb.tcp->state == ESTABLISHED) {
if (((nc->flags & MG_F_WANT_WRITE) ||
((nc->send_mbuf.len > 0) &&
(nc->flags & MG_F_SSL_HANDSHAKE_DONE))) &&
cs->pcb.tcp->snd_buf > 0) {
/* Can write more. */
if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
if (!(nc->flags & MG_F_CONNECTING)) mg_lwip_ssl_send(nc);
} else {
mg_lwip_ssl_do_hs(nc);
}
}
if (cs->rx_chain != NULL || (nc->flags & MG_F_WANT_READ)) {
if (nc->flags & MG_F_SSL_HANDSHAKE_DONE) {
if (!(nc->flags & MG_F_CONNECTING)) mg_lwip_ssl_recv(nc);
} else {
mg_lwip_ssl_do_hs(nc);
}
}
} else
#endif /* MG_ENABLE_SSL */
{
if (!(nc->flags & (MG_F_CONNECTING | MG_F_UDP))) {
if (nc->send_mbuf.len > 0) mg_lwip_send_more(nc);
}
}
if (nc->sock != INVALID_SOCKET &&
!(nc->flags & (MG_F_UDP | MG_F_LISTENING)) && cs->pcb.tcp != NULL &&
cs->pcb.tcp->unsent != NULL) {
tcp_output(cs->pcb.tcp);
}
if (nc->ev_timer_time > 0) {
if (num_timers == 0 || nc->ev_timer_time < min_timer) {
min_timer = nc->ev_timer_time;
}
num_timers++;
}
}
#if 0
DBG(("end poll @%u, %d conns, %d timers (min %u), next in %d ms",
(unsigned int) (now * 1000), n, num_timers,
(unsigned int) (min_timer * 1000), timeout_ms));
#endif
(void) timeout_ms;
return now;
}
uint32_t mg_lwip_get_poll_delay_ms(struct mg_mgr *mgr) {
struct mg_connection *nc;
double now = mg_time();
double min_timer = 0;
int num_timers = 0;
mg_ev_mgr_lwip_process_signals(mgr);
for (nc = mg_next(mgr, NULL); nc != NULL; nc = mg_next(mgr, nc)) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
if (nc->ev_timer_time > 0) {
if (num_timers == 0 || nc->ev_timer_time < min_timer) {
min_timer = nc->ev_timer_time;
}
num_timers++;
}
if (nc->send_mbuf.len > 0) {
int can_send = 0;
/* We have stuff to send, but can we? */
if (nc->flags & MG_F_UDP) {
/* UDP is always ready for sending. */
can_send = (cs->pcb.udp != NULL);
} else {
can_send = (cs->pcb.tcp != NULL && cs->pcb.tcp->snd_buf > 0);
}
/* We want and can send, request a poll immediately. */
if (can_send) return 0;
}
}
uint32_t timeout_ms = ~0;
if (num_timers > 0) {
double timer_timeout_ms = (min_timer - now) * 1000 + 1 /* rounding */;
if (timer_timeout_ms < timeout_ms) {
timeout_ms = timer_timeout_ms;
}
}
return timeout_ms;
}
#endif /* MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/lwip/mg_lwip_ssl_if.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_SSL && MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL
/* Amalgamated: #include "common/mg_mem.h" */
/* Amalgamated: #include "common/cs_dbg.h" */
#include <lwip/pbuf.h>
#include <lwip/tcp.h>
#ifndef MG_LWIP_SSL_IO_SIZE
#define MG_LWIP_SSL_IO_SIZE 1024
#endif
/*
* Stop processing incoming SSL traffic when recv_mbuf.size is this big.
* It'a a uick solution for SSL recv pushback.
*/
#ifndef MG_LWIP_SSL_RECV_MBUF_LIMIT
#define MG_LWIP_SSL_RECV_MBUF_LIMIT 3072
#endif
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
void mg_lwip_ssl_do_hs(struct mg_connection *nc) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
int server_side = (nc->listener != NULL);
enum mg_ssl_if_result res;
if (nc->flags & MG_F_CLOSE_IMMEDIATELY) return;
res = mg_ssl_if_handshake(nc);
DBG(("%p %d %d %d", nc, nc->flags, server_side, res));
if (res != MG_SSL_OK) {
if (res == MG_SSL_WANT_WRITE) {
nc->flags |= MG_F_WANT_WRITE;
cs->err = 0;
} else if (res == MG_SSL_WANT_READ) {
/*
* Nothing to do in particular, we are callback-driven.
* What we definitely do not need anymore is SSL reading (nothing left).
*/
nc->flags &= ~MG_F_WANT_READ;
cs->err = 0;
} else {
cs->err = res;
if (server_side) {
mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
} else {
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
}
}
} else {
cs->err = 0;
nc->flags &= ~MG_F_WANT_WRITE;
/*
* Handshake is done. Schedule a read immediately to consume app data
* which may already be waiting.
*/
nc->flags |= (MG_F_SSL_HANDSHAKE_DONE | MG_F_WANT_READ);
if (server_side) {
mg_lwip_accept_conn(nc, cs->pcb.tcp);
} else {
mg_lwip_post_signal(MG_SIG_CONNECT_RESULT, nc);
}
}
}
void mg_lwip_ssl_send(struct mg_connection *nc) {
if (nc->sock == INVALID_SOCKET) {
DBG(("%p invalid socket", nc));
return;
}
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
/* It's ok if the buffer is empty. Return value of 0 may also be valid. */
int len = cs->last_ssl_write_size;
if (len == 0) {
len = MIN(MG_LWIP_SSL_IO_SIZE, nc->send_mbuf.len);
}
int ret = mg_ssl_if_write(nc, nc->send_mbuf.buf, len);
DBG(("%p SSL_write %u = %d, %d", nc, len, ret));
if (ret > 0) {
mbuf_remove(&nc->send_mbuf, ret);
mbuf_trim(&nc->send_mbuf);
cs->last_ssl_write_size = 0;
} else if (ret < 0) {
/* This is tricky. We must remember the exact data we were sending to retry
* exactly the same send next time. */
cs->last_ssl_write_size = len;
}
if (ret == len) {
nc->flags &= ~MG_F_WANT_WRITE;
} else if (ret == MG_SSL_WANT_WRITE) {
nc->flags |= MG_F_WANT_WRITE;
} else {
mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
}
}
void mg_lwip_ssl_recv(struct mg_connection *nc) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
/* Don't deliver data before connect callback */
if (nc->flags & MG_F_CONNECTING) return;
while (nc->recv_mbuf.len < MG_LWIP_SSL_RECV_MBUF_LIMIT) {
char *buf = (char *) MG_MALLOC(MG_LWIP_SSL_IO_SIZE);
if (buf == NULL) return;
int ret = mg_ssl_if_read(nc, buf, MG_LWIP_SSL_IO_SIZE);
DBG(("%p %p SSL_read %u = %d", nc, cs->rx_chain, MG_LWIP_SSL_IO_SIZE, ret));
if (ret <= 0) {
MG_FREE(buf);
if (ret == MG_SSL_WANT_WRITE) {
nc->flags |= MG_F_WANT_WRITE;
return;
} else if (ret == MG_SSL_WANT_READ) {
/*
* Nothing to do in particular, we are callback-driven.
* What we definitely do not need anymore is SSL reading (nothing left).
*/
nc->flags &= ~MG_F_WANT_READ;
cs->err = 0;
return;
} else {
mg_lwip_post_signal(MG_SIG_CLOSE_CONN, nc);
return;
}
} else {
mg_if_recv_tcp_cb(nc, buf, ret, 1 /* own */);
}
}
}
#ifdef KR_VERSION
ssize_t kr_send(int fd, const void *buf, size_t len) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) fd;
int ret = mg_lwip_tcp_write(cs->nc, buf, len);
DBG(("%p mg_lwip_tcp_write %u = %d", cs->nc, len, ret));
if (ret == 0) ret = KR_IO_WOULDBLOCK;
return ret;
}
ssize_t kr_recv(int fd, void *buf, size_t len) {
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) fd;
struct pbuf *seg = cs->rx_chain;
if (seg == NULL) {
DBG(("%u - nothing to read", len));
return KR_IO_WOULDBLOCK;
}
size_t seg_len = (seg->len - cs->rx_offset);
DBG(("%u %u %u %u", len, cs->rx_chain->len, seg_len, cs->rx_chain->tot_len));
len = MIN(len, seg_len);
pbuf_copy_partial(seg, buf, len, cs->rx_offset);
cs->rx_offset += len;
tcp_recved(cs->pcb.tcp, len);
if (cs->rx_offset == cs->rx_chain->len) {
cs->rx_chain = pbuf_dechain(cs->rx_chain);
pbuf_free(seg);
cs->rx_offset = 0;
}
return len;
}
#elif MG_SSL_IF == MG_SSL_IF_MBEDTLS
int ssl_socket_send(void *ctx, const unsigned char *buf, size_t len) {
struct mg_connection *nc = (struct mg_connection *) ctx;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
int ret = mg_lwip_tcp_write(cs->nc, buf, len);
LOG(LL_DEBUG, ("%p %d -> %d", nc, len, ret));
if (ret == 0) ret = MBEDTLS_ERR_SSL_WANT_WRITE;
return ret;
}
int ssl_socket_recv(void *ctx, unsigned char *buf, size_t len) {
struct mg_connection *nc = (struct mg_connection *) ctx;
struct mg_lwip_conn_state *cs = (struct mg_lwip_conn_state *) nc->sock;
struct pbuf *seg = cs->rx_chain;
if (seg == NULL) {
DBG(("%u - nothing to read", len));
return MBEDTLS_ERR_SSL_WANT_READ;
}
size_t seg_len = (seg->len - cs->rx_offset);
DBG(("%u %u %u %u", len, cs->rx_chain->len, seg_len, cs->rx_chain->tot_len));
len = MIN(len, seg_len);
pbuf_copy_partial(seg, buf, len, cs->rx_offset);
cs->rx_offset += len;
/* TCP PCB may be NULL if connection has already been closed
* but we still have data to deliver to SSL. */
if (cs->pcb.tcp != NULL) tcp_recved(cs->pcb.tcp, len);
if (cs->rx_offset == cs->rx_chain->len) {
cs->rx_chain = pbuf_dechain(cs->rx_chain);
pbuf_free(seg);
cs->rx_offset = 0;
}
LOG(LL_DEBUG, ("%p <- %d", nc, (int) len));
return len;
}
#endif
#endif /* MG_ENABLE_SSL && MG_NET_IF == MG_NET_IF_LWIP_LOW_LEVEL */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/wince/wince_libc.c"
#endif
/*
* Copyright (c) 2016 Cesanta Software Limited
* All rights reserved
*/
#ifdef WINCE
const char *strerror(int err) {
/*
* TODO(alashkin): there is no strerror on WinCE;
* look for similar wce_xxxx function
*/
static char buf[10];
snprintf(buf, sizeof(buf), "%d", err);
return buf;
}
int open(const char *filename, int oflag, int pmode) {
/*
* TODO(alashkin): mg_open function is not used in mongoose
* but exists in documentation as utility function
* Shall we delete it at all or implement for WinCE as well?
*/
DebugBreak();
return 0; /* for compiler */
}
int _wstati64(const wchar_t *path, cs_stat_t *st) {
DWORD fa = GetFileAttributesW(path);
if (fa == INVALID_FILE_ATTRIBUTES) {
return -1;
}
memset(st, 0, sizeof(*st));
if ((fa & FILE_ATTRIBUTE_DIRECTORY) == 0) {
HANDLE h;
FILETIME ftime;
st->st_mode |= _S_IFREG;
h = CreateFileW(path, GENERIC_READ, 0, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
if (h == INVALID_HANDLE_VALUE) {
return -1;
}
st->st_size = GetFileSize(h, NULL);
GetFileTime(h, NULL, NULL, &ftime);
st->st_mtime = (uint32_t)((((uint64_t) ftime.dwLowDateTime +
((uint64_t) ftime.dwHighDateTime << 32)) /
10000000.0) -
11644473600);
CloseHandle(h);
} else {
st->st_mode |= _S_IFDIR;
}
return 0;
}
/* Windows CE doesn't have neither gmtime nor strftime */
static void mg_gmt_time_string(char *buf, size_t buf_len, time_t *t) {
FILETIME ft;
SYSTEMTIME systime;
if (t != NULL) {
uint64_t filetime = (*t + 11644473600) * 10000000;
ft.dwLowDateTime = filetime & 0xFFFFFFFF;
ft.dwHighDateTime = (filetime & 0xFFFFFFFF00000000) >> 32;
FileTimeToSystemTime(&ft, &systime);
} else {
GetSystemTime(&systime);
}
/* There is no PRIu16 in WinCE SDK */
snprintf(buf, buf_len, "%d.%d.%d %d:%d:%d GMT", (int) systime.wYear,
(int) systime.wMonth, (int) systime.wDay, (int) systime.wHour,
(int) systime.wMinute, (int) systime.wSecond);
}
#endif
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/pic32/pic32_net_if.h"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#ifndef CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
#define CS_COMMON_PLATFORMS_PIC32_NET_IF_H_
/* Amalgamated: #include "mongoose/src/net_if.h" */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#ifndef MG_ENABLE_NET_IF_PIC32
#define MG_ENABLE_NET_IF_PIC32 MG_NET_IF == MG_NET_IF_PIC32
#endif
extern const struct mg_iface_vtable mg_pic32_iface_vtable;
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* CS_COMMON_PLATFORMS_PIC32_NET_IF_H_ */
#ifdef MG_MODULE_LINES
#line 1 "common/platforms/pic32/pic32_net_if.c"
#endif
/*
* Copyright (c) 2014-2016 Cesanta Software Limited
* All rights reserved
*/
#if MG_ENABLE_NET_IF_PIC32
int mg_pic32_if_create_conn(struct mg_connection *nc) {
(void) nc;
return 1;
}
void mg_pic32_if_recved(struct mg_connection *nc, size_t len) {
(void) nc;
(void) len;
}
void mg_pic32_if_add_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_pic32_if_init(struct mg_iface *iface) {
(void) iface;
(void) mg_get_errno(); /* Shutup compiler */
}
void mg_pic32_if_free(struct mg_iface *iface) {
(void) iface;
}
void mg_pic32_if_remove_conn(struct mg_connection *nc) {
(void) nc;
}
void mg_pic32_if_destroy_conn(struct mg_connection *nc) {
if (nc->sock == INVALID_SOCKET) return;
/* For UDP, only close outgoing sockets or listeners. */
if (!(nc->flags & MG_F_UDP)) {
/* Close TCP */
TCPIP_TCP_Close((TCP_SOCKET) nc->sock);
} else if (nc->listener == NULL) {
/* Only close outgoing UDP or listeners. */
TCPIP_UDP_Close((UDP_SOCKET) nc->sock);
}
nc->sock = INVALID_SOCKET;
}
int mg_pic32_if_listen_udp(struct mg_connection *nc, union socket_address *sa) {
nc->sock = TCPIP_UDP_ServerOpen(
sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
: IP_ADDRESS_TYPE_IPV6,
ntohs(sa->sin.sin_port),
sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
if (nc->sock == INVALID_SOCKET) {
return -1;
}
return 0;
}
void mg_pic32_if_udp_send(struct mg_connection *nc, const void *buf,
size_t len) {
mbuf_append(&nc->send_mbuf, buf, len);
}
void mg_pic32_if_tcp_send(struct mg_connection *nc, const void *buf,
size_t len) {
mbuf_append(&nc->send_mbuf, buf, len);
}
int mg_pic32_if_listen_tcp(struct mg_connection *nc, union socket_address *sa) {
nc->sock = TCPIP_TCP_ServerOpen(
sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
: IP_ADDRESS_TYPE_IPV6,
ntohs(sa->sin.sin_port),
sa->sin.sin_addr.s_addr == 0 ? 0 : (IP_MULTI_ADDRESS *) &sa->sin);
memcpy(&nc->sa, sa, sizeof(*sa));
if (nc->sock == INVALID_SOCKET) {
return -1;
}
return 0;
}
static int mg_accept_conn(struct mg_connection *lc) {
struct mg_connection *nc;
TCP_SOCKET_INFO si;
union socket_address sa;
nc = mg_if_accept_new_conn(lc);
if (nc == NULL) {
return 0;
}
nc->sock = lc->sock;
nc->flags &= ~MG_F_LISTENING;
if (!TCPIP_TCP_SocketInfoGet((TCP_SOCKET) nc->sock, &si)) {
return 0;
}
if (si.addressType == IP_ADDRESS_TYPE_IPV4) {
sa.sin.sin_family = AF_INET;
sa.sin.sin_port = htons(si.remotePort);
sa.sin.sin_addr.s_addr = si.remoteIPaddress.v4Add.Val;
} else {
/* TODO(alashkin): do something with _potential_ IPv6 */
memset(&sa, 0, sizeof(sa));
}
mg_if_accept_tcp_cb(nc, (union socket_address *) &sa, sizeof(sa));
return mg_pic32_if_listen_tcp(lc, &lc->sa) >= 0;
}
char *inet_ntoa(struct in_addr in) {
static char addr[17];
snprintf(addr, sizeof(addr), "%d.%d.%d.%d", (int) in.S_un.S_un_b.s_b1,
(int) in.S_un.S_un_b.s_b2, (int) in.S_un.S_un_b.s_b3,
(int) in.S_un.S_un_b.s_b4);
return addr;
}
static void mg_handle_send(struct mg_connection *nc) {
uint16_t bytes_written = 0;
if (nc->flags & MG_F_UDP) {
if (!TCPIP_UDP_RemoteBind(
(UDP_SOCKET) nc->sock,
nc->sa.sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
: IP_ADDRESS_TYPE_IPV6,
ntohs(nc->sa.sin.sin_port), (IP_MULTI_ADDRESS *) &nc->sa.sin)) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
return;
}
bytes_written = TCPIP_UDP_TxPutIsReady((UDP_SOCKET) nc->sock, 0);
if (bytes_written >= nc->send_mbuf.len) {
if (TCPIP_UDP_ArrayPut((UDP_SOCKET) nc->sock,
(uint8_t *) nc->send_mbuf.buf,
nc->send_mbuf.len) != nc->send_mbuf.len) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
bytes_written = 0;
}
}
} else {
bytes_written = TCPIP_TCP_FifoTxFreeGet((TCP_SOCKET) nc->sock);
if (bytes_written != 0) {
if (bytes_written > nc->send_mbuf.len) {
bytes_written = nc->send_mbuf.len;
}
if (TCPIP_TCP_ArrayPut((TCP_SOCKET) nc->sock,
(uint8_t *) nc->send_mbuf.buf,
bytes_written) != bytes_written) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
bytes_written = 0;
}
}
}
if (bytes_written != 0) {
mbuf_remove(&nc->send_mbuf, bytes_written);
mg_if_sent_cb(nc, bytes_written);
}
}
static void mg_handle_recv(struct mg_connection *nc) {
uint16_t bytes_read = 0;
uint8_t *buf = NULL;
if (nc->flags & MG_F_UDP) {
bytes_read = TCPIP_UDP_GetIsReady((UDP_SOCKET) nc->sock);
if (bytes_read != 0 &&
(nc->recv_mbuf_limit == -1 ||
nc->recv_mbuf.len + bytes_read < nc->recv_mbuf_limit)) {
buf = (uint8_t *) MG_MALLOC(bytes_read);
if (TCPIP_UDP_ArrayGet((UDP_SOCKET) nc->sock, buf, bytes_read) !=
bytes_read) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
bytes_read = 0;
MG_FREE(buf);
}
}
} else {
bytes_read = TCPIP_TCP_GetIsReady((TCP_SOCKET) nc->sock);
if (bytes_read != 0) {
if (nc->recv_mbuf_limit != -1 &&
nc->recv_mbuf_limit - nc->recv_mbuf.len > bytes_read) {
bytes_read = nc->recv_mbuf_limit - nc->recv_mbuf.len;
}
buf = (uint8_t *) MG_MALLOC(bytes_read);
if (TCPIP_TCP_ArrayGet((TCP_SOCKET) nc->sock, buf, bytes_read) !=
bytes_read) {
nc->flags |= MG_F_CLOSE_IMMEDIATELY;
MG_FREE(buf);
bytes_read = 0;
}
}
}
if (bytes_read != 0) {
mg_if_recv_tcp_cb(nc, buf, bytes_read, 1 /* own */);
}
}
time_t mg_pic32_if_poll(struct mg_iface *iface, int timeout_ms) {
struct mg_mgr *mgr = iface->mgr;
double now = mg_time();
struct mg_connection *nc, *tmp;
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
tmp = nc->next;
if (nc->flags & MG_F_CONNECTING) {
/* processing connections */
if (nc->flags & MG_F_UDP ||
TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
mg_if_connect_cb(nc, 0);
}
} else if (nc->flags & MG_F_LISTENING) {
if (TCPIP_TCP_IsConnected((TCP_SOCKET) nc->sock)) {
/* accept new connections */
mg_accept_conn(nc);
}
} else {
if (nc->send_mbuf.len != 0) {
mg_handle_send(nc);
}
if (nc->recv_mbuf_limit == -1 ||
nc->recv_mbuf.len < nc->recv_mbuf_limit) {
mg_handle_recv(nc);
}
}
}
for (nc = mgr->active_connections; nc != NULL; nc = tmp) {
tmp = nc->next;
if ((nc->flags & MG_F_CLOSE_IMMEDIATELY) ||
(nc->send_mbuf.len == 0 && (nc->flags & MG_F_SEND_AND_CLOSE))) {
mg_close_conn(nc);
}
}
return now;
}
void mg_pic32_if_sock_set(struct mg_connection *nc, sock_t sock) {
nc->sock = sock;
}
void mg_pic32_if_get_conn_addr(struct mg_connection *nc, int remote,
union socket_address *sa) {
/* TODO(alaskin): not implemented yet */
}
void mg_pic32_if_connect_tcp(struct mg_connection *nc,
const union socket_address *sa) {
nc->sock = TCPIP_TCP_ClientOpen(
sa->sin.sin_family == AF_INET ? IP_ADDRESS_TYPE_IPV4
: IP_ADDRESS_TYPE_IPV6,
ntohs(sa->sin.sin_port), (IP_MULTI_ADDRESS *) &sa->sin);
nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
}
void mg_pic32_if_connect_udp(struct mg_connection *nc) {
nc->sock = TCPIP_UDP_ClientOpen(IP_ADDRESS_TYPE_ANY, 0, NULL);
nc->err = (nc->sock == INVALID_SOCKET) ? -1 : 0;
}
/* clang-format off */
#define MG_PIC32_IFACE_VTABLE \
{ \
mg_pic32_if_init, \
mg_pic32_if_free, \
mg_pic32_if_add_conn, \
mg_pic32_if_remove_conn, \
mg_pic32_if_poll, \
mg_pic32_if_listen_tcp, \
mg_pic32_if_listen_udp, \
mg_pic32_if_connect_tcp, \
mg_pic32_if_connect_udp, \
mg_pic32_if_tcp_send, \
mg_pic32_if_udp_send, \
mg_pic32_if_recved, \
mg_pic32_if_create_conn, \
mg_pic32_if_destroy_conn, \
mg_pic32_if_sock_set, \
mg_pic32_if_get_conn_addr, \
}
/* clang-format on */
const struct mg_iface_vtable mg_pic32_iface_vtable = MG_PIC32_IFACE_VTABLE;
#if MG_NET_IF == MG_NET_IF_PIC32
const struct mg_iface_vtable mg_default_iface_vtable = MG_PIC32_IFACE_VTABLE;
#endif
#endif /* MG_ENABLE_NET_IF_PIC32 */
| ./CrossVul/dataset_final_sorted/CWE-416/c/good_3242_0 |
crossvul-cpp_data_bad_4020_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>
#define CHECKOVERFLOW(offset,datasize,structsize) (( offset >= datasize) || (structsize > datasize) || (offset > datasize - structsize ))
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 (CHECKOVERFLOW(datao, buf_size, 2)) {
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 (CHECKOVERFLOW(o,buf_size,12)) {
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));
/* Check if we overflow the multiplication. Use buf_size as the max size for integer overflow detection,
* we will check the buffer sizes closer later. */
if ( exif_format_get_size (n->entries[tcount].format) &&
buf_size / exif_format_get_size (n->entries[tcount].format) < n->entries[tcount].components
) {
exif_log (ne->log, EXIF_LOG_CODE_CORRUPT_DATA,
"ExifMnoteCanon", "Tag size overflow detected (%u * %lu)", exif_format_get_size (n->entries[tcount].format), n->entries[tcount].components);
continue;
}
/*
* Size? If bigger than 4 bytes, the actual data is not
* in the entry but somewhere else (offset).
*/
s = exif_format_get_size (n->entries[tcount].format) *
n->entries[tcount].components;
n->entries[tcount].size = s;
if (!s) {
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 (CHECKOVERFLOW(dataofs, buf_size, s)) {
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-416/c/bad_4020_0 |
crossvul-cpp_data_bad_388_5 | // SPDX-License-Identifier: GPL-2.0
/*
* Copyright (C) 2014 Davidlohr Bueso.
*/
#include <linux/sched/signal.h>
#include <linux/sched/task.h>
#include <linux/mm.h>
#include <linux/vmacache.h>
#include <asm/pgtable.h>
/*
* Hash based on the pmd of addr if configured with MMU, which provides a good
* hit rate for workloads with spatial locality. Otherwise, use pages.
*/
#ifdef CONFIG_MMU
#define VMACACHE_SHIFT PMD_SHIFT
#else
#define VMACACHE_SHIFT PAGE_SHIFT
#endif
#define VMACACHE_HASH(addr) ((addr >> VMACACHE_SHIFT) & VMACACHE_MASK)
/*
* Flush vma caches for threads that share a given mm.
*
* The operation is safe because the caller holds the mmap_sem
* exclusively and other threads accessing the vma cache will
* have mmap_sem held at least for read, so no extra locking
* is required to maintain the vma cache.
*/
void vmacache_flush_all(struct mm_struct *mm)
{
struct task_struct *g, *p;
count_vm_vmacache_event(VMACACHE_FULL_FLUSHES);
/*
* Single threaded tasks need not iterate the entire
* list of process. We can avoid the flushing as well
* since the mm's seqnum was increased and don't have
* to worry about other threads' seqnum. Current's
* flush will occur upon the next lookup.
*/
if (atomic_read(&mm->mm_users) == 1)
return;
rcu_read_lock();
for_each_process_thread(g, p) {
/*
* Only flush the vmacache pointers as the
* mm seqnum is already set and curr's will
* be set upon invalidation when the next
* lookup is done.
*/
if (mm == p->mm)
vmacache_flush(p);
}
rcu_read_unlock();
}
/*
* This task may be accessing a foreign mm via (for example)
* get_user_pages()->find_vma(). The vmacache is task-local and this
* task's vmacache pertains to a different mm (ie, its own). There is
* nothing we can do here.
*
* Also handle the case where a kernel thread has adopted this mm via use_mm().
* That kernel thread's vmacache is not applicable to this mm.
*/
static inline bool vmacache_valid_mm(struct mm_struct *mm)
{
return current->mm == mm && !(current->flags & PF_KTHREAD);
}
void vmacache_update(unsigned long addr, struct vm_area_struct *newvma)
{
if (vmacache_valid_mm(newvma->vm_mm))
current->vmacache.vmas[VMACACHE_HASH(addr)] = newvma;
}
static bool vmacache_valid(struct mm_struct *mm)
{
struct task_struct *curr;
if (!vmacache_valid_mm(mm))
return false;
curr = current;
if (mm->vmacache_seqnum != curr->vmacache.seqnum) {
/*
* First attempt will always be invalid, initialize
* the new cache for this task here.
*/
curr->vmacache.seqnum = mm->vmacache_seqnum;
vmacache_flush(curr);
return false;
}
return true;
}
struct vm_area_struct *vmacache_find(struct mm_struct *mm, unsigned long addr)
{
int idx = VMACACHE_HASH(addr);
int i;
count_vm_vmacache_event(VMACACHE_FIND_CALLS);
if (!vmacache_valid(mm))
return NULL;
for (i = 0; i < VMACACHE_SIZE; i++) {
struct vm_area_struct *vma = current->vmacache.vmas[idx];
if (vma) {
#ifdef CONFIG_DEBUG_VM_VMACACHE
if (WARN_ON_ONCE(vma->vm_mm != mm))
break;
#endif
if (vma->vm_start <= addr && vma->vm_end > addr) {
count_vm_vmacache_event(VMACACHE_FIND_HITS);
return vma;
}
}
if (++idx == VMACACHE_SIZE)
idx = 0;
}
return NULL;
}
#ifndef CONFIG_MMU
struct vm_area_struct *vmacache_find_exact(struct mm_struct *mm,
unsigned long start,
unsigned long end)
{
int idx = VMACACHE_HASH(start);
int i;
count_vm_vmacache_event(VMACACHE_FIND_CALLS);
if (!vmacache_valid(mm))
return NULL;
for (i = 0; i < VMACACHE_SIZE; i++) {
struct vm_area_struct *vma = current->vmacache.vmas[idx];
if (vma && vma->vm_start == start && vma->vm_end == end) {
count_vm_vmacache_event(VMACACHE_FIND_HITS);
return vma;
}
if (++idx == VMACACHE_SIZE)
idx = 0;
}
return NULL;
}
#endif
| ./CrossVul/dataset_final_sorted/CWE-416/c/bad_388_5 |
crossvul-cpp_data_good_3326_0 | /*
* i386 translation
*
* Copyright (c) 2003 Fabrice Bellard
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "qemu/osdep.h"
#include "qemu/host-utils.h"
#include "cpu.h"
#include "disas/disas.h"
#include "exec/exec-all.h"
#include "tcg-op.h"
#include "exec/cpu_ldst.h"
#include "exec/helper-proto.h"
#include "exec/helper-gen.h"
#include "trace-tcg.h"
#include "exec/log.h"
#define PREFIX_REPZ 0x01
#define PREFIX_REPNZ 0x02
#define PREFIX_LOCK 0x04
#define PREFIX_DATA 0x08
#define PREFIX_ADR 0x10
#define PREFIX_VEX 0x20
#ifdef TARGET_X86_64
#define CODE64(s) ((s)->code64)
#define REX_X(s) ((s)->rex_x)
#define REX_B(s) ((s)->rex_b)
#else
#define CODE64(s) 0
#define REX_X(s) 0
#define REX_B(s) 0
#endif
#ifdef TARGET_X86_64
# define ctztl ctz64
# define clztl clz64
#else
# define ctztl ctz32
# define clztl clz32
#endif
/* For a switch indexed by MODRM, match all memory operands for a given OP. */
#define CASE_MODRM_MEM_OP(OP) \
case (0 << 6) | (OP << 3) | 0 ... (0 << 6) | (OP << 3) | 7: \
case (1 << 6) | (OP << 3) | 0 ... (1 << 6) | (OP << 3) | 7: \
case (2 << 6) | (OP << 3) | 0 ... (2 << 6) | (OP << 3) | 7
#define CASE_MODRM_OP(OP) \
case (0 << 6) | (OP << 3) | 0 ... (0 << 6) | (OP << 3) | 7: \
case (1 << 6) | (OP << 3) | 0 ... (1 << 6) | (OP << 3) | 7: \
case (2 << 6) | (OP << 3) | 0 ... (2 << 6) | (OP << 3) | 7: \
case (3 << 6) | (OP << 3) | 0 ... (3 << 6) | (OP << 3) | 7
//#define MACRO_TEST 1
/* global register indexes */
static TCGv_env cpu_env;
static TCGv cpu_A0;
static TCGv cpu_cc_dst, cpu_cc_src, cpu_cc_src2, cpu_cc_srcT;
static TCGv_i32 cpu_cc_op;
static TCGv cpu_regs[CPU_NB_REGS];
static TCGv cpu_seg_base[6];
static TCGv_i64 cpu_bndl[4];
static TCGv_i64 cpu_bndu[4];
/* local temps */
static TCGv cpu_T0, cpu_T1;
/* local register indexes (only used inside old micro ops) */
static TCGv cpu_tmp0, cpu_tmp4;
static TCGv_ptr cpu_ptr0, cpu_ptr1;
static TCGv_i32 cpu_tmp2_i32, cpu_tmp3_i32;
static TCGv_i64 cpu_tmp1_i64;
#include "exec/gen-icount.h"
#ifdef TARGET_X86_64
static int x86_64_hregs;
#endif
typedef struct DisasContext {
/* current insn context */
int override; /* -1 if no override */
int prefix;
TCGMemOp aflag;
TCGMemOp dflag;
target_ulong pc_start;
target_ulong pc; /* pc = eip + cs_base */
int is_jmp; /* 1 = means jump (stop translation), 2 means CPU
static state change (stop translation) */
/* current block context */
target_ulong cs_base; /* base of CS segment */
int pe; /* protected mode */
int code32; /* 32 bit code segment */
#ifdef TARGET_X86_64
int lma; /* long mode active */
int code64; /* 64 bit code segment */
int rex_x, rex_b;
#endif
int vex_l; /* vex vector length */
int vex_v; /* vex vvvv register, without 1's compliment. */
int ss32; /* 32 bit stack segment */
CCOp cc_op; /* current CC operation */
bool cc_op_dirty;
int addseg; /* non zero if either DS/ES/SS have a non zero base */
int f_st; /* currently unused */
int vm86; /* vm86 mode */
int cpl;
int iopl;
int tf; /* TF cpu flag */
int singlestep_enabled; /* "hardware" single step enabled */
int jmp_opt; /* use direct block chaining for direct jumps */
int repz_opt; /* optimize jumps within repz instructions */
int mem_index; /* select memory access functions */
uint64_t flags; /* all execution flags */
struct TranslationBlock *tb;
int popl_esp_hack; /* for correct popl with esp base handling */
int rip_offset; /* only used in x86_64, but left for simplicity */
int cpuid_features;
int cpuid_ext_features;
int cpuid_ext2_features;
int cpuid_ext3_features;
int cpuid_7_0_ebx_features;
int cpuid_xsave_features;
} DisasContext;
static void gen_eob(DisasContext *s);
static void gen_jmp(DisasContext *s, target_ulong eip);
static void gen_jmp_tb(DisasContext *s, target_ulong eip, int tb_num);
static void gen_op(DisasContext *s1, int op, TCGMemOp ot, int d);
/* i386 arith/logic operations */
enum {
OP_ADDL,
OP_ORL,
OP_ADCL,
OP_SBBL,
OP_ANDL,
OP_SUBL,
OP_XORL,
OP_CMPL,
};
/* i386 shift ops */
enum {
OP_ROL,
OP_ROR,
OP_RCL,
OP_RCR,
OP_SHL,
OP_SHR,
OP_SHL1, /* undocumented */
OP_SAR = 7,
};
enum {
JCC_O,
JCC_B,
JCC_Z,
JCC_BE,
JCC_S,
JCC_P,
JCC_L,
JCC_LE,
};
enum {
/* I386 int registers */
OR_EAX, /* MUST be even numbered */
OR_ECX,
OR_EDX,
OR_EBX,
OR_ESP,
OR_EBP,
OR_ESI,
OR_EDI,
OR_TMP0 = 16, /* temporary operand register */
OR_TMP1,
OR_A0, /* temporary register used when doing address evaluation */
};
enum {
USES_CC_DST = 1,
USES_CC_SRC = 2,
USES_CC_SRC2 = 4,
USES_CC_SRCT = 8,
};
/* Bit set if the global variable is live after setting CC_OP to X. */
static const uint8_t cc_op_live[CC_OP_NB] = {
[CC_OP_DYNAMIC] = USES_CC_DST | USES_CC_SRC | USES_CC_SRC2,
[CC_OP_EFLAGS] = USES_CC_SRC,
[CC_OP_MULB ... CC_OP_MULQ] = USES_CC_DST | USES_CC_SRC,
[CC_OP_ADDB ... CC_OP_ADDQ] = USES_CC_DST | USES_CC_SRC,
[CC_OP_ADCB ... CC_OP_ADCQ] = USES_CC_DST | USES_CC_SRC | USES_CC_SRC2,
[CC_OP_SUBB ... CC_OP_SUBQ] = USES_CC_DST | USES_CC_SRC | USES_CC_SRCT,
[CC_OP_SBBB ... CC_OP_SBBQ] = USES_CC_DST | USES_CC_SRC | USES_CC_SRC2,
[CC_OP_LOGICB ... CC_OP_LOGICQ] = USES_CC_DST,
[CC_OP_INCB ... CC_OP_INCQ] = USES_CC_DST | USES_CC_SRC,
[CC_OP_DECB ... CC_OP_DECQ] = USES_CC_DST | USES_CC_SRC,
[CC_OP_SHLB ... CC_OP_SHLQ] = USES_CC_DST | USES_CC_SRC,
[CC_OP_SARB ... CC_OP_SARQ] = USES_CC_DST | USES_CC_SRC,
[CC_OP_BMILGB ... CC_OP_BMILGQ] = USES_CC_DST | USES_CC_SRC,
[CC_OP_ADCX] = USES_CC_DST | USES_CC_SRC,
[CC_OP_ADOX] = USES_CC_SRC | USES_CC_SRC2,
[CC_OP_ADCOX] = USES_CC_DST | USES_CC_SRC | USES_CC_SRC2,
[CC_OP_CLR] = 0,
[CC_OP_POPCNT] = USES_CC_SRC,
};
static void set_cc_op(DisasContext *s, CCOp op)
{
int dead;
if (s->cc_op == op) {
return;
}
/* Discard CC computation that will no longer be used. */
dead = cc_op_live[s->cc_op] & ~cc_op_live[op];
if (dead & USES_CC_DST) {
tcg_gen_discard_tl(cpu_cc_dst);
}
if (dead & USES_CC_SRC) {
tcg_gen_discard_tl(cpu_cc_src);
}
if (dead & USES_CC_SRC2) {
tcg_gen_discard_tl(cpu_cc_src2);
}
if (dead & USES_CC_SRCT) {
tcg_gen_discard_tl(cpu_cc_srcT);
}
if (op == CC_OP_DYNAMIC) {
/* The DYNAMIC setting is translator only, and should never be
stored. Thus we always consider it clean. */
s->cc_op_dirty = false;
} else {
/* Discard any computed CC_OP value (see shifts). */
if (s->cc_op == CC_OP_DYNAMIC) {
tcg_gen_discard_i32(cpu_cc_op);
}
s->cc_op_dirty = true;
}
s->cc_op = op;
}
static void gen_update_cc_op(DisasContext *s)
{
if (s->cc_op_dirty) {
tcg_gen_movi_i32(cpu_cc_op, s->cc_op);
s->cc_op_dirty = false;
}
}
#ifdef TARGET_X86_64
#define NB_OP_SIZES 4
#else /* !TARGET_X86_64 */
#define NB_OP_SIZES 3
#endif /* !TARGET_X86_64 */
#if defined(HOST_WORDS_BIGENDIAN)
#define REG_B_OFFSET (sizeof(target_ulong) - 1)
#define REG_H_OFFSET (sizeof(target_ulong) - 2)
#define REG_W_OFFSET (sizeof(target_ulong) - 2)
#define REG_L_OFFSET (sizeof(target_ulong) - 4)
#define REG_LH_OFFSET (sizeof(target_ulong) - 8)
#else
#define REG_B_OFFSET 0
#define REG_H_OFFSET 1
#define REG_W_OFFSET 0
#define REG_L_OFFSET 0
#define REG_LH_OFFSET 4
#endif
/* In instruction encodings for byte register accesses the
* register number usually indicates "low 8 bits of register N";
* however there are some special cases where N 4..7 indicates
* [AH, CH, DH, BH], ie "bits 15..8 of register N-4". Return
* true for this special case, false otherwise.
*/
static inline bool byte_reg_is_xH(int reg)
{
if (reg < 4) {
return false;
}
#ifdef TARGET_X86_64
if (reg >= 8 || x86_64_hregs) {
return false;
}
#endif
return true;
}
/* Select the size of a push/pop operation. */
static inline TCGMemOp mo_pushpop(DisasContext *s, TCGMemOp ot)
{
if (CODE64(s)) {
return ot == MO_16 ? MO_16 : MO_64;
} else {
return ot;
}
}
/* Select the size of the stack pointer. */
static inline TCGMemOp mo_stacksize(DisasContext *s)
{
return CODE64(s) ? MO_64 : s->ss32 ? MO_32 : MO_16;
}
/* Select only size 64 else 32. Used for SSE operand sizes. */
static inline TCGMemOp mo_64_32(TCGMemOp ot)
{
#ifdef TARGET_X86_64
return ot == MO_64 ? MO_64 : MO_32;
#else
return MO_32;
#endif
}
/* Select size 8 if lsb of B is clear, else OT. Used for decoding
byte vs word opcodes. */
static inline TCGMemOp mo_b_d(int b, TCGMemOp ot)
{
return b & 1 ? ot : MO_8;
}
/* Select size 8 if lsb of B is clear, else OT capped at 32.
Used for decoding operand size of port opcodes. */
static inline TCGMemOp mo_b_d32(int b, TCGMemOp ot)
{
return b & 1 ? (ot == MO_16 ? MO_16 : MO_32) : MO_8;
}
static void gen_op_mov_reg_v(TCGMemOp ot, int reg, TCGv t0)
{
switch(ot) {
case MO_8:
if (!byte_reg_is_xH(reg)) {
tcg_gen_deposit_tl(cpu_regs[reg], cpu_regs[reg], t0, 0, 8);
} else {
tcg_gen_deposit_tl(cpu_regs[reg - 4], cpu_regs[reg - 4], t0, 8, 8);
}
break;
case MO_16:
tcg_gen_deposit_tl(cpu_regs[reg], cpu_regs[reg], t0, 0, 16);
break;
case MO_32:
/* For x86_64, this sets the higher half of register to zero.
For i386, this is equivalent to a mov. */
tcg_gen_ext32u_tl(cpu_regs[reg], t0);
break;
#ifdef TARGET_X86_64
case MO_64:
tcg_gen_mov_tl(cpu_regs[reg], t0);
break;
#endif
default:
tcg_abort();
}
}
static inline void gen_op_mov_v_reg(TCGMemOp ot, TCGv t0, int reg)
{
if (ot == MO_8 && byte_reg_is_xH(reg)) {
tcg_gen_extract_tl(t0, cpu_regs[reg - 4], 8, 8);
} else {
tcg_gen_mov_tl(t0, cpu_regs[reg]);
}
}
static void gen_add_A0_im(DisasContext *s, int val)
{
tcg_gen_addi_tl(cpu_A0, cpu_A0, val);
if (!CODE64(s)) {
tcg_gen_ext32u_tl(cpu_A0, cpu_A0);
}
}
static inline void gen_op_jmp_v(TCGv dest)
{
tcg_gen_st_tl(dest, cpu_env, offsetof(CPUX86State, eip));
}
static inline void gen_op_add_reg_im(TCGMemOp size, int reg, int32_t val)
{
tcg_gen_addi_tl(cpu_tmp0, cpu_regs[reg], val);
gen_op_mov_reg_v(size, reg, cpu_tmp0);
}
static inline void gen_op_add_reg_T0(TCGMemOp size, int reg)
{
tcg_gen_add_tl(cpu_tmp0, cpu_regs[reg], cpu_T0);
gen_op_mov_reg_v(size, reg, cpu_tmp0);
}
static inline void gen_op_ld_v(DisasContext *s, int idx, TCGv t0, TCGv a0)
{
tcg_gen_qemu_ld_tl(t0, a0, s->mem_index, idx | MO_LE);
}
static inline void gen_op_st_v(DisasContext *s, int idx, TCGv t0, TCGv a0)
{
tcg_gen_qemu_st_tl(t0, a0, s->mem_index, idx | MO_LE);
}
static inline void gen_op_st_rm_T0_A0(DisasContext *s, int idx, int d)
{
if (d == OR_TMP0) {
gen_op_st_v(s, idx, cpu_T0, cpu_A0);
} else {
gen_op_mov_reg_v(idx, d, cpu_T0);
}
}
static inline void gen_jmp_im(target_ulong pc)
{
tcg_gen_movi_tl(cpu_tmp0, pc);
gen_op_jmp_v(cpu_tmp0);
}
/* Compute SEG:REG into A0. SEG is selected from the override segment
(OVR_SEG) and the default segment (DEF_SEG). OVR_SEG may be -1 to
indicate no override. */
static void gen_lea_v_seg(DisasContext *s, TCGMemOp aflag, TCGv a0,
int def_seg, int ovr_seg)
{
switch (aflag) {
#ifdef TARGET_X86_64
case MO_64:
if (ovr_seg < 0) {
tcg_gen_mov_tl(cpu_A0, a0);
return;
}
break;
#endif
case MO_32:
/* 32 bit address */
if (ovr_seg < 0 && s->addseg) {
ovr_seg = def_seg;
}
if (ovr_seg < 0) {
tcg_gen_ext32u_tl(cpu_A0, a0);
return;
}
break;
case MO_16:
/* 16 bit address */
tcg_gen_ext16u_tl(cpu_A0, a0);
a0 = cpu_A0;
if (ovr_seg < 0) {
if (s->addseg) {
ovr_seg = def_seg;
} else {
return;
}
}
break;
default:
tcg_abort();
}
if (ovr_seg >= 0) {
TCGv seg = cpu_seg_base[ovr_seg];
if (aflag == MO_64) {
tcg_gen_add_tl(cpu_A0, a0, seg);
} else if (CODE64(s)) {
tcg_gen_ext32u_tl(cpu_A0, a0);
tcg_gen_add_tl(cpu_A0, cpu_A0, seg);
} else {
tcg_gen_add_tl(cpu_A0, a0, seg);
tcg_gen_ext32u_tl(cpu_A0, cpu_A0);
}
}
}
static inline void gen_string_movl_A0_ESI(DisasContext *s)
{
gen_lea_v_seg(s, s->aflag, cpu_regs[R_ESI], R_DS, s->override);
}
static inline void gen_string_movl_A0_EDI(DisasContext *s)
{
gen_lea_v_seg(s, s->aflag, cpu_regs[R_EDI], R_ES, -1);
}
static inline void gen_op_movl_T0_Dshift(TCGMemOp ot)
{
tcg_gen_ld32s_tl(cpu_T0, cpu_env, offsetof(CPUX86State, df));
tcg_gen_shli_tl(cpu_T0, cpu_T0, ot);
};
static TCGv gen_ext_tl(TCGv dst, TCGv src, TCGMemOp size, bool sign)
{
switch (size) {
case MO_8:
if (sign) {
tcg_gen_ext8s_tl(dst, src);
} else {
tcg_gen_ext8u_tl(dst, src);
}
return dst;
case MO_16:
if (sign) {
tcg_gen_ext16s_tl(dst, src);
} else {
tcg_gen_ext16u_tl(dst, src);
}
return dst;
#ifdef TARGET_X86_64
case MO_32:
if (sign) {
tcg_gen_ext32s_tl(dst, src);
} else {
tcg_gen_ext32u_tl(dst, src);
}
return dst;
#endif
default:
return src;
}
}
static void gen_extu(TCGMemOp ot, TCGv reg)
{
gen_ext_tl(reg, reg, ot, false);
}
static void gen_exts(TCGMemOp ot, TCGv reg)
{
gen_ext_tl(reg, reg, ot, true);
}
static inline void gen_op_jnz_ecx(TCGMemOp size, TCGLabel *label1)
{
tcg_gen_mov_tl(cpu_tmp0, cpu_regs[R_ECX]);
gen_extu(size, cpu_tmp0);
tcg_gen_brcondi_tl(TCG_COND_NE, cpu_tmp0, 0, label1);
}
static inline void gen_op_jz_ecx(TCGMemOp size, TCGLabel *label1)
{
tcg_gen_mov_tl(cpu_tmp0, cpu_regs[R_ECX]);
gen_extu(size, cpu_tmp0);
tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_tmp0, 0, label1);
}
static void gen_helper_in_func(TCGMemOp ot, TCGv v, TCGv_i32 n)
{
switch (ot) {
case MO_8:
gen_helper_inb(v, cpu_env, n);
break;
case MO_16:
gen_helper_inw(v, cpu_env, n);
break;
case MO_32:
gen_helper_inl(v, cpu_env, n);
break;
default:
tcg_abort();
}
}
static void gen_helper_out_func(TCGMemOp ot, TCGv_i32 v, TCGv_i32 n)
{
switch (ot) {
case MO_8:
gen_helper_outb(cpu_env, v, n);
break;
case MO_16:
gen_helper_outw(cpu_env, v, n);
break;
case MO_32:
gen_helper_outl(cpu_env, v, n);
break;
default:
tcg_abort();
}
}
static void gen_check_io(DisasContext *s, TCGMemOp ot, target_ulong cur_eip,
uint32_t svm_flags)
{
target_ulong next_eip;
if (s->pe && (s->cpl > s->iopl || s->vm86)) {
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
switch (ot) {
case MO_8:
gen_helper_check_iob(cpu_env, cpu_tmp2_i32);
break;
case MO_16:
gen_helper_check_iow(cpu_env, cpu_tmp2_i32);
break;
case MO_32:
gen_helper_check_iol(cpu_env, cpu_tmp2_i32);
break;
default:
tcg_abort();
}
}
if(s->flags & HF_SVMI_MASK) {
gen_update_cc_op(s);
gen_jmp_im(cur_eip);
svm_flags |= (1 << (4 + ot));
next_eip = s->pc - s->cs_base;
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_svm_check_io(cpu_env, cpu_tmp2_i32,
tcg_const_i32(svm_flags),
tcg_const_i32(next_eip - cur_eip));
}
}
static inline void gen_movs(DisasContext *s, TCGMemOp ot)
{
gen_string_movl_A0_ESI(s);
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
gen_string_movl_A0_EDI(s);
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_ESI);
gen_op_add_reg_T0(s->aflag, R_EDI);
}
static void gen_op_update1_cc(void)
{
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
}
static void gen_op_update2_cc(void)
{
tcg_gen_mov_tl(cpu_cc_src, cpu_T1);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
}
static void gen_op_update3_cc(TCGv reg)
{
tcg_gen_mov_tl(cpu_cc_src2, reg);
tcg_gen_mov_tl(cpu_cc_src, cpu_T1);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
}
static inline void gen_op_testl_T0_T1_cc(void)
{
tcg_gen_and_tl(cpu_cc_dst, cpu_T0, cpu_T1);
}
static void gen_op_update_neg_cc(void)
{
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
tcg_gen_neg_tl(cpu_cc_src, cpu_T0);
tcg_gen_movi_tl(cpu_cc_srcT, 0);
}
/* compute all eflags to cc_src */
static void gen_compute_eflags(DisasContext *s)
{
TCGv zero, dst, src1, src2;
int live, dead;
if (s->cc_op == CC_OP_EFLAGS) {
return;
}
if (s->cc_op == CC_OP_CLR) {
tcg_gen_movi_tl(cpu_cc_src, CC_Z | CC_P);
set_cc_op(s, CC_OP_EFLAGS);
return;
}
TCGV_UNUSED(zero);
dst = cpu_cc_dst;
src1 = cpu_cc_src;
src2 = cpu_cc_src2;
/* Take care to not read values that are not live. */
live = cc_op_live[s->cc_op] & ~USES_CC_SRCT;
dead = live ^ (USES_CC_DST | USES_CC_SRC | USES_CC_SRC2);
if (dead) {
zero = tcg_const_tl(0);
if (dead & USES_CC_DST) {
dst = zero;
}
if (dead & USES_CC_SRC) {
src1 = zero;
}
if (dead & USES_CC_SRC2) {
src2 = zero;
}
}
gen_update_cc_op(s);
gen_helper_cc_compute_all(cpu_cc_src, dst, src1, src2, cpu_cc_op);
set_cc_op(s, CC_OP_EFLAGS);
if (dead) {
tcg_temp_free(zero);
}
}
typedef struct CCPrepare {
TCGCond cond;
TCGv reg;
TCGv reg2;
target_ulong imm;
target_ulong mask;
bool use_reg2;
bool no_setcond;
} CCPrepare;
/* compute eflags.C to reg */
static CCPrepare gen_prepare_eflags_c(DisasContext *s, TCGv reg)
{
TCGv t0, t1;
int size, shift;
switch (s->cc_op) {
case CC_OP_SUBB ... CC_OP_SUBQ:
/* (DATA_TYPE)CC_SRCT < (DATA_TYPE)CC_SRC */
size = s->cc_op - CC_OP_SUBB;
t1 = gen_ext_tl(cpu_tmp0, cpu_cc_src, size, false);
/* If no temporary was used, be careful not to alias t1 and t0. */
t0 = TCGV_EQUAL(t1, cpu_cc_src) ? cpu_tmp0 : reg;
tcg_gen_mov_tl(t0, cpu_cc_srcT);
gen_extu(size, t0);
goto add_sub;
case CC_OP_ADDB ... CC_OP_ADDQ:
/* (DATA_TYPE)CC_DST < (DATA_TYPE)CC_SRC */
size = s->cc_op - CC_OP_ADDB;
t1 = gen_ext_tl(cpu_tmp0, cpu_cc_src, size, false);
t0 = gen_ext_tl(reg, cpu_cc_dst, size, false);
add_sub:
return (CCPrepare) { .cond = TCG_COND_LTU, .reg = t0,
.reg2 = t1, .mask = -1, .use_reg2 = true };
case CC_OP_LOGICB ... CC_OP_LOGICQ:
case CC_OP_CLR:
case CC_OP_POPCNT:
return (CCPrepare) { .cond = TCG_COND_NEVER, .mask = -1 };
case CC_OP_INCB ... CC_OP_INCQ:
case CC_OP_DECB ... CC_OP_DECQ:
return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src,
.mask = -1, .no_setcond = true };
case CC_OP_SHLB ... CC_OP_SHLQ:
/* (CC_SRC >> (DATA_BITS - 1)) & 1 */
size = s->cc_op - CC_OP_SHLB;
shift = (8 << size) - 1;
return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src,
.mask = (target_ulong)1 << shift };
case CC_OP_MULB ... CC_OP_MULQ:
return (CCPrepare) { .cond = TCG_COND_NE,
.reg = cpu_cc_src, .mask = -1 };
case CC_OP_BMILGB ... CC_OP_BMILGQ:
size = s->cc_op - CC_OP_BMILGB;
t0 = gen_ext_tl(reg, cpu_cc_src, size, false);
return (CCPrepare) { .cond = TCG_COND_EQ, .reg = t0, .mask = -1 };
case CC_OP_ADCX:
case CC_OP_ADCOX:
return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_dst,
.mask = -1, .no_setcond = true };
case CC_OP_EFLAGS:
case CC_OP_SARB ... CC_OP_SARQ:
/* CC_SRC & 1 */
return (CCPrepare) { .cond = TCG_COND_NE,
.reg = cpu_cc_src, .mask = CC_C };
default:
/* The need to compute only C from CC_OP_DYNAMIC is important
in efficiently implementing e.g. INC at the start of a TB. */
gen_update_cc_op(s);
gen_helper_cc_compute_c(reg, cpu_cc_dst, cpu_cc_src,
cpu_cc_src2, cpu_cc_op);
return (CCPrepare) { .cond = TCG_COND_NE, .reg = reg,
.mask = -1, .no_setcond = true };
}
}
/* compute eflags.P to reg */
static CCPrepare gen_prepare_eflags_p(DisasContext *s, TCGv reg)
{
gen_compute_eflags(s);
return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src,
.mask = CC_P };
}
/* compute eflags.S to reg */
static CCPrepare gen_prepare_eflags_s(DisasContext *s, TCGv reg)
{
switch (s->cc_op) {
case CC_OP_DYNAMIC:
gen_compute_eflags(s);
/* FALLTHRU */
case CC_OP_EFLAGS:
case CC_OP_ADCX:
case CC_OP_ADOX:
case CC_OP_ADCOX:
return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src,
.mask = CC_S };
case CC_OP_CLR:
case CC_OP_POPCNT:
return (CCPrepare) { .cond = TCG_COND_NEVER, .mask = -1 };
default:
{
TCGMemOp size = (s->cc_op - CC_OP_ADDB) & 3;
TCGv t0 = gen_ext_tl(reg, cpu_cc_dst, size, true);
return (CCPrepare) { .cond = TCG_COND_LT, .reg = t0, .mask = -1 };
}
}
}
/* compute eflags.O to reg */
static CCPrepare gen_prepare_eflags_o(DisasContext *s, TCGv reg)
{
switch (s->cc_op) {
case CC_OP_ADOX:
case CC_OP_ADCOX:
return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src2,
.mask = -1, .no_setcond = true };
case CC_OP_CLR:
case CC_OP_POPCNT:
return (CCPrepare) { .cond = TCG_COND_NEVER, .mask = -1 };
default:
gen_compute_eflags(s);
return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src,
.mask = CC_O };
}
}
/* compute eflags.Z to reg */
static CCPrepare gen_prepare_eflags_z(DisasContext *s, TCGv reg)
{
switch (s->cc_op) {
case CC_OP_DYNAMIC:
gen_compute_eflags(s);
/* FALLTHRU */
case CC_OP_EFLAGS:
case CC_OP_ADCX:
case CC_OP_ADOX:
case CC_OP_ADCOX:
return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src,
.mask = CC_Z };
case CC_OP_CLR:
return (CCPrepare) { .cond = TCG_COND_ALWAYS, .mask = -1 };
case CC_OP_POPCNT:
return (CCPrepare) { .cond = TCG_COND_EQ, .reg = cpu_cc_src,
.mask = -1 };
default:
{
TCGMemOp size = (s->cc_op - CC_OP_ADDB) & 3;
TCGv t0 = gen_ext_tl(reg, cpu_cc_dst, size, false);
return (CCPrepare) { .cond = TCG_COND_EQ, .reg = t0, .mask = -1 };
}
}
}
/* perform a conditional store into register 'reg' according to jump opcode
value 'b'. In the fast case, T0 is guaranted not to be used. */
static CCPrepare gen_prepare_cc(DisasContext *s, int b, TCGv reg)
{
int inv, jcc_op, cond;
TCGMemOp size;
CCPrepare cc;
TCGv t0;
inv = b & 1;
jcc_op = (b >> 1) & 7;
switch (s->cc_op) {
case CC_OP_SUBB ... CC_OP_SUBQ:
/* We optimize relational operators for the cmp/jcc case. */
size = s->cc_op - CC_OP_SUBB;
switch (jcc_op) {
case JCC_BE:
tcg_gen_mov_tl(cpu_tmp4, cpu_cc_srcT);
gen_extu(size, cpu_tmp4);
t0 = gen_ext_tl(cpu_tmp0, cpu_cc_src, size, false);
cc = (CCPrepare) { .cond = TCG_COND_LEU, .reg = cpu_tmp4,
.reg2 = t0, .mask = -1, .use_reg2 = true };
break;
case JCC_L:
cond = TCG_COND_LT;
goto fast_jcc_l;
case JCC_LE:
cond = TCG_COND_LE;
fast_jcc_l:
tcg_gen_mov_tl(cpu_tmp4, cpu_cc_srcT);
gen_exts(size, cpu_tmp4);
t0 = gen_ext_tl(cpu_tmp0, cpu_cc_src, size, true);
cc = (CCPrepare) { .cond = cond, .reg = cpu_tmp4,
.reg2 = t0, .mask = -1, .use_reg2 = true };
break;
default:
goto slow_jcc;
}
break;
default:
slow_jcc:
/* This actually generates good code for JC, JZ and JS. */
switch (jcc_op) {
case JCC_O:
cc = gen_prepare_eflags_o(s, reg);
break;
case JCC_B:
cc = gen_prepare_eflags_c(s, reg);
break;
case JCC_Z:
cc = gen_prepare_eflags_z(s, reg);
break;
case JCC_BE:
gen_compute_eflags(s);
cc = (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src,
.mask = CC_Z | CC_C };
break;
case JCC_S:
cc = gen_prepare_eflags_s(s, reg);
break;
case JCC_P:
cc = gen_prepare_eflags_p(s, reg);
break;
case JCC_L:
gen_compute_eflags(s);
if (TCGV_EQUAL(reg, cpu_cc_src)) {
reg = cpu_tmp0;
}
tcg_gen_shri_tl(reg, cpu_cc_src, 4); /* CC_O -> CC_S */
tcg_gen_xor_tl(reg, reg, cpu_cc_src);
cc = (CCPrepare) { .cond = TCG_COND_NE, .reg = reg,
.mask = CC_S };
break;
default:
case JCC_LE:
gen_compute_eflags(s);
if (TCGV_EQUAL(reg, cpu_cc_src)) {
reg = cpu_tmp0;
}
tcg_gen_shri_tl(reg, cpu_cc_src, 4); /* CC_O -> CC_S */
tcg_gen_xor_tl(reg, reg, cpu_cc_src);
cc = (CCPrepare) { .cond = TCG_COND_NE, .reg = reg,
.mask = CC_S | CC_Z };
break;
}
break;
}
if (inv) {
cc.cond = tcg_invert_cond(cc.cond);
}
return cc;
}
static void gen_setcc1(DisasContext *s, int b, TCGv reg)
{
CCPrepare cc = gen_prepare_cc(s, b, reg);
if (cc.no_setcond) {
if (cc.cond == TCG_COND_EQ) {
tcg_gen_xori_tl(reg, cc.reg, 1);
} else {
tcg_gen_mov_tl(reg, cc.reg);
}
return;
}
if (cc.cond == TCG_COND_NE && !cc.use_reg2 && cc.imm == 0 &&
cc.mask != 0 && (cc.mask & (cc.mask - 1)) == 0) {
tcg_gen_shri_tl(reg, cc.reg, ctztl(cc.mask));
tcg_gen_andi_tl(reg, reg, 1);
return;
}
if (cc.mask != -1) {
tcg_gen_andi_tl(reg, cc.reg, cc.mask);
cc.reg = reg;
}
if (cc.use_reg2) {
tcg_gen_setcond_tl(cc.cond, reg, cc.reg, cc.reg2);
} else {
tcg_gen_setcondi_tl(cc.cond, reg, cc.reg, cc.imm);
}
}
static inline void gen_compute_eflags_c(DisasContext *s, TCGv reg)
{
gen_setcc1(s, JCC_B << 1, reg);
}
/* generate a conditional jump to label 'l1' according to jump opcode
value 'b'. In the fast case, T0 is guaranted not to be used. */
static inline void gen_jcc1_noeob(DisasContext *s, int b, TCGLabel *l1)
{
CCPrepare cc = gen_prepare_cc(s, b, cpu_T0);
if (cc.mask != -1) {
tcg_gen_andi_tl(cpu_T0, cc.reg, cc.mask);
cc.reg = cpu_T0;
}
if (cc.use_reg2) {
tcg_gen_brcond_tl(cc.cond, cc.reg, cc.reg2, l1);
} else {
tcg_gen_brcondi_tl(cc.cond, cc.reg, cc.imm, l1);
}
}
/* Generate a conditional jump to label 'l1' according to jump opcode
value 'b'. In the fast case, T0 is guaranted not to be used.
A translation block must end soon. */
static inline void gen_jcc1(DisasContext *s, int b, TCGLabel *l1)
{
CCPrepare cc = gen_prepare_cc(s, b, cpu_T0);
gen_update_cc_op(s);
if (cc.mask != -1) {
tcg_gen_andi_tl(cpu_T0, cc.reg, cc.mask);
cc.reg = cpu_T0;
}
set_cc_op(s, CC_OP_DYNAMIC);
if (cc.use_reg2) {
tcg_gen_brcond_tl(cc.cond, cc.reg, cc.reg2, l1);
} else {
tcg_gen_brcondi_tl(cc.cond, cc.reg, cc.imm, l1);
}
}
/* XXX: does not work with gdbstub "ice" single step - not a
serious problem */
static TCGLabel *gen_jz_ecx_string(DisasContext *s, target_ulong next_eip)
{
TCGLabel *l1 = gen_new_label();
TCGLabel *l2 = gen_new_label();
gen_op_jnz_ecx(s->aflag, l1);
gen_set_label(l2);
gen_jmp_tb(s, next_eip, 1);
gen_set_label(l1);
return l2;
}
static inline void gen_stos(DisasContext *s, TCGMemOp ot)
{
gen_op_mov_v_reg(MO_32, cpu_T0, R_EAX);
gen_string_movl_A0_EDI(s);
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_EDI);
}
static inline void gen_lods(DisasContext *s, TCGMemOp ot)
{
gen_string_movl_A0_ESI(s);
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
gen_op_mov_reg_v(ot, R_EAX, cpu_T0);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_ESI);
}
static inline void gen_scas(DisasContext *s, TCGMemOp ot)
{
gen_string_movl_A0_EDI(s);
gen_op_ld_v(s, ot, cpu_T1, cpu_A0);
gen_op(s, OP_CMPL, ot, R_EAX);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_EDI);
}
static inline void gen_cmps(DisasContext *s, TCGMemOp ot)
{
gen_string_movl_A0_EDI(s);
gen_op_ld_v(s, ot, cpu_T1, cpu_A0);
gen_string_movl_A0_ESI(s);
gen_op(s, OP_CMPL, ot, OR_TMP0);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_ESI);
gen_op_add_reg_T0(s->aflag, R_EDI);
}
static void gen_bpt_io(DisasContext *s, TCGv_i32 t_port, int ot)
{
if (s->flags & HF_IOBPT_MASK) {
TCGv_i32 t_size = tcg_const_i32(1 << ot);
TCGv t_next = tcg_const_tl(s->pc - s->cs_base);
gen_helper_bpt_io(cpu_env, t_port, t_size, t_next);
tcg_temp_free_i32(t_size);
tcg_temp_free(t_next);
}
}
static inline void gen_ins(DisasContext *s, TCGMemOp ot)
{
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_start();
}
gen_string_movl_A0_EDI(s);
/* Note: we must do this dummy write first to be restartable in
case of page fault. */
tcg_gen_movi_tl(cpu_T0, 0);
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_EDX]);
tcg_gen_andi_i32(cpu_tmp2_i32, cpu_tmp2_i32, 0xffff);
gen_helper_in_func(ot, cpu_T0, cpu_tmp2_i32);
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_EDI);
gen_bpt_io(s, cpu_tmp2_i32, ot);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_end();
}
}
static inline void gen_outs(DisasContext *s, TCGMemOp ot)
{
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_start();
}
gen_string_movl_A0_ESI(s);
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_EDX]);
tcg_gen_andi_i32(cpu_tmp2_i32, cpu_tmp2_i32, 0xffff);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T0);
gen_helper_out_func(ot, cpu_tmp2_i32, cpu_tmp3_i32);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_ESI);
gen_bpt_io(s, cpu_tmp2_i32, ot);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_end();
}
}
/* same method as Valgrind : we generate jumps to current or next
instruction */
#define GEN_REPZ(op) \
static inline void gen_repz_ ## op(DisasContext *s, TCGMemOp ot, \
target_ulong cur_eip, target_ulong next_eip) \
{ \
TCGLabel *l2; \
gen_update_cc_op(s); \
l2 = gen_jz_ecx_string(s, next_eip); \
gen_ ## op(s, ot); \
gen_op_add_reg_im(s->aflag, R_ECX, -1); \
/* a loop would cause two single step exceptions if ECX = 1 \
before rep string_insn */ \
if (s->repz_opt) \
gen_op_jz_ecx(s->aflag, l2); \
gen_jmp(s, cur_eip); \
}
#define GEN_REPZ2(op) \
static inline void gen_repz_ ## op(DisasContext *s, TCGMemOp ot, \
target_ulong cur_eip, \
target_ulong next_eip, \
int nz) \
{ \
TCGLabel *l2; \
gen_update_cc_op(s); \
l2 = gen_jz_ecx_string(s, next_eip); \
gen_ ## op(s, ot); \
gen_op_add_reg_im(s->aflag, R_ECX, -1); \
gen_update_cc_op(s); \
gen_jcc1(s, (JCC_Z << 1) | (nz ^ 1), l2); \
if (s->repz_opt) \
gen_op_jz_ecx(s->aflag, l2); \
gen_jmp(s, cur_eip); \
}
GEN_REPZ(movs)
GEN_REPZ(stos)
GEN_REPZ(lods)
GEN_REPZ(ins)
GEN_REPZ(outs)
GEN_REPZ2(scas)
GEN_REPZ2(cmps)
static void gen_helper_fp_arith_ST0_FT0(int op)
{
switch (op) {
case 0:
gen_helper_fadd_ST0_FT0(cpu_env);
break;
case 1:
gen_helper_fmul_ST0_FT0(cpu_env);
break;
case 2:
gen_helper_fcom_ST0_FT0(cpu_env);
break;
case 3:
gen_helper_fcom_ST0_FT0(cpu_env);
break;
case 4:
gen_helper_fsub_ST0_FT0(cpu_env);
break;
case 5:
gen_helper_fsubr_ST0_FT0(cpu_env);
break;
case 6:
gen_helper_fdiv_ST0_FT0(cpu_env);
break;
case 7:
gen_helper_fdivr_ST0_FT0(cpu_env);
break;
}
}
/* NOTE the exception in "r" op ordering */
static void gen_helper_fp_arith_STN_ST0(int op, int opreg)
{
TCGv_i32 tmp = tcg_const_i32(opreg);
switch (op) {
case 0:
gen_helper_fadd_STN_ST0(cpu_env, tmp);
break;
case 1:
gen_helper_fmul_STN_ST0(cpu_env, tmp);
break;
case 4:
gen_helper_fsubr_STN_ST0(cpu_env, tmp);
break;
case 5:
gen_helper_fsub_STN_ST0(cpu_env, tmp);
break;
case 6:
gen_helper_fdivr_STN_ST0(cpu_env, tmp);
break;
case 7:
gen_helper_fdiv_STN_ST0(cpu_env, tmp);
break;
}
}
/* if d == OR_TMP0, it means memory operand (address in A0) */
static void gen_op(DisasContext *s1, int op, TCGMemOp ot, int d)
{
if (d != OR_TMP0) {
gen_op_mov_v_reg(ot, cpu_T0, d);
} else if (!(s1->prefix & PREFIX_LOCK)) {
gen_op_ld_v(s1, ot, cpu_T0, cpu_A0);
}
switch(op) {
case OP_ADCL:
gen_compute_eflags_c(s1, cpu_tmp4);
if (s1->prefix & PREFIX_LOCK) {
tcg_gen_add_tl(cpu_T0, cpu_tmp4, cpu_T1);
tcg_gen_atomic_add_fetch_tl(cpu_T0, cpu_A0, cpu_T0,
s1->mem_index, ot | MO_LE);
} else {
tcg_gen_add_tl(cpu_T0, cpu_T0, cpu_T1);
tcg_gen_add_tl(cpu_T0, cpu_T0, cpu_tmp4);
gen_op_st_rm_T0_A0(s1, ot, d);
}
gen_op_update3_cc(cpu_tmp4);
set_cc_op(s1, CC_OP_ADCB + ot);
break;
case OP_SBBL:
gen_compute_eflags_c(s1, cpu_tmp4);
if (s1->prefix & PREFIX_LOCK) {
tcg_gen_add_tl(cpu_T0, cpu_T1, cpu_tmp4);
tcg_gen_neg_tl(cpu_T0, cpu_T0);
tcg_gen_atomic_add_fetch_tl(cpu_T0, cpu_A0, cpu_T0,
s1->mem_index, ot | MO_LE);
} else {
tcg_gen_sub_tl(cpu_T0, cpu_T0, cpu_T1);
tcg_gen_sub_tl(cpu_T0, cpu_T0, cpu_tmp4);
gen_op_st_rm_T0_A0(s1, ot, d);
}
gen_op_update3_cc(cpu_tmp4);
set_cc_op(s1, CC_OP_SBBB + ot);
break;
case OP_ADDL:
if (s1->prefix & PREFIX_LOCK) {
tcg_gen_atomic_add_fetch_tl(cpu_T0, cpu_A0, cpu_T1,
s1->mem_index, ot | MO_LE);
} else {
tcg_gen_add_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_st_rm_T0_A0(s1, ot, d);
}
gen_op_update2_cc();
set_cc_op(s1, CC_OP_ADDB + ot);
break;
case OP_SUBL:
if (s1->prefix & PREFIX_LOCK) {
tcg_gen_neg_tl(cpu_T0, cpu_T1);
tcg_gen_atomic_fetch_add_tl(cpu_cc_srcT, cpu_A0, cpu_T0,
s1->mem_index, ot | MO_LE);
tcg_gen_sub_tl(cpu_T0, cpu_cc_srcT, cpu_T1);
} else {
tcg_gen_mov_tl(cpu_cc_srcT, cpu_T0);
tcg_gen_sub_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_st_rm_T0_A0(s1, ot, d);
}
gen_op_update2_cc();
set_cc_op(s1, CC_OP_SUBB + ot);
break;
default:
case OP_ANDL:
if (s1->prefix & PREFIX_LOCK) {
tcg_gen_atomic_and_fetch_tl(cpu_T0, cpu_A0, cpu_T1,
s1->mem_index, ot | MO_LE);
} else {
tcg_gen_and_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_st_rm_T0_A0(s1, ot, d);
}
gen_op_update1_cc();
set_cc_op(s1, CC_OP_LOGICB + ot);
break;
case OP_ORL:
if (s1->prefix & PREFIX_LOCK) {
tcg_gen_atomic_or_fetch_tl(cpu_T0, cpu_A0, cpu_T1,
s1->mem_index, ot | MO_LE);
} else {
tcg_gen_or_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_st_rm_T0_A0(s1, ot, d);
}
gen_op_update1_cc();
set_cc_op(s1, CC_OP_LOGICB + ot);
break;
case OP_XORL:
if (s1->prefix & PREFIX_LOCK) {
tcg_gen_atomic_xor_fetch_tl(cpu_T0, cpu_A0, cpu_T1,
s1->mem_index, ot | MO_LE);
} else {
tcg_gen_xor_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_st_rm_T0_A0(s1, ot, d);
}
gen_op_update1_cc();
set_cc_op(s1, CC_OP_LOGICB + ot);
break;
case OP_CMPL:
tcg_gen_mov_tl(cpu_cc_src, cpu_T1);
tcg_gen_mov_tl(cpu_cc_srcT, cpu_T0);
tcg_gen_sub_tl(cpu_cc_dst, cpu_T0, cpu_T1);
set_cc_op(s1, CC_OP_SUBB + ot);
break;
}
}
/* if d == OR_TMP0, it means memory operand (address in A0) */
static void gen_inc(DisasContext *s1, TCGMemOp ot, int d, int c)
{
if (s1->prefix & PREFIX_LOCK) {
tcg_gen_movi_tl(cpu_T0, c > 0 ? 1 : -1);
tcg_gen_atomic_add_fetch_tl(cpu_T0, cpu_A0, cpu_T0,
s1->mem_index, ot | MO_LE);
} else {
if (d != OR_TMP0) {
gen_op_mov_v_reg(ot, cpu_T0, d);
} else {
gen_op_ld_v(s1, ot, cpu_T0, cpu_A0);
}
tcg_gen_addi_tl(cpu_T0, cpu_T0, (c > 0 ? 1 : -1));
gen_op_st_rm_T0_A0(s1, ot, d);
}
gen_compute_eflags_c(s1, cpu_cc_src);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
set_cc_op(s1, (c > 0 ? CC_OP_INCB : CC_OP_DECB) + ot);
}
static void gen_shift_flags(DisasContext *s, TCGMemOp ot, TCGv result,
TCGv shm1, TCGv count, bool is_right)
{
TCGv_i32 z32, s32, oldop;
TCGv z_tl;
/* Store the results into the CC variables. If we know that the
variable must be dead, store unconditionally. Otherwise we'll
need to not disrupt the current contents. */
z_tl = tcg_const_tl(0);
if (cc_op_live[s->cc_op] & USES_CC_DST) {
tcg_gen_movcond_tl(TCG_COND_NE, cpu_cc_dst, count, z_tl,
result, cpu_cc_dst);
} else {
tcg_gen_mov_tl(cpu_cc_dst, result);
}
if (cc_op_live[s->cc_op] & USES_CC_SRC) {
tcg_gen_movcond_tl(TCG_COND_NE, cpu_cc_src, count, z_tl,
shm1, cpu_cc_src);
} else {
tcg_gen_mov_tl(cpu_cc_src, shm1);
}
tcg_temp_free(z_tl);
/* Get the two potential CC_OP values into temporaries. */
tcg_gen_movi_i32(cpu_tmp2_i32, (is_right ? CC_OP_SARB : CC_OP_SHLB) + ot);
if (s->cc_op == CC_OP_DYNAMIC) {
oldop = cpu_cc_op;
} else {
tcg_gen_movi_i32(cpu_tmp3_i32, s->cc_op);
oldop = cpu_tmp3_i32;
}
/* Conditionally store the CC_OP value. */
z32 = tcg_const_i32(0);
s32 = tcg_temp_new_i32();
tcg_gen_trunc_tl_i32(s32, count);
tcg_gen_movcond_i32(TCG_COND_NE, cpu_cc_op, s32, z32, cpu_tmp2_i32, oldop);
tcg_temp_free_i32(z32);
tcg_temp_free_i32(s32);
/* The CC_OP value is no longer predictable. */
set_cc_op(s, CC_OP_DYNAMIC);
}
static void gen_shift_rm_T1(DisasContext *s, TCGMemOp ot, int op1,
int is_right, int is_arith)
{
target_ulong mask = (ot == MO_64 ? 0x3f : 0x1f);
/* load */
if (op1 == OR_TMP0) {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_v_reg(ot, cpu_T0, op1);
}
tcg_gen_andi_tl(cpu_T1, cpu_T1, mask);
tcg_gen_subi_tl(cpu_tmp0, cpu_T1, 1);
if (is_right) {
if (is_arith) {
gen_exts(ot, cpu_T0);
tcg_gen_sar_tl(cpu_tmp0, cpu_T0, cpu_tmp0);
tcg_gen_sar_tl(cpu_T0, cpu_T0, cpu_T1);
} else {
gen_extu(ot, cpu_T0);
tcg_gen_shr_tl(cpu_tmp0, cpu_T0, cpu_tmp0);
tcg_gen_shr_tl(cpu_T0, cpu_T0, cpu_T1);
}
} else {
tcg_gen_shl_tl(cpu_tmp0, cpu_T0, cpu_tmp0);
tcg_gen_shl_tl(cpu_T0, cpu_T0, cpu_T1);
}
/* store */
gen_op_st_rm_T0_A0(s, ot, op1);
gen_shift_flags(s, ot, cpu_T0, cpu_tmp0, cpu_T1, is_right);
}
static void gen_shift_rm_im(DisasContext *s, TCGMemOp ot, int op1, int op2,
int is_right, int is_arith)
{
int mask = (ot == MO_64 ? 0x3f : 0x1f);
/* load */
if (op1 == OR_TMP0)
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
else
gen_op_mov_v_reg(ot, cpu_T0, op1);
op2 &= mask;
if (op2 != 0) {
if (is_right) {
if (is_arith) {
gen_exts(ot, cpu_T0);
tcg_gen_sari_tl(cpu_tmp4, cpu_T0, op2 - 1);
tcg_gen_sari_tl(cpu_T0, cpu_T0, op2);
} else {
gen_extu(ot, cpu_T0);
tcg_gen_shri_tl(cpu_tmp4, cpu_T0, op2 - 1);
tcg_gen_shri_tl(cpu_T0, cpu_T0, op2);
}
} else {
tcg_gen_shli_tl(cpu_tmp4, cpu_T0, op2 - 1);
tcg_gen_shli_tl(cpu_T0, cpu_T0, op2);
}
}
/* store */
gen_op_st_rm_T0_A0(s, ot, op1);
/* update eflags if non zero shift */
if (op2 != 0) {
tcg_gen_mov_tl(cpu_cc_src, cpu_tmp4);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
set_cc_op(s, (is_right ? CC_OP_SARB : CC_OP_SHLB) + ot);
}
}
static void gen_rot_rm_T1(DisasContext *s, TCGMemOp ot, int op1, int is_right)
{
target_ulong mask = (ot == MO_64 ? 0x3f : 0x1f);
TCGv_i32 t0, t1;
/* load */
if (op1 == OR_TMP0) {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_v_reg(ot, cpu_T0, op1);
}
tcg_gen_andi_tl(cpu_T1, cpu_T1, mask);
switch (ot) {
case MO_8:
/* Replicate the 8-bit input so that a 32-bit rotate works. */
tcg_gen_ext8u_tl(cpu_T0, cpu_T0);
tcg_gen_muli_tl(cpu_T0, cpu_T0, 0x01010101);
goto do_long;
case MO_16:
/* Replicate the 16-bit input so that a 32-bit rotate works. */
tcg_gen_deposit_tl(cpu_T0, cpu_T0, cpu_T0, 16, 16);
goto do_long;
do_long:
#ifdef TARGET_X86_64
case MO_32:
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T1);
if (is_right) {
tcg_gen_rotr_i32(cpu_tmp2_i32, cpu_tmp2_i32, cpu_tmp3_i32);
} else {
tcg_gen_rotl_i32(cpu_tmp2_i32, cpu_tmp2_i32, cpu_tmp3_i32);
}
tcg_gen_extu_i32_tl(cpu_T0, cpu_tmp2_i32);
break;
#endif
default:
if (is_right) {
tcg_gen_rotr_tl(cpu_T0, cpu_T0, cpu_T1);
} else {
tcg_gen_rotl_tl(cpu_T0, cpu_T0, cpu_T1);
}
break;
}
/* store */
gen_op_st_rm_T0_A0(s, ot, op1);
/* We'll need the flags computed into CC_SRC. */
gen_compute_eflags(s);
/* The value that was "rotated out" is now present at the other end
of the word. Compute C into CC_DST and O into CC_SRC2. Note that
since we've computed the flags into CC_SRC, these variables are
currently dead. */
if (is_right) {
tcg_gen_shri_tl(cpu_cc_src2, cpu_T0, mask - 1);
tcg_gen_shri_tl(cpu_cc_dst, cpu_T0, mask);
tcg_gen_andi_tl(cpu_cc_dst, cpu_cc_dst, 1);
} else {
tcg_gen_shri_tl(cpu_cc_src2, cpu_T0, mask);
tcg_gen_andi_tl(cpu_cc_dst, cpu_T0, 1);
}
tcg_gen_andi_tl(cpu_cc_src2, cpu_cc_src2, 1);
tcg_gen_xor_tl(cpu_cc_src2, cpu_cc_src2, cpu_cc_dst);
/* Now conditionally store the new CC_OP value. If the shift count
is 0 we keep the CC_OP_EFLAGS setting so that only CC_SRC is live.
Otherwise reuse CC_OP_ADCOX which have the C and O flags split out
exactly as we computed above. */
t0 = tcg_const_i32(0);
t1 = tcg_temp_new_i32();
tcg_gen_trunc_tl_i32(t1, cpu_T1);
tcg_gen_movi_i32(cpu_tmp2_i32, CC_OP_ADCOX);
tcg_gen_movi_i32(cpu_tmp3_i32, CC_OP_EFLAGS);
tcg_gen_movcond_i32(TCG_COND_NE, cpu_cc_op, t1, t0,
cpu_tmp2_i32, cpu_tmp3_i32);
tcg_temp_free_i32(t0);
tcg_temp_free_i32(t1);
/* The CC_OP value is no longer predictable. */
set_cc_op(s, CC_OP_DYNAMIC);
}
static void gen_rot_rm_im(DisasContext *s, TCGMemOp ot, int op1, int op2,
int is_right)
{
int mask = (ot == MO_64 ? 0x3f : 0x1f);
int shift;
/* load */
if (op1 == OR_TMP0) {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_v_reg(ot, cpu_T0, op1);
}
op2 &= mask;
if (op2 != 0) {
switch (ot) {
#ifdef TARGET_X86_64
case MO_32:
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
if (is_right) {
tcg_gen_rotri_i32(cpu_tmp2_i32, cpu_tmp2_i32, op2);
} else {
tcg_gen_rotli_i32(cpu_tmp2_i32, cpu_tmp2_i32, op2);
}
tcg_gen_extu_i32_tl(cpu_T0, cpu_tmp2_i32);
break;
#endif
default:
if (is_right) {
tcg_gen_rotri_tl(cpu_T0, cpu_T0, op2);
} else {
tcg_gen_rotli_tl(cpu_T0, cpu_T0, op2);
}
break;
case MO_8:
mask = 7;
goto do_shifts;
case MO_16:
mask = 15;
do_shifts:
shift = op2 & mask;
if (is_right) {
shift = mask + 1 - shift;
}
gen_extu(ot, cpu_T0);
tcg_gen_shli_tl(cpu_tmp0, cpu_T0, shift);
tcg_gen_shri_tl(cpu_T0, cpu_T0, mask + 1 - shift);
tcg_gen_or_tl(cpu_T0, cpu_T0, cpu_tmp0);
break;
}
}
/* store */
gen_op_st_rm_T0_A0(s, ot, op1);
if (op2 != 0) {
/* Compute the flags into CC_SRC. */
gen_compute_eflags(s);
/* The value that was "rotated out" is now present at the other end
of the word. Compute C into CC_DST and O into CC_SRC2. Note that
since we've computed the flags into CC_SRC, these variables are
currently dead. */
if (is_right) {
tcg_gen_shri_tl(cpu_cc_src2, cpu_T0, mask - 1);
tcg_gen_shri_tl(cpu_cc_dst, cpu_T0, mask);
tcg_gen_andi_tl(cpu_cc_dst, cpu_cc_dst, 1);
} else {
tcg_gen_shri_tl(cpu_cc_src2, cpu_T0, mask);
tcg_gen_andi_tl(cpu_cc_dst, cpu_T0, 1);
}
tcg_gen_andi_tl(cpu_cc_src2, cpu_cc_src2, 1);
tcg_gen_xor_tl(cpu_cc_src2, cpu_cc_src2, cpu_cc_dst);
set_cc_op(s, CC_OP_ADCOX);
}
}
/* XXX: add faster immediate = 1 case */
static void gen_rotc_rm_T1(DisasContext *s, TCGMemOp ot, int op1,
int is_right)
{
gen_compute_eflags(s);
assert(s->cc_op == CC_OP_EFLAGS);
/* load */
if (op1 == OR_TMP0)
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
else
gen_op_mov_v_reg(ot, cpu_T0, op1);
if (is_right) {
switch (ot) {
case MO_8:
gen_helper_rcrb(cpu_T0, cpu_env, cpu_T0, cpu_T1);
break;
case MO_16:
gen_helper_rcrw(cpu_T0, cpu_env, cpu_T0, cpu_T1);
break;
case MO_32:
gen_helper_rcrl(cpu_T0, cpu_env, cpu_T0, cpu_T1);
break;
#ifdef TARGET_X86_64
case MO_64:
gen_helper_rcrq(cpu_T0, cpu_env, cpu_T0, cpu_T1);
break;
#endif
default:
tcg_abort();
}
} else {
switch (ot) {
case MO_8:
gen_helper_rclb(cpu_T0, cpu_env, cpu_T0, cpu_T1);
break;
case MO_16:
gen_helper_rclw(cpu_T0, cpu_env, cpu_T0, cpu_T1);
break;
case MO_32:
gen_helper_rcll(cpu_T0, cpu_env, cpu_T0, cpu_T1);
break;
#ifdef TARGET_X86_64
case MO_64:
gen_helper_rclq(cpu_T0, cpu_env, cpu_T0, cpu_T1);
break;
#endif
default:
tcg_abort();
}
}
/* store */
gen_op_st_rm_T0_A0(s, ot, op1);
}
/* XXX: add faster immediate case */
static void gen_shiftd_rm_T1(DisasContext *s, TCGMemOp ot, int op1,
bool is_right, TCGv count_in)
{
target_ulong mask = (ot == MO_64 ? 63 : 31);
TCGv count;
/* load */
if (op1 == OR_TMP0) {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_v_reg(ot, cpu_T0, op1);
}
count = tcg_temp_new();
tcg_gen_andi_tl(count, count_in, mask);
switch (ot) {
case MO_16:
/* Note: we implement the Intel behaviour for shift count > 16.
This means "shrdw C, B, A" shifts A:B:A >> C. Build the B:A
portion by constructing it as a 32-bit value. */
if (is_right) {
tcg_gen_deposit_tl(cpu_tmp0, cpu_T0, cpu_T1, 16, 16);
tcg_gen_mov_tl(cpu_T1, cpu_T0);
tcg_gen_mov_tl(cpu_T0, cpu_tmp0);
} else {
tcg_gen_deposit_tl(cpu_T1, cpu_T0, cpu_T1, 16, 16);
}
/* FALLTHRU */
#ifdef TARGET_X86_64
case MO_32:
/* Concatenate the two 32-bit values and use a 64-bit shift. */
tcg_gen_subi_tl(cpu_tmp0, count, 1);
if (is_right) {
tcg_gen_concat_tl_i64(cpu_T0, cpu_T0, cpu_T1);
tcg_gen_shr_i64(cpu_tmp0, cpu_T0, cpu_tmp0);
tcg_gen_shr_i64(cpu_T0, cpu_T0, count);
} else {
tcg_gen_concat_tl_i64(cpu_T0, cpu_T1, cpu_T0);
tcg_gen_shl_i64(cpu_tmp0, cpu_T0, cpu_tmp0);
tcg_gen_shl_i64(cpu_T0, cpu_T0, count);
tcg_gen_shri_i64(cpu_tmp0, cpu_tmp0, 32);
tcg_gen_shri_i64(cpu_T0, cpu_T0, 32);
}
break;
#endif
default:
tcg_gen_subi_tl(cpu_tmp0, count, 1);
if (is_right) {
tcg_gen_shr_tl(cpu_tmp0, cpu_T0, cpu_tmp0);
tcg_gen_subfi_tl(cpu_tmp4, mask + 1, count);
tcg_gen_shr_tl(cpu_T0, cpu_T0, count);
tcg_gen_shl_tl(cpu_T1, cpu_T1, cpu_tmp4);
} else {
tcg_gen_shl_tl(cpu_tmp0, cpu_T0, cpu_tmp0);
if (ot == MO_16) {
/* Only needed if count > 16, for Intel behaviour. */
tcg_gen_subfi_tl(cpu_tmp4, 33, count);
tcg_gen_shr_tl(cpu_tmp4, cpu_T1, cpu_tmp4);
tcg_gen_or_tl(cpu_tmp0, cpu_tmp0, cpu_tmp4);
}
tcg_gen_subfi_tl(cpu_tmp4, mask + 1, count);
tcg_gen_shl_tl(cpu_T0, cpu_T0, count);
tcg_gen_shr_tl(cpu_T1, cpu_T1, cpu_tmp4);
}
tcg_gen_movi_tl(cpu_tmp4, 0);
tcg_gen_movcond_tl(TCG_COND_EQ, cpu_T1, count, cpu_tmp4,
cpu_tmp4, cpu_T1);
tcg_gen_or_tl(cpu_T0, cpu_T0, cpu_T1);
break;
}
/* store */
gen_op_st_rm_T0_A0(s, ot, op1);
gen_shift_flags(s, ot, cpu_T0, cpu_tmp0, count, is_right);
tcg_temp_free(count);
}
static void gen_shift(DisasContext *s1, int op, TCGMemOp ot, int d, int s)
{
if (s != OR_TMP1)
gen_op_mov_v_reg(ot, cpu_T1, s);
switch(op) {
case OP_ROL:
gen_rot_rm_T1(s1, ot, d, 0);
break;
case OP_ROR:
gen_rot_rm_T1(s1, ot, d, 1);
break;
case OP_SHL:
case OP_SHL1:
gen_shift_rm_T1(s1, ot, d, 0, 0);
break;
case OP_SHR:
gen_shift_rm_T1(s1, ot, d, 1, 0);
break;
case OP_SAR:
gen_shift_rm_T1(s1, ot, d, 1, 1);
break;
case OP_RCL:
gen_rotc_rm_T1(s1, ot, d, 0);
break;
case OP_RCR:
gen_rotc_rm_T1(s1, ot, d, 1);
break;
}
}
static void gen_shifti(DisasContext *s1, int op, TCGMemOp ot, int d, int c)
{
switch(op) {
case OP_ROL:
gen_rot_rm_im(s1, ot, d, c, 0);
break;
case OP_ROR:
gen_rot_rm_im(s1, ot, d, c, 1);
break;
case OP_SHL:
case OP_SHL1:
gen_shift_rm_im(s1, ot, d, c, 0, 0);
break;
case OP_SHR:
gen_shift_rm_im(s1, ot, d, c, 1, 0);
break;
case OP_SAR:
gen_shift_rm_im(s1, ot, d, c, 1, 1);
break;
default:
/* currently not optimized */
tcg_gen_movi_tl(cpu_T1, c);
gen_shift(s1, op, ot, d, OR_TMP1);
break;
}
}
/* Decompose an address. */
typedef struct AddressParts {
int def_seg;
int base;
int index;
int scale;
target_long disp;
} AddressParts;
static AddressParts gen_lea_modrm_0(CPUX86State *env, DisasContext *s,
int modrm)
{
int def_seg, base, index, scale, mod, rm;
target_long disp;
bool havesib;
def_seg = R_DS;
index = -1;
scale = 0;
disp = 0;
mod = (modrm >> 6) & 3;
rm = modrm & 7;
base = rm | REX_B(s);
if (mod == 3) {
/* Normally filtered out earlier, but including this path
simplifies multi-byte nop, as well as bndcl, bndcu, bndcn. */
goto done;
}
switch (s->aflag) {
case MO_64:
case MO_32:
havesib = 0;
if (rm == 4) {
int code = cpu_ldub_code(env, s->pc++);
scale = (code >> 6) & 3;
index = ((code >> 3) & 7) | REX_X(s);
if (index == 4) {
index = -1; /* no index */
}
base = (code & 7) | REX_B(s);
havesib = 1;
}
switch (mod) {
case 0:
if ((base & 7) == 5) {
base = -1;
disp = (int32_t)cpu_ldl_code(env, s->pc);
s->pc += 4;
if (CODE64(s) && !havesib) {
base = -2;
disp += s->pc + s->rip_offset;
}
}
break;
case 1:
disp = (int8_t)cpu_ldub_code(env, s->pc++);
break;
default:
case 2:
disp = (int32_t)cpu_ldl_code(env, s->pc);
s->pc += 4;
break;
}
/* For correct popl handling with esp. */
if (base == R_ESP && s->popl_esp_hack) {
disp += s->popl_esp_hack;
}
if (base == R_EBP || base == R_ESP) {
def_seg = R_SS;
}
break;
case MO_16:
if (mod == 0) {
if (rm == 6) {
base = -1;
disp = cpu_lduw_code(env, s->pc);
s->pc += 2;
break;
}
} else if (mod == 1) {
disp = (int8_t)cpu_ldub_code(env, s->pc++);
} else {
disp = (int16_t)cpu_lduw_code(env, s->pc);
s->pc += 2;
}
switch (rm) {
case 0:
base = R_EBX;
index = R_ESI;
break;
case 1:
base = R_EBX;
index = R_EDI;
break;
case 2:
base = R_EBP;
index = R_ESI;
def_seg = R_SS;
break;
case 3:
base = R_EBP;
index = R_EDI;
def_seg = R_SS;
break;
case 4:
base = R_ESI;
break;
case 5:
base = R_EDI;
break;
case 6:
base = R_EBP;
def_seg = R_SS;
break;
default:
case 7:
base = R_EBX;
break;
}
break;
default:
tcg_abort();
}
done:
return (AddressParts){ def_seg, base, index, scale, disp };
}
/* Compute the address, with a minimum number of TCG ops. */
static TCGv gen_lea_modrm_1(AddressParts a)
{
TCGv ea;
TCGV_UNUSED(ea);
if (a.index >= 0) {
if (a.scale == 0) {
ea = cpu_regs[a.index];
} else {
tcg_gen_shli_tl(cpu_A0, cpu_regs[a.index], a.scale);
ea = cpu_A0;
}
if (a.base >= 0) {
tcg_gen_add_tl(cpu_A0, ea, cpu_regs[a.base]);
ea = cpu_A0;
}
} else if (a.base >= 0) {
ea = cpu_regs[a.base];
}
if (TCGV_IS_UNUSED(ea)) {
tcg_gen_movi_tl(cpu_A0, a.disp);
ea = cpu_A0;
} else if (a.disp != 0) {
tcg_gen_addi_tl(cpu_A0, ea, a.disp);
ea = cpu_A0;
}
return ea;
}
static void gen_lea_modrm(CPUX86State *env, DisasContext *s, int modrm)
{
AddressParts a = gen_lea_modrm_0(env, s, modrm);
TCGv ea = gen_lea_modrm_1(a);
gen_lea_v_seg(s, s->aflag, ea, a.def_seg, s->override);
}
static void gen_nop_modrm(CPUX86State *env, DisasContext *s, int modrm)
{
(void)gen_lea_modrm_0(env, s, modrm);
}
/* Used for BNDCL, BNDCU, BNDCN. */
static void gen_bndck(CPUX86State *env, DisasContext *s, int modrm,
TCGCond cond, TCGv_i64 bndv)
{
TCGv ea = gen_lea_modrm_1(gen_lea_modrm_0(env, s, modrm));
tcg_gen_extu_tl_i64(cpu_tmp1_i64, ea);
if (!CODE64(s)) {
tcg_gen_ext32u_i64(cpu_tmp1_i64, cpu_tmp1_i64);
}
tcg_gen_setcond_i64(cond, cpu_tmp1_i64, cpu_tmp1_i64, bndv);
tcg_gen_extrl_i64_i32(cpu_tmp2_i32, cpu_tmp1_i64);
gen_helper_bndck(cpu_env, cpu_tmp2_i32);
}
/* used for LEA and MOV AX, mem */
static void gen_add_A0_ds_seg(DisasContext *s)
{
gen_lea_v_seg(s, s->aflag, cpu_A0, R_DS, s->override);
}
/* generate modrm memory load or store of 'reg'. TMP0 is used if reg ==
OR_TMP0 */
static void gen_ldst_modrm(CPUX86State *env, DisasContext *s, int modrm,
TCGMemOp ot, int reg, int is_store)
{
int mod, rm;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
if (mod == 3) {
if (is_store) {
if (reg != OR_TMP0)
gen_op_mov_v_reg(ot, cpu_T0, reg);
gen_op_mov_reg_v(ot, rm, cpu_T0);
} else {
gen_op_mov_v_reg(ot, cpu_T0, rm);
if (reg != OR_TMP0)
gen_op_mov_reg_v(ot, reg, cpu_T0);
}
} else {
gen_lea_modrm(env, s, modrm);
if (is_store) {
if (reg != OR_TMP0)
gen_op_mov_v_reg(ot, cpu_T0, reg);
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
if (reg != OR_TMP0)
gen_op_mov_reg_v(ot, reg, cpu_T0);
}
}
}
static inline uint32_t insn_get(CPUX86State *env, DisasContext *s, TCGMemOp ot)
{
uint32_t ret;
switch (ot) {
case MO_8:
ret = cpu_ldub_code(env, s->pc);
s->pc++;
break;
case MO_16:
ret = cpu_lduw_code(env, s->pc);
s->pc += 2;
break;
case MO_32:
#ifdef TARGET_X86_64
case MO_64:
#endif
ret = cpu_ldl_code(env, s->pc);
s->pc += 4;
break;
default:
tcg_abort();
}
return ret;
}
static inline int insn_const_size(TCGMemOp ot)
{
if (ot <= MO_32) {
return 1 << ot;
} else {
return 4;
}
}
static inline bool use_goto_tb(DisasContext *s, target_ulong pc)
{
#ifndef CONFIG_USER_ONLY
return (pc & TARGET_PAGE_MASK) == (s->tb->pc & TARGET_PAGE_MASK) ||
(pc & TARGET_PAGE_MASK) == (s->pc_start & TARGET_PAGE_MASK);
#else
return true;
#endif
}
static inline void gen_goto_tb(DisasContext *s, int tb_num, target_ulong eip)
{
target_ulong pc = s->cs_base + eip;
if (use_goto_tb(s, pc)) {
/* jump to same page: we can use a direct jump */
tcg_gen_goto_tb(tb_num);
gen_jmp_im(eip);
tcg_gen_exit_tb((uintptr_t)s->tb + tb_num);
} else {
/* jump to another page: currently not optimized */
gen_jmp_im(eip);
gen_eob(s);
}
}
static inline void gen_jcc(DisasContext *s, int b,
target_ulong val, target_ulong next_eip)
{
TCGLabel *l1, *l2;
if (s->jmp_opt) {
l1 = gen_new_label();
gen_jcc1(s, b, l1);
gen_goto_tb(s, 0, next_eip);
gen_set_label(l1);
gen_goto_tb(s, 1, val);
s->is_jmp = DISAS_TB_JUMP;
} else {
l1 = gen_new_label();
l2 = gen_new_label();
gen_jcc1(s, b, l1);
gen_jmp_im(next_eip);
tcg_gen_br(l2);
gen_set_label(l1);
gen_jmp_im(val);
gen_set_label(l2);
gen_eob(s);
}
}
static void gen_cmovcc1(CPUX86State *env, DisasContext *s, TCGMemOp ot, int b,
int modrm, int reg)
{
CCPrepare cc;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
cc = gen_prepare_cc(s, b, cpu_T1);
if (cc.mask != -1) {
TCGv t0 = tcg_temp_new();
tcg_gen_andi_tl(t0, cc.reg, cc.mask);
cc.reg = t0;
}
if (!cc.use_reg2) {
cc.reg2 = tcg_const_tl(cc.imm);
}
tcg_gen_movcond_tl(cc.cond, cpu_T0, cc.reg, cc.reg2,
cpu_T0, cpu_regs[reg]);
gen_op_mov_reg_v(ot, reg, cpu_T0);
if (cc.mask != -1) {
tcg_temp_free(cc.reg);
}
if (!cc.use_reg2) {
tcg_temp_free(cc.reg2);
}
}
static inline void gen_op_movl_T0_seg(int seg_reg)
{
tcg_gen_ld32u_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,segs[seg_reg].selector));
}
static inline void gen_op_movl_seg_T0_vm(int seg_reg)
{
tcg_gen_ext16u_tl(cpu_T0, cpu_T0);
tcg_gen_st32_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,segs[seg_reg].selector));
tcg_gen_shli_tl(cpu_seg_base[seg_reg], cpu_T0, 4);
}
/* move T0 to seg_reg and compute if the CPU state may change. Never
call this function with seg_reg == R_CS */
static void gen_movl_seg_T0(DisasContext *s, int seg_reg)
{
if (s->pe && !s->vm86) {
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_load_seg(cpu_env, tcg_const_i32(seg_reg), cpu_tmp2_i32);
/* abort translation because the addseg value may change or
because ss32 may change. For R_SS, translation must always
stop as a special handling must be done to disable hardware
interrupts for the next instruction */
if (seg_reg == R_SS || (s->code32 && seg_reg < R_FS))
s->is_jmp = DISAS_TB_JUMP;
} else {
gen_op_movl_seg_T0_vm(seg_reg);
if (seg_reg == R_SS)
s->is_jmp = DISAS_TB_JUMP;
}
}
static inline int svm_is_rep(int prefixes)
{
return ((prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) ? 8 : 0);
}
static inline void
gen_svm_check_intercept_param(DisasContext *s, target_ulong pc_start,
uint32_t type, uint64_t param)
{
/* no SVM activated; fast case */
if (likely(!(s->flags & HF_SVMI_MASK)))
return;
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_svm_check_intercept_param(cpu_env, tcg_const_i32(type),
tcg_const_i64(param));
}
static inline void
gen_svm_check_intercept(DisasContext *s, target_ulong pc_start, uint64_t type)
{
gen_svm_check_intercept_param(s, pc_start, type, 0);
}
static inline void gen_stack_update(DisasContext *s, int addend)
{
gen_op_add_reg_im(mo_stacksize(s), R_ESP, addend);
}
/* Generate a push. It depends on ss32, addseg and dflag. */
static void gen_push_v(DisasContext *s, TCGv val)
{
TCGMemOp d_ot = mo_pushpop(s, s->dflag);
TCGMemOp a_ot = mo_stacksize(s);
int size = 1 << d_ot;
TCGv new_esp = cpu_A0;
tcg_gen_subi_tl(cpu_A0, cpu_regs[R_ESP], size);
if (!CODE64(s)) {
if (s->addseg) {
new_esp = cpu_tmp4;
tcg_gen_mov_tl(new_esp, cpu_A0);
}
gen_lea_v_seg(s, a_ot, cpu_A0, R_SS, -1);
}
gen_op_st_v(s, d_ot, val, cpu_A0);
gen_op_mov_reg_v(a_ot, R_ESP, new_esp);
}
/* two step pop is necessary for precise exceptions */
static TCGMemOp gen_pop_T0(DisasContext *s)
{
TCGMemOp d_ot = mo_pushpop(s, s->dflag);
gen_lea_v_seg(s, mo_stacksize(s), cpu_regs[R_ESP], R_SS, -1);
gen_op_ld_v(s, d_ot, cpu_T0, cpu_A0);
return d_ot;
}
static inline void gen_pop_update(DisasContext *s, TCGMemOp ot)
{
gen_stack_update(s, 1 << ot);
}
static inline void gen_stack_A0(DisasContext *s)
{
gen_lea_v_seg(s, s->ss32 ? MO_32 : MO_16, cpu_regs[R_ESP], R_SS, -1);
}
static void gen_pusha(DisasContext *s)
{
TCGMemOp s_ot = s->ss32 ? MO_32 : MO_16;
TCGMemOp d_ot = s->dflag;
int size = 1 << d_ot;
int i;
for (i = 0; i < 8; i++) {
tcg_gen_addi_tl(cpu_A0, cpu_regs[R_ESP], (i - 8) * size);
gen_lea_v_seg(s, s_ot, cpu_A0, R_SS, -1);
gen_op_st_v(s, d_ot, cpu_regs[7 - i], cpu_A0);
}
gen_stack_update(s, -8 * size);
}
static void gen_popa(DisasContext *s)
{
TCGMemOp s_ot = s->ss32 ? MO_32 : MO_16;
TCGMemOp d_ot = s->dflag;
int size = 1 << d_ot;
int i;
for (i = 0; i < 8; i++) {
/* ESP is not reloaded */
if (7 - i == R_ESP) {
continue;
}
tcg_gen_addi_tl(cpu_A0, cpu_regs[R_ESP], i * size);
gen_lea_v_seg(s, s_ot, cpu_A0, R_SS, -1);
gen_op_ld_v(s, d_ot, cpu_T0, cpu_A0);
gen_op_mov_reg_v(d_ot, 7 - i, cpu_T0);
}
gen_stack_update(s, 8 * size);
}
static void gen_enter(DisasContext *s, int esp_addend, int level)
{
TCGMemOp d_ot = mo_pushpop(s, s->dflag);
TCGMemOp a_ot = CODE64(s) ? MO_64 : s->ss32 ? MO_32 : MO_16;
int size = 1 << d_ot;
/* Push BP; compute FrameTemp into T1. */
tcg_gen_subi_tl(cpu_T1, cpu_regs[R_ESP], size);
gen_lea_v_seg(s, a_ot, cpu_T1, R_SS, -1);
gen_op_st_v(s, d_ot, cpu_regs[R_EBP], cpu_A0);
level &= 31;
if (level != 0) {
int i;
/* Copy level-1 pointers from the previous frame. */
for (i = 1; i < level; ++i) {
tcg_gen_subi_tl(cpu_A0, cpu_regs[R_EBP], size * i);
gen_lea_v_seg(s, a_ot, cpu_A0, R_SS, -1);
gen_op_ld_v(s, d_ot, cpu_tmp0, cpu_A0);
tcg_gen_subi_tl(cpu_A0, cpu_T1, size * i);
gen_lea_v_seg(s, a_ot, cpu_A0, R_SS, -1);
gen_op_st_v(s, d_ot, cpu_tmp0, cpu_A0);
}
/* Push the current FrameTemp as the last level. */
tcg_gen_subi_tl(cpu_A0, cpu_T1, size * level);
gen_lea_v_seg(s, a_ot, cpu_A0, R_SS, -1);
gen_op_st_v(s, d_ot, cpu_T1, cpu_A0);
}
/* Copy the FrameTemp value to EBP. */
gen_op_mov_reg_v(a_ot, R_EBP, cpu_T1);
/* Compute the final value of ESP. */
tcg_gen_subi_tl(cpu_T1, cpu_T1, esp_addend + size * level);
gen_op_mov_reg_v(a_ot, R_ESP, cpu_T1);
}
static void gen_leave(DisasContext *s)
{
TCGMemOp d_ot = mo_pushpop(s, s->dflag);
TCGMemOp a_ot = mo_stacksize(s);
gen_lea_v_seg(s, a_ot, cpu_regs[R_EBP], R_SS, -1);
gen_op_ld_v(s, d_ot, cpu_T0, cpu_A0);
tcg_gen_addi_tl(cpu_T1, cpu_regs[R_EBP], 1 << d_ot);
gen_op_mov_reg_v(d_ot, R_EBP, cpu_T0);
gen_op_mov_reg_v(a_ot, R_ESP, cpu_T1);
}
static void gen_exception(DisasContext *s, int trapno, target_ulong cur_eip)
{
gen_update_cc_op(s);
gen_jmp_im(cur_eip);
gen_helper_raise_exception(cpu_env, tcg_const_i32(trapno));
s->is_jmp = DISAS_TB_JUMP;
}
/* Generate #UD for the current instruction. The assumption here is that
the instruction is known, but it isn't allowed in the current cpu mode. */
static void gen_illegal_opcode(DisasContext *s)
{
gen_exception(s, EXCP06_ILLOP, s->pc_start - s->cs_base);
}
/* Similarly, except that the assumption here is that we don't decode
the instruction at all -- either a missing opcode, an unimplemented
feature, or just a bogus instruction stream. */
static void gen_unknown_opcode(CPUX86State *env, DisasContext *s)
{
gen_illegal_opcode(s);
if (qemu_loglevel_mask(LOG_UNIMP)) {
target_ulong pc = s->pc_start, end = s->pc;
qemu_log_lock();
qemu_log("ILLOPC: " TARGET_FMT_lx ":", pc);
for (; pc < end; ++pc) {
qemu_log(" %02x", cpu_ldub_code(env, pc));
}
qemu_log("\n");
qemu_log_unlock();
}
}
/* an interrupt is different from an exception because of the
privilege checks */
static void gen_interrupt(DisasContext *s, int intno,
target_ulong cur_eip, target_ulong next_eip)
{
gen_update_cc_op(s);
gen_jmp_im(cur_eip);
gen_helper_raise_interrupt(cpu_env, tcg_const_i32(intno),
tcg_const_i32(next_eip - cur_eip));
s->is_jmp = DISAS_TB_JUMP;
}
static void gen_debug(DisasContext *s, target_ulong cur_eip)
{
gen_update_cc_op(s);
gen_jmp_im(cur_eip);
gen_helper_debug(cpu_env);
s->is_jmp = DISAS_TB_JUMP;
}
static void gen_set_hflag(DisasContext *s, uint32_t mask)
{
if ((s->flags & mask) == 0) {
TCGv_i32 t = tcg_temp_new_i32();
tcg_gen_ld_i32(t, cpu_env, offsetof(CPUX86State, hflags));
tcg_gen_ori_i32(t, t, mask);
tcg_gen_st_i32(t, cpu_env, offsetof(CPUX86State, hflags));
tcg_temp_free_i32(t);
s->flags |= mask;
}
}
static void gen_reset_hflag(DisasContext *s, uint32_t mask)
{
if (s->flags & mask) {
TCGv_i32 t = tcg_temp_new_i32();
tcg_gen_ld_i32(t, cpu_env, offsetof(CPUX86State, hflags));
tcg_gen_andi_i32(t, t, ~mask);
tcg_gen_st_i32(t, cpu_env, offsetof(CPUX86State, hflags));
tcg_temp_free_i32(t);
s->flags &= ~mask;
}
}
/* Clear BND registers during legacy branches. */
static void gen_bnd_jmp(DisasContext *s)
{
/* Clear the registers only if BND prefix is missing, MPX is enabled,
and if the BNDREGs are known to be in use (non-zero) already.
The helper itself will check BNDPRESERVE at runtime. */
if ((s->prefix & PREFIX_REPNZ) == 0
&& (s->flags & HF_MPX_EN_MASK) != 0
&& (s->flags & HF_MPX_IU_MASK) != 0) {
gen_helper_bnd_jmp(cpu_env);
}
}
/* Generate an end of block. Trace exception is also generated if needed.
If INHIBIT, set HF_INHIBIT_IRQ_MASK if it isn't already set.
If RECHECK_TF, emit a rechecking helper for #DB, ignoring the state of
S->TF. This is used by the syscall/sysret insns. */
static void gen_eob_worker(DisasContext *s, bool inhibit, bool recheck_tf)
{
gen_update_cc_op(s);
/* If several instructions disable interrupts, only the first does it. */
if (inhibit && !(s->flags & HF_INHIBIT_IRQ_MASK)) {
gen_set_hflag(s, HF_INHIBIT_IRQ_MASK);
} else {
gen_reset_hflag(s, HF_INHIBIT_IRQ_MASK);
}
if (s->tb->flags & HF_RF_MASK) {
gen_helper_reset_rf(cpu_env);
}
if (s->singlestep_enabled) {
gen_helper_debug(cpu_env);
} else if (recheck_tf) {
gen_helper_rechecking_single_step(cpu_env);
tcg_gen_exit_tb(0);
} else if (s->tf) {
gen_helper_single_step(cpu_env);
} else {
tcg_gen_exit_tb(0);
}
s->is_jmp = DISAS_TB_JUMP;
}
/* End of block.
If INHIBIT, set HF_INHIBIT_IRQ_MASK if it isn't already set. */
static void gen_eob_inhibit_irq(DisasContext *s, bool inhibit)
{
gen_eob_worker(s, inhibit, false);
}
/* End of block, resetting the inhibit irq flag. */
static void gen_eob(DisasContext *s)
{
gen_eob_worker(s, false, false);
}
/* generate a jump to eip. No segment change must happen before as a
direct call to the next block may occur */
static void gen_jmp_tb(DisasContext *s, target_ulong eip, int tb_num)
{
gen_update_cc_op(s);
set_cc_op(s, CC_OP_DYNAMIC);
if (s->jmp_opt) {
gen_goto_tb(s, tb_num, eip);
s->is_jmp = DISAS_TB_JUMP;
} else {
gen_jmp_im(eip);
gen_eob(s);
}
}
static void gen_jmp(DisasContext *s, target_ulong eip)
{
gen_jmp_tb(s, eip, 0);
}
static inline void gen_ldq_env_A0(DisasContext *s, int offset)
{
tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_A0, s->mem_index, MO_LEQ);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, offset);
}
static inline void gen_stq_env_A0(DisasContext *s, int offset)
{
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, offset);
tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_A0, s->mem_index, MO_LEQ);
}
static inline void gen_ldo_env_A0(DisasContext *s, int offset)
{
int mem_index = s->mem_index;
tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_A0, mem_index, MO_LEQ);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, offset + offsetof(ZMMReg, ZMM_Q(0)));
tcg_gen_addi_tl(cpu_tmp0, cpu_A0, 8);
tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_tmp0, mem_index, MO_LEQ);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, offset + offsetof(ZMMReg, ZMM_Q(1)));
}
static inline void gen_sto_env_A0(DisasContext *s, int offset)
{
int mem_index = s->mem_index;
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, offset + offsetof(ZMMReg, ZMM_Q(0)));
tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_A0, mem_index, MO_LEQ);
tcg_gen_addi_tl(cpu_tmp0, cpu_A0, 8);
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, offset + offsetof(ZMMReg, ZMM_Q(1)));
tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_tmp0, mem_index, MO_LEQ);
}
static inline void gen_op_movo(int d_offset, int s_offset)
{
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, s_offset + offsetof(ZMMReg, ZMM_Q(0)));
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, d_offset + offsetof(ZMMReg, ZMM_Q(0)));
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, s_offset + offsetof(ZMMReg, ZMM_Q(1)));
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, d_offset + offsetof(ZMMReg, ZMM_Q(1)));
}
static inline void gen_op_movq(int d_offset, int s_offset)
{
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, s_offset);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, d_offset);
}
static inline void gen_op_movl(int d_offset, int s_offset)
{
tcg_gen_ld_i32(cpu_tmp2_i32, cpu_env, s_offset);
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, d_offset);
}
static inline void gen_op_movq_env_0(int d_offset)
{
tcg_gen_movi_i64(cpu_tmp1_i64, 0);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, d_offset);
}
typedef void (*SSEFunc_i_ep)(TCGv_i32 val, TCGv_ptr env, TCGv_ptr reg);
typedef void (*SSEFunc_l_ep)(TCGv_i64 val, TCGv_ptr env, TCGv_ptr reg);
typedef void (*SSEFunc_0_epi)(TCGv_ptr env, TCGv_ptr reg, TCGv_i32 val);
typedef void (*SSEFunc_0_epl)(TCGv_ptr env, TCGv_ptr reg, TCGv_i64 val);
typedef void (*SSEFunc_0_epp)(TCGv_ptr env, TCGv_ptr reg_a, TCGv_ptr reg_b);
typedef void (*SSEFunc_0_eppi)(TCGv_ptr env, TCGv_ptr reg_a, TCGv_ptr reg_b,
TCGv_i32 val);
typedef void (*SSEFunc_0_ppi)(TCGv_ptr reg_a, TCGv_ptr reg_b, TCGv_i32 val);
typedef void (*SSEFunc_0_eppt)(TCGv_ptr env, TCGv_ptr reg_a, TCGv_ptr reg_b,
TCGv val);
#define SSE_SPECIAL ((void *)1)
#define SSE_DUMMY ((void *)2)
#define MMX_OP2(x) { gen_helper_ ## x ## _mmx, gen_helper_ ## x ## _xmm }
#define SSE_FOP(x) { gen_helper_ ## x ## ps, gen_helper_ ## x ## pd, \
gen_helper_ ## x ## ss, gen_helper_ ## x ## sd, }
static const SSEFunc_0_epp sse_op_table1[256][4] = {
/* 3DNow! extensions */
[0x0e] = { SSE_DUMMY }, /* femms */
[0x0f] = { SSE_DUMMY }, /* pf... */
/* pure SSE operations */
[0x10] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movups, movupd, movss, movsd */
[0x11] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movups, movupd, movss, movsd */
[0x12] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movlps, movlpd, movsldup, movddup */
[0x13] = { SSE_SPECIAL, SSE_SPECIAL }, /* movlps, movlpd */
[0x14] = { gen_helper_punpckldq_xmm, gen_helper_punpcklqdq_xmm },
[0x15] = { gen_helper_punpckhdq_xmm, gen_helper_punpckhqdq_xmm },
[0x16] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movhps, movhpd, movshdup */
[0x17] = { SSE_SPECIAL, SSE_SPECIAL }, /* movhps, movhpd */
[0x28] = { SSE_SPECIAL, SSE_SPECIAL }, /* movaps, movapd */
[0x29] = { SSE_SPECIAL, SSE_SPECIAL }, /* movaps, movapd */
[0x2a] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* cvtpi2ps, cvtpi2pd, cvtsi2ss, cvtsi2sd */
[0x2b] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movntps, movntpd, movntss, movntsd */
[0x2c] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* cvttps2pi, cvttpd2pi, cvttsd2si, cvttss2si */
[0x2d] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* cvtps2pi, cvtpd2pi, cvtsd2si, cvtss2si */
[0x2e] = { gen_helper_ucomiss, gen_helper_ucomisd },
[0x2f] = { gen_helper_comiss, gen_helper_comisd },
[0x50] = { SSE_SPECIAL, SSE_SPECIAL }, /* movmskps, movmskpd */
[0x51] = SSE_FOP(sqrt),
[0x52] = { gen_helper_rsqrtps, NULL, gen_helper_rsqrtss, NULL },
[0x53] = { gen_helper_rcpps, NULL, gen_helper_rcpss, NULL },
[0x54] = { gen_helper_pand_xmm, gen_helper_pand_xmm }, /* andps, andpd */
[0x55] = { gen_helper_pandn_xmm, gen_helper_pandn_xmm }, /* andnps, andnpd */
[0x56] = { gen_helper_por_xmm, gen_helper_por_xmm }, /* orps, orpd */
[0x57] = { gen_helper_pxor_xmm, gen_helper_pxor_xmm }, /* xorps, xorpd */
[0x58] = SSE_FOP(add),
[0x59] = SSE_FOP(mul),
[0x5a] = { gen_helper_cvtps2pd, gen_helper_cvtpd2ps,
gen_helper_cvtss2sd, gen_helper_cvtsd2ss },
[0x5b] = { gen_helper_cvtdq2ps, gen_helper_cvtps2dq, gen_helper_cvttps2dq },
[0x5c] = SSE_FOP(sub),
[0x5d] = SSE_FOP(min),
[0x5e] = SSE_FOP(div),
[0x5f] = SSE_FOP(max),
[0xc2] = SSE_FOP(cmpeq),
[0xc6] = { (SSEFunc_0_epp)gen_helper_shufps,
(SSEFunc_0_epp)gen_helper_shufpd }, /* XXX: casts */
/* SSSE3, SSE4, MOVBE, CRC32, BMI1, BMI2, ADX. */
[0x38] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL },
[0x3a] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL },
/* MMX ops and their SSE extensions */
[0x60] = MMX_OP2(punpcklbw),
[0x61] = MMX_OP2(punpcklwd),
[0x62] = MMX_OP2(punpckldq),
[0x63] = MMX_OP2(packsswb),
[0x64] = MMX_OP2(pcmpgtb),
[0x65] = MMX_OP2(pcmpgtw),
[0x66] = MMX_OP2(pcmpgtl),
[0x67] = MMX_OP2(packuswb),
[0x68] = MMX_OP2(punpckhbw),
[0x69] = MMX_OP2(punpckhwd),
[0x6a] = MMX_OP2(punpckhdq),
[0x6b] = MMX_OP2(packssdw),
[0x6c] = { NULL, gen_helper_punpcklqdq_xmm },
[0x6d] = { NULL, gen_helper_punpckhqdq_xmm },
[0x6e] = { SSE_SPECIAL, SSE_SPECIAL }, /* movd mm, ea */
[0x6f] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movq, movdqa, , movqdu */
[0x70] = { (SSEFunc_0_epp)gen_helper_pshufw_mmx,
(SSEFunc_0_epp)gen_helper_pshufd_xmm,
(SSEFunc_0_epp)gen_helper_pshufhw_xmm,
(SSEFunc_0_epp)gen_helper_pshuflw_xmm }, /* XXX: casts */
[0x71] = { SSE_SPECIAL, SSE_SPECIAL }, /* shiftw */
[0x72] = { SSE_SPECIAL, SSE_SPECIAL }, /* shiftd */
[0x73] = { SSE_SPECIAL, SSE_SPECIAL }, /* shiftq */
[0x74] = MMX_OP2(pcmpeqb),
[0x75] = MMX_OP2(pcmpeqw),
[0x76] = MMX_OP2(pcmpeql),
[0x77] = { SSE_DUMMY }, /* emms */
[0x78] = { NULL, SSE_SPECIAL, NULL, SSE_SPECIAL }, /* extrq_i, insertq_i */
[0x79] = { NULL, gen_helper_extrq_r, NULL, gen_helper_insertq_r },
[0x7c] = { NULL, gen_helper_haddpd, NULL, gen_helper_haddps },
[0x7d] = { NULL, gen_helper_hsubpd, NULL, gen_helper_hsubps },
[0x7e] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movd, movd, , movq */
[0x7f] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movq, movdqa, movdqu */
[0xc4] = { SSE_SPECIAL, SSE_SPECIAL }, /* pinsrw */
[0xc5] = { SSE_SPECIAL, SSE_SPECIAL }, /* pextrw */
[0xd0] = { NULL, gen_helper_addsubpd, NULL, gen_helper_addsubps },
[0xd1] = MMX_OP2(psrlw),
[0xd2] = MMX_OP2(psrld),
[0xd3] = MMX_OP2(psrlq),
[0xd4] = MMX_OP2(paddq),
[0xd5] = MMX_OP2(pmullw),
[0xd6] = { NULL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL },
[0xd7] = { SSE_SPECIAL, SSE_SPECIAL }, /* pmovmskb */
[0xd8] = MMX_OP2(psubusb),
[0xd9] = MMX_OP2(psubusw),
[0xda] = MMX_OP2(pminub),
[0xdb] = MMX_OP2(pand),
[0xdc] = MMX_OP2(paddusb),
[0xdd] = MMX_OP2(paddusw),
[0xde] = MMX_OP2(pmaxub),
[0xdf] = MMX_OP2(pandn),
[0xe0] = MMX_OP2(pavgb),
[0xe1] = MMX_OP2(psraw),
[0xe2] = MMX_OP2(psrad),
[0xe3] = MMX_OP2(pavgw),
[0xe4] = MMX_OP2(pmulhuw),
[0xe5] = MMX_OP2(pmulhw),
[0xe6] = { NULL, gen_helper_cvttpd2dq, gen_helper_cvtdq2pd, gen_helper_cvtpd2dq },
[0xe7] = { SSE_SPECIAL , SSE_SPECIAL }, /* movntq, movntq */
[0xe8] = MMX_OP2(psubsb),
[0xe9] = MMX_OP2(psubsw),
[0xea] = MMX_OP2(pminsw),
[0xeb] = MMX_OP2(por),
[0xec] = MMX_OP2(paddsb),
[0xed] = MMX_OP2(paddsw),
[0xee] = MMX_OP2(pmaxsw),
[0xef] = MMX_OP2(pxor),
[0xf0] = { NULL, NULL, NULL, SSE_SPECIAL }, /* lddqu */
[0xf1] = MMX_OP2(psllw),
[0xf2] = MMX_OP2(pslld),
[0xf3] = MMX_OP2(psllq),
[0xf4] = MMX_OP2(pmuludq),
[0xf5] = MMX_OP2(pmaddwd),
[0xf6] = MMX_OP2(psadbw),
[0xf7] = { (SSEFunc_0_epp)gen_helper_maskmov_mmx,
(SSEFunc_0_epp)gen_helper_maskmov_xmm }, /* XXX: casts */
[0xf8] = MMX_OP2(psubb),
[0xf9] = MMX_OP2(psubw),
[0xfa] = MMX_OP2(psubl),
[0xfb] = MMX_OP2(psubq),
[0xfc] = MMX_OP2(paddb),
[0xfd] = MMX_OP2(paddw),
[0xfe] = MMX_OP2(paddl),
};
static const SSEFunc_0_epp sse_op_table2[3 * 8][2] = {
[0 + 2] = MMX_OP2(psrlw),
[0 + 4] = MMX_OP2(psraw),
[0 + 6] = MMX_OP2(psllw),
[8 + 2] = MMX_OP2(psrld),
[8 + 4] = MMX_OP2(psrad),
[8 + 6] = MMX_OP2(pslld),
[16 + 2] = MMX_OP2(psrlq),
[16 + 3] = { NULL, gen_helper_psrldq_xmm },
[16 + 6] = MMX_OP2(psllq),
[16 + 7] = { NULL, gen_helper_pslldq_xmm },
};
static const SSEFunc_0_epi sse_op_table3ai[] = {
gen_helper_cvtsi2ss,
gen_helper_cvtsi2sd
};
#ifdef TARGET_X86_64
static const SSEFunc_0_epl sse_op_table3aq[] = {
gen_helper_cvtsq2ss,
gen_helper_cvtsq2sd
};
#endif
static const SSEFunc_i_ep sse_op_table3bi[] = {
gen_helper_cvttss2si,
gen_helper_cvtss2si,
gen_helper_cvttsd2si,
gen_helper_cvtsd2si
};
#ifdef TARGET_X86_64
static const SSEFunc_l_ep sse_op_table3bq[] = {
gen_helper_cvttss2sq,
gen_helper_cvtss2sq,
gen_helper_cvttsd2sq,
gen_helper_cvtsd2sq
};
#endif
static const SSEFunc_0_epp sse_op_table4[8][4] = {
SSE_FOP(cmpeq),
SSE_FOP(cmplt),
SSE_FOP(cmple),
SSE_FOP(cmpunord),
SSE_FOP(cmpneq),
SSE_FOP(cmpnlt),
SSE_FOP(cmpnle),
SSE_FOP(cmpord),
};
static const SSEFunc_0_epp sse_op_table5[256] = {
[0x0c] = gen_helper_pi2fw,
[0x0d] = gen_helper_pi2fd,
[0x1c] = gen_helper_pf2iw,
[0x1d] = gen_helper_pf2id,
[0x8a] = gen_helper_pfnacc,
[0x8e] = gen_helper_pfpnacc,
[0x90] = gen_helper_pfcmpge,
[0x94] = gen_helper_pfmin,
[0x96] = gen_helper_pfrcp,
[0x97] = gen_helper_pfrsqrt,
[0x9a] = gen_helper_pfsub,
[0x9e] = gen_helper_pfadd,
[0xa0] = gen_helper_pfcmpgt,
[0xa4] = gen_helper_pfmax,
[0xa6] = gen_helper_movq, /* pfrcpit1; no need to actually increase precision */
[0xa7] = gen_helper_movq, /* pfrsqit1 */
[0xaa] = gen_helper_pfsubr,
[0xae] = gen_helper_pfacc,
[0xb0] = gen_helper_pfcmpeq,
[0xb4] = gen_helper_pfmul,
[0xb6] = gen_helper_movq, /* pfrcpit2 */
[0xb7] = gen_helper_pmulhrw_mmx,
[0xbb] = gen_helper_pswapd,
[0xbf] = gen_helper_pavgb_mmx /* pavgusb */
};
struct SSEOpHelper_epp {
SSEFunc_0_epp op[2];
uint32_t ext_mask;
};
struct SSEOpHelper_eppi {
SSEFunc_0_eppi op[2];
uint32_t ext_mask;
};
#define SSSE3_OP(x) { MMX_OP2(x), CPUID_EXT_SSSE3 }
#define SSE41_OP(x) { { NULL, gen_helper_ ## x ## _xmm }, CPUID_EXT_SSE41 }
#define SSE42_OP(x) { { NULL, gen_helper_ ## x ## _xmm }, CPUID_EXT_SSE42 }
#define SSE41_SPECIAL { { NULL, SSE_SPECIAL }, CPUID_EXT_SSE41 }
#define PCLMULQDQ_OP(x) { { NULL, gen_helper_ ## x ## _xmm }, \
CPUID_EXT_PCLMULQDQ }
#define AESNI_OP(x) { { NULL, gen_helper_ ## x ## _xmm }, CPUID_EXT_AES }
static const struct SSEOpHelper_epp sse_op_table6[256] = {
[0x00] = SSSE3_OP(pshufb),
[0x01] = SSSE3_OP(phaddw),
[0x02] = SSSE3_OP(phaddd),
[0x03] = SSSE3_OP(phaddsw),
[0x04] = SSSE3_OP(pmaddubsw),
[0x05] = SSSE3_OP(phsubw),
[0x06] = SSSE3_OP(phsubd),
[0x07] = SSSE3_OP(phsubsw),
[0x08] = SSSE3_OP(psignb),
[0x09] = SSSE3_OP(psignw),
[0x0a] = SSSE3_OP(psignd),
[0x0b] = SSSE3_OP(pmulhrsw),
[0x10] = SSE41_OP(pblendvb),
[0x14] = SSE41_OP(blendvps),
[0x15] = SSE41_OP(blendvpd),
[0x17] = SSE41_OP(ptest),
[0x1c] = SSSE3_OP(pabsb),
[0x1d] = SSSE3_OP(pabsw),
[0x1e] = SSSE3_OP(pabsd),
[0x20] = SSE41_OP(pmovsxbw),
[0x21] = SSE41_OP(pmovsxbd),
[0x22] = SSE41_OP(pmovsxbq),
[0x23] = SSE41_OP(pmovsxwd),
[0x24] = SSE41_OP(pmovsxwq),
[0x25] = SSE41_OP(pmovsxdq),
[0x28] = SSE41_OP(pmuldq),
[0x29] = SSE41_OP(pcmpeqq),
[0x2a] = SSE41_SPECIAL, /* movntqda */
[0x2b] = SSE41_OP(packusdw),
[0x30] = SSE41_OP(pmovzxbw),
[0x31] = SSE41_OP(pmovzxbd),
[0x32] = SSE41_OP(pmovzxbq),
[0x33] = SSE41_OP(pmovzxwd),
[0x34] = SSE41_OP(pmovzxwq),
[0x35] = SSE41_OP(pmovzxdq),
[0x37] = SSE42_OP(pcmpgtq),
[0x38] = SSE41_OP(pminsb),
[0x39] = SSE41_OP(pminsd),
[0x3a] = SSE41_OP(pminuw),
[0x3b] = SSE41_OP(pminud),
[0x3c] = SSE41_OP(pmaxsb),
[0x3d] = SSE41_OP(pmaxsd),
[0x3e] = SSE41_OP(pmaxuw),
[0x3f] = SSE41_OP(pmaxud),
[0x40] = SSE41_OP(pmulld),
[0x41] = SSE41_OP(phminposuw),
[0xdb] = AESNI_OP(aesimc),
[0xdc] = AESNI_OP(aesenc),
[0xdd] = AESNI_OP(aesenclast),
[0xde] = AESNI_OP(aesdec),
[0xdf] = AESNI_OP(aesdeclast),
};
static const struct SSEOpHelper_eppi sse_op_table7[256] = {
[0x08] = SSE41_OP(roundps),
[0x09] = SSE41_OP(roundpd),
[0x0a] = SSE41_OP(roundss),
[0x0b] = SSE41_OP(roundsd),
[0x0c] = SSE41_OP(blendps),
[0x0d] = SSE41_OP(blendpd),
[0x0e] = SSE41_OP(pblendw),
[0x0f] = SSSE3_OP(palignr),
[0x14] = SSE41_SPECIAL, /* pextrb */
[0x15] = SSE41_SPECIAL, /* pextrw */
[0x16] = SSE41_SPECIAL, /* pextrd/pextrq */
[0x17] = SSE41_SPECIAL, /* extractps */
[0x20] = SSE41_SPECIAL, /* pinsrb */
[0x21] = SSE41_SPECIAL, /* insertps */
[0x22] = SSE41_SPECIAL, /* pinsrd/pinsrq */
[0x40] = SSE41_OP(dpps),
[0x41] = SSE41_OP(dppd),
[0x42] = SSE41_OP(mpsadbw),
[0x44] = PCLMULQDQ_OP(pclmulqdq),
[0x60] = SSE42_OP(pcmpestrm),
[0x61] = SSE42_OP(pcmpestri),
[0x62] = SSE42_OP(pcmpistrm),
[0x63] = SSE42_OP(pcmpistri),
[0xdf] = AESNI_OP(aeskeygenassist),
};
static void gen_sse(CPUX86State *env, DisasContext *s, int b,
target_ulong pc_start, int rex_r)
{
int b1, op1_offset, op2_offset, is_xmm, val;
int modrm, mod, rm, reg;
SSEFunc_0_epp sse_fn_epp;
SSEFunc_0_eppi sse_fn_eppi;
SSEFunc_0_ppi sse_fn_ppi;
SSEFunc_0_eppt sse_fn_eppt;
TCGMemOp ot;
b &= 0xff;
if (s->prefix & PREFIX_DATA)
b1 = 1;
else if (s->prefix & PREFIX_REPZ)
b1 = 2;
else if (s->prefix & PREFIX_REPNZ)
b1 = 3;
else
b1 = 0;
sse_fn_epp = sse_op_table1[b][b1];
if (!sse_fn_epp) {
goto unknown_op;
}
if ((b <= 0x5f && b >= 0x10) || b == 0xc6 || b == 0xc2) {
is_xmm = 1;
} else {
if (b1 == 0) {
/* MMX case */
is_xmm = 0;
} else {
is_xmm = 1;
}
}
/* simple MMX/SSE operation */
if (s->flags & HF_TS_MASK) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
return;
}
if (s->flags & HF_EM_MASK) {
illegal_op:
gen_illegal_opcode(s);
return;
}
if (is_xmm
&& !(s->flags & HF_OSFXSR_MASK)
&& ((b != 0x38 && b != 0x3a) || (s->prefix & PREFIX_DATA))) {
goto unknown_op;
}
if (b == 0x0e) {
if (!(s->cpuid_ext2_features & CPUID_EXT2_3DNOW)) {
/* If we were fully decoding this we might use illegal_op. */
goto unknown_op;
}
/* femms */
gen_helper_emms(cpu_env);
return;
}
if (b == 0x77) {
/* emms */
gen_helper_emms(cpu_env);
return;
}
/* prepare MMX state (XXX: optimize by storing fptt and fptags in
the static cpu state) */
if (!is_xmm) {
gen_helper_enter_mmx(cpu_env);
}
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7);
if (is_xmm)
reg |= rex_r;
mod = (modrm >> 6) & 3;
if (sse_fn_epp == SSE_SPECIAL) {
b |= (b1 << 8);
switch(b) {
case 0x0e7: /* movntq */
if (mod == 3) {
goto illegal_op;
}
gen_lea_modrm(env, s, modrm);
gen_stq_env_A0(s, offsetof(CPUX86State, fpregs[reg].mmx));
break;
case 0x1e7: /* movntdq */
case 0x02b: /* movntps */
case 0x12b: /* movntps */
if (mod == 3)
goto illegal_op;
gen_lea_modrm(env, s, modrm);
gen_sto_env_A0(s, offsetof(CPUX86State, xmm_regs[reg]));
break;
case 0x3f0: /* lddqu */
if (mod == 3)
goto illegal_op;
gen_lea_modrm(env, s, modrm);
gen_ldo_env_A0(s, offsetof(CPUX86State, xmm_regs[reg]));
break;
case 0x22b: /* movntss */
case 0x32b: /* movntsd */
if (mod == 3)
goto illegal_op;
gen_lea_modrm(env, s, modrm);
if (b1 & 1) {
gen_stq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(0)));
} else {
tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_L(0)));
gen_op_st_v(s, MO_32, cpu_T0, cpu_A0);
}
break;
case 0x6e: /* movd mm, ea */
#ifdef TARGET_X86_64
if (s->dflag == MO_64) {
gen_ldst_modrm(env, s, modrm, MO_64, OR_TMP0, 0);
tcg_gen_st_tl(cpu_T0, cpu_env, offsetof(CPUX86State,fpregs[reg].mmx));
} else
#endif
{
gen_ldst_modrm(env, s, modrm, MO_32, OR_TMP0, 0);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,fpregs[reg].mmx));
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_movl_mm_T0_mmx(cpu_ptr0, cpu_tmp2_i32);
}
break;
case 0x16e: /* movd xmm, ea */
#ifdef TARGET_X86_64
if (s->dflag == MO_64) {
gen_ldst_modrm(env, s, modrm, MO_64, OR_TMP0, 0);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,xmm_regs[reg]));
gen_helper_movq_mm_T0_xmm(cpu_ptr0, cpu_T0);
} else
#endif
{
gen_ldst_modrm(env, s, modrm, MO_32, OR_TMP0, 0);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,xmm_regs[reg]));
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_movl_mm_T0_xmm(cpu_ptr0, cpu_tmp2_i32);
}
break;
case 0x6f: /* movq mm, ea */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldq_env_A0(s, offsetof(CPUX86State, fpregs[reg].mmx));
} else {
rm = (modrm & 7);
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env,
offsetof(CPUX86State,fpregs[rm].mmx));
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env,
offsetof(CPUX86State,fpregs[reg].mmx));
}
break;
case 0x010: /* movups */
case 0x110: /* movupd */
case 0x028: /* movaps */
case 0x128: /* movapd */
case 0x16f: /* movdqa xmm, ea */
case 0x26f: /* movdqu xmm, ea */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldo_env_A0(s, offsetof(CPUX86State, xmm_regs[reg]));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movo(offsetof(CPUX86State,xmm_regs[reg]),
offsetof(CPUX86State,xmm_regs[rm]));
}
break;
case 0x210: /* movss xmm, ea */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, MO_32, cpu_T0, cpu_A0);
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)));
tcg_gen_movi_tl(cpu_T0, 0);
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(1)));
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(2)));
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(3)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_L(0)));
}
break;
case 0x310: /* movsd xmm, ea */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(0)));
tcg_gen_movi_tl(cpu_T0, 0);
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(2)));
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(3)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0)));
}
break;
case 0x012: /* movlps */
case 0x112: /* movlpd */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(0)));
} else {
/* movhlps */
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(1)));
}
break;
case 0x212: /* movsldup */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldo_env_A0(s, offsetof(CPUX86State, xmm_regs[reg]));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_L(0)));
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(2)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_L(2)));
}
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(1)),
offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)));
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(3)),
offsetof(CPUX86State,xmm_regs[reg].ZMM_L(2)));
break;
case 0x312: /* movddup */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(0)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0)));
}
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(1)),
offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)));
break;
case 0x016: /* movhps */
case 0x116: /* movhpd */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(1)));
} else {
/* movlhps */
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(1)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0)));
}
break;
case 0x216: /* movshdup */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldo_env_A0(s, offsetof(CPUX86State, xmm_regs[reg]));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(1)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_L(1)));
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(3)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_L(3)));
}
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)),
offsetof(CPUX86State,xmm_regs[reg].ZMM_L(1)));
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(2)),
offsetof(CPUX86State,xmm_regs[reg].ZMM_L(3)));
break;
case 0x178:
case 0x378:
{
int bit_index, field_length;
if (b1 == 1 && reg != 0)
goto illegal_op;
field_length = cpu_ldub_code(env, s->pc++) & 0x3F;
bit_index = cpu_ldub_code(env, s->pc++) & 0x3F;
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,xmm_regs[reg]));
if (b1 == 1)
gen_helper_extrq_i(cpu_env, cpu_ptr0,
tcg_const_i32(bit_index),
tcg_const_i32(field_length));
else
gen_helper_insertq_i(cpu_env, cpu_ptr0,
tcg_const_i32(bit_index),
tcg_const_i32(field_length));
}
break;
case 0x7e: /* movd ea, mm */
#ifdef TARGET_X86_64
if (s->dflag == MO_64) {
tcg_gen_ld_i64(cpu_T0, cpu_env,
offsetof(CPUX86State,fpregs[reg].mmx));
gen_ldst_modrm(env, s, modrm, MO_64, OR_TMP0, 1);
} else
#endif
{
tcg_gen_ld32u_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,fpregs[reg].mmx.MMX_L(0)));
gen_ldst_modrm(env, s, modrm, MO_32, OR_TMP0, 1);
}
break;
case 0x17e: /* movd ea, xmm */
#ifdef TARGET_X86_64
if (s->dflag == MO_64) {
tcg_gen_ld_i64(cpu_T0, cpu_env,
offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)));
gen_ldst_modrm(env, s, modrm, MO_64, OR_TMP0, 1);
} else
#endif
{
tcg_gen_ld32u_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)));
gen_ldst_modrm(env, s, modrm, MO_32, OR_TMP0, 1);
}
break;
case 0x27e: /* movq xmm, ea */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(0)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0)));
}
gen_op_movq_env_0(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(1)));
break;
case 0x7f: /* movq ea, mm */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_stq_env_A0(s, offsetof(CPUX86State, fpregs[reg].mmx));
} else {
rm = (modrm & 7);
gen_op_movq(offsetof(CPUX86State,fpregs[rm].mmx),
offsetof(CPUX86State,fpregs[reg].mmx));
}
break;
case 0x011: /* movups */
case 0x111: /* movupd */
case 0x029: /* movaps */
case 0x129: /* movapd */
case 0x17f: /* movdqa ea, xmm */
case 0x27f: /* movdqu ea, xmm */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_sto_env_A0(s, offsetof(CPUX86State, xmm_regs[reg]));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movo(offsetof(CPUX86State,xmm_regs[rm]),
offsetof(CPUX86State,xmm_regs[reg]));
}
break;
case 0x211: /* movss ea, xmm */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)));
gen_op_st_v(s, MO_32, cpu_T0, cpu_A0);
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movl(offsetof(CPUX86State,xmm_regs[rm].ZMM_L(0)),
offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)));
}
break;
case 0x311: /* movsd ea, xmm */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_stq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(0)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0)),
offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)));
}
break;
case 0x013: /* movlps */
case 0x113: /* movlpd */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_stq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(0)));
} else {
goto illegal_op;
}
break;
case 0x017: /* movhps */
case 0x117: /* movhpd */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_stq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(1)));
} else {
goto illegal_op;
}
break;
case 0x71: /* shift mm, im */
case 0x72:
case 0x73:
case 0x171: /* shift xmm, im */
case 0x172:
case 0x173:
if (b1 >= 2) {
goto unknown_op;
}
val = cpu_ldub_code(env, s->pc++);
if (is_xmm) {
tcg_gen_movi_tl(cpu_T0, val);
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_t0.ZMM_L(0)));
tcg_gen_movi_tl(cpu_T0, 0);
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_t0.ZMM_L(1)));
op1_offset = offsetof(CPUX86State,xmm_t0);
} else {
tcg_gen_movi_tl(cpu_T0, val);
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,mmx_t0.MMX_L(0)));
tcg_gen_movi_tl(cpu_T0, 0);
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,mmx_t0.MMX_L(1)));
op1_offset = offsetof(CPUX86State,mmx_t0);
}
sse_fn_epp = sse_op_table2[((b - 1) & 3) * 8 +
(((modrm >> 3)) & 7)][b1];
if (!sse_fn_epp) {
goto unknown_op;
}
if (is_xmm) {
rm = (modrm & 7) | REX_B(s);
op2_offset = offsetof(CPUX86State,xmm_regs[rm]);
} else {
rm = (modrm & 7);
op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);
}
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op2_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op1_offset);
sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1);
break;
case 0x050: /* movmskps */
rm = (modrm & 7) | REX_B(s);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,xmm_regs[rm]));
gen_helper_movmskps(cpu_tmp2_i32, cpu_env, cpu_ptr0);
tcg_gen_extu_i32_tl(cpu_regs[reg], cpu_tmp2_i32);
break;
case 0x150: /* movmskpd */
rm = (modrm & 7) | REX_B(s);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,xmm_regs[rm]));
gen_helper_movmskpd(cpu_tmp2_i32, cpu_env, cpu_ptr0);
tcg_gen_extu_i32_tl(cpu_regs[reg], cpu_tmp2_i32);
break;
case 0x02a: /* cvtpi2ps */
case 0x12a: /* cvtpi2pd */
gen_helper_enter_mmx(cpu_env);
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
op2_offset = offsetof(CPUX86State,mmx_t0);
gen_ldq_env_A0(s, op2_offset);
} else {
rm = (modrm & 7);
op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);
}
op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
switch(b >> 8) {
case 0x0:
gen_helper_cvtpi2ps(cpu_env, cpu_ptr0, cpu_ptr1);
break;
default:
case 0x1:
gen_helper_cvtpi2pd(cpu_env, cpu_ptr0, cpu_ptr1);
break;
}
break;
case 0x22a: /* cvtsi2ss */
case 0x32a: /* cvtsi2sd */
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
if (ot == MO_32) {
SSEFunc_0_epi sse_fn_epi = sse_op_table3ai[(b >> 8) & 1];
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
sse_fn_epi(cpu_env, cpu_ptr0, cpu_tmp2_i32);
} else {
#ifdef TARGET_X86_64
SSEFunc_0_epl sse_fn_epl = sse_op_table3aq[(b >> 8) & 1];
sse_fn_epl(cpu_env, cpu_ptr0, cpu_T0);
#else
goto illegal_op;
#endif
}
break;
case 0x02c: /* cvttps2pi */
case 0x12c: /* cvttpd2pi */
case 0x02d: /* cvtps2pi */
case 0x12d: /* cvtpd2pi */
gen_helper_enter_mmx(cpu_env);
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
op2_offset = offsetof(CPUX86State,xmm_t0);
gen_ldo_env_A0(s, op2_offset);
} else {
rm = (modrm & 7) | REX_B(s);
op2_offset = offsetof(CPUX86State,xmm_regs[rm]);
}
op1_offset = offsetof(CPUX86State,fpregs[reg & 7].mmx);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
switch(b) {
case 0x02c:
gen_helper_cvttps2pi(cpu_env, cpu_ptr0, cpu_ptr1);
break;
case 0x12c:
gen_helper_cvttpd2pi(cpu_env, cpu_ptr0, cpu_ptr1);
break;
case 0x02d:
gen_helper_cvtps2pi(cpu_env, cpu_ptr0, cpu_ptr1);
break;
case 0x12d:
gen_helper_cvtpd2pi(cpu_env, cpu_ptr0, cpu_ptr1);
break;
}
break;
case 0x22c: /* cvttss2si */
case 0x32c: /* cvttsd2si */
case 0x22d: /* cvtss2si */
case 0x32d: /* cvtsd2si */
ot = mo_64_32(s->dflag);
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
if ((b >> 8) & 1) {
gen_ldq_env_A0(s, offsetof(CPUX86State, xmm_t0.ZMM_Q(0)));
} else {
gen_op_ld_v(s, MO_32, cpu_T0, cpu_A0);
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_t0.ZMM_L(0)));
}
op2_offset = offsetof(CPUX86State,xmm_t0);
} else {
rm = (modrm & 7) | REX_B(s);
op2_offset = offsetof(CPUX86State,xmm_regs[rm]);
}
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op2_offset);
if (ot == MO_32) {
SSEFunc_i_ep sse_fn_i_ep =
sse_op_table3bi[((b >> 7) & 2) | (b & 1)];
sse_fn_i_ep(cpu_tmp2_i32, cpu_env, cpu_ptr0);
tcg_gen_extu_i32_tl(cpu_T0, cpu_tmp2_i32);
} else {
#ifdef TARGET_X86_64
SSEFunc_l_ep sse_fn_l_ep =
sse_op_table3bq[((b >> 7) & 2) | (b & 1)];
sse_fn_l_ep(cpu_T0, cpu_env, cpu_ptr0);
#else
goto illegal_op;
#endif
}
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
case 0xc4: /* pinsrw */
case 0x1c4:
s->rip_offset = 1;
gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0);
val = cpu_ldub_code(env, s->pc++);
if (b1) {
val &= 7;
tcg_gen_st16_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,xmm_regs[reg].ZMM_W(val)));
} else {
val &= 3;
tcg_gen_st16_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,fpregs[reg].mmx.MMX_W(val)));
}
break;
case 0xc5: /* pextrw */
case 0x1c5:
if (mod != 3)
goto illegal_op;
ot = mo_64_32(s->dflag);
val = cpu_ldub_code(env, s->pc++);
if (b1) {
val &= 7;
rm = (modrm & 7) | REX_B(s);
tcg_gen_ld16u_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,xmm_regs[rm].ZMM_W(val)));
} else {
val &= 3;
rm = (modrm & 7);
tcg_gen_ld16u_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,fpregs[rm].mmx.MMX_W(val)));
}
reg = ((modrm >> 3) & 7) | rex_r;
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
case 0x1d6: /* movq ea, xmm */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_stq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(0)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0)),
offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)));
gen_op_movq_env_0(offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(1)));
}
break;
case 0x2d6: /* movq2dq */
gen_helper_enter_mmx(cpu_env);
rm = (modrm & 7);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)),
offsetof(CPUX86State,fpregs[rm].mmx));
gen_op_movq_env_0(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(1)));
break;
case 0x3d6: /* movdq2q */
gen_helper_enter_mmx(cpu_env);
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,fpregs[reg & 7].mmx),
offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0)));
break;
case 0xd7: /* pmovmskb */
case 0x1d7:
if (mod != 3)
goto illegal_op;
if (b1) {
rm = (modrm & 7) | REX_B(s);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, offsetof(CPUX86State,xmm_regs[rm]));
gen_helper_pmovmskb_xmm(cpu_tmp2_i32, cpu_env, cpu_ptr0);
} else {
rm = (modrm & 7);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, offsetof(CPUX86State,fpregs[rm].mmx));
gen_helper_pmovmskb_mmx(cpu_tmp2_i32, cpu_env, cpu_ptr0);
}
reg = ((modrm >> 3) & 7) | rex_r;
tcg_gen_extu_i32_tl(cpu_regs[reg], cpu_tmp2_i32);
break;
case 0x138:
case 0x038:
b = modrm;
if ((b & 0xf0) == 0xf0) {
goto do_0f_38_fx;
}
modrm = cpu_ldub_code(env, s->pc++);
rm = modrm & 7;
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
if (b1 >= 2) {
goto unknown_op;
}
sse_fn_epp = sse_op_table6[b].op[b1];
if (!sse_fn_epp) {
goto unknown_op;
}
if (!(s->cpuid_ext_features & sse_op_table6[b].ext_mask))
goto illegal_op;
if (b1) {
op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
if (mod == 3) {
op2_offset = offsetof(CPUX86State,xmm_regs[rm | REX_B(s)]);
} else {
op2_offset = offsetof(CPUX86State,xmm_t0);
gen_lea_modrm(env, s, modrm);
switch (b) {
case 0x20: case 0x30: /* pmovsxbw, pmovzxbw */
case 0x23: case 0x33: /* pmovsxwd, pmovzxwd */
case 0x25: case 0x35: /* pmovsxdq, pmovzxdq */
gen_ldq_env_A0(s, op2_offset +
offsetof(ZMMReg, ZMM_Q(0)));
break;
case 0x21: case 0x31: /* pmovsxbd, pmovzxbd */
case 0x24: case 0x34: /* pmovsxwq, pmovzxwq */
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, op2_offset +
offsetof(ZMMReg, ZMM_L(0)));
break;
case 0x22: case 0x32: /* pmovsxbq, pmovzxbq */
tcg_gen_qemu_ld_tl(cpu_tmp0, cpu_A0,
s->mem_index, MO_LEUW);
tcg_gen_st16_tl(cpu_tmp0, cpu_env, op2_offset +
offsetof(ZMMReg, ZMM_W(0)));
break;
case 0x2a: /* movntqda */
gen_ldo_env_A0(s, op1_offset);
return;
default:
gen_ldo_env_A0(s, op2_offset);
}
}
} else {
op1_offset = offsetof(CPUX86State,fpregs[reg].mmx);
if (mod == 3) {
op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);
} else {
op2_offset = offsetof(CPUX86State,mmx_t0);
gen_lea_modrm(env, s, modrm);
gen_ldq_env_A0(s, op2_offset);
}
}
if (sse_fn_epp == SSE_SPECIAL) {
goto unknown_op;
}
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1);
if (b == 0x17) {
set_cc_op(s, CC_OP_EFLAGS);
}
break;
case 0x238:
case 0x338:
do_0f_38_fx:
/* Various integer extensions at 0f 38 f[0-f]. */
b = modrm | (b1 << 8);
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
switch (b) {
case 0x3f0: /* crc32 Gd,Eb */
case 0x3f1: /* crc32 Gd,Ey */
do_crc32:
if (!(s->cpuid_ext_features & CPUID_EXT_SSE42)) {
goto illegal_op;
}
if ((b & 0xff) == 0xf0) {
ot = MO_8;
} else if (s->dflag != MO_64) {
ot = (s->prefix & PREFIX_DATA ? MO_16 : MO_32);
} else {
ot = MO_64;
}
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[reg]);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
gen_helper_crc32(cpu_T0, cpu_tmp2_i32,
cpu_T0, tcg_const_i32(8 << ot));
ot = mo_64_32(s->dflag);
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
case 0x1f0: /* crc32 or movbe */
case 0x1f1:
/* For these insns, the f3 prefix is supposed to have priority
over the 66 prefix, but that's not what we implement above
setting b1. */
if (s->prefix & PREFIX_REPNZ) {
goto do_crc32;
}
/* FALLTHRU */
case 0x0f0: /* movbe Gy,My */
case 0x0f1: /* movbe My,Gy */
if (!(s->cpuid_ext_features & CPUID_EXT_MOVBE)) {
goto illegal_op;
}
if (s->dflag != MO_64) {
ot = (s->prefix & PREFIX_DATA ? MO_16 : MO_32);
} else {
ot = MO_64;
}
gen_lea_modrm(env, s, modrm);
if ((b & 1) == 0) {
tcg_gen_qemu_ld_tl(cpu_T0, cpu_A0,
s->mem_index, ot | MO_BE);
gen_op_mov_reg_v(ot, reg, cpu_T0);
} else {
tcg_gen_qemu_st_tl(cpu_regs[reg], cpu_A0,
s->mem_index, ot | MO_BE);
}
break;
case 0x0f2: /* andn Gy, By, Ey */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI1)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
tcg_gen_andc_tl(cpu_T0, cpu_regs[s->vex_v], cpu_T0);
gen_op_mov_reg_v(ot, reg, cpu_T0);
gen_op_update1_cc();
set_cc_op(s, CC_OP_LOGICB + ot);
break;
case 0x0f7: /* bextr Gy, Ey, By */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI1)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
{
TCGv bound, zero;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
/* Extract START, and shift the operand.
Shifts larger than operand size get zeros. */
tcg_gen_ext8u_tl(cpu_A0, cpu_regs[s->vex_v]);
tcg_gen_shr_tl(cpu_T0, cpu_T0, cpu_A0);
bound = tcg_const_tl(ot == MO_64 ? 63 : 31);
zero = tcg_const_tl(0);
tcg_gen_movcond_tl(TCG_COND_LEU, cpu_T0, cpu_A0, bound,
cpu_T0, zero);
tcg_temp_free(zero);
/* Extract the LEN into a mask. Lengths larger than
operand size get all ones. */
tcg_gen_extract_tl(cpu_A0, cpu_regs[s->vex_v], 8, 8);
tcg_gen_movcond_tl(TCG_COND_LEU, cpu_A0, cpu_A0, bound,
cpu_A0, bound);
tcg_temp_free(bound);
tcg_gen_movi_tl(cpu_T1, 1);
tcg_gen_shl_tl(cpu_T1, cpu_T1, cpu_A0);
tcg_gen_subi_tl(cpu_T1, cpu_T1, 1);
tcg_gen_and_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_mov_reg_v(ot, reg, cpu_T0);
gen_op_update1_cc();
set_cc_op(s, CC_OP_LOGICB + ot);
}
break;
case 0x0f5: /* bzhi Gy, Ey, By */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
tcg_gen_ext8u_tl(cpu_T1, cpu_regs[s->vex_v]);
{
TCGv bound = tcg_const_tl(ot == MO_64 ? 63 : 31);
/* Note that since we're using BMILG (in order to get O
cleared) we need to store the inverse into C. */
tcg_gen_setcond_tl(TCG_COND_LT, cpu_cc_src,
cpu_T1, bound);
tcg_gen_movcond_tl(TCG_COND_GT, cpu_T1, cpu_T1,
bound, bound, cpu_T1);
tcg_temp_free(bound);
}
tcg_gen_movi_tl(cpu_A0, -1);
tcg_gen_shl_tl(cpu_A0, cpu_A0, cpu_T1);
tcg_gen_andc_tl(cpu_T0, cpu_T0, cpu_A0);
gen_op_mov_reg_v(ot, reg, cpu_T0);
gen_op_update1_cc();
set_cc_op(s, CC_OP_BMILGB + ot);
break;
case 0x3f6: /* mulx By, Gy, rdx, Ey */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
switch (ot) {
default:
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_regs[R_EDX]);
tcg_gen_mulu2_i32(cpu_tmp2_i32, cpu_tmp3_i32,
cpu_tmp2_i32, cpu_tmp3_i32);
tcg_gen_extu_i32_tl(cpu_regs[s->vex_v], cpu_tmp2_i32);
tcg_gen_extu_i32_tl(cpu_regs[reg], cpu_tmp3_i32);
break;
#ifdef TARGET_X86_64
case MO_64:
tcg_gen_mulu2_i64(cpu_T0, cpu_T1,
cpu_T0, cpu_regs[R_EDX]);
tcg_gen_mov_i64(cpu_regs[s->vex_v], cpu_T0);
tcg_gen_mov_i64(cpu_regs[reg], cpu_T1);
break;
#endif
}
break;
case 0x3f5: /* pdep Gy, By, Ey */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
/* Note that by zero-extending the mask operand, we
automatically handle zero-extending the result. */
if (ot == MO_64) {
tcg_gen_mov_tl(cpu_T1, cpu_regs[s->vex_v]);
} else {
tcg_gen_ext32u_tl(cpu_T1, cpu_regs[s->vex_v]);
}
gen_helper_pdep(cpu_regs[reg], cpu_T0, cpu_T1);
break;
case 0x2f5: /* pext Gy, By, Ey */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
/* Note that by zero-extending the mask operand, we
automatically handle zero-extending the result. */
if (ot == MO_64) {
tcg_gen_mov_tl(cpu_T1, cpu_regs[s->vex_v]);
} else {
tcg_gen_ext32u_tl(cpu_T1, cpu_regs[s->vex_v]);
}
gen_helper_pext(cpu_regs[reg], cpu_T0, cpu_T1);
break;
case 0x1f6: /* adcx Gy, Ey */
case 0x2f6: /* adox Gy, Ey */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_ADX)) {
goto illegal_op;
} else {
TCGv carry_in, carry_out, zero;
int end_op;
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
/* Re-use the carry-out from a previous round. */
TCGV_UNUSED(carry_in);
carry_out = (b == 0x1f6 ? cpu_cc_dst : cpu_cc_src2);
switch (s->cc_op) {
case CC_OP_ADCX:
if (b == 0x1f6) {
carry_in = cpu_cc_dst;
end_op = CC_OP_ADCX;
} else {
end_op = CC_OP_ADCOX;
}
break;
case CC_OP_ADOX:
if (b == 0x1f6) {
end_op = CC_OP_ADCOX;
} else {
carry_in = cpu_cc_src2;
end_op = CC_OP_ADOX;
}
break;
case CC_OP_ADCOX:
end_op = CC_OP_ADCOX;
carry_in = carry_out;
break;
default:
end_op = (b == 0x1f6 ? CC_OP_ADCX : CC_OP_ADOX);
break;
}
/* If we can't reuse carry-out, get it out of EFLAGS. */
if (TCGV_IS_UNUSED(carry_in)) {
if (s->cc_op != CC_OP_ADCX && s->cc_op != CC_OP_ADOX) {
gen_compute_eflags(s);
}
carry_in = cpu_tmp0;
tcg_gen_extract_tl(carry_in, cpu_cc_src,
ctz32(b == 0x1f6 ? CC_C : CC_O), 1);
}
switch (ot) {
#ifdef TARGET_X86_64
case MO_32:
/* If we know TL is 64-bit, and we want a 32-bit
result, just do everything in 64-bit arithmetic. */
tcg_gen_ext32u_i64(cpu_regs[reg], cpu_regs[reg]);
tcg_gen_ext32u_i64(cpu_T0, cpu_T0);
tcg_gen_add_i64(cpu_T0, cpu_T0, cpu_regs[reg]);
tcg_gen_add_i64(cpu_T0, cpu_T0, carry_in);
tcg_gen_ext32u_i64(cpu_regs[reg], cpu_T0);
tcg_gen_shri_i64(carry_out, cpu_T0, 32);
break;
#endif
default:
/* Otherwise compute the carry-out in two steps. */
zero = tcg_const_tl(0);
tcg_gen_add2_tl(cpu_T0, carry_out,
cpu_T0, zero,
carry_in, zero);
tcg_gen_add2_tl(cpu_regs[reg], carry_out,
cpu_regs[reg], carry_out,
cpu_T0, zero);
tcg_temp_free(zero);
break;
}
set_cc_op(s, end_op);
}
break;
case 0x1f7: /* shlx Gy, Ey, By */
case 0x2f7: /* sarx Gy, Ey, By */
case 0x3f7: /* shrx Gy, Ey, By */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
if (ot == MO_64) {
tcg_gen_andi_tl(cpu_T1, cpu_regs[s->vex_v], 63);
} else {
tcg_gen_andi_tl(cpu_T1, cpu_regs[s->vex_v], 31);
}
if (b == 0x1f7) {
tcg_gen_shl_tl(cpu_T0, cpu_T0, cpu_T1);
} else if (b == 0x2f7) {
if (ot != MO_64) {
tcg_gen_ext32s_tl(cpu_T0, cpu_T0);
}
tcg_gen_sar_tl(cpu_T0, cpu_T0, cpu_T1);
} else {
if (ot != MO_64) {
tcg_gen_ext32u_tl(cpu_T0, cpu_T0);
}
tcg_gen_shr_tl(cpu_T0, cpu_T0, cpu_T1);
}
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
case 0x0f3:
case 0x1f3:
case 0x2f3:
case 0x3f3: /* Group 17 */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI1)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
switch (reg & 7) {
case 1: /* blsr By,Ey */
tcg_gen_neg_tl(cpu_T1, cpu_T0);
tcg_gen_and_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_mov_reg_v(ot, s->vex_v, cpu_T0);
gen_op_update2_cc();
set_cc_op(s, CC_OP_BMILGB + ot);
break;
case 2: /* blsmsk By,Ey */
tcg_gen_mov_tl(cpu_cc_src, cpu_T0);
tcg_gen_subi_tl(cpu_T0, cpu_T0, 1);
tcg_gen_xor_tl(cpu_T0, cpu_T0, cpu_cc_src);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
set_cc_op(s, CC_OP_BMILGB + ot);
break;
case 3: /* blsi By, Ey */
tcg_gen_mov_tl(cpu_cc_src, cpu_T0);
tcg_gen_subi_tl(cpu_T0, cpu_T0, 1);
tcg_gen_and_tl(cpu_T0, cpu_T0, cpu_cc_src);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
set_cc_op(s, CC_OP_BMILGB + ot);
break;
default:
goto unknown_op;
}
break;
default:
goto unknown_op;
}
break;
case 0x03a:
case 0x13a:
b = modrm;
modrm = cpu_ldub_code(env, s->pc++);
rm = modrm & 7;
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
if (b1 >= 2) {
goto unknown_op;
}
sse_fn_eppi = sse_op_table7[b].op[b1];
if (!sse_fn_eppi) {
goto unknown_op;
}
if (!(s->cpuid_ext_features & sse_op_table7[b].ext_mask))
goto illegal_op;
if (sse_fn_eppi == SSE_SPECIAL) {
ot = mo_64_32(s->dflag);
rm = (modrm & 7) | REX_B(s);
if (mod != 3)
gen_lea_modrm(env, s, modrm);
reg = ((modrm >> 3) & 7) | rex_r;
val = cpu_ldub_code(env, s->pc++);
switch (b) {
case 0x14: /* pextrb */
tcg_gen_ld8u_tl(cpu_T0, cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_B(val & 15)));
if (mod == 3) {
gen_op_mov_reg_v(ot, rm, cpu_T0);
} else {
tcg_gen_qemu_st_tl(cpu_T0, cpu_A0,
s->mem_index, MO_UB);
}
break;
case 0x15: /* pextrw */
tcg_gen_ld16u_tl(cpu_T0, cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_W(val & 7)));
if (mod == 3) {
gen_op_mov_reg_v(ot, rm, cpu_T0);
} else {
tcg_gen_qemu_st_tl(cpu_T0, cpu_A0,
s->mem_index, MO_LEUW);
}
break;
case 0x16:
if (ot == MO_32) { /* pextrd */
tcg_gen_ld_i32(cpu_tmp2_i32, cpu_env,
offsetof(CPUX86State,
xmm_regs[reg].ZMM_L(val & 3)));
if (mod == 3) {
tcg_gen_extu_i32_tl(cpu_regs[rm], cpu_tmp2_i32);
} else {
tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
}
} else { /* pextrq */
#ifdef TARGET_X86_64
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env,
offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(val & 1)));
if (mod == 3) {
tcg_gen_mov_i64(cpu_regs[rm], cpu_tmp1_i64);
} else {
tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_A0,
s->mem_index, MO_LEQ);
}
#else
goto illegal_op;
#endif
}
break;
case 0x17: /* extractps */
tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_L(val & 3)));
if (mod == 3) {
gen_op_mov_reg_v(ot, rm, cpu_T0);
} else {
tcg_gen_qemu_st_tl(cpu_T0, cpu_A0,
s->mem_index, MO_LEUL);
}
break;
case 0x20: /* pinsrb */
if (mod == 3) {
gen_op_mov_v_reg(MO_32, cpu_T0, rm);
} else {
tcg_gen_qemu_ld_tl(cpu_T0, cpu_A0,
s->mem_index, MO_UB);
}
tcg_gen_st8_tl(cpu_T0, cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_B(val & 15)));
break;
case 0x21: /* insertps */
if (mod == 3) {
tcg_gen_ld_i32(cpu_tmp2_i32, cpu_env,
offsetof(CPUX86State,xmm_regs[rm]
.ZMM_L((val >> 6) & 3)));
} else {
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
}
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env,
offsetof(CPUX86State,xmm_regs[reg]
.ZMM_L((val >> 4) & 3)));
if ((val >> 0) & 1)
tcg_gen_st_i32(tcg_const_i32(0 /*float32_zero*/),
cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_L(0)));
if ((val >> 1) & 1)
tcg_gen_st_i32(tcg_const_i32(0 /*float32_zero*/),
cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_L(1)));
if ((val >> 2) & 1)
tcg_gen_st_i32(tcg_const_i32(0 /*float32_zero*/),
cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_L(2)));
if ((val >> 3) & 1)
tcg_gen_st_i32(tcg_const_i32(0 /*float32_zero*/),
cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_L(3)));
break;
case 0x22:
if (ot == MO_32) { /* pinsrd */
if (mod == 3) {
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[rm]);
} else {
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
}
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env,
offsetof(CPUX86State,
xmm_regs[reg].ZMM_L(val & 3)));
} else { /* pinsrq */
#ifdef TARGET_X86_64
if (mod == 3) {
gen_op_mov_v_reg(ot, cpu_tmp1_i64, rm);
} else {
tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_A0,
s->mem_index, MO_LEQ);
}
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env,
offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(val & 1)));
#else
goto illegal_op;
#endif
}
break;
}
return;
}
if (b1) {
op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
if (mod == 3) {
op2_offset = offsetof(CPUX86State,xmm_regs[rm | REX_B(s)]);
} else {
op2_offset = offsetof(CPUX86State,xmm_t0);
gen_lea_modrm(env, s, modrm);
gen_ldo_env_A0(s, op2_offset);
}
} else {
op1_offset = offsetof(CPUX86State,fpregs[reg].mmx);
if (mod == 3) {
op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);
} else {
op2_offset = offsetof(CPUX86State,mmx_t0);
gen_lea_modrm(env, s, modrm);
gen_ldq_env_A0(s, op2_offset);
}
}
val = cpu_ldub_code(env, s->pc++);
if ((b & 0xfc) == 0x60) { /* pcmpXstrX */
set_cc_op(s, CC_OP_EFLAGS);
if (s->dflag == MO_64) {
/* The helper must use entire 64-bit gp registers */
val |= 1 << 8;
}
}
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
sse_fn_eppi(cpu_env, cpu_ptr0, cpu_ptr1, tcg_const_i32(val));
break;
case 0x33a:
/* Various integer extensions at 0f 3a f[0-f]. */
b = modrm | (b1 << 8);
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
switch (b) {
case 0x3f0: /* rorx Gy,Ey, Ib */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
b = cpu_ldub_code(env, s->pc++);
if (ot == MO_64) {
tcg_gen_rotri_tl(cpu_T0, cpu_T0, b & 63);
} else {
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
tcg_gen_rotri_i32(cpu_tmp2_i32, cpu_tmp2_i32, b & 31);
tcg_gen_extu_i32_tl(cpu_T0, cpu_tmp2_i32);
}
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
default:
goto unknown_op;
}
break;
default:
unknown_op:
gen_unknown_opcode(env, s);
return;
}
} else {
/* generic MMX or SSE operation */
switch(b) {
case 0x70: /* pshufx insn */
case 0xc6: /* pshufx insn */
case 0xc2: /* compare insns */
s->rip_offset = 1;
break;
default:
break;
}
if (is_xmm) {
op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
if (mod != 3) {
int sz = 4;
gen_lea_modrm(env, s, modrm);
op2_offset = offsetof(CPUX86State,xmm_t0);
switch (b) {
case 0x50 ... 0x5a:
case 0x5c ... 0x5f:
case 0xc2:
/* Most sse scalar operations. */
if (b1 == 2) {
sz = 2;
} else if (b1 == 3) {
sz = 3;
}
break;
case 0x2e: /* ucomis[sd] */
case 0x2f: /* comis[sd] */
if (b1 == 0) {
sz = 2;
} else {
sz = 3;
}
break;
}
switch (sz) {
case 2:
/* 32 bit access */
gen_op_ld_v(s, MO_32, cpu_T0, cpu_A0);
tcg_gen_st32_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,xmm_t0.ZMM_L(0)));
break;
case 3:
/* 64 bit access */
gen_ldq_env_A0(s, offsetof(CPUX86State, xmm_t0.ZMM_D(0)));
break;
default:
/* 128 bit access */
gen_ldo_env_A0(s, op2_offset);
break;
}
} else {
rm = (modrm & 7) | REX_B(s);
op2_offset = offsetof(CPUX86State,xmm_regs[rm]);
}
} else {
op1_offset = offsetof(CPUX86State,fpregs[reg].mmx);
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
op2_offset = offsetof(CPUX86State,mmx_t0);
gen_ldq_env_A0(s, op2_offset);
} else {
rm = (modrm & 7);
op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);
}
}
switch(b) {
case 0x0f: /* 3DNow! data insns */
val = cpu_ldub_code(env, s->pc++);
sse_fn_epp = sse_op_table5[val];
if (!sse_fn_epp) {
goto unknown_op;
}
if (!(s->cpuid_ext2_features & CPUID_EXT2_3DNOW)) {
goto illegal_op;
}
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1);
break;
case 0x70: /* pshufx insn */
case 0xc6: /* pshufx insn */
val = cpu_ldub_code(env, s->pc++);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
/* XXX: introduce a new table? */
sse_fn_ppi = (SSEFunc_0_ppi)sse_fn_epp;
sse_fn_ppi(cpu_ptr0, cpu_ptr1, tcg_const_i32(val));
break;
case 0xc2:
/* compare insns */
val = cpu_ldub_code(env, s->pc++);
if (val >= 8)
goto unknown_op;
sse_fn_epp = sse_op_table4[val][b1];
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1);
break;
case 0xf7:
/* maskmov : we must prepare A0 */
if (mod != 3)
goto illegal_op;
tcg_gen_mov_tl(cpu_A0, cpu_regs[R_EDI]);
gen_extu(s->aflag, cpu_A0);
gen_add_A0_ds_seg(s);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
/* XXX: introduce a new table? */
sse_fn_eppt = (SSEFunc_0_eppt)sse_fn_epp;
sse_fn_eppt(cpu_env, cpu_ptr0, cpu_ptr1, cpu_A0);
break;
default:
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1);
break;
}
if (b == 0x2e || b == 0x2f) {
set_cc_op(s, CC_OP_EFLAGS);
}
}
}
/* convert one instruction. s->is_jmp is set if the translation must
be stopped. Return the next pc value */
static target_ulong disas_insn(CPUX86State *env, DisasContext *s,
target_ulong pc_start)
{
int b, prefixes;
int shift;
TCGMemOp ot, aflag, dflag;
int modrm, reg, rm, mod, op, opreg, val;
target_ulong next_eip, tval;
int rex_w, rex_r;
s->pc_start = s->pc = pc_start;
prefixes = 0;
s->override = -1;
rex_w = -1;
rex_r = 0;
#ifdef TARGET_X86_64
s->rex_x = 0;
s->rex_b = 0;
x86_64_hregs = 0;
#endif
s->rip_offset = 0; /* for relative ip address */
s->vex_l = 0;
s->vex_v = 0;
next_byte:
/* x86 has an upper limit of 15 bytes for an instruction. Since we
* do not want to decode and generate IR for an illegal
* instruction, the following check limits the instruction size to
* 25 bytes: 14 prefix + 1 opc + 6 (modrm+sib+ofs) + 4 imm */
if (s->pc - pc_start > 14) {
goto illegal_op;
}
b = cpu_ldub_code(env, s->pc);
s->pc++;
/* Collect prefixes. */
switch (b) {
case 0xf3:
prefixes |= PREFIX_REPZ;
goto next_byte;
case 0xf2:
prefixes |= PREFIX_REPNZ;
goto next_byte;
case 0xf0:
prefixes |= PREFIX_LOCK;
goto next_byte;
case 0x2e:
s->override = R_CS;
goto next_byte;
case 0x36:
s->override = R_SS;
goto next_byte;
case 0x3e:
s->override = R_DS;
goto next_byte;
case 0x26:
s->override = R_ES;
goto next_byte;
case 0x64:
s->override = R_FS;
goto next_byte;
case 0x65:
s->override = R_GS;
goto next_byte;
case 0x66:
prefixes |= PREFIX_DATA;
goto next_byte;
case 0x67:
prefixes |= PREFIX_ADR;
goto next_byte;
#ifdef TARGET_X86_64
case 0x40 ... 0x4f:
if (CODE64(s)) {
/* REX prefix */
rex_w = (b >> 3) & 1;
rex_r = (b & 0x4) << 1;
s->rex_x = (b & 0x2) << 2;
REX_B(s) = (b & 0x1) << 3;
x86_64_hregs = 1; /* select uniform byte register addressing */
goto next_byte;
}
break;
#endif
case 0xc5: /* 2-byte VEX */
case 0xc4: /* 3-byte VEX */
/* VEX prefixes cannot be used except in 32-bit mode.
Otherwise the instruction is LES or LDS. */
if (s->code32 && !s->vm86) {
static const int pp_prefix[4] = {
0, PREFIX_DATA, PREFIX_REPZ, PREFIX_REPNZ
};
int vex3, vex2 = cpu_ldub_code(env, s->pc);
if (!CODE64(s) && (vex2 & 0xc0) != 0xc0) {
/* 4.1.4.6: In 32-bit mode, bits [7:6] must be 11b,
otherwise the instruction is LES or LDS. */
break;
}
s->pc++;
/* 4.1.1-4.1.3: No preceding lock, 66, f2, f3, or rex prefixes. */
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ
| PREFIX_LOCK | PREFIX_DATA)) {
goto illegal_op;
}
#ifdef TARGET_X86_64
if (x86_64_hregs) {
goto illegal_op;
}
#endif
rex_r = (~vex2 >> 4) & 8;
if (b == 0xc5) {
vex3 = vex2;
b = cpu_ldub_code(env, s->pc++);
} else {
#ifdef TARGET_X86_64
s->rex_x = (~vex2 >> 3) & 8;
s->rex_b = (~vex2 >> 2) & 8;
#endif
vex3 = cpu_ldub_code(env, s->pc++);
rex_w = (vex3 >> 7) & 1;
switch (vex2 & 0x1f) {
case 0x01: /* Implied 0f leading opcode bytes. */
b = cpu_ldub_code(env, s->pc++) | 0x100;
break;
case 0x02: /* Implied 0f 38 leading opcode bytes. */
b = 0x138;
break;
case 0x03: /* Implied 0f 3a leading opcode bytes. */
b = 0x13a;
break;
default: /* Reserved for future use. */
goto unknown_op;
}
}
s->vex_v = (~vex3 >> 3) & 0xf;
s->vex_l = (vex3 >> 2) & 1;
prefixes |= pp_prefix[vex3 & 3] | PREFIX_VEX;
}
break;
}
/* Post-process prefixes. */
if (CODE64(s)) {
/* In 64-bit mode, the default data size is 32-bit. Select 64-bit
data with rex_w, and 16-bit data with 0x66; rex_w takes precedence
over 0x66 if both are present. */
dflag = (rex_w > 0 ? MO_64 : prefixes & PREFIX_DATA ? MO_16 : MO_32);
/* In 64-bit mode, 0x67 selects 32-bit addressing. */
aflag = (prefixes & PREFIX_ADR ? MO_32 : MO_64);
} else {
/* In 16/32-bit mode, 0x66 selects the opposite data size. */
if (s->code32 ^ ((prefixes & PREFIX_DATA) != 0)) {
dflag = MO_32;
} else {
dflag = MO_16;
}
/* In 16/32-bit mode, 0x67 selects the opposite addressing. */
if (s->code32 ^ ((prefixes & PREFIX_ADR) != 0)) {
aflag = MO_32;
} else {
aflag = MO_16;
}
}
s->prefix = prefixes;
s->aflag = aflag;
s->dflag = dflag;
/* now check op code */
reswitch:
switch(b) {
case 0x0f:
/**************************/
/* extended op code */
b = cpu_ldub_code(env, s->pc++) | 0x100;
goto reswitch;
/**************************/
/* arith & logic */
case 0x00 ... 0x05:
case 0x08 ... 0x0d:
case 0x10 ... 0x15:
case 0x18 ... 0x1d:
case 0x20 ... 0x25:
case 0x28 ... 0x2d:
case 0x30 ... 0x35:
case 0x38 ... 0x3d:
{
int op, f, val;
op = (b >> 3) & 7;
f = (b >> 1) & 3;
ot = mo_b_d(b, dflag);
switch(f) {
case 0: /* OP Ev, Gv */
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
opreg = OR_TMP0;
} else if (op == OP_XORL && rm == reg) {
xor_zero:
/* xor reg, reg optimisation */
set_cc_op(s, CC_OP_CLR);
tcg_gen_movi_tl(cpu_T0, 0);
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
} else {
opreg = rm;
}
gen_op_mov_v_reg(ot, cpu_T1, reg);
gen_op(s, op, ot, opreg);
break;
case 1: /* OP Gv, Ev */
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
reg = ((modrm >> 3) & 7) | rex_r;
rm = (modrm & 7) | REX_B(s);
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, ot, cpu_T1, cpu_A0);
} else if (op == OP_XORL && rm == reg) {
goto xor_zero;
} else {
gen_op_mov_v_reg(ot, cpu_T1, rm);
}
gen_op(s, op, ot, reg);
break;
case 2: /* OP A, Iv */
val = insn_get(env, s, ot);
tcg_gen_movi_tl(cpu_T1, val);
gen_op(s, op, ot, OR_EAX);
break;
}
}
break;
case 0x82:
if (CODE64(s))
goto illegal_op;
case 0x80: /* GRP1 */
case 0x81:
case 0x83:
{
int val;
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
op = (modrm >> 3) & 7;
if (mod != 3) {
if (b == 0x83)
s->rip_offset = 1;
else
s->rip_offset = insn_const_size(ot);
gen_lea_modrm(env, s, modrm);
opreg = OR_TMP0;
} else {
opreg = rm;
}
switch(b) {
default:
case 0x80:
case 0x81:
case 0x82:
val = insn_get(env, s, ot);
break;
case 0x83:
val = (int8_t)insn_get(env, s, MO_8);
break;
}
tcg_gen_movi_tl(cpu_T1, val);
gen_op(s, op, ot, opreg);
}
break;
/**************************/
/* inc, dec, and other misc arith */
case 0x40 ... 0x47: /* inc Gv */
ot = dflag;
gen_inc(s, ot, OR_EAX + (b & 7), 1);
break;
case 0x48 ... 0x4f: /* dec Gv */
ot = dflag;
gen_inc(s, ot, OR_EAX + (b & 7), -1);
break;
case 0xf6: /* GRP3 */
case 0xf7:
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
op = (modrm >> 3) & 7;
if (mod != 3) {
if (op == 0) {
s->rip_offset = insn_const_size(ot);
}
gen_lea_modrm(env, s, modrm);
/* For those below that handle locked memory, don't load here. */
if (!(s->prefix & PREFIX_LOCK)
|| op != 2) {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
}
} else {
gen_op_mov_v_reg(ot, cpu_T0, rm);
}
switch(op) {
case 0: /* test */
val = insn_get(env, s, ot);
tcg_gen_movi_tl(cpu_T1, val);
gen_op_testl_T0_T1_cc();
set_cc_op(s, CC_OP_LOGICB + ot);
break;
case 2: /* not */
if (s->prefix & PREFIX_LOCK) {
if (mod == 3) {
goto illegal_op;
}
tcg_gen_movi_tl(cpu_T0, ~0);
tcg_gen_atomic_xor_fetch_tl(cpu_T0, cpu_A0, cpu_T0,
s->mem_index, ot | MO_LE);
} else {
tcg_gen_not_tl(cpu_T0, cpu_T0);
if (mod != 3) {
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_reg_v(ot, rm, cpu_T0);
}
}
break;
case 3: /* neg */
if (s->prefix & PREFIX_LOCK) {
TCGLabel *label1;
TCGv a0, t0, t1, t2;
if (mod == 3) {
goto illegal_op;
}
a0 = tcg_temp_local_new();
t0 = tcg_temp_local_new();
label1 = gen_new_label();
tcg_gen_mov_tl(a0, cpu_A0);
tcg_gen_mov_tl(t0, cpu_T0);
gen_set_label(label1);
t1 = tcg_temp_new();
t2 = tcg_temp_new();
tcg_gen_mov_tl(t2, t0);
tcg_gen_neg_tl(t1, t0);
tcg_gen_atomic_cmpxchg_tl(t0, a0, t0, t1,
s->mem_index, ot | MO_LE);
tcg_temp_free(t1);
tcg_gen_brcond_tl(TCG_COND_NE, t0, t2, label1);
tcg_temp_free(t2);
tcg_temp_free(a0);
tcg_gen_mov_tl(cpu_T0, t0);
tcg_temp_free(t0);
} else {
tcg_gen_neg_tl(cpu_T0, cpu_T0);
if (mod != 3) {
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_reg_v(ot, rm, cpu_T0);
}
}
gen_op_update_neg_cc();
set_cc_op(s, CC_OP_SUBB + ot);
break;
case 4: /* mul */
switch(ot) {
case MO_8:
gen_op_mov_v_reg(MO_8, cpu_T1, R_EAX);
tcg_gen_ext8u_tl(cpu_T0, cpu_T0);
tcg_gen_ext8u_tl(cpu_T1, cpu_T1);
/* XXX: use 32 bit mul which could be faster */
tcg_gen_mul_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
tcg_gen_andi_tl(cpu_cc_src, cpu_T0, 0xff00);
set_cc_op(s, CC_OP_MULB);
break;
case MO_16:
gen_op_mov_v_reg(MO_16, cpu_T1, R_EAX);
tcg_gen_ext16u_tl(cpu_T0, cpu_T0);
tcg_gen_ext16u_tl(cpu_T1, cpu_T1);
/* XXX: use 32 bit mul which could be faster */
tcg_gen_mul_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
tcg_gen_shri_tl(cpu_T0, cpu_T0, 16);
gen_op_mov_reg_v(MO_16, R_EDX, cpu_T0);
tcg_gen_mov_tl(cpu_cc_src, cpu_T0);
set_cc_op(s, CC_OP_MULW);
break;
default:
case MO_32:
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_regs[R_EAX]);
tcg_gen_mulu2_i32(cpu_tmp2_i32, cpu_tmp3_i32,
cpu_tmp2_i32, cpu_tmp3_i32);
tcg_gen_extu_i32_tl(cpu_regs[R_EAX], cpu_tmp2_i32);
tcg_gen_extu_i32_tl(cpu_regs[R_EDX], cpu_tmp3_i32);
tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[R_EAX]);
tcg_gen_mov_tl(cpu_cc_src, cpu_regs[R_EDX]);
set_cc_op(s, CC_OP_MULL);
break;
#ifdef TARGET_X86_64
case MO_64:
tcg_gen_mulu2_i64(cpu_regs[R_EAX], cpu_regs[R_EDX],
cpu_T0, cpu_regs[R_EAX]);
tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[R_EAX]);
tcg_gen_mov_tl(cpu_cc_src, cpu_regs[R_EDX]);
set_cc_op(s, CC_OP_MULQ);
break;
#endif
}
break;
case 5: /* imul */
switch(ot) {
case MO_8:
gen_op_mov_v_reg(MO_8, cpu_T1, R_EAX);
tcg_gen_ext8s_tl(cpu_T0, cpu_T0);
tcg_gen_ext8s_tl(cpu_T1, cpu_T1);
/* XXX: use 32 bit mul which could be faster */
tcg_gen_mul_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
tcg_gen_ext8s_tl(cpu_tmp0, cpu_T0);
tcg_gen_sub_tl(cpu_cc_src, cpu_T0, cpu_tmp0);
set_cc_op(s, CC_OP_MULB);
break;
case MO_16:
gen_op_mov_v_reg(MO_16, cpu_T1, R_EAX);
tcg_gen_ext16s_tl(cpu_T0, cpu_T0);
tcg_gen_ext16s_tl(cpu_T1, cpu_T1);
/* XXX: use 32 bit mul which could be faster */
tcg_gen_mul_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
tcg_gen_ext16s_tl(cpu_tmp0, cpu_T0);
tcg_gen_sub_tl(cpu_cc_src, cpu_T0, cpu_tmp0);
tcg_gen_shri_tl(cpu_T0, cpu_T0, 16);
gen_op_mov_reg_v(MO_16, R_EDX, cpu_T0);
set_cc_op(s, CC_OP_MULW);
break;
default:
case MO_32:
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_regs[R_EAX]);
tcg_gen_muls2_i32(cpu_tmp2_i32, cpu_tmp3_i32,
cpu_tmp2_i32, cpu_tmp3_i32);
tcg_gen_extu_i32_tl(cpu_regs[R_EAX], cpu_tmp2_i32);
tcg_gen_extu_i32_tl(cpu_regs[R_EDX], cpu_tmp3_i32);
tcg_gen_sari_i32(cpu_tmp2_i32, cpu_tmp2_i32, 31);
tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[R_EAX]);
tcg_gen_sub_i32(cpu_tmp2_i32, cpu_tmp2_i32, cpu_tmp3_i32);
tcg_gen_extu_i32_tl(cpu_cc_src, cpu_tmp2_i32);
set_cc_op(s, CC_OP_MULL);
break;
#ifdef TARGET_X86_64
case MO_64:
tcg_gen_muls2_i64(cpu_regs[R_EAX], cpu_regs[R_EDX],
cpu_T0, cpu_regs[R_EAX]);
tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[R_EAX]);
tcg_gen_sari_tl(cpu_cc_src, cpu_regs[R_EAX], 63);
tcg_gen_sub_tl(cpu_cc_src, cpu_cc_src, cpu_regs[R_EDX]);
set_cc_op(s, CC_OP_MULQ);
break;
#endif
}
break;
case 6: /* div */
switch(ot) {
case MO_8:
gen_helper_divb_AL(cpu_env, cpu_T0);
break;
case MO_16:
gen_helper_divw_AX(cpu_env, cpu_T0);
break;
default:
case MO_32:
gen_helper_divl_EAX(cpu_env, cpu_T0);
break;
#ifdef TARGET_X86_64
case MO_64:
gen_helper_divq_EAX(cpu_env, cpu_T0);
break;
#endif
}
break;
case 7: /* idiv */
switch(ot) {
case MO_8:
gen_helper_idivb_AL(cpu_env, cpu_T0);
break;
case MO_16:
gen_helper_idivw_AX(cpu_env, cpu_T0);
break;
default:
case MO_32:
gen_helper_idivl_EAX(cpu_env, cpu_T0);
break;
#ifdef TARGET_X86_64
case MO_64:
gen_helper_idivq_EAX(cpu_env, cpu_T0);
break;
#endif
}
break;
default:
goto unknown_op;
}
break;
case 0xfe: /* GRP4 */
case 0xff: /* GRP5 */
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
op = (modrm >> 3) & 7;
if (op >= 2 && b == 0xfe) {
goto unknown_op;
}
if (CODE64(s)) {
if (op == 2 || op == 4) {
/* operand size for jumps is 64 bit */
ot = MO_64;
} else if (op == 3 || op == 5) {
ot = dflag != MO_16 ? MO_32 + (rex_w == 1) : MO_16;
} else if (op == 6) {
/* default push size is 64 bit */
ot = mo_pushpop(s, dflag);
}
}
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
if (op >= 2 && op != 3 && op != 5)
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_v_reg(ot, cpu_T0, rm);
}
switch(op) {
case 0: /* inc Ev */
if (mod != 3)
opreg = OR_TMP0;
else
opreg = rm;
gen_inc(s, ot, opreg, 1);
break;
case 1: /* dec Ev */
if (mod != 3)
opreg = OR_TMP0;
else
opreg = rm;
gen_inc(s, ot, opreg, -1);
break;
case 2: /* call Ev */
/* XXX: optimize if memory (no 'and' is necessary) */
if (dflag == MO_16) {
tcg_gen_ext16u_tl(cpu_T0, cpu_T0);
}
next_eip = s->pc - s->cs_base;
tcg_gen_movi_tl(cpu_T1, next_eip);
gen_push_v(s, cpu_T1);
gen_op_jmp_v(cpu_T0);
gen_bnd_jmp(s);
gen_eob(s);
break;
case 3: /* lcall Ev */
gen_op_ld_v(s, ot, cpu_T1, cpu_A0);
gen_add_A0_im(s, 1 << ot);
gen_op_ld_v(s, MO_16, cpu_T0, cpu_A0);
do_lcall:
if (s->pe && !s->vm86) {
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_lcall_protected(cpu_env, cpu_tmp2_i32, cpu_T1,
tcg_const_i32(dflag - 1),
tcg_const_tl(s->pc - s->cs_base));
} else {
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_lcall_real(cpu_env, cpu_tmp2_i32, cpu_T1,
tcg_const_i32(dflag - 1),
tcg_const_i32(s->pc - s->cs_base));
}
gen_eob(s);
break;
case 4: /* jmp Ev */
if (dflag == MO_16) {
tcg_gen_ext16u_tl(cpu_T0, cpu_T0);
}
gen_op_jmp_v(cpu_T0);
gen_bnd_jmp(s);
gen_eob(s);
break;
case 5: /* ljmp Ev */
gen_op_ld_v(s, ot, cpu_T1, cpu_A0);
gen_add_A0_im(s, 1 << ot);
gen_op_ld_v(s, MO_16, cpu_T0, cpu_A0);
do_ljmp:
if (s->pe && !s->vm86) {
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_ljmp_protected(cpu_env, cpu_tmp2_i32, cpu_T1,
tcg_const_tl(s->pc - s->cs_base));
} else {
gen_op_movl_seg_T0_vm(R_CS);
gen_op_jmp_v(cpu_T1);
}
gen_eob(s);
break;
case 6: /* push Ev */
gen_push_v(s, cpu_T0);
break;
default:
goto unknown_op;
}
break;
case 0x84: /* test Ev, Gv */
case 0x85:
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
gen_op_mov_v_reg(ot, cpu_T1, reg);
gen_op_testl_T0_T1_cc();
set_cc_op(s, CC_OP_LOGICB + ot);
break;
case 0xa8: /* test eAX, Iv */
case 0xa9:
ot = mo_b_d(b, dflag);
val = insn_get(env, s, ot);
gen_op_mov_v_reg(ot, cpu_T0, OR_EAX);
tcg_gen_movi_tl(cpu_T1, val);
gen_op_testl_T0_T1_cc();
set_cc_op(s, CC_OP_LOGICB + ot);
break;
case 0x98: /* CWDE/CBW */
switch (dflag) {
#ifdef TARGET_X86_64
case MO_64:
gen_op_mov_v_reg(MO_32, cpu_T0, R_EAX);
tcg_gen_ext32s_tl(cpu_T0, cpu_T0);
gen_op_mov_reg_v(MO_64, R_EAX, cpu_T0);
break;
#endif
case MO_32:
gen_op_mov_v_reg(MO_16, cpu_T0, R_EAX);
tcg_gen_ext16s_tl(cpu_T0, cpu_T0);
gen_op_mov_reg_v(MO_32, R_EAX, cpu_T0);
break;
case MO_16:
gen_op_mov_v_reg(MO_8, cpu_T0, R_EAX);
tcg_gen_ext8s_tl(cpu_T0, cpu_T0);
gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0);
break;
default:
tcg_abort();
}
break;
case 0x99: /* CDQ/CWD */
switch (dflag) {
#ifdef TARGET_X86_64
case MO_64:
gen_op_mov_v_reg(MO_64, cpu_T0, R_EAX);
tcg_gen_sari_tl(cpu_T0, cpu_T0, 63);
gen_op_mov_reg_v(MO_64, R_EDX, cpu_T0);
break;
#endif
case MO_32:
gen_op_mov_v_reg(MO_32, cpu_T0, R_EAX);
tcg_gen_ext32s_tl(cpu_T0, cpu_T0);
tcg_gen_sari_tl(cpu_T0, cpu_T0, 31);
gen_op_mov_reg_v(MO_32, R_EDX, cpu_T0);
break;
case MO_16:
gen_op_mov_v_reg(MO_16, cpu_T0, R_EAX);
tcg_gen_ext16s_tl(cpu_T0, cpu_T0);
tcg_gen_sari_tl(cpu_T0, cpu_T0, 15);
gen_op_mov_reg_v(MO_16, R_EDX, cpu_T0);
break;
default:
tcg_abort();
}
break;
case 0x1af: /* imul Gv, Ev */
case 0x69: /* imul Gv, Ev, I */
case 0x6b:
ot = dflag;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
if (b == 0x69)
s->rip_offset = insn_const_size(ot);
else if (b == 0x6b)
s->rip_offset = 1;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
if (b == 0x69) {
val = insn_get(env, s, ot);
tcg_gen_movi_tl(cpu_T1, val);
} else if (b == 0x6b) {
val = (int8_t)insn_get(env, s, MO_8);
tcg_gen_movi_tl(cpu_T1, val);
} else {
gen_op_mov_v_reg(ot, cpu_T1, reg);
}
switch (ot) {
#ifdef TARGET_X86_64
case MO_64:
tcg_gen_muls2_i64(cpu_regs[reg], cpu_T1, cpu_T0, cpu_T1);
tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[reg]);
tcg_gen_sari_tl(cpu_cc_src, cpu_cc_dst, 63);
tcg_gen_sub_tl(cpu_cc_src, cpu_cc_src, cpu_T1);
break;
#endif
case MO_32:
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T1);
tcg_gen_muls2_i32(cpu_tmp2_i32, cpu_tmp3_i32,
cpu_tmp2_i32, cpu_tmp3_i32);
tcg_gen_extu_i32_tl(cpu_regs[reg], cpu_tmp2_i32);
tcg_gen_sari_i32(cpu_tmp2_i32, cpu_tmp2_i32, 31);
tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[reg]);
tcg_gen_sub_i32(cpu_tmp2_i32, cpu_tmp2_i32, cpu_tmp3_i32);
tcg_gen_extu_i32_tl(cpu_cc_src, cpu_tmp2_i32);
break;
default:
tcg_gen_ext16s_tl(cpu_T0, cpu_T0);
tcg_gen_ext16s_tl(cpu_T1, cpu_T1);
/* XXX: use 32 bit mul which could be faster */
tcg_gen_mul_tl(cpu_T0, cpu_T0, cpu_T1);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
tcg_gen_ext16s_tl(cpu_tmp0, cpu_T0);
tcg_gen_sub_tl(cpu_cc_src, cpu_T0, cpu_tmp0);
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
}
set_cc_op(s, CC_OP_MULB + ot);
break;
case 0x1c0:
case 0x1c1: /* xadd Ev, Gv */
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
gen_op_mov_v_reg(ot, cpu_T0, reg);
if (mod == 3) {
rm = (modrm & 7) | REX_B(s);
gen_op_mov_v_reg(ot, cpu_T1, rm);
tcg_gen_add_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_mov_reg_v(ot, reg, cpu_T1);
gen_op_mov_reg_v(ot, rm, cpu_T0);
} else {
gen_lea_modrm(env, s, modrm);
if (s->prefix & PREFIX_LOCK) {
tcg_gen_atomic_fetch_add_tl(cpu_T1, cpu_A0, cpu_T0,
s->mem_index, ot | MO_LE);
tcg_gen_add_tl(cpu_T0, cpu_T0, cpu_T1);
} else {
gen_op_ld_v(s, ot, cpu_T1, cpu_A0);
tcg_gen_add_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
}
gen_op_mov_reg_v(ot, reg, cpu_T1);
}
gen_op_update2_cc();
set_cc_op(s, CC_OP_ADDB + ot);
break;
case 0x1b0:
case 0x1b1: /* cmpxchg Ev, Gv */
{
TCGv oldv, newv, cmpv;
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
oldv = tcg_temp_new();
newv = tcg_temp_new();
cmpv = tcg_temp_new();
gen_op_mov_v_reg(ot, newv, reg);
tcg_gen_mov_tl(cmpv, cpu_regs[R_EAX]);
if (s->prefix & PREFIX_LOCK) {
if (mod == 3) {
goto illegal_op;
}
gen_lea_modrm(env, s, modrm);
tcg_gen_atomic_cmpxchg_tl(oldv, cpu_A0, cmpv, newv,
s->mem_index, ot | MO_LE);
gen_op_mov_reg_v(ot, R_EAX, oldv);
} else {
if (mod == 3) {
rm = (modrm & 7) | REX_B(s);
gen_op_mov_v_reg(ot, oldv, rm);
} else {
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, ot, oldv, cpu_A0);
rm = 0; /* avoid warning */
}
gen_extu(ot, oldv);
gen_extu(ot, cmpv);
/* store value = (old == cmp ? new : old); */
tcg_gen_movcond_tl(TCG_COND_EQ, newv, oldv, cmpv, newv, oldv);
if (mod == 3) {
gen_op_mov_reg_v(ot, R_EAX, oldv);
gen_op_mov_reg_v(ot, rm, newv);
} else {
/* Perform an unconditional store cycle like physical cpu;
must be before changing accumulator to ensure
idempotency if the store faults and the instruction
is restarted */
gen_op_st_v(s, ot, newv, cpu_A0);
gen_op_mov_reg_v(ot, R_EAX, oldv);
}
}
tcg_gen_mov_tl(cpu_cc_src, oldv);
tcg_gen_mov_tl(cpu_cc_srcT, cmpv);
tcg_gen_sub_tl(cpu_cc_dst, cmpv, oldv);
set_cc_op(s, CC_OP_SUBB + ot);
tcg_temp_free(oldv);
tcg_temp_free(newv);
tcg_temp_free(cmpv);
}
break;
case 0x1c7: /* cmpxchg8b */
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
if ((mod == 3) || ((modrm & 0x38) != 0x8))
goto illegal_op;
#ifdef TARGET_X86_64
if (dflag == MO_64) {
if (!(s->cpuid_ext_features & CPUID_EXT_CX16))
goto illegal_op;
gen_lea_modrm(env, s, modrm);
if ((s->prefix & PREFIX_LOCK) && parallel_cpus) {
gen_helper_cmpxchg16b(cpu_env, cpu_A0);
} else {
gen_helper_cmpxchg16b_unlocked(cpu_env, cpu_A0);
}
} else
#endif
{
if (!(s->cpuid_features & CPUID_CX8))
goto illegal_op;
gen_lea_modrm(env, s, modrm);
if ((s->prefix & PREFIX_LOCK) && parallel_cpus) {
gen_helper_cmpxchg8b(cpu_env, cpu_A0);
} else {
gen_helper_cmpxchg8b_unlocked(cpu_env, cpu_A0);
}
}
set_cc_op(s, CC_OP_EFLAGS);
break;
/**************************/
/* push/pop */
case 0x50 ... 0x57: /* push */
gen_op_mov_v_reg(MO_32, cpu_T0, (b & 7) | REX_B(s));
gen_push_v(s, cpu_T0);
break;
case 0x58 ... 0x5f: /* pop */
ot = gen_pop_T0(s);
/* NOTE: order is important for pop %sp */
gen_pop_update(s, ot);
gen_op_mov_reg_v(ot, (b & 7) | REX_B(s), cpu_T0);
break;
case 0x60: /* pusha */
if (CODE64(s))
goto illegal_op;
gen_pusha(s);
break;
case 0x61: /* popa */
if (CODE64(s))
goto illegal_op;
gen_popa(s);
break;
case 0x68: /* push Iv */
case 0x6a:
ot = mo_pushpop(s, dflag);
if (b == 0x68)
val = insn_get(env, s, ot);
else
val = (int8_t)insn_get(env, s, MO_8);
tcg_gen_movi_tl(cpu_T0, val);
gen_push_v(s, cpu_T0);
break;
case 0x8f: /* pop Ev */
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
ot = gen_pop_T0(s);
if (mod == 3) {
/* NOTE: order is important for pop %sp */
gen_pop_update(s, ot);
rm = (modrm & 7) | REX_B(s);
gen_op_mov_reg_v(ot, rm, cpu_T0);
} else {
/* NOTE: order is important too for MMU exceptions */
s->popl_esp_hack = 1 << ot;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 1);
s->popl_esp_hack = 0;
gen_pop_update(s, ot);
}
break;
case 0xc8: /* enter */
{
int level;
val = cpu_lduw_code(env, s->pc);
s->pc += 2;
level = cpu_ldub_code(env, s->pc++);
gen_enter(s, val, level);
}
break;
case 0xc9: /* leave */
gen_leave(s);
break;
case 0x06: /* push es */
case 0x0e: /* push cs */
case 0x16: /* push ss */
case 0x1e: /* push ds */
if (CODE64(s))
goto illegal_op;
gen_op_movl_T0_seg(b >> 3);
gen_push_v(s, cpu_T0);
break;
case 0x1a0: /* push fs */
case 0x1a8: /* push gs */
gen_op_movl_T0_seg((b >> 3) & 7);
gen_push_v(s, cpu_T0);
break;
case 0x07: /* pop es */
case 0x17: /* pop ss */
case 0x1f: /* pop ds */
if (CODE64(s))
goto illegal_op;
reg = b >> 3;
ot = gen_pop_T0(s);
gen_movl_seg_T0(s, reg);
gen_pop_update(s, ot);
/* Note that reg == R_SS in gen_movl_seg_T0 always sets is_jmp. */
if (s->is_jmp) {
gen_jmp_im(s->pc - s->cs_base);
if (reg == R_SS) {
s->tf = 0;
gen_eob_inhibit_irq(s, true);
} else {
gen_eob(s);
}
}
break;
case 0x1a1: /* pop fs */
case 0x1a9: /* pop gs */
ot = gen_pop_T0(s);
gen_movl_seg_T0(s, (b >> 3) & 7);
gen_pop_update(s, ot);
if (s->is_jmp) {
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
}
break;
/**************************/
/* mov */
case 0x88:
case 0x89: /* mov Gv, Ev */
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
/* generate a generic store */
gen_ldst_modrm(env, s, modrm, ot, reg, 1);
break;
case 0xc6:
case 0xc7: /* mov Ev, Iv */
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
if (mod != 3) {
s->rip_offset = insn_const_size(ot);
gen_lea_modrm(env, s, modrm);
}
val = insn_get(env, s, ot);
tcg_gen_movi_tl(cpu_T0, val);
if (mod != 3) {
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_reg_v(ot, (modrm & 7) | REX_B(s), cpu_T0);
}
break;
case 0x8a:
case 0x8b: /* mov Ev, Gv */
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
case 0x8e: /* mov seg, Gv */
modrm = cpu_ldub_code(env, s->pc++);
reg = (modrm >> 3) & 7;
if (reg >= 6 || reg == R_CS)
goto illegal_op;
gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0);
gen_movl_seg_T0(s, reg);
/* Note that reg == R_SS in gen_movl_seg_T0 always sets is_jmp. */
if (s->is_jmp) {
gen_jmp_im(s->pc - s->cs_base);
if (reg == R_SS) {
s->tf = 0;
gen_eob_inhibit_irq(s, true);
} else {
gen_eob(s);
}
}
break;
case 0x8c: /* mov Gv, seg */
modrm = cpu_ldub_code(env, s->pc++);
reg = (modrm >> 3) & 7;
mod = (modrm >> 6) & 3;
if (reg >= 6)
goto illegal_op;
gen_op_movl_T0_seg(reg);
ot = mod == 3 ? dflag : MO_16;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 1);
break;
case 0x1b6: /* movzbS Gv, Eb */
case 0x1b7: /* movzwS Gv, Eb */
case 0x1be: /* movsbS Gv, Eb */
case 0x1bf: /* movswS Gv, Eb */
{
TCGMemOp d_ot;
TCGMemOp s_ot;
/* d_ot is the size of destination */
d_ot = dflag;
/* ot is the size of source */
ot = (b & 1) + MO_8;
/* s_ot is the sign+size of source */
s_ot = b & 8 ? MO_SIGN | ot : ot;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
if (mod == 3) {
if (s_ot == MO_SB && byte_reg_is_xH(rm)) {
tcg_gen_sextract_tl(cpu_T0, cpu_regs[rm - 4], 8, 8);
} else {
gen_op_mov_v_reg(ot, cpu_T0, rm);
switch (s_ot) {
case MO_UB:
tcg_gen_ext8u_tl(cpu_T0, cpu_T0);
break;
case MO_SB:
tcg_gen_ext8s_tl(cpu_T0, cpu_T0);
break;
case MO_UW:
tcg_gen_ext16u_tl(cpu_T0, cpu_T0);
break;
default:
case MO_SW:
tcg_gen_ext16s_tl(cpu_T0, cpu_T0);
break;
}
}
gen_op_mov_reg_v(d_ot, reg, cpu_T0);
} else {
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, s_ot, cpu_T0, cpu_A0);
gen_op_mov_reg_v(d_ot, reg, cpu_T0);
}
}
break;
case 0x8d: /* lea */
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
if (mod == 3)
goto illegal_op;
reg = ((modrm >> 3) & 7) | rex_r;
{
AddressParts a = gen_lea_modrm_0(env, s, modrm);
TCGv ea = gen_lea_modrm_1(a);
gen_lea_v_seg(s, s->aflag, ea, -1, -1);
gen_op_mov_reg_v(dflag, reg, cpu_A0);
}
break;
case 0xa0: /* mov EAX, Ov */
case 0xa1:
case 0xa2: /* mov Ov, EAX */
case 0xa3:
{
target_ulong offset_addr;
ot = mo_b_d(b, dflag);
switch (s->aflag) {
#ifdef TARGET_X86_64
case MO_64:
offset_addr = cpu_ldq_code(env, s->pc);
s->pc += 8;
break;
#endif
default:
offset_addr = insn_get(env, s, s->aflag);
break;
}
tcg_gen_movi_tl(cpu_A0, offset_addr);
gen_add_A0_ds_seg(s);
if ((b & 2) == 0) {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
gen_op_mov_reg_v(ot, R_EAX, cpu_T0);
} else {
gen_op_mov_v_reg(ot, cpu_T0, R_EAX);
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
}
}
break;
case 0xd7: /* xlat */
tcg_gen_mov_tl(cpu_A0, cpu_regs[R_EBX]);
tcg_gen_ext8u_tl(cpu_T0, cpu_regs[R_EAX]);
tcg_gen_add_tl(cpu_A0, cpu_A0, cpu_T0);
gen_extu(s->aflag, cpu_A0);
gen_add_A0_ds_seg(s);
gen_op_ld_v(s, MO_8, cpu_T0, cpu_A0);
gen_op_mov_reg_v(MO_8, R_EAX, cpu_T0);
break;
case 0xb0 ... 0xb7: /* mov R, Ib */
val = insn_get(env, s, MO_8);
tcg_gen_movi_tl(cpu_T0, val);
gen_op_mov_reg_v(MO_8, (b & 7) | REX_B(s), cpu_T0);
break;
case 0xb8 ... 0xbf: /* mov R, Iv */
#ifdef TARGET_X86_64
if (dflag == MO_64) {
uint64_t tmp;
/* 64 bit case */
tmp = cpu_ldq_code(env, s->pc);
s->pc += 8;
reg = (b & 7) | REX_B(s);
tcg_gen_movi_tl(cpu_T0, tmp);
gen_op_mov_reg_v(MO_64, reg, cpu_T0);
} else
#endif
{
ot = dflag;
val = insn_get(env, s, ot);
reg = (b & 7) | REX_B(s);
tcg_gen_movi_tl(cpu_T0, val);
gen_op_mov_reg_v(ot, reg, cpu_T0);
}
break;
case 0x91 ... 0x97: /* xchg R, EAX */
do_xchg_reg_eax:
ot = dflag;
reg = (b & 7) | REX_B(s);
rm = R_EAX;
goto do_xchg_reg;
case 0x86:
case 0x87: /* xchg Ev, Gv */
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
if (mod == 3) {
rm = (modrm & 7) | REX_B(s);
do_xchg_reg:
gen_op_mov_v_reg(ot, cpu_T0, reg);
gen_op_mov_v_reg(ot, cpu_T1, rm);
gen_op_mov_reg_v(ot, rm, cpu_T0);
gen_op_mov_reg_v(ot, reg, cpu_T1);
} else {
gen_lea_modrm(env, s, modrm);
gen_op_mov_v_reg(ot, cpu_T0, reg);
/* for xchg, lock is implicit */
tcg_gen_atomic_xchg_tl(cpu_T1, cpu_A0, cpu_T0,
s->mem_index, ot | MO_LE);
gen_op_mov_reg_v(ot, reg, cpu_T1);
}
break;
case 0xc4: /* les Gv */
/* In CODE64 this is VEX3; see above. */
op = R_ES;
goto do_lxx;
case 0xc5: /* lds Gv */
/* In CODE64 this is VEX2; see above. */
op = R_DS;
goto do_lxx;
case 0x1b2: /* lss Gv */
op = R_SS;
goto do_lxx;
case 0x1b4: /* lfs Gv */
op = R_FS;
goto do_lxx;
case 0x1b5: /* lgs Gv */
op = R_GS;
do_lxx:
ot = dflag != MO_16 ? MO_32 : MO_16;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
if (mod == 3)
goto illegal_op;
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, ot, cpu_T1, cpu_A0);
gen_add_A0_im(s, 1 << ot);
/* load the segment first to handle exceptions properly */
gen_op_ld_v(s, MO_16, cpu_T0, cpu_A0);
gen_movl_seg_T0(s, op);
/* then put the data */
gen_op_mov_reg_v(ot, reg, cpu_T1);
if (s->is_jmp) {
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
}
break;
/************************/
/* shifts */
case 0xc0:
case 0xc1:
/* shift Ev,Ib */
shift = 2;
grp2:
{
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
op = (modrm >> 3) & 7;
if (mod != 3) {
if (shift == 2) {
s->rip_offset = 1;
}
gen_lea_modrm(env, s, modrm);
opreg = OR_TMP0;
} else {
opreg = (modrm & 7) | REX_B(s);
}
/* simpler op */
if (shift == 0) {
gen_shift(s, op, ot, opreg, OR_ECX);
} else {
if (shift == 2) {
shift = cpu_ldub_code(env, s->pc++);
}
gen_shifti(s, op, ot, opreg, shift);
}
}
break;
case 0xd0:
case 0xd1:
/* shift Ev,1 */
shift = 1;
goto grp2;
case 0xd2:
case 0xd3:
/* shift Ev,cl */
shift = 0;
goto grp2;
case 0x1a4: /* shld imm */
op = 0;
shift = 1;
goto do_shiftd;
case 0x1a5: /* shld cl */
op = 0;
shift = 0;
goto do_shiftd;
case 0x1ac: /* shrd imm */
op = 1;
shift = 1;
goto do_shiftd;
case 0x1ad: /* shrd cl */
op = 1;
shift = 0;
do_shiftd:
ot = dflag;
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
reg = ((modrm >> 3) & 7) | rex_r;
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
opreg = OR_TMP0;
} else {
opreg = rm;
}
gen_op_mov_v_reg(ot, cpu_T1, reg);
if (shift) {
TCGv imm = tcg_const_tl(cpu_ldub_code(env, s->pc++));
gen_shiftd_rm_T1(s, ot, opreg, op, imm);
tcg_temp_free(imm);
} else {
gen_shiftd_rm_T1(s, ot, opreg, op, cpu_regs[R_ECX]);
}
break;
/************************/
/* floats */
case 0xd8 ... 0xdf:
if (s->flags & (HF_EM_MASK | HF_TS_MASK)) {
/* if CR0.EM or CR0.TS are set, generate an FPU exception */
/* XXX: what to do if illegal op ? */
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
break;
}
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
rm = modrm & 7;
op = ((b & 7) << 3) | ((modrm >> 3) & 7);
if (mod != 3) {
/* memory op */
gen_lea_modrm(env, s, modrm);
switch(op) {
case 0x00 ... 0x07: /* fxxxs */
case 0x10 ... 0x17: /* fixxxl */
case 0x20 ... 0x27: /* fxxxl */
case 0x30 ... 0x37: /* fixxx */
{
int op1;
op1 = op & 7;
switch(op >> 4) {
case 0:
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
gen_helper_flds_FT0(cpu_env, cpu_tmp2_i32);
break;
case 1:
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
gen_helper_fildl_FT0(cpu_env, cpu_tmp2_i32);
break;
case 2:
tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_A0,
s->mem_index, MO_LEQ);
gen_helper_fldl_FT0(cpu_env, cpu_tmp1_i64);
break;
case 3:
default:
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LESW);
gen_helper_fildl_FT0(cpu_env, cpu_tmp2_i32);
break;
}
gen_helper_fp_arith_ST0_FT0(op1);
if (op1 == 3) {
/* fcomp needs pop */
gen_helper_fpop(cpu_env);
}
}
break;
case 0x08: /* flds */
case 0x0a: /* fsts */
case 0x0b: /* fstps */
case 0x18 ... 0x1b: /* fildl, fisttpl, fistl, fistpl */
case 0x28 ... 0x2b: /* fldl, fisttpll, fstl, fstpl */
case 0x38 ... 0x3b: /* filds, fisttps, fists, fistps */
switch(op & 7) {
case 0:
switch(op >> 4) {
case 0:
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
gen_helper_flds_ST0(cpu_env, cpu_tmp2_i32);
break;
case 1:
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
gen_helper_fildl_ST0(cpu_env, cpu_tmp2_i32);
break;
case 2:
tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_A0,
s->mem_index, MO_LEQ);
gen_helper_fldl_ST0(cpu_env, cpu_tmp1_i64);
break;
case 3:
default:
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LESW);
gen_helper_fildl_ST0(cpu_env, cpu_tmp2_i32);
break;
}
break;
case 1:
/* XXX: the corresponding CPUID bit must be tested ! */
switch(op >> 4) {
case 1:
gen_helper_fisttl_ST0(cpu_tmp2_i32, cpu_env);
tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
break;
case 2:
gen_helper_fisttll_ST0(cpu_tmp1_i64, cpu_env);
tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_A0,
s->mem_index, MO_LEQ);
break;
case 3:
default:
gen_helper_fistt_ST0(cpu_tmp2_i32, cpu_env);
tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUW);
break;
}
gen_helper_fpop(cpu_env);
break;
default:
switch(op >> 4) {
case 0:
gen_helper_fsts_ST0(cpu_tmp2_i32, cpu_env);
tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
break;
case 1:
gen_helper_fistl_ST0(cpu_tmp2_i32, cpu_env);
tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
break;
case 2:
gen_helper_fstl_ST0(cpu_tmp1_i64, cpu_env);
tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_A0,
s->mem_index, MO_LEQ);
break;
case 3:
default:
gen_helper_fist_ST0(cpu_tmp2_i32, cpu_env);
tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUW);
break;
}
if ((op & 7) == 3)
gen_helper_fpop(cpu_env);
break;
}
break;
case 0x0c: /* fldenv mem */
gen_helper_fldenv(cpu_env, cpu_A0, tcg_const_i32(dflag - 1));
break;
case 0x0d: /* fldcw mem */
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUW);
gen_helper_fldcw(cpu_env, cpu_tmp2_i32);
break;
case 0x0e: /* fnstenv mem */
gen_helper_fstenv(cpu_env, cpu_A0, tcg_const_i32(dflag - 1));
break;
case 0x0f: /* fnstcw mem */
gen_helper_fnstcw(cpu_tmp2_i32, cpu_env);
tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUW);
break;
case 0x1d: /* fldt mem */
gen_helper_fldt_ST0(cpu_env, cpu_A0);
break;
case 0x1f: /* fstpt mem */
gen_helper_fstt_ST0(cpu_env, cpu_A0);
gen_helper_fpop(cpu_env);
break;
case 0x2c: /* frstor mem */
gen_helper_frstor(cpu_env, cpu_A0, tcg_const_i32(dflag - 1));
break;
case 0x2e: /* fnsave mem */
gen_helper_fsave(cpu_env, cpu_A0, tcg_const_i32(dflag - 1));
break;
case 0x2f: /* fnstsw mem */
gen_helper_fnstsw(cpu_tmp2_i32, cpu_env);
tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUW);
break;
case 0x3c: /* fbld */
gen_helper_fbld_ST0(cpu_env, cpu_A0);
break;
case 0x3e: /* fbstp */
gen_helper_fbst_ST0(cpu_env, cpu_A0);
gen_helper_fpop(cpu_env);
break;
case 0x3d: /* fildll */
tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_A0, s->mem_index, MO_LEQ);
gen_helper_fildll_ST0(cpu_env, cpu_tmp1_i64);
break;
case 0x3f: /* fistpll */
gen_helper_fistll_ST0(cpu_tmp1_i64, cpu_env);
tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_A0, s->mem_index, MO_LEQ);
gen_helper_fpop(cpu_env);
break;
default:
goto unknown_op;
}
} else {
/* register float ops */
opreg = rm;
switch(op) {
case 0x08: /* fld sti */
gen_helper_fpush(cpu_env);
gen_helper_fmov_ST0_STN(cpu_env,
tcg_const_i32((opreg + 1) & 7));
break;
case 0x09: /* fxchg sti */
case 0x29: /* fxchg4 sti, undocumented op */
case 0x39: /* fxchg7 sti, undocumented op */
gen_helper_fxchg_ST0_STN(cpu_env, tcg_const_i32(opreg));
break;
case 0x0a: /* grp d9/2 */
switch(rm) {
case 0: /* fnop */
/* check exceptions (FreeBSD FPU probe) */
gen_helper_fwait(cpu_env);
break;
default:
goto unknown_op;
}
break;
case 0x0c: /* grp d9/4 */
switch(rm) {
case 0: /* fchs */
gen_helper_fchs_ST0(cpu_env);
break;
case 1: /* fabs */
gen_helper_fabs_ST0(cpu_env);
break;
case 4: /* ftst */
gen_helper_fldz_FT0(cpu_env);
gen_helper_fcom_ST0_FT0(cpu_env);
break;
case 5: /* fxam */
gen_helper_fxam_ST0(cpu_env);
break;
default:
goto unknown_op;
}
break;
case 0x0d: /* grp d9/5 */
{
switch(rm) {
case 0:
gen_helper_fpush(cpu_env);
gen_helper_fld1_ST0(cpu_env);
break;
case 1:
gen_helper_fpush(cpu_env);
gen_helper_fldl2t_ST0(cpu_env);
break;
case 2:
gen_helper_fpush(cpu_env);
gen_helper_fldl2e_ST0(cpu_env);
break;
case 3:
gen_helper_fpush(cpu_env);
gen_helper_fldpi_ST0(cpu_env);
break;
case 4:
gen_helper_fpush(cpu_env);
gen_helper_fldlg2_ST0(cpu_env);
break;
case 5:
gen_helper_fpush(cpu_env);
gen_helper_fldln2_ST0(cpu_env);
break;
case 6:
gen_helper_fpush(cpu_env);
gen_helper_fldz_ST0(cpu_env);
break;
default:
goto unknown_op;
}
}
break;
case 0x0e: /* grp d9/6 */
switch(rm) {
case 0: /* f2xm1 */
gen_helper_f2xm1(cpu_env);
break;
case 1: /* fyl2x */
gen_helper_fyl2x(cpu_env);
break;
case 2: /* fptan */
gen_helper_fptan(cpu_env);
break;
case 3: /* fpatan */
gen_helper_fpatan(cpu_env);
break;
case 4: /* fxtract */
gen_helper_fxtract(cpu_env);
break;
case 5: /* fprem1 */
gen_helper_fprem1(cpu_env);
break;
case 6: /* fdecstp */
gen_helper_fdecstp(cpu_env);
break;
default:
case 7: /* fincstp */
gen_helper_fincstp(cpu_env);
break;
}
break;
case 0x0f: /* grp d9/7 */
switch(rm) {
case 0: /* fprem */
gen_helper_fprem(cpu_env);
break;
case 1: /* fyl2xp1 */
gen_helper_fyl2xp1(cpu_env);
break;
case 2: /* fsqrt */
gen_helper_fsqrt(cpu_env);
break;
case 3: /* fsincos */
gen_helper_fsincos(cpu_env);
break;
case 5: /* fscale */
gen_helper_fscale(cpu_env);
break;
case 4: /* frndint */
gen_helper_frndint(cpu_env);
break;
case 6: /* fsin */
gen_helper_fsin(cpu_env);
break;
default:
case 7: /* fcos */
gen_helper_fcos(cpu_env);
break;
}
break;
case 0x00: case 0x01: case 0x04 ... 0x07: /* fxxx st, sti */
case 0x20: case 0x21: case 0x24 ... 0x27: /* fxxx sti, st */
case 0x30: case 0x31: case 0x34 ... 0x37: /* fxxxp sti, st */
{
int op1;
op1 = op & 7;
if (op >= 0x20) {
gen_helper_fp_arith_STN_ST0(op1, opreg);
if (op >= 0x30)
gen_helper_fpop(cpu_env);
} else {
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fp_arith_ST0_FT0(op1);
}
}
break;
case 0x02: /* fcom */
case 0x22: /* fcom2, undocumented op */
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fcom_ST0_FT0(cpu_env);
break;
case 0x03: /* fcomp */
case 0x23: /* fcomp3, undocumented op */
case 0x32: /* fcomp5, undocumented op */
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fcom_ST0_FT0(cpu_env);
gen_helper_fpop(cpu_env);
break;
case 0x15: /* da/5 */
switch(rm) {
case 1: /* fucompp */
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(1));
gen_helper_fucom_ST0_FT0(cpu_env);
gen_helper_fpop(cpu_env);
gen_helper_fpop(cpu_env);
break;
default:
goto unknown_op;
}
break;
case 0x1c:
switch(rm) {
case 0: /* feni (287 only, just do nop here) */
break;
case 1: /* fdisi (287 only, just do nop here) */
break;
case 2: /* fclex */
gen_helper_fclex(cpu_env);
break;
case 3: /* fninit */
gen_helper_fninit(cpu_env);
break;
case 4: /* fsetpm (287 only, just do nop here) */
break;
default:
goto unknown_op;
}
break;
case 0x1d: /* fucomi */
if (!(s->cpuid_features & CPUID_CMOV)) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fucomi_ST0_FT0(cpu_env);
set_cc_op(s, CC_OP_EFLAGS);
break;
case 0x1e: /* fcomi */
if (!(s->cpuid_features & CPUID_CMOV)) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fcomi_ST0_FT0(cpu_env);
set_cc_op(s, CC_OP_EFLAGS);
break;
case 0x28: /* ffree sti */
gen_helper_ffree_STN(cpu_env, tcg_const_i32(opreg));
break;
case 0x2a: /* fst sti */
gen_helper_fmov_STN_ST0(cpu_env, tcg_const_i32(opreg));
break;
case 0x2b: /* fstp sti */
case 0x0b: /* fstp1 sti, undocumented op */
case 0x3a: /* fstp8 sti, undocumented op */
case 0x3b: /* fstp9 sti, undocumented op */
gen_helper_fmov_STN_ST0(cpu_env, tcg_const_i32(opreg));
gen_helper_fpop(cpu_env);
break;
case 0x2c: /* fucom st(i) */
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fucom_ST0_FT0(cpu_env);
break;
case 0x2d: /* fucomp st(i) */
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fucom_ST0_FT0(cpu_env);
gen_helper_fpop(cpu_env);
break;
case 0x33: /* de/3 */
switch(rm) {
case 1: /* fcompp */
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(1));
gen_helper_fcom_ST0_FT0(cpu_env);
gen_helper_fpop(cpu_env);
gen_helper_fpop(cpu_env);
break;
default:
goto unknown_op;
}
break;
case 0x38: /* ffreep sti, undocumented op */
gen_helper_ffree_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fpop(cpu_env);
break;
case 0x3c: /* df/4 */
switch(rm) {
case 0:
gen_helper_fnstsw(cpu_tmp2_i32, cpu_env);
tcg_gen_extu_i32_tl(cpu_T0, cpu_tmp2_i32);
gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0);
break;
default:
goto unknown_op;
}
break;
case 0x3d: /* fucomip */
if (!(s->cpuid_features & CPUID_CMOV)) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fucomi_ST0_FT0(cpu_env);
gen_helper_fpop(cpu_env);
set_cc_op(s, CC_OP_EFLAGS);
break;
case 0x3e: /* fcomip */
if (!(s->cpuid_features & CPUID_CMOV)) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fcomi_ST0_FT0(cpu_env);
gen_helper_fpop(cpu_env);
set_cc_op(s, CC_OP_EFLAGS);
break;
case 0x10 ... 0x13: /* fcmovxx */
case 0x18 ... 0x1b:
{
int op1;
TCGLabel *l1;
static const uint8_t fcmov_cc[8] = {
(JCC_B << 1),
(JCC_Z << 1),
(JCC_BE << 1),
(JCC_P << 1),
};
if (!(s->cpuid_features & CPUID_CMOV)) {
goto illegal_op;
}
op1 = fcmov_cc[op & 3] | (((op >> 3) & 1) ^ 1);
l1 = gen_new_label();
gen_jcc1_noeob(s, op1, l1);
gen_helper_fmov_ST0_STN(cpu_env, tcg_const_i32(opreg));
gen_set_label(l1);
}
break;
default:
goto unknown_op;
}
}
break;
/************************/
/* string ops */
case 0xa4: /* movsS */
case 0xa5:
ot = mo_b_d(b, dflag);
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) {
gen_repz_movs(s, ot, pc_start - s->cs_base, s->pc - s->cs_base);
} else {
gen_movs(s, ot);
}
break;
case 0xaa: /* stosS */
case 0xab:
ot = mo_b_d(b, dflag);
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) {
gen_repz_stos(s, ot, pc_start - s->cs_base, s->pc - s->cs_base);
} else {
gen_stos(s, ot);
}
break;
case 0xac: /* lodsS */
case 0xad:
ot = mo_b_d(b, dflag);
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) {
gen_repz_lods(s, ot, pc_start - s->cs_base, s->pc - s->cs_base);
} else {
gen_lods(s, ot);
}
break;
case 0xae: /* scasS */
case 0xaf:
ot = mo_b_d(b, dflag);
if (prefixes & PREFIX_REPNZ) {
gen_repz_scas(s, ot, pc_start - s->cs_base, s->pc - s->cs_base, 1);
} else if (prefixes & PREFIX_REPZ) {
gen_repz_scas(s, ot, pc_start - s->cs_base, s->pc - s->cs_base, 0);
} else {
gen_scas(s, ot);
}
break;
case 0xa6: /* cmpsS */
case 0xa7:
ot = mo_b_d(b, dflag);
if (prefixes & PREFIX_REPNZ) {
gen_repz_cmps(s, ot, pc_start - s->cs_base, s->pc - s->cs_base, 1);
} else if (prefixes & PREFIX_REPZ) {
gen_repz_cmps(s, ot, pc_start - s->cs_base, s->pc - s->cs_base, 0);
} else {
gen_cmps(s, ot);
}
break;
case 0x6c: /* insS */
case 0x6d:
ot = mo_b_d32(b, dflag);
tcg_gen_ext16u_tl(cpu_T0, cpu_regs[R_EDX]);
gen_check_io(s, ot, pc_start - s->cs_base,
SVM_IOIO_TYPE_MASK | svm_is_rep(prefixes) | 4);
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) {
gen_repz_ins(s, ot, pc_start - s->cs_base, s->pc - s->cs_base);
} else {
gen_ins(s, ot);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_jmp(s, s->pc - s->cs_base);
}
}
break;
case 0x6e: /* outsS */
case 0x6f:
ot = mo_b_d32(b, dflag);
tcg_gen_ext16u_tl(cpu_T0, cpu_regs[R_EDX]);
gen_check_io(s, ot, pc_start - s->cs_base,
svm_is_rep(prefixes) | 4);
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) {
gen_repz_outs(s, ot, pc_start - s->cs_base, s->pc - s->cs_base);
} else {
gen_outs(s, ot);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_jmp(s, s->pc - s->cs_base);
}
}
break;
/************************/
/* port I/O */
case 0xe4:
case 0xe5:
ot = mo_b_d32(b, dflag);
val = cpu_ldub_code(env, s->pc++);
tcg_gen_movi_tl(cpu_T0, val);
gen_check_io(s, ot, pc_start - s->cs_base,
SVM_IOIO_TYPE_MASK | svm_is_rep(prefixes));
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_start();
}
tcg_gen_movi_i32(cpu_tmp2_i32, val);
gen_helper_in_func(ot, cpu_T1, cpu_tmp2_i32);
gen_op_mov_reg_v(ot, R_EAX, cpu_T1);
gen_bpt_io(s, cpu_tmp2_i32, ot);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
case 0xe6:
case 0xe7:
ot = mo_b_d32(b, dflag);
val = cpu_ldub_code(env, s->pc++);
tcg_gen_movi_tl(cpu_T0, val);
gen_check_io(s, ot, pc_start - s->cs_base,
svm_is_rep(prefixes));
gen_op_mov_v_reg(ot, cpu_T1, R_EAX);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_start();
}
tcg_gen_movi_i32(cpu_tmp2_i32, val);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T1);
gen_helper_out_func(ot, cpu_tmp2_i32, cpu_tmp3_i32);
gen_bpt_io(s, cpu_tmp2_i32, ot);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
case 0xec:
case 0xed:
ot = mo_b_d32(b, dflag);
tcg_gen_ext16u_tl(cpu_T0, cpu_regs[R_EDX]);
gen_check_io(s, ot, pc_start - s->cs_base,
SVM_IOIO_TYPE_MASK | svm_is_rep(prefixes));
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_start();
}
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_in_func(ot, cpu_T1, cpu_tmp2_i32);
gen_op_mov_reg_v(ot, R_EAX, cpu_T1);
gen_bpt_io(s, cpu_tmp2_i32, ot);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
case 0xee:
case 0xef:
ot = mo_b_d32(b, dflag);
tcg_gen_ext16u_tl(cpu_T0, cpu_regs[R_EDX]);
gen_check_io(s, ot, pc_start - s->cs_base,
svm_is_rep(prefixes));
gen_op_mov_v_reg(ot, cpu_T1, R_EAX);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_start();
}
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T1);
gen_helper_out_func(ot, cpu_tmp2_i32, cpu_tmp3_i32);
gen_bpt_io(s, cpu_tmp2_i32, ot);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
/************************/
/* control */
case 0xc2: /* ret im */
val = cpu_ldsw_code(env, s->pc);
s->pc += 2;
ot = gen_pop_T0(s);
gen_stack_update(s, val + (1 << ot));
/* Note that gen_pop_T0 uses a zero-extending load. */
gen_op_jmp_v(cpu_T0);
gen_bnd_jmp(s);
gen_eob(s);
break;
case 0xc3: /* ret */
ot = gen_pop_T0(s);
gen_pop_update(s, ot);
/* Note that gen_pop_T0 uses a zero-extending load. */
gen_op_jmp_v(cpu_T0);
gen_bnd_jmp(s);
gen_eob(s);
break;
case 0xca: /* lret im */
val = cpu_ldsw_code(env, s->pc);
s->pc += 2;
do_lret:
if (s->pe && !s->vm86) {
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_lret_protected(cpu_env, tcg_const_i32(dflag - 1),
tcg_const_i32(val));
} else {
gen_stack_A0(s);
/* pop offset */
gen_op_ld_v(s, dflag, cpu_T0, cpu_A0);
/* NOTE: keeping EIP updated is not a problem in case of
exception */
gen_op_jmp_v(cpu_T0);
/* pop selector */
gen_add_A0_im(s, 1 << dflag);
gen_op_ld_v(s, dflag, cpu_T0, cpu_A0);
gen_op_movl_seg_T0_vm(R_CS);
/* add stack offset */
gen_stack_update(s, val + (2 << dflag));
}
gen_eob(s);
break;
case 0xcb: /* lret */
val = 0;
goto do_lret;
case 0xcf: /* iret */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_IRET);
if (!s->pe) {
/* real mode */
gen_helper_iret_real(cpu_env, tcg_const_i32(dflag - 1));
set_cc_op(s, CC_OP_EFLAGS);
} else if (s->vm86) {
if (s->iopl != 3) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_helper_iret_real(cpu_env, tcg_const_i32(dflag - 1));
set_cc_op(s, CC_OP_EFLAGS);
}
} else {
gen_helper_iret_protected(cpu_env, tcg_const_i32(dflag - 1),
tcg_const_i32(s->pc - s->cs_base));
set_cc_op(s, CC_OP_EFLAGS);
}
gen_eob(s);
break;
case 0xe8: /* call im */
{
if (dflag != MO_16) {
tval = (int32_t)insn_get(env, s, MO_32);
} else {
tval = (int16_t)insn_get(env, s, MO_16);
}
next_eip = s->pc - s->cs_base;
tval += next_eip;
if (dflag == MO_16) {
tval &= 0xffff;
} else if (!CODE64(s)) {
tval &= 0xffffffff;
}
tcg_gen_movi_tl(cpu_T0, next_eip);
gen_push_v(s, cpu_T0);
gen_bnd_jmp(s);
gen_jmp(s, tval);
}
break;
case 0x9a: /* lcall im */
{
unsigned int selector, offset;
if (CODE64(s))
goto illegal_op;
ot = dflag;
offset = insn_get(env, s, ot);
selector = insn_get(env, s, MO_16);
tcg_gen_movi_tl(cpu_T0, selector);
tcg_gen_movi_tl(cpu_T1, offset);
}
goto do_lcall;
case 0xe9: /* jmp im */
if (dflag != MO_16) {
tval = (int32_t)insn_get(env, s, MO_32);
} else {
tval = (int16_t)insn_get(env, s, MO_16);
}
tval += s->pc - s->cs_base;
if (dflag == MO_16) {
tval &= 0xffff;
} else if (!CODE64(s)) {
tval &= 0xffffffff;
}
gen_bnd_jmp(s);
gen_jmp(s, tval);
break;
case 0xea: /* ljmp im */
{
unsigned int selector, offset;
if (CODE64(s))
goto illegal_op;
ot = dflag;
offset = insn_get(env, s, ot);
selector = insn_get(env, s, MO_16);
tcg_gen_movi_tl(cpu_T0, selector);
tcg_gen_movi_tl(cpu_T1, offset);
}
goto do_ljmp;
case 0xeb: /* jmp Jb */
tval = (int8_t)insn_get(env, s, MO_8);
tval += s->pc - s->cs_base;
if (dflag == MO_16) {
tval &= 0xffff;
}
gen_jmp(s, tval);
break;
case 0x70 ... 0x7f: /* jcc Jb */
tval = (int8_t)insn_get(env, s, MO_8);
goto do_jcc;
case 0x180 ... 0x18f: /* jcc Jv */
if (dflag != MO_16) {
tval = (int32_t)insn_get(env, s, MO_32);
} else {
tval = (int16_t)insn_get(env, s, MO_16);
}
do_jcc:
next_eip = s->pc - s->cs_base;
tval += next_eip;
if (dflag == MO_16) {
tval &= 0xffff;
}
gen_bnd_jmp(s);
gen_jcc(s, b, tval, next_eip);
break;
case 0x190 ... 0x19f: /* setcc Gv */
modrm = cpu_ldub_code(env, s->pc++);
gen_setcc1(s, b, cpu_T0);
gen_ldst_modrm(env, s, modrm, MO_8, OR_TMP0, 1);
break;
case 0x140 ... 0x14f: /* cmov Gv, Ev */
if (!(s->cpuid_features & CPUID_CMOV)) {
goto illegal_op;
}
ot = dflag;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
gen_cmovcc1(env, s, ot, b, modrm, reg);
break;
/************************/
/* flags */
case 0x9c: /* pushf */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_PUSHF);
if (s->vm86 && s->iopl != 3) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_update_cc_op(s);
gen_helper_read_eflags(cpu_T0, cpu_env);
gen_push_v(s, cpu_T0);
}
break;
case 0x9d: /* popf */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_POPF);
if (s->vm86 && s->iopl != 3) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
ot = gen_pop_T0(s);
if (s->cpl == 0) {
if (dflag != MO_16) {
gen_helper_write_eflags(cpu_env, cpu_T0,
tcg_const_i32((TF_MASK | AC_MASK |
ID_MASK | NT_MASK |
IF_MASK |
IOPL_MASK)));
} else {
gen_helper_write_eflags(cpu_env, cpu_T0,
tcg_const_i32((TF_MASK | AC_MASK |
ID_MASK | NT_MASK |
IF_MASK | IOPL_MASK)
& 0xffff));
}
} else {
if (s->cpl <= s->iopl) {
if (dflag != MO_16) {
gen_helper_write_eflags(cpu_env, cpu_T0,
tcg_const_i32((TF_MASK |
AC_MASK |
ID_MASK |
NT_MASK |
IF_MASK)));
} else {
gen_helper_write_eflags(cpu_env, cpu_T0,
tcg_const_i32((TF_MASK |
AC_MASK |
ID_MASK |
NT_MASK |
IF_MASK)
& 0xffff));
}
} else {
if (dflag != MO_16) {
gen_helper_write_eflags(cpu_env, cpu_T0,
tcg_const_i32((TF_MASK | AC_MASK |
ID_MASK | NT_MASK)));
} else {
gen_helper_write_eflags(cpu_env, cpu_T0,
tcg_const_i32((TF_MASK | AC_MASK |
ID_MASK | NT_MASK)
& 0xffff));
}
}
}
gen_pop_update(s, ot);
set_cc_op(s, CC_OP_EFLAGS);
/* abort translation because TF/AC flag may change */
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
}
break;
case 0x9e: /* sahf */
if (CODE64(s) && !(s->cpuid_ext3_features & CPUID_EXT3_LAHF_LM))
goto illegal_op;
gen_op_mov_v_reg(MO_8, cpu_T0, R_AH);
gen_compute_eflags(s);
tcg_gen_andi_tl(cpu_cc_src, cpu_cc_src, CC_O);
tcg_gen_andi_tl(cpu_T0, cpu_T0, CC_S | CC_Z | CC_A | CC_P | CC_C);
tcg_gen_or_tl(cpu_cc_src, cpu_cc_src, cpu_T0);
break;
case 0x9f: /* lahf */
if (CODE64(s) && !(s->cpuid_ext3_features & CPUID_EXT3_LAHF_LM))
goto illegal_op;
gen_compute_eflags(s);
/* Note: gen_compute_eflags() only gives the condition codes */
tcg_gen_ori_tl(cpu_T0, cpu_cc_src, 0x02);
gen_op_mov_reg_v(MO_8, R_AH, cpu_T0);
break;
case 0xf5: /* cmc */
gen_compute_eflags(s);
tcg_gen_xori_tl(cpu_cc_src, cpu_cc_src, CC_C);
break;
case 0xf8: /* clc */
gen_compute_eflags(s);
tcg_gen_andi_tl(cpu_cc_src, cpu_cc_src, ~CC_C);
break;
case 0xf9: /* stc */
gen_compute_eflags(s);
tcg_gen_ori_tl(cpu_cc_src, cpu_cc_src, CC_C);
break;
case 0xfc: /* cld */
tcg_gen_movi_i32(cpu_tmp2_i32, 1);
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, offsetof(CPUX86State, df));
break;
case 0xfd: /* std */
tcg_gen_movi_i32(cpu_tmp2_i32, -1);
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, offsetof(CPUX86State, df));
break;
/************************/
/* bit operations */
case 0x1ba: /* bt/bts/btr/btc Gv, im */
ot = dflag;
modrm = cpu_ldub_code(env, s->pc++);
op = (modrm >> 3) & 7;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
if (mod != 3) {
s->rip_offset = 1;
gen_lea_modrm(env, s, modrm);
if (!(s->prefix & PREFIX_LOCK)) {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
}
} else {
gen_op_mov_v_reg(ot, cpu_T0, rm);
}
/* load shift */
val = cpu_ldub_code(env, s->pc++);
tcg_gen_movi_tl(cpu_T1, val);
if (op < 4)
goto unknown_op;
op -= 4;
goto bt_op;
case 0x1a3: /* bt Gv, Ev */
op = 0;
goto do_btx;
case 0x1ab: /* bts */
op = 1;
goto do_btx;
case 0x1b3: /* btr */
op = 2;
goto do_btx;
case 0x1bb: /* btc */
op = 3;
do_btx:
ot = dflag;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
gen_op_mov_v_reg(MO_32, cpu_T1, reg);
if (mod != 3) {
AddressParts a = gen_lea_modrm_0(env, s, modrm);
/* specific case: we need to add a displacement */
gen_exts(ot, cpu_T1);
tcg_gen_sari_tl(cpu_tmp0, cpu_T1, 3 + ot);
tcg_gen_shli_tl(cpu_tmp0, cpu_tmp0, ot);
tcg_gen_add_tl(cpu_A0, gen_lea_modrm_1(a), cpu_tmp0);
gen_lea_v_seg(s, s->aflag, cpu_A0, a.def_seg, s->override);
if (!(s->prefix & PREFIX_LOCK)) {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
}
} else {
gen_op_mov_v_reg(ot, cpu_T0, rm);
}
bt_op:
tcg_gen_andi_tl(cpu_T1, cpu_T1, (1 << (3 + ot)) - 1);
tcg_gen_movi_tl(cpu_tmp0, 1);
tcg_gen_shl_tl(cpu_tmp0, cpu_tmp0, cpu_T1);
if (s->prefix & PREFIX_LOCK) {
switch (op) {
case 0: /* bt */
/* Needs no atomic ops; we surpressed the normal
memory load for LOCK above so do it now. */
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
break;
case 1: /* bts */
tcg_gen_atomic_fetch_or_tl(cpu_T0, cpu_A0, cpu_tmp0,
s->mem_index, ot | MO_LE);
break;
case 2: /* btr */
tcg_gen_not_tl(cpu_tmp0, cpu_tmp0);
tcg_gen_atomic_fetch_and_tl(cpu_T0, cpu_A0, cpu_tmp0,
s->mem_index, ot | MO_LE);
break;
default:
case 3: /* btc */
tcg_gen_atomic_fetch_xor_tl(cpu_T0, cpu_A0, cpu_tmp0,
s->mem_index, ot | MO_LE);
break;
}
tcg_gen_shr_tl(cpu_tmp4, cpu_T0, cpu_T1);
} else {
tcg_gen_shr_tl(cpu_tmp4, cpu_T0, cpu_T1);
switch (op) {
case 0: /* bt */
/* Data already loaded; nothing to do. */
break;
case 1: /* bts */
tcg_gen_or_tl(cpu_T0, cpu_T0, cpu_tmp0);
break;
case 2: /* btr */
tcg_gen_andc_tl(cpu_T0, cpu_T0, cpu_tmp0);
break;
default:
case 3: /* btc */
tcg_gen_xor_tl(cpu_T0, cpu_T0, cpu_tmp0);
break;
}
if (op != 0) {
if (mod != 3) {
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_reg_v(ot, rm, cpu_T0);
}
}
}
/* Delay all CC updates until after the store above. Note that
C is the result of the test, Z is unchanged, and the others
are all undefined. */
switch (s->cc_op) {
case CC_OP_MULB ... CC_OP_MULQ:
case CC_OP_ADDB ... CC_OP_ADDQ:
case CC_OP_ADCB ... CC_OP_ADCQ:
case CC_OP_SUBB ... CC_OP_SUBQ:
case CC_OP_SBBB ... CC_OP_SBBQ:
case CC_OP_LOGICB ... CC_OP_LOGICQ:
case CC_OP_INCB ... CC_OP_INCQ:
case CC_OP_DECB ... CC_OP_DECQ:
case CC_OP_SHLB ... CC_OP_SHLQ:
case CC_OP_SARB ... CC_OP_SARQ:
case CC_OP_BMILGB ... CC_OP_BMILGQ:
/* Z was going to be computed from the non-zero status of CC_DST.
We can get that same Z value (and the new C value) by leaving
CC_DST alone, setting CC_SRC, and using a CC_OP_SAR of the
same width. */
tcg_gen_mov_tl(cpu_cc_src, cpu_tmp4);
set_cc_op(s, ((s->cc_op - CC_OP_MULB) & 3) + CC_OP_SARB);
break;
default:
/* Otherwise, generate EFLAGS and replace the C bit. */
gen_compute_eflags(s);
tcg_gen_deposit_tl(cpu_cc_src, cpu_cc_src, cpu_tmp4,
ctz32(CC_C), 1);
break;
}
break;
case 0x1bc: /* bsf / tzcnt */
case 0x1bd: /* bsr / lzcnt */
ot = dflag;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
gen_extu(ot, cpu_T0);
/* Note that lzcnt and tzcnt are in different extensions. */
if ((prefixes & PREFIX_REPZ)
&& (b & 1
? s->cpuid_ext3_features & CPUID_EXT3_ABM
: s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI1)) {
int size = 8 << ot;
/* For lzcnt/tzcnt, C bit is defined related to the input. */
tcg_gen_mov_tl(cpu_cc_src, cpu_T0);
if (b & 1) {
/* For lzcnt, reduce the target_ulong result by the
number of zeros that we expect to find at the top. */
tcg_gen_clzi_tl(cpu_T0, cpu_T0, TARGET_LONG_BITS);
tcg_gen_subi_tl(cpu_T0, cpu_T0, TARGET_LONG_BITS - size);
} else {
/* For tzcnt, a zero input must return the operand size. */
tcg_gen_ctzi_tl(cpu_T0, cpu_T0, size);
}
/* For lzcnt/tzcnt, Z bit is defined related to the result. */
gen_op_update1_cc();
set_cc_op(s, CC_OP_BMILGB + ot);
} else {
/* For bsr/bsf, only the Z bit is defined and it is related
to the input and not the result. */
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
set_cc_op(s, CC_OP_LOGICB + ot);
/* ??? The manual says that the output is undefined when the
input is zero, but real hardware leaves it unchanged, and
real programs appear to depend on that. Accomplish this
by passing the output as the value to return upon zero. */
if (b & 1) {
/* For bsr, return the bit index of the first 1 bit,
not the count of leading zeros. */
tcg_gen_xori_tl(cpu_T1, cpu_regs[reg], TARGET_LONG_BITS - 1);
tcg_gen_clz_tl(cpu_T0, cpu_T0, cpu_T1);
tcg_gen_xori_tl(cpu_T0, cpu_T0, TARGET_LONG_BITS - 1);
} else {
tcg_gen_ctz_tl(cpu_T0, cpu_T0, cpu_regs[reg]);
}
}
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
/************************/
/* bcd */
case 0x27: /* daa */
if (CODE64(s))
goto illegal_op;
gen_update_cc_op(s);
gen_helper_daa(cpu_env);
set_cc_op(s, CC_OP_EFLAGS);
break;
case 0x2f: /* das */
if (CODE64(s))
goto illegal_op;
gen_update_cc_op(s);
gen_helper_das(cpu_env);
set_cc_op(s, CC_OP_EFLAGS);
break;
case 0x37: /* aaa */
if (CODE64(s))
goto illegal_op;
gen_update_cc_op(s);
gen_helper_aaa(cpu_env);
set_cc_op(s, CC_OP_EFLAGS);
break;
case 0x3f: /* aas */
if (CODE64(s))
goto illegal_op;
gen_update_cc_op(s);
gen_helper_aas(cpu_env);
set_cc_op(s, CC_OP_EFLAGS);
break;
case 0xd4: /* aam */
if (CODE64(s))
goto illegal_op;
val = cpu_ldub_code(env, s->pc++);
if (val == 0) {
gen_exception(s, EXCP00_DIVZ, pc_start - s->cs_base);
} else {
gen_helper_aam(cpu_env, tcg_const_i32(val));
set_cc_op(s, CC_OP_LOGICB);
}
break;
case 0xd5: /* aad */
if (CODE64(s))
goto illegal_op;
val = cpu_ldub_code(env, s->pc++);
gen_helper_aad(cpu_env, tcg_const_i32(val));
set_cc_op(s, CC_OP_LOGICB);
break;
/************************/
/* misc */
case 0x90: /* nop */
/* XXX: correct lock test for all insn */
if (prefixes & PREFIX_LOCK) {
goto illegal_op;
}
/* If REX_B is set, then this is xchg eax, r8d, not a nop. */
if (REX_B(s)) {
goto do_xchg_reg_eax;
}
if (prefixes & PREFIX_REPZ) {
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_pause(cpu_env, tcg_const_i32(s->pc - pc_start));
s->is_jmp = DISAS_TB_JUMP;
}
break;
case 0x9b: /* fwait */
if ((s->flags & (HF_MP_MASK | HF_TS_MASK)) ==
(HF_MP_MASK | HF_TS_MASK)) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
} else {
gen_helper_fwait(cpu_env);
}
break;
case 0xcc: /* int3 */
gen_interrupt(s, EXCP03_INT3, pc_start - s->cs_base, s->pc - s->cs_base);
break;
case 0xcd: /* int N */
val = cpu_ldub_code(env, s->pc++);
if (s->vm86 && s->iopl != 3) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_interrupt(s, val, pc_start - s->cs_base, s->pc - s->cs_base);
}
break;
case 0xce: /* into */
if (CODE64(s))
goto illegal_op;
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_into(cpu_env, tcg_const_i32(s->pc - pc_start));
break;
#ifdef WANT_ICEBP
case 0xf1: /* icebp (undocumented, exits to external debugger) */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_ICEBP);
#if 1
gen_debug(s, pc_start - s->cs_base);
#else
/* start debug */
tb_flush(CPU(x86_env_get_cpu(env)));
qemu_set_log(CPU_LOG_INT | CPU_LOG_TB_IN_ASM);
#endif
break;
#endif
case 0xfa: /* cli */
if (!s->vm86) {
if (s->cpl <= s->iopl) {
gen_helper_cli(cpu_env);
} else {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
}
} else {
if (s->iopl == 3) {
gen_helper_cli(cpu_env);
} else {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
}
}
break;
case 0xfb: /* sti */
if (s->vm86 ? s->iopl == 3 : s->cpl <= s->iopl) {
gen_helper_sti(cpu_env);
/* interruptions are enabled only the first insn after sti */
gen_jmp_im(s->pc - s->cs_base);
gen_eob_inhibit_irq(s, true);
} else {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
}
break;
case 0x62: /* bound */
if (CODE64(s))
goto illegal_op;
ot = dflag;
modrm = cpu_ldub_code(env, s->pc++);
reg = (modrm >> 3) & 7;
mod = (modrm >> 6) & 3;
if (mod == 3)
goto illegal_op;
gen_op_mov_v_reg(ot, cpu_T0, reg);
gen_lea_modrm(env, s, modrm);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
if (ot == MO_16) {
gen_helper_boundw(cpu_env, cpu_A0, cpu_tmp2_i32);
} else {
gen_helper_boundl(cpu_env, cpu_A0, cpu_tmp2_i32);
}
break;
case 0x1c8 ... 0x1cf: /* bswap reg */
reg = (b & 7) | REX_B(s);
#ifdef TARGET_X86_64
if (dflag == MO_64) {
gen_op_mov_v_reg(MO_64, cpu_T0, reg);
tcg_gen_bswap64_i64(cpu_T0, cpu_T0);
gen_op_mov_reg_v(MO_64, reg, cpu_T0);
} else
#endif
{
gen_op_mov_v_reg(MO_32, cpu_T0, reg);
tcg_gen_ext32u_tl(cpu_T0, cpu_T0);
tcg_gen_bswap32_tl(cpu_T0, cpu_T0);
gen_op_mov_reg_v(MO_32, reg, cpu_T0);
}
break;
case 0xd6: /* salc */
if (CODE64(s))
goto illegal_op;
gen_compute_eflags_c(s, cpu_T0);
tcg_gen_neg_tl(cpu_T0, cpu_T0);
gen_op_mov_reg_v(MO_8, R_EAX, cpu_T0);
break;
case 0xe0: /* loopnz */
case 0xe1: /* loopz */
case 0xe2: /* loop */
case 0xe3: /* jecxz */
{
TCGLabel *l1, *l2, *l3;
tval = (int8_t)insn_get(env, s, MO_8);
next_eip = s->pc - s->cs_base;
tval += next_eip;
if (dflag == MO_16) {
tval &= 0xffff;
}
l1 = gen_new_label();
l2 = gen_new_label();
l3 = gen_new_label();
b &= 3;
switch(b) {
case 0: /* loopnz */
case 1: /* loopz */
gen_op_add_reg_im(s->aflag, R_ECX, -1);
gen_op_jz_ecx(s->aflag, l3);
gen_jcc1(s, (JCC_Z << 1) | (b ^ 1), l1);
break;
case 2: /* loop */
gen_op_add_reg_im(s->aflag, R_ECX, -1);
gen_op_jnz_ecx(s->aflag, l1);
break;
default:
case 3: /* jcxz */
gen_op_jz_ecx(s->aflag, l1);
break;
}
gen_set_label(l3);
gen_jmp_im(next_eip);
tcg_gen_br(l2);
gen_set_label(l1);
gen_jmp_im(tval);
gen_set_label(l2);
gen_eob(s);
}
break;
case 0x130: /* wrmsr */
case 0x132: /* rdmsr */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
if (b & 2) {
gen_helper_rdmsr(cpu_env);
} else {
gen_helper_wrmsr(cpu_env);
}
}
break;
case 0x131: /* rdtsc */
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_start();
}
gen_helper_rdtsc(cpu_env);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
case 0x133: /* rdpmc */
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_rdpmc(cpu_env);
break;
case 0x134: /* sysenter */
/* For Intel SYSENTER is valid on 64-bit */
if (CODE64(s) && env->cpuid_vendor1 != CPUID_VENDOR_INTEL_1)
goto illegal_op;
if (!s->pe) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_helper_sysenter(cpu_env);
gen_eob(s);
}
break;
case 0x135: /* sysexit */
/* For Intel SYSEXIT is valid on 64-bit */
if (CODE64(s) && env->cpuid_vendor1 != CPUID_VENDOR_INTEL_1)
goto illegal_op;
if (!s->pe) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_helper_sysexit(cpu_env, tcg_const_i32(dflag - 1));
gen_eob(s);
}
break;
#ifdef TARGET_X86_64
case 0x105: /* syscall */
/* XXX: is it usable in real mode ? */
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_syscall(cpu_env, tcg_const_i32(s->pc - pc_start));
/* TF handling for the syscall insn is different. The TF bit is checked
after the syscall insn completes. This allows #DB to not be
generated after one has entered CPL0 if TF is set in FMASK. */
gen_eob_worker(s, false, true);
break;
case 0x107: /* sysret */
if (!s->pe) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_helper_sysret(cpu_env, tcg_const_i32(dflag - 1));
/* condition codes are modified only in long mode */
if (s->lma) {
set_cc_op(s, CC_OP_EFLAGS);
}
/* TF handling for the sysret insn is different. The TF bit is
checked after the sysret insn completes. This allows #DB to be
generated "as if" the syscall insn in userspace has just
completed. */
gen_eob_worker(s, false, true);
}
break;
#endif
case 0x1a2: /* cpuid */
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_cpuid(cpu_env);
break;
case 0xf4: /* hlt */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_hlt(cpu_env, tcg_const_i32(s->pc - pc_start));
s->is_jmp = DISAS_TB_JUMP;
}
break;
case 0x100:
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
op = (modrm >> 3) & 7;
switch(op) {
case 0: /* sldt */
if (!s->pe || s->vm86)
goto illegal_op;
gen_svm_check_intercept(s, pc_start, SVM_EXIT_LDTR_READ);
tcg_gen_ld32u_tl(cpu_T0, cpu_env,
offsetof(CPUX86State, ldt.selector));
ot = mod == 3 ? dflag : MO_16;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 1);
break;
case 2: /* lldt */
if (!s->pe || s->vm86)
goto illegal_op;
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_LDTR_WRITE);
gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_lldt(cpu_env, cpu_tmp2_i32);
}
break;
case 1: /* str */
if (!s->pe || s->vm86)
goto illegal_op;
gen_svm_check_intercept(s, pc_start, SVM_EXIT_TR_READ);
tcg_gen_ld32u_tl(cpu_T0, cpu_env,
offsetof(CPUX86State, tr.selector));
ot = mod == 3 ? dflag : MO_16;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 1);
break;
case 3: /* ltr */
if (!s->pe || s->vm86)
goto illegal_op;
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_TR_WRITE);
gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_ltr(cpu_env, cpu_tmp2_i32);
}
break;
case 4: /* verr */
case 5: /* verw */
if (!s->pe || s->vm86)
goto illegal_op;
gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0);
gen_update_cc_op(s);
if (op == 4) {
gen_helper_verr(cpu_env, cpu_T0);
} else {
gen_helper_verw(cpu_env, cpu_T0);
}
set_cc_op(s, CC_OP_EFLAGS);
break;
default:
goto unknown_op;
}
break;
case 0x101:
modrm = cpu_ldub_code(env, s->pc++);
switch (modrm) {
CASE_MODRM_MEM_OP(0): /* sgdt */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_GDTR_READ);
gen_lea_modrm(env, s, modrm);
tcg_gen_ld32u_tl(cpu_T0,
cpu_env, offsetof(CPUX86State, gdt.limit));
gen_op_st_v(s, MO_16, cpu_T0, cpu_A0);
gen_add_A0_im(s, 2);
tcg_gen_ld_tl(cpu_T0, cpu_env, offsetof(CPUX86State, gdt.base));
if (dflag == MO_16) {
tcg_gen_andi_tl(cpu_T0, cpu_T0, 0xffffff);
}
gen_op_st_v(s, CODE64(s) + MO_32, cpu_T0, cpu_A0);
break;
case 0xc8: /* monitor */
if (!(s->cpuid_ext_features & CPUID_EXT_MONITOR) || s->cpl != 0) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
tcg_gen_mov_tl(cpu_A0, cpu_regs[R_EAX]);
gen_extu(s->aflag, cpu_A0);
gen_add_A0_ds_seg(s);
gen_helper_monitor(cpu_env, cpu_A0);
break;
case 0xc9: /* mwait */
if (!(s->cpuid_ext_features & CPUID_EXT_MONITOR) || s->cpl != 0) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_mwait(cpu_env, tcg_const_i32(s->pc - pc_start));
gen_eob(s);
break;
case 0xca: /* clac */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_SMAP)
|| s->cpl != 0) {
goto illegal_op;
}
gen_helper_clac(cpu_env);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
break;
case 0xcb: /* stac */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_SMAP)
|| s->cpl != 0) {
goto illegal_op;
}
gen_helper_stac(cpu_env);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
break;
CASE_MODRM_MEM_OP(1): /* sidt */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_IDTR_READ);
gen_lea_modrm(env, s, modrm);
tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State, idt.limit));
gen_op_st_v(s, MO_16, cpu_T0, cpu_A0);
gen_add_A0_im(s, 2);
tcg_gen_ld_tl(cpu_T0, cpu_env, offsetof(CPUX86State, idt.base));
if (dflag == MO_16) {
tcg_gen_andi_tl(cpu_T0, cpu_T0, 0xffffff);
}
gen_op_st_v(s, CODE64(s) + MO_32, cpu_T0, cpu_A0);
break;
case 0xd0: /* xgetbv */
if ((s->cpuid_ext_features & CPUID_EXT_XSAVE) == 0
|| (s->prefix & (PREFIX_LOCK | PREFIX_DATA
| PREFIX_REPZ | PREFIX_REPNZ))) {
goto illegal_op;
}
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_ECX]);
gen_helper_xgetbv(cpu_tmp1_i64, cpu_env, cpu_tmp2_i32);
tcg_gen_extr_i64_tl(cpu_regs[R_EAX], cpu_regs[R_EDX], cpu_tmp1_i64);
break;
case 0xd1: /* xsetbv */
if ((s->cpuid_ext_features & CPUID_EXT_XSAVE) == 0
|| (s->prefix & (PREFIX_LOCK | PREFIX_DATA
| PREFIX_REPZ | PREFIX_REPNZ))) {
goto illegal_op;
}
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
tcg_gen_concat_tl_i64(cpu_tmp1_i64, cpu_regs[R_EAX],
cpu_regs[R_EDX]);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_ECX]);
gen_helper_xsetbv(cpu_env, cpu_tmp2_i32, cpu_tmp1_i64);
/* End TB because translation flags may change. */
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
break;
case 0xd8: /* VMRUN */
if (!(s->flags & HF_SVME_MASK) || !s->pe) {
goto illegal_op;
}
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_vmrun(cpu_env, tcg_const_i32(s->aflag - 1),
tcg_const_i32(s->pc - pc_start));
tcg_gen_exit_tb(0);
s->is_jmp = DISAS_TB_JUMP;
break;
case 0xd9: /* VMMCALL */
if (!(s->flags & HF_SVME_MASK)) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_vmmcall(cpu_env);
break;
case 0xda: /* VMLOAD */
if (!(s->flags & HF_SVME_MASK) || !s->pe) {
goto illegal_op;
}
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_vmload(cpu_env, tcg_const_i32(s->aflag - 1));
break;
case 0xdb: /* VMSAVE */
if (!(s->flags & HF_SVME_MASK) || !s->pe) {
goto illegal_op;
}
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_vmsave(cpu_env, tcg_const_i32(s->aflag - 1));
break;
case 0xdc: /* STGI */
if ((!(s->flags & HF_SVME_MASK)
&& !(s->cpuid_ext3_features & CPUID_EXT3_SKINIT))
|| !s->pe) {
goto illegal_op;
}
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_stgi(cpu_env);
break;
case 0xdd: /* CLGI */
if (!(s->flags & HF_SVME_MASK) || !s->pe) {
goto illegal_op;
}
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_clgi(cpu_env);
break;
case 0xde: /* SKINIT */
if ((!(s->flags & HF_SVME_MASK)
&& !(s->cpuid_ext3_features & CPUID_EXT3_SKINIT))
|| !s->pe) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_skinit(cpu_env);
break;
case 0xdf: /* INVLPGA */
if (!(s->flags & HF_SVME_MASK) || !s->pe) {
goto illegal_op;
}
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_invlpga(cpu_env, tcg_const_i32(s->aflag - 1));
break;
CASE_MODRM_MEM_OP(2): /* lgdt */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_svm_check_intercept(s, pc_start, SVM_EXIT_GDTR_WRITE);
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, MO_16, cpu_T1, cpu_A0);
gen_add_A0_im(s, 2);
gen_op_ld_v(s, CODE64(s) + MO_32, cpu_T0, cpu_A0);
if (dflag == MO_16) {
tcg_gen_andi_tl(cpu_T0, cpu_T0, 0xffffff);
}
tcg_gen_st_tl(cpu_T0, cpu_env, offsetof(CPUX86State, gdt.base));
tcg_gen_st32_tl(cpu_T1, cpu_env, offsetof(CPUX86State, gdt.limit));
break;
CASE_MODRM_MEM_OP(3): /* lidt */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_svm_check_intercept(s, pc_start, SVM_EXIT_IDTR_WRITE);
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, MO_16, cpu_T1, cpu_A0);
gen_add_A0_im(s, 2);
gen_op_ld_v(s, CODE64(s) + MO_32, cpu_T0, cpu_A0);
if (dflag == MO_16) {
tcg_gen_andi_tl(cpu_T0, cpu_T0, 0xffffff);
}
tcg_gen_st_tl(cpu_T0, cpu_env, offsetof(CPUX86State, idt.base));
tcg_gen_st32_tl(cpu_T1, cpu_env, offsetof(CPUX86State, idt.limit));
break;
CASE_MODRM_OP(4): /* smsw */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_READ_CR0);
tcg_gen_ld_tl(cpu_T0, cpu_env, offsetof(CPUX86State, cr[0]));
if (CODE64(s)) {
mod = (modrm >> 6) & 3;
ot = (mod != 3 ? MO_16 : s->dflag);
} else {
ot = MO_16;
}
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 1);
break;
case 0xee: /* rdpkru */
if (prefixes & PREFIX_LOCK) {
goto illegal_op;
}
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_ECX]);
gen_helper_rdpkru(cpu_tmp1_i64, cpu_env, cpu_tmp2_i32);
tcg_gen_extr_i64_tl(cpu_regs[R_EAX], cpu_regs[R_EDX], cpu_tmp1_i64);
break;
case 0xef: /* wrpkru */
if (prefixes & PREFIX_LOCK) {
goto illegal_op;
}
tcg_gen_concat_tl_i64(cpu_tmp1_i64, cpu_regs[R_EAX],
cpu_regs[R_EDX]);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_ECX]);
gen_helper_wrpkru(cpu_env, cpu_tmp2_i32, cpu_tmp1_i64);
break;
CASE_MODRM_OP(6): /* lmsw */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_svm_check_intercept(s, pc_start, SVM_EXIT_WRITE_CR0);
gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0);
gen_helper_lmsw(cpu_env, cpu_T0);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
break;
CASE_MODRM_MEM_OP(7): /* invlpg */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_lea_modrm(env, s, modrm);
gen_helper_invlpg(cpu_env, cpu_A0);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
break;
case 0xf8: /* swapgs */
#ifdef TARGET_X86_64
if (CODE64(s)) {
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
tcg_gen_mov_tl(cpu_T0, cpu_seg_base[R_GS]);
tcg_gen_ld_tl(cpu_seg_base[R_GS], cpu_env,
offsetof(CPUX86State, kernelgsbase));
tcg_gen_st_tl(cpu_T0, cpu_env,
offsetof(CPUX86State, kernelgsbase));
}
break;
}
#endif
goto illegal_op;
case 0xf9: /* rdtscp */
if (!(s->cpuid_ext2_features & CPUID_EXT2_RDTSCP)) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_start();
}
gen_helper_rdtscp(cpu_env);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
default:
goto unknown_op;
}
break;
case 0x108: /* invd */
case 0x109: /* wbinvd */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_svm_check_intercept(s, pc_start, (b & 2) ? SVM_EXIT_INVD : SVM_EXIT_WBINVD);
/* nothing to do */
}
break;
case 0x63: /* arpl or movslS (x86_64) */
#ifdef TARGET_X86_64
if (CODE64(s)) {
int d_ot;
/* d_ot is the size of destination */
d_ot = dflag;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
if (mod == 3) {
gen_op_mov_v_reg(MO_32, cpu_T0, rm);
/* sign extend */
if (d_ot == MO_64) {
tcg_gen_ext32s_tl(cpu_T0, cpu_T0);
}
gen_op_mov_reg_v(d_ot, reg, cpu_T0);
} else {
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, MO_32 | MO_SIGN, cpu_T0, cpu_A0);
gen_op_mov_reg_v(d_ot, reg, cpu_T0);
}
} else
#endif
{
TCGLabel *label1;
TCGv t0, t1, t2, a0;
if (!s->pe || s->vm86)
goto illegal_op;
t0 = tcg_temp_local_new();
t1 = tcg_temp_local_new();
t2 = tcg_temp_local_new();
ot = MO_16;
modrm = cpu_ldub_code(env, s->pc++);
reg = (modrm >> 3) & 7;
mod = (modrm >> 6) & 3;
rm = modrm & 7;
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, ot, t0, cpu_A0);
a0 = tcg_temp_local_new();
tcg_gen_mov_tl(a0, cpu_A0);
} else {
gen_op_mov_v_reg(ot, t0, rm);
TCGV_UNUSED(a0);
}
gen_op_mov_v_reg(ot, t1, reg);
tcg_gen_andi_tl(cpu_tmp0, t0, 3);
tcg_gen_andi_tl(t1, t1, 3);
tcg_gen_movi_tl(t2, 0);
label1 = gen_new_label();
tcg_gen_brcond_tl(TCG_COND_GE, cpu_tmp0, t1, label1);
tcg_gen_andi_tl(t0, t0, ~3);
tcg_gen_or_tl(t0, t0, t1);
tcg_gen_movi_tl(t2, CC_Z);
gen_set_label(label1);
if (mod != 3) {
gen_op_st_v(s, ot, t0, a0);
tcg_temp_free(a0);
} else {
gen_op_mov_reg_v(ot, rm, t0);
}
gen_compute_eflags(s);
tcg_gen_andi_tl(cpu_cc_src, cpu_cc_src, ~CC_Z);
tcg_gen_or_tl(cpu_cc_src, cpu_cc_src, t2);
tcg_temp_free(t0);
tcg_temp_free(t1);
tcg_temp_free(t2);
}
break;
case 0x102: /* lar */
case 0x103: /* lsl */
{
TCGLabel *label1;
TCGv t0;
if (!s->pe || s->vm86)
goto illegal_op;
ot = dflag != MO_16 ? MO_32 : MO_16;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0);
t0 = tcg_temp_local_new();
gen_update_cc_op(s);
if (b == 0x102) {
gen_helper_lar(t0, cpu_env, cpu_T0);
} else {
gen_helper_lsl(t0, cpu_env, cpu_T0);
}
tcg_gen_andi_tl(cpu_tmp0, cpu_cc_src, CC_Z);
label1 = gen_new_label();
tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_tmp0, 0, label1);
gen_op_mov_reg_v(ot, reg, t0);
gen_set_label(label1);
set_cc_op(s, CC_OP_EFLAGS);
tcg_temp_free(t0);
}
break;
case 0x118:
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
op = (modrm >> 3) & 7;
switch(op) {
case 0: /* prefetchnta */
case 1: /* prefetchnt0 */
case 2: /* prefetchnt0 */
case 3: /* prefetchnt0 */
if (mod == 3)
goto illegal_op;
gen_nop_modrm(env, s, modrm);
/* nothing more to do */
break;
default: /* nop (multi byte) */
gen_nop_modrm(env, s, modrm);
break;
}
break;
case 0x11a:
modrm = cpu_ldub_code(env, s->pc++);
if (s->flags & HF_MPX_EN_MASK) {
mod = (modrm >> 6) & 3;
reg = ((modrm >> 3) & 7) | rex_r;
if (prefixes & PREFIX_REPZ) {
/* bndcl */
if (reg >= 4
|| (prefixes & PREFIX_LOCK)
|| s->aflag == MO_16) {
goto illegal_op;
}
gen_bndck(env, s, modrm, TCG_COND_LTU, cpu_bndl[reg]);
} else if (prefixes & PREFIX_REPNZ) {
/* bndcu */
if (reg >= 4
|| (prefixes & PREFIX_LOCK)
|| s->aflag == MO_16) {
goto illegal_op;
}
TCGv_i64 notu = tcg_temp_new_i64();
tcg_gen_not_i64(notu, cpu_bndu[reg]);
gen_bndck(env, s, modrm, TCG_COND_GTU, notu);
tcg_temp_free_i64(notu);
} else if (prefixes & PREFIX_DATA) {
/* bndmov -- from reg/mem */
if (reg >= 4 || s->aflag == MO_16) {
goto illegal_op;
}
if (mod == 3) {
int reg2 = (modrm & 7) | REX_B(s);
if (reg2 >= 4 || (prefixes & PREFIX_LOCK)) {
goto illegal_op;
}
if (s->flags & HF_MPX_IU_MASK) {
tcg_gen_mov_i64(cpu_bndl[reg], cpu_bndl[reg2]);
tcg_gen_mov_i64(cpu_bndu[reg], cpu_bndu[reg2]);
}
} else {
gen_lea_modrm(env, s, modrm);
if (CODE64(s)) {
tcg_gen_qemu_ld_i64(cpu_bndl[reg], cpu_A0,
s->mem_index, MO_LEQ);
tcg_gen_addi_tl(cpu_A0, cpu_A0, 8);
tcg_gen_qemu_ld_i64(cpu_bndu[reg], cpu_A0,
s->mem_index, MO_LEQ);
} else {
tcg_gen_qemu_ld_i64(cpu_bndl[reg], cpu_A0,
s->mem_index, MO_LEUL);
tcg_gen_addi_tl(cpu_A0, cpu_A0, 4);
tcg_gen_qemu_ld_i64(cpu_bndu[reg], cpu_A0,
s->mem_index, MO_LEUL);
}
/* bnd registers are now in-use */
gen_set_hflag(s, HF_MPX_IU_MASK);
}
} else if (mod != 3) {
/* bndldx */
AddressParts a = gen_lea_modrm_0(env, s, modrm);
if (reg >= 4
|| (prefixes & PREFIX_LOCK)
|| s->aflag == MO_16
|| a.base < -1) {
goto illegal_op;
}
if (a.base >= 0) {
tcg_gen_addi_tl(cpu_A0, cpu_regs[a.base], a.disp);
} else {
tcg_gen_movi_tl(cpu_A0, 0);
}
gen_lea_v_seg(s, s->aflag, cpu_A0, a.def_seg, s->override);
if (a.index >= 0) {
tcg_gen_mov_tl(cpu_T0, cpu_regs[a.index]);
} else {
tcg_gen_movi_tl(cpu_T0, 0);
}
if (CODE64(s)) {
gen_helper_bndldx64(cpu_bndl[reg], cpu_env, cpu_A0, cpu_T0);
tcg_gen_ld_i64(cpu_bndu[reg], cpu_env,
offsetof(CPUX86State, mmx_t0.MMX_Q(0)));
} else {
gen_helper_bndldx32(cpu_bndu[reg], cpu_env, cpu_A0, cpu_T0);
tcg_gen_ext32u_i64(cpu_bndl[reg], cpu_bndu[reg]);
tcg_gen_shri_i64(cpu_bndu[reg], cpu_bndu[reg], 32);
}
gen_set_hflag(s, HF_MPX_IU_MASK);
}
}
gen_nop_modrm(env, s, modrm);
break;
case 0x11b:
modrm = cpu_ldub_code(env, s->pc++);
if (s->flags & HF_MPX_EN_MASK) {
mod = (modrm >> 6) & 3;
reg = ((modrm >> 3) & 7) | rex_r;
if (mod != 3 && (prefixes & PREFIX_REPZ)) {
/* bndmk */
if (reg >= 4
|| (prefixes & PREFIX_LOCK)
|| s->aflag == MO_16) {
goto illegal_op;
}
AddressParts a = gen_lea_modrm_0(env, s, modrm);
if (a.base >= 0) {
tcg_gen_extu_tl_i64(cpu_bndl[reg], cpu_regs[a.base]);
if (!CODE64(s)) {
tcg_gen_ext32u_i64(cpu_bndl[reg], cpu_bndl[reg]);
}
} else if (a.base == -1) {
/* no base register has lower bound of 0 */
tcg_gen_movi_i64(cpu_bndl[reg], 0);
} else {
/* rip-relative generates #ud */
goto illegal_op;
}
tcg_gen_not_tl(cpu_A0, gen_lea_modrm_1(a));
if (!CODE64(s)) {
tcg_gen_ext32u_tl(cpu_A0, cpu_A0);
}
tcg_gen_extu_tl_i64(cpu_bndu[reg], cpu_A0);
/* bnd registers are now in-use */
gen_set_hflag(s, HF_MPX_IU_MASK);
break;
} else if (prefixes & PREFIX_REPNZ) {
/* bndcn */
if (reg >= 4
|| (prefixes & PREFIX_LOCK)
|| s->aflag == MO_16) {
goto illegal_op;
}
gen_bndck(env, s, modrm, TCG_COND_GTU, cpu_bndu[reg]);
} else if (prefixes & PREFIX_DATA) {
/* bndmov -- to reg/mem */
if (reg >= 4 || s->aflag == MO_16) {
goto illegal_op;
}
if (mod == 3) {
int reg2 = (modrm & 7) | REX_B(s);
if (reg2 >= 4 || (prefixes & PREFIX_LOCK)) {
goto illegal_op;
}
if (s->flags & HF_MPX_IU_MASK) {
tcg_gen_mov_i64(cpu_bndl[reg2], cpu_bndl[reg]);
tcg_gen_mov_i64(cpu_bndu[reg2], cpu_bndu[reg]);
}
} else {
gen_lea_modrm(env, s, modrm);
if (CODE64(s)) {
tcg_gen_qemu_st_i64(cpu_bndl[reg], cpu_A0,
s->mem_index, MO_LEQ);
tcg_gen_addi_tl(cpu_A0, cpu_A0, 8);
tcg_gen_qemu_st_i64(cpu_bndu[reg], cpu_A0,
s->mem_index, MO_LEQ);
} else {
tcg_gen_qemu_st_i64(cpu_bndl[reg], cpu_A0,
s->mem_index, MO_LEUL);
tcg_gen_addi_tl(cpu_A0, cpu_A0, 4);
tcg_gen_qemu_st_i64(cpu_bndu[reg], cpu_A0,
s->mem_index, MO_LEUL);
}
}
} else if (mod != 3) {
/* bndstx */
AddressParts a = gen_lea_modrm_0(env, s, modrm);
if (reg >= 4
|| (prefixes & PREFIX_LOCK)
|| s->aflag == MO_16
|| a.base < -1) {
goto illegal_op;
}
if (a.base >= 0) {
tcg_gen_addi_tl(cpu_A0, cpu_regs[a.base], a.disp);
} else {
tcg_gen_movi_tl(cpu_A0, 0);
}
gen_lea_v_seg(s, s->aflag, cpu_A0, a.def_seg, s->override);
if (a.index >= 0) {
tcg_gen_mov_tl(cpu_T0, cpu_regs[a.index]);
} else {
tcg_gen_movi_tl(cpu_T0, 0);
}
if (CODE64(s)) {
gen_helper_bndstx64(cpu_env, cpu_A0, cpu_T0,
cpu_bndl[reg], cpu_bndu[reg]);
} else {
gen_helper_bndstx32(cpu_env, cpu_A0, cpu_T0,
cpu_bndl[reg], cpu_bndu[reg]);
}
}
}
gen_nop_modrm(env, s, modrm);
break;
case 0x119: case 0x11c ... 0x11f: /* nop (multi byte) */
modrm = cpu_ldub_code(env, s->pc++);
gen_nop_modrm(env, s, modrm);
break;
case 0x120: /* mov reg, crN */
case 0x122: /* mov crN, reg */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
modrm = cpu_ldub_code(env, s->pc++);
/* Ignore the mod bits (assume (modrm&0xc0)==0xc0).
* AMD documentation (24594.pdf) and testing of
* intel 386 and 486 processors all show that the mod bits
* are assumed to be 1's, regardless of actual values.
*/
rm = (modrm & 7) | REX_B(s);
reg = ((modrm >> 3) & 7) | rex_r;
if (CODE64(s))
ot = MO_64;
else
ot = MO_32;
if ((prefixes & PREFIX_LOCK) && (reg == 0) &&
(s->cpuid_ext3_features & CPUID_EXT3_CR8LEG)) {
reg = 8;
}
switch(reg) {
case 0:
case 2:
case 3:
case 4:
case 8:
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
if (b & 2) {
gen_op_mov_v_reg(ot, cpu_T0, rm);
gen_helper_write_crN(cpu_env, tcg_const_i32(reg),
cpu_T0);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
} else {
gen_helper_read_crN(cpu_T0, cpu_env, tcg_const_i32(reg));
gen_op_mov_reg_v(ot, rm, cpu_T0);
}
break;
default:
goto unknown_op;
}
}
break;
case 0x121: /* mov reg, drN */
case 0x123: /* mov drN, reg */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
modrm = cpu_ldub_code(env, s->pc++);
/* Ignore the mod bits (assume (modrm&0xc0)==0xc0).
* AMD documentation (24594.pdf) and testing of
* intel 386 and 486 processors all show that the mod bits
* are assumed to be 1's, regardless of actual values.
*/
rm = (modrm & 7) | REX_B(s);
reg = ((modrm >> 3) & 7) | rex_r;
if (CODE64(s))
ot = MO_64;
else
ot = MO_32;
if (reg >= 8) {
goto illegal_op;
}
if (b & 2) {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_WRITE_DR0 + reg);
gen_op_mov_v_reg(ot, cpu_T0, rm);
tcg_gen_movi_i32(cpu_tmp2_i32, reg);
gen_helper_set_dr(cpu_env, cpu_tmp2_i32, cpu_T0);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
} else {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_READ_DR0 + reg);
tcg_gen_movi_i32(cpu_tmp2_i32, reg);
gen_helper_get_dr(cpu_T0, cpu_env, cpu_tmp2_i32);
gen_op_mov_reg_v(ot, rm, cpu_T0);
}
}
break;
case 0x106: /* clts */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_WRITE_CR0);
gen_helper_clts(cpu_env);
/* abort block because static cpu state changed */
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
}
break;
/* MMX/3DNow!/SSE/SSE2/SSE3/SSSE3/SSE4 support */
case 0x1c3: /* MOVNTI reg, mem */
if (!(s->cpuid_features & CPUID_SSE2))
goto illegal_op;
ot = mo_64_32(dflag);
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
if (mod == 3)
goto illegal_op;
reg = ((modrm >> 3) & 7) | rex_r;
/* generate a generic store */
gen_ldst_modrm(env, s, modrm, ot, reg, 1);
break;
case 0x1ae:
modrm = cpu_ldub_code(env, s->pc++);
switch (modrm) {
CASE_MODRM_MEM_OP(0): /* fxsave */
if (!(s->cpuid_features & CPUID_FXSR)
|| (prefixes & PREFIX_LOCK)) {
goto illegal_op;
}
if ((s->flags & HF_EM_MASK) || (s->flags & HF_TS_MASK)) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
break;
}
gen_lea_modrm(env, s, modrm);
gen_helper_fxsave(cpu_env, cpu_A0);
break;
CASE_MODRM_MEM_OP(1): /* fxrstor */
if (!(s->cpuid_features & CPUID_FXSR)
|| (prefixes & PREFIX_LOCK)) {
goto illegal_op;
}
if ((s->flags & HF_EM_MASK) || (s->flags & HF_TS_MASK)) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
break;
}
gen_lea_modrm(env, s, modrm);
gen_helper_fxrstor(cpu_env, cpu_A0);
break;
CASE_MODRM_MEM_OP(2): /* ldmxcsr */
if ((s->flags & HF_EM_MASK) || !(s->flags & HF_OSFXSR_MASK)) {
goto illegal_op;
}
if (s->flags & HF_TS_MASK) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
break;
}
gen_lea_modrm(env, s, modrm);
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUL);
gen_helper_ldmxcsr(cpu_env, cpu_tmp2_i32);
break;
CASE_MODRM_MEM_OP(3): /* stmxcsr */
if ((s->flags & HF_EM_MASK) || !(s->flags & HF_OSFXSR_MASK)) {
goto illegal_op;
}
if (s->flags & HF_TS_MASK) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
break;
}
gen_lea_modrm(env, s, modrm);
tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State, mxcsr));
gen_op_st_v(s, MO_32, cpu_T0, cpu_A0);
break;
CASE_MODRM_MEM_OP(4): /* xsave */
if ((s->cpuid_ext_features & CPUID_EXT_XSAVE) == 0
|| (prefixes & (PREFIX_LOCK | PREFIX_DATA
| PREFIX_REPZ | PREFIX_REPNZ))) {
goto illegal_op;
}
gen_lea_modrm(env, s, modrm);
tcg_gen_concat_tl_i64(cpu_tmp1_i64, cpu_regs[R_EAX],
cpu_regs[R_EDX]);
gen_helper_xsave(cpu_env, cpu_A0, cpu_tmp1_i64);
break;
CASE_MODRM_MEM_OP(5): /* xrstor */
if ((s->cpuid_ext_features & CPUID_EXT_XSAVE) == 0
|| (prefixes & (PREFIX_LOCK | PREFIX_DATA
| PREFIX_REPZ | PREFIX_REPNZ))) {
goto illegal_op;
}
gen_lea_modrm(env, s, modrm);
tcg_gen_concat_tl_i64(cpu_tmp1_i64, cpu_regs[R_EAX],
cpu_regs[R_EDX]);
gen_helper_xrstor(cpu_env, cpu_A0, cpu_tmp1_i64);
/* XRSTOR is how MPX is enabled, which changes how
we translate. Thus we need to end the TB. */
gen_update_cc_op(s);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
break;
CASE_MODRM_MEM_OP(6): /* xsaveopt / clwb */
if (prefixes & PREFIX_LOCK) {
goto illegal_op;
}
if (prefixes & PREFIX_DATA) {
/* clwb */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_CLWB)) {
goto illegal_op;
}
gen_nop_modrm(env, s, modrm);
} else {
/* xsaveopt */
if ((s->cpuid_ext_features & CPUID_EXT_XSAVE) == 0
|| (s->cpuid_xsave_features & CPUID_XSAVE_XSAVEOPT) == 0
|| (prefixes & (PREFIX_REPZ | PREFIX_REPNZ))) {
goto illegal_op;
}
gen_lea_modrm(env, s, modrm);
tcg_gen_concat_tl_i64(cpu_tmp1_i64, cpu_regs[R_EAX],
cpu_regs[R_EDX]);
gen_helper_xsaveopt(cpu_env, cpu_A0, cpu_tmp1_i64);
}
break;
CASE_MODRM_MEM_OP(7): /* clflush / clflushopt */
if (prefixes & PREFIX_LOCK) {
goto illegal_op;
}
if (prefixes & PREFIX_DATA) {
/* clflushopt */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_CLFLUSHOPT)) {
goto illegal_op;
}
} else {
/* clflush */
if ((s->prefix & (PREFIX_REPZ | PREFIX_REPNZ))
|| !(s->cpuid_features & CPUID_CLFLUSH)) {
goto illegal_op;
}
}
gen_nop_modrm(env, s, modrm);
break;
case 0xc0 ... 0xc7: /* rdfsbase (f3 0f ae /0) */
case 0xc8 ... 0xc8: /* rdgsbase (f3 0f ae /1) */
case 0xd0 ... 0xd7: /* wrfsbase (f3 0f ae /2) */
case 0xd8 ... 0xd8: /* wrgsbase (f3 0f ae /3) */
if (CODE64(s)
&& (prefixes & PREFIX_REPZ)
&& !(prefixes & PREFIX_LOCK)
&& (s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_FSGSBASE)) {
TCGv base, treg, src, dst;
/* Preserve hflags bits by testing CR4 at runtime. */
tcg_gen_movi_i32(cpu_tmp2_i32, CR4_FSGSBASE_MASK);
gen_helper_cr4_testbit(cpu_env, cpu_tmp2_i32);
base = cpu_seg_base[modrm & 8 ? R_GS : R_FS];
treg = cpu_regs[(modrm & 7) | REX_B(s)];
if (modrm & 0x10) {
/* wr*base */
dst = base, src = treg;
} else {
/* rd*base */
dst = treg, src = base;
}
if (s->dflag == MO_32) {
tcg_gen_ext32u_tl(dst, src);
} else {
tcg_gen_mov_tl(dst, src);
}
break;
}
goto unknown_op;
case 0xf8: /* sfence / pcommit */
if (prefixes & PREFIX_DATA) {
/* pcommit */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_PCOMMIT)
|| (prefixes & PREFIX_LOCK)) {
goto illegal_op;
}
break;
}
/* fallthru */
case 0xf9 ... 0xff: /* sfence */
if (!(s->cpuid_features & CPUID_SSE)
|| (prefixes & PREFIX_LOCK)) {
goto illegal_op;
}
tcg_gen_mb(TCG_MO_ST_ST | TCG_BAR_SC);
break;
case 0xe8 ... 0xef: /* lfence */
if (!(s->cpuid_features & CPUID_SSE)
|| (prefixes & PREFIX_LOCK)) {
goto illegal_op;
}
tcg_gen_mb(TCG_MO_LD_LD | TCG_BAR_SC);
break;
case 0xf0 ... 0xf7: /* mfence */
if (!(s->cpuid_features & CPUID_SSE2)
|| (prefixes & PREFIX_LOCK)) {
goto illegal_op;
}
tcg_gen_mb(TCG_MO_ALL | TCG_BAR_SC);
break;
default:
goto unknown_op;
}
break;
case 0x10d: /* 3DNow! prefetch(w) */
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
if (mod == 3)
goto illegal_op;
gen_nop_modrm(env, s, modrm);
break;
case 0x1aa: /* rsm */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_RSM);
if (!(s->flags & HF_SMM_MASK))
goto illegal_op;
gen_update_cc_op(s);
gen_jmp_im(s->pc - s->cs_base);
gen_helper_rsm(cpu_env);
gen_eob(s);
break;
case 0x1b8: /* SSE4.2 popcnt */
if ((prefixes & (PREFIX_REPZ | PREFIX_LOCK | PREFIX_REPNZ)) !=
PREFIX_REPZ)
goto illegal_op;
if (!(s->cpuid_ext_features & CPUID_EXT_POPCNT))
goto illegal_op;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
if (s->prefix & PREFIX_DATA) {
ot = MO_16;
} else {
ot = mo_64_32(dflag);
}
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
gen_extu(ot, cpu_T0);
tcg_gen_mov_tl(cpu_cc_src, cpu_T0);
tcg_gen_ctpop_tl(cpu_T0, cpu_T0);
gen_op_mov_reg_v(ot, reg, cpu_T0);
set_cc_op(s, CC_OP_POPCNT);
break;
case 0x10e ... 0x10f:
/* 3DNow! instructions, ignore prefixes */
s->prefix &= ~(PREFIX_REPZ | PREFIX_REPNZ | PREFIX_DATA);
case 0x110 ... 0x117:
case 0x128 ... 0x12f:
case 0x138 ... 0x13a:
case 0x150 ... 0x179:
case 0x17c ... 0x17f:
case 0x1c2:
case 0x1c4 ... 0x1c6:
case 0x1d0 ... 0x1fe:
gen_sse(env, s, b, pc_start, rex_r);
break;
default:
goto unknown_op;
}
return s->pc;
illegal_op:
gen_illegal_opcode(s);
return s->pc;
unknown_op:
gen_unknown_opcode(env, s);
return s->pc;
}
void tcg_x86_init(void)
{
static const char reg_names[CPU_NB_REGS][4] = {
#ifdef TARGET_X86_64
[R_EAX] = "rax",
[R_EBX] = "rbx",
[R_ECX] = "rcx",
[R_EDX] = "rdx",
[R_ESI] = "rsi",
[R_EDI] = "rdi",
[R_EBP] = "rbp",
[R_ESP] = "rsp",
[8] = "r8",
[9] = "r9",
[10] = "r10",
[11] = "r11",
[12] = "r12",
[13] = "r13",
[14] = "r14",
[15] = "r15",
#else
[R_EAX] = "eax",
[R_EBX] = "ebx",
[R_ECX] = "ecx",
[R_EDX] = "edx",
[R_ESI] = "esi",
[R_EDI] = "edi",
[R_EBP] = "ebp",
[R_ESP] = "esp",
#endif
};
static const char seg_base_names[6][8] = {
[R_CS] = "cs_base",
[R_DS] = "ds_base",
[R_ES] = "es_base",
[R_FS] = "fs_base",
[R_GS] = "gs_base",
[R_SS] = "ss_base",
};
static const char bnd_regl_names[4][8] = {
"bnd0_lb", "bnd1_lb", "bnd2_lb", "bnd3_lb"
};
static const char bnd_regu_names[4][8] = {
"bnd0_ub", "bnd1_ub", "bnd2_ub", "bnd3_ub"
};
int i;
static bool initialized;
if (initialized) {
return;
}
initialized = true;
cpu_env = tcg_global_reg_new_ptr(TCG_AREG0, "env");
tcg_ctx.tcg_env = cpu_env;
cpu_cc_op = tcg_global_mem_new_i32(cpu_env,
offsetof(CPUX86State, cc_op), "cc_op");
cpu_cc_dst = tcg_global_mem_new(cpu_env, offsetof(CPUX86State, cc_dst),
"cc_dst");
cpu_cc_src = tcg_global_mem_new(cpu_env, offsetof(CPUX86State, cc_src),
"cc_src");
cpu_cc_src2 = tcg_global_mem_new(cpu_env, offsetof(CPUX86State, cc_src2),
"cc_src2");
for (i = 0; i < CPU_NB_REGS; ++i) {
cpu_regs[i] = tcg_global_mem_new(cpu_env,
offsetof(CPUX86State, regs[i]),
reg_names[i]);
}
for (i = 0; i < 6; ++i) {
cpu_seg_base[i]
= tcg_global_mem_new(cpu_env,
offsetof(CPUX86State, segs[i].base),
seg_base_names[i]);
}
for (i = 0; i < 4; ++i) {
cpu_bndl[i]
= tcg_global_mem_new_i64(cpu_env,
offsetof(CPUX86State, bnd_regs[i].lb),
bnd_regl_names[i]);
cpu_bndu[i]
= tcg_global_mem_new_i64(cpu_env,
offsetof(CPUX86State, bnd_regs[i].ub),
bnd_regu_names[i]);
}
}
/* generate intermediate code for basic block 'tb'. */
void gen_intermediate_code(CPUX86State *env, TranslationBlock *tb)
{
X86CPU *cpu = x86_env_get_cpu(env);
CPUState *cs = CPU(cpu);
DisasContext dc1, *dc = &dc1;
target_ulong pc_ptr;
uint32_t flags;
target_ulong pc_start;
target_ulong cs_base;
int num_insns;
int max_insns;
/* generate intermediate code */
pc_start = tb->pc;
cs_base = tb->cs_base;
flags = tb->flags;
dc->pe = (flags >> HF_PE_SHIFT) & 1;
dc->code32 = (flags >> HF_CS32_SHIFT) & 1;
dc->ss32 = (flags >> HF_SS32_SHIFT) & 1;
dc->addseg = (flags >> HF_ADDSEG_SHIFT) & 1;
dc->f_st = 0;
dc->vm86 = (flags >> VM_SHIFT) & 1;
dc->cpl = (flags >> HF_CPL_SHIFT) & 3;
dc->iopl = (flags >> IOPL_SHIFT) & 3;
dc->tf = (flags >> TF_SHIFT) & 1;
dc->singlestep_enabled = cs->singlestep_enabled;
dc->cc_op = CC_OP_DYNAMIC;
dc->cc_op_dirty = false;
dc->cs_base = cs_base;
dc->tb = tb;
dc->popl_esp_hack = 0;
/* select memory access functions */
dc->mem_index = 0;
#ifdef CONFIG_SOFTMMU
dc->mem_index = cpu_mmu_index(env, false);
#endif
dc->cpuid_features = env->features[FEAT_1_EDX];
dc->cpuid_ext_features = env->features[FEAT_1_ECX];
dc->cpuid_ext2_features = env->features[FEAT_8000_0001_EDX];
dc->cpuid_ext3_features = env->features[FEAT_8000_0001_ECX];
dc->cpuid_7_0_ebx_features = env->features[FEAT_7_0_EBX];
dc->cpuid_xsave_features = env->features[FEAT_XSAVE];
#ifdef TARGET_X86_64
dc->lma = (flags >> HF_LMA_SHIFT) & 1;
dc->code64 = (flags >> HF_CS64_SHIFT) & 1;
#endif
dc->flags = flags;
dc->jmp_opt = !(dc->tf || cs->singlestep_enabled ||
(flags & HF_INHIBIT_IRQ_MASK));
/* Do not optimize repz jumps at all in icount mode, because
rep movsS instructions are execured with different paths
in !repz_opt and repz_opt modes. The first one was used
always except single step mode. And this setting
disables jumps optimization and control paths become
equivalent in run and single step modes.
Now there will be no jump optimization for repz in
record/replay modes and there will always be an
additional step for ecx=0 when icount is enabled.
*/
dc->repz_opt = !dc->jmp_opt && !(tb->cflags & CF_USE_ICOUNT);
#if 0
/* check addseg logic */
if (!dc->addseg && (dc->vm86 || !dc->pe || !dc->code32))
printf("ERROR addseg\n");
#endif
cpu_T0 = tcg_temp_new();
cpu_T1 = tcg_temp_new();
cpu_A0 = tcg_temp_new();
cpu_tmp0 = tcg_temp_new();
cpu_tmp1_i64 = tcg_temp_new_i64();
cpu_tmp2_i32 = tcg_temp_new_i32();
cpu_tmp3_i32 = tcg_temp_new_i32();
cpu_tmp4 = tcg_temp_new();
cpu_ptr0 = tcg_temp_new_ptr();
cpu_ptr1 = tcg_temp_new_ptr();
cpu_cc_srcT = tcg_temp_local_new();
dc->is_jmp = DISAS_NEXT;
pc_ptr = pc_start;
num_insns = 0;
max_insns = tb->cflags & CF_COUNT_MASK;
if (max_insns == 0) {
max_insns = CF_COUNT_MASK;
}
if (max_insns > TCG_MAX_INSNS) {
max_insns = TCG_MAX_INSNS;
}
gen_tb_start(tb);
for(;;) {
tcg_gen_insn_start(pc_ptr, dc->cc_op);
num_insns++;
/* If RF is set, suppress an internally generated breakpoint. */
if (unlikely(cpu_breakpoint_test(cs, pc_ptr,
tb->flags & HF_RF_MASK
? BP_GDB : BP_ANY))) {
gen_debug(dc, pc_ptr - dc->cs_base);
/* The address covered by the breakpoint must be included in
[tb->pc, tb->pc + tb->size) in order to for it to be
properly cleared -- thus we increment the PC here so that
the logic setting tb->size below does the right thing. */
pc_ptr += 1;
goto done_generating;
}
if (num_insns == max_insns && (tb->cflags & CF_LAST_IO)) {
gen_io_start();
}
pc_ptr = disas_insn(env, dc, pc_ptr);
/* stop translation if indicated */
if (dc->is_jmp)
break;
/* if single step mode, we generate only one instruction and
generate an exception */
/* if irq were inhibited with HF_INHIBIT_IRQ_MASK, we clear
the flag and abort the translation to give the irqs a
change to be happen */
if (dc->tf || dc->singlestep_enabled ||
(flags & HF_INHIBIT_IRQ_MASK)) {
gen_jmp_im(pc_ptr - dc->cs_base);
gen_eob(dc);
break;
}
/* Do not cross the boundary of the pages in icount mode,
it can cause an exception. Do it only when boundary is
crossed by the first instruction in the block.
If current instruction already crossed the bound - it's ok,
because an exception hasn't stopped this code.
*/
if ((tb->cflags & CF_USE_ICOUNT)
&& ((pc_ptr & TARGET_PAGE_MASK)
!= ((pc_ptr + TARGET_MAX_INSN_SIZE - 1) & TARGET_PAGE_MASK)
|| (pc_ptr & ~TARGET_PAGE_MASK) == 0)) {
gen_jmp_im(pc_ptr - dc->cs_base);
gen_eob(dc);
break;
}
/* if too long translation, stop generation too */
if (tcg_op_buf_full() ||
(pc_ptr - pc_start) >= (TARGET_PAGE_SIZE - 32) ||
num_insns >= max_insns) {
gen_jmp_im(pc_ptr - dc->cs_base);
gen_eob(dc);
break;
}
if (singlestep) {
gen_jmp_im(pc_ptr - dc->cs_base);
gen_eob(dc);
break;
}
}
if (tb->cflags & CF_LAST_IO)
gen_io_end();
done_generating:
gen_tb_end(tb, num_insns);
#ifdef DEBUG_DISAS
if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)
&& qemu_log_in_addr_range(pc_start)) {
int disas_flags;
qemu_log_lock();
qemu_log("----------------\n");
qemu_log("IN: %s\n", lookup_symbol(pc_start));
#ifdef TARGET_X86_64
if (dc->code64)
disas_flags = 2;
else
#endif
disas_flags = !dc->code32;
log_target_disas(cs, pc_start, pc_ptr - pc_start, disas_flags);
qemu_log("\n");
qemu_log_unlock();
}
#endif
tb->size = pc_ptr - pc_start;
tb->icount = num_insns;
}
void restore_state_to_opc(CPUX86State *env, TranslationBlock *tb,
target_ulong *data)
{
int cc_op = data[1];
env->eip = data[0] - tb->cs_base;
if (cc_op != CC_OP_DYNAMIC) {
env->cc_op = cc_op;
}
}
| ./CrossVul/dataset_final_sorted/CWE-94/c/good_3326_0 |
crossvul-cpp_data_bad_3326_0 | /*
* i386 translation
*
* Copyright (c) 2003 Fabrice Bellard
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "qemu/osdep.h"
#include "qemu/host-utils.h"
#include "cpu.h"
#include "disas/disas.h"
#include "exec/exec-all.h"
#include "tcg-op.h"
#include "exec/cpu_ldst.h"
#include "exec/helper-proto.h"
#include "exec/helper-gen.h"
#include "trace-tcg.h"
#include "exec/log.h"
#define PREFIX_REPZ 0x01
#define PREFIX_REPNZ 0x02
#define PREFIX_LOCK 0x04
#define PREFIX_DATA 0x08
#define PREFIX_ADR 0x10
#define PREFIX_VEX 0x20
#ifdef TARGET_X86_64
#define CODE64(s) ((s)->code64)
#define REX_X(s) ((s)->rex_x)
#define REX_B(s) ((s)->rex_b)
#else
#define CODE64(s) 0
#define REX_X(s) 0
#define REX_B(s) 0
#endif
#ifdef TARGET_X86_64
# define ctztl ctz64
# define clztl clz64
#else
# define ctztl ctz32
# define clztl clz32
#endif
/* For a switch indexed by MODRM, match all memory operands for a given OP. */
#define CASE_MODRM_MEM_OP(OP) \
case (0 << 6) | (OP << 3) | 0 ... (0 << 6) | (OP << 3) | 7: \
case (1 << 6) | (OP << 3) | 0 ... (1 << 6) | (OP << 3) | 7: \
case (2 << 6) | (OP << 3) | 0 ... (2 << 6) | (OP << 3) | 7
#define CASE_MODRM_OP(OP) \
case (0 << 6) | (OP << 3) | 0 ... (0 << 6) | (OP << 3) | 7: \
case (1 << 6) | (OP << 3) | 0 ... (1 << 6) | (OP << 3) | 7: \
case (2 << 6) | (OP << 3) | 0 ... (2 << 6) | (OP << 3) | 7: \
case (3 << 6) | (OP << 3) | 0 ... (3 << 6) | (OP << 3) | 7
//#define MACRO_TEST 1
/* global register indexes */
static TCGv_env cpu_env;
static TCGv cpu_A0;
static TCGv cpu_cc_dst, cpu_cc_src, cpu_cc_src2, cpu_cc_srcT;
static TCGv_i32 cpu_cc_op;
static TCGv cpu_regs[CPU_NB_REGS];
static TCGv cpu_seg_base[6];
static TCGv_i64 cpu_bndl[4];
static TCGv_i64 cpu_bndu[4];
/* local temps */
static TCGv cpu_T0, cpu_T1;
/* local register indexes (only used inside old micro ops) */
static TCGv cpu_tmp0, cpu_tmp4;
static TCGv_ptr cpu_ptr0, cpu_ptr1;
static TCGv_i32 cpu_tmp2_i32, cpu_tmp3_i32;
static TCGv_i64 cpu_tmp1_i64;
#include "exec/gen-icount.h"
#ifdef TARGET_X86_64
static int x86_64_hregs;
#endif
typedef struct DisasContext {
/* current insn context */
int override; /* -1 if no override */
int prefix;
TCGMemOp aflag;
TCGMemOp dflag;
target_ulong pc_start;
target_ulong pc; /* pc = eip + cs_base */
int is_jmp; /* 1 = means jump (stop translation), 2 means CPU
static state change (stop translation) */
/* current block context */
target_ulong cs_base; /* base of CS segment */
int pe; /* protected mode */
int code32; /* 32 bit code segment */
#ifdef TARGET_X86_64
int lma; /* long mode active */
int code64; /* 64 bit code segment */
int rex_x, rex_b;
#endif
int vex_l; /* vex vector length */
int vex_v; /* vex vvvv register, without 1's compliment. */
int ss32; /* 32 bit stack segment */
CCOp cc_op; /* current CC operation */
bool cc_op_dirty;
int addseg; /* non zero if either DS/ES/SS have a non zero base */
int f_st; /* currently unused */
int vm86; /* vm86 mode */
int cpl;
int iopl;
int tf; /* TF cpu flag */
int singlestep_enabled; /* "hardware" single step enabled */
int jmp_opt; /* use direct block chaining for direct jumps */
int repz_opt; /* optimize jumps within repz instructions */
int mem_index; /* select memory access functions */
uint64_t flags; /* all execution flags */
struct TranslationBlock *tb;
int popl_esp_hack; /* for correct popl with esp base handling */
int rip_offset; /* only used in x86_64, but left for simplicity */
int cpuid_features;
int cpuid_ext_features;
int cpuid_ext2_features;
int cpuid_ext3_features;
int cpuid_7_0_ebx_features;
int cpuid_xsave_features;
} DisasContext;
static void gen_eob(DisasContext *s);
static void gen_jmp(DisasContext *s, target_ulong eip);
static void gen_jmp_tb(DisasContext *s, target_ulong eip, int tb_num);
static void gen_op(DisasContext *s1, int op, TCGMemOp ot, int d);
/* i386 arith/logic operations */
enum {
OP_ADDL,
OP_ORL,
OP_ADCL,
OP_SBBL,
OP_ANDL,
OP_SUBL,
OP_XORL,
OP_CMPL,
};
/* i386 shift ops */
enum {
OP_ROL,
OP_ROR,
OP_RCL,
OP_RCR,
OP_SHL,
OP_SHR,
OP_SHL1, /* undocumented */
OP_SAR = 7,
};
enum {
JCC_O,
JCC_B,
JCC_Z,
JCC_BE,
JCC_S,
JCC_P,
JCC_L,
JCC_LE,
};
enum {
/* I386 int registers */
OR_EAX, /* MUST be even numbered */
OR_ECX,
OR_EDX,
OR_EBX,
OR_ESP,
OR_EBP,
OR_ESI,
OR_EDI,
OR_TMP0 = 16, /* temporary operand register */
OR_TMP1,
OR_A0, /* temporary register used when doing address evaluation */
};
enum {
USES_CC_DST = 1,
USES_CC_SRC = 2,
USES_CC_SRC2 = 4,
USES_CC_SRCT = 8,
};
/* Bit set if the global variable is live after setting CC_OP to X. */
static const uint8_t cc_op_live[CC_OP_NB] = {
[CC_OP_DYNAMIC] = USES_CC_DST | USES_CC_SRC | USES_CC_SRC2,
[CC_OP_EFLAGS] = USES_CC_SRC,
[CC_OP_MULB ... CC_OP_MULQ] = USES_CC_DST | USES_CC_SRC,
[CC_OP_ADDB ... CC_OP_ADDQ] = USES_CC_DST | USES_CC_SRC,
[CC_OP_ADCB ... CC_OP_ADCQ] = USES_CC_DST | USES_CC_SRC | USES_CC_SRC2,
[CC_OP_SUBB ... CC_OP_SUBQ] = USES_CC_DST | USES_CC_SRC | USES_CC_SRCT,
[CC_OP_SBBB ... CC_OP_SBBQ] = USES_CC_DST | USES_CC_SRC | USES_CC_SRC2,
[CC_OP_LOGICB ... CC_OP_LOGICQ] = USES_CC_DST,
[CC_OP_INCB ... CC_OP_INCQ] = USES_CC_DST | USES_CC_SRC,
[CC_OP_DECB ... CC_OP_DECQ] = USES_CC_DST | USES_CC_SRC,
[CC_OP_SHLB ... CC_OP_SHLQ] = USES_CC_DST | USES_CC_SRC,
[CC_OP_SARB ... CC_OP_SARQ] = USES_CC_DST | USES_CC_SRC,
[CC_OP_BMILGB ... CC_OP_BMILGQ] = USES_CC_DST | USES_CC_SRC,
[CC_OP_ADCX] = USES_CC_DST | USES_CC_SRC,
[CC_OP_ADOX] = USES_CC_SRC | USES_CC_SRC2,
[CC_OP_ADCOX] = USES_CC_DST | USES_CC_SRC | USES_CC_SRC2,
[CC_OP_CLR] = 0,
[CC_OP_POPCNT] = USES_CC_SRC,
};
static void set_cc_op(DisasContext *s, CCOp op)
{
int dead;
if (s->cc_op == op) {
return;
}
/* Discard CC computation that will no longer be used. */
dead = cc_op_live[s->cc_op] & ~cc_op_live[op];
if (dead & USES_CC_DST) {
tcg_gen_discard_tl(cpu_cc_dst);
}
if (dead & USES_CC_SRC) {
tcg_gen_discard_tl(cpu_cc_src);
}
if (dead & USES_CC_SRC2) {
tcg_gen_discard_tl(cpu_cc_src2);
}
if (dead & USES_CC_SRCT) {
tcg_gen_discard_tl(cpu_cc_srcT);
}
if (op == CC_OP_DYNAMIC) {
/* The DYNAMIC setting is translator only, and should never be
stored. Thus we always consider it clean. */
s->cc_op_dirty = false;
} else {
/* Discard any computed CC_OP value (see shifts). */
if (s->cc_op == CC_OP_DYNAMIC) {
tcg_gen_discard_i32(cpu_cc_op);
}
s->cc_op_dirty = true;
}
s->cc_op = op;
}
static void gen_update_cc_op(DisasContext *s)
{
if (s->cc_op_dirty) {
tcg_gen_movi_i32(cpu_cc_op, s->cc_op);
s->cc_op_dirty = false;
}
}
#ifdef TARGET_X86_64
#define NB_OP_SIZES 4
#else /* !TARGET_X86_64 */
#define NB_OP_SIZES 3
#endif /* !TARGET_X86_64 */
#if defined(HOST_WORDS_BIGENDIAN)
#define REG_B_OFFSET (sizeof(target_ulong) - 1)
#define REG_H_OFFSET (sizeof(target_ulong) - 2)
#define REG_W_OFFSET (sizeof(target_ulong) - 2)
#define REG_L_OFFSET (sizeof(target_ulong) - 4)
#define REG_LH_OFFSET (sizeof(target_ulong) - 8)
#else
#define REG_B_OFFSET 0
#define REG_H_OFFSET 1
#define REG_W_OFFSET 0
#define REG_L_OFFSET 0
#define REG_LH_OFFSET 4
#endif
/* In instruction encodings for byte register accesses the
* register number usually indicates "low 8 bits of register N";
* however there are some special cases where N 4..7 indicates
* [AH, CH, DH, BH], ie "bits 15..8 of register N-4". Return
* true for this special case, false otherwise.
*/
static inline bool byte_reg_is_xH(int reg)
{
if (reg < 4) {
return false;
}
#ifdef TARGET_X86_64
if (reg >= 8 || x86_64_hregs) {
return false;
}
#endif
return true;
}
/* Select the size of a push/pop operation. */
static inline TCGMemOp mo_pushpop(DisasContext *s, TCGMemOp ot)
{
if (CODE64(s)) {
return ot == MO_16 ? MO_16 : MO_64;
} else {
return ot;
}
}
/* Select the size of the stack pointer. */
static inline TCGMemOp mo_stacksize(DisasContext *s)
{
return CODE64(s) ? MO_64 : s->ss32 ? MO_32 : MO_16;
}
/* Select only size 64 else 32. Used for SSE operand sizes. */
static inline TCGMemOp mo_64_32(TCGMemOp ot)
{
#ifdef TARGET_X86_64
return ot == MO_64 ? MO_64 : MO_32;
#else
return MO_32;
#endif
}
/* Select size 8 if lsb of B is clear, else OT. Used for decoding
byte vs word opcodes. */
static inline TCGMemOp mo_b_d(int b, TCGMemOp ot)
{
return b & 1 ? ot : MO_8;
}
/* Select size 8 if lsb of B is clear, else OT capped at 32.
Used for decoding operand size of port opcodes. */
static inline TCGMemOp mo_b_d32(int b, TCGMemOp ot)
{
return b & 1 ? (ot == MO_16 ? MO_16 : MO_32) : MO_8;
}
static void gen_op_mov_reg_v(TCGMemOp ot, int reg, TCGv t0)
{
switch(ot) {
case MO_8:
if (!byte_reg_is_xH(reg)) {
tcg_gen_deposit_tl(cpu_regs[reg], cpu_regs[reg], t0, 0, 8);
} else {
tcg_gen_deposit_tl(cpu_regs[reg - 4], cpu_regs[reg - 4], t0, 8, 8);
}
break;
case MO_16:
tcg_gen_deposit_tl(cpu_regs[reg], cpu_regs[reg], t0, 0, 16);
break;
case MO_32:
/* For x86_64, this sets the higher half of register to zero.
For i386, this is equivalent to a mov. */
tcg_gen_ext32u_tl(cpu_regs[reg], t0);
break;
#ifdef TARGET_X86_64
case MO_64:
tcg_gen_mov_tl(cpu_regs[reg], t0);
break;
#endif
default:
tcg_abort();
}
}
static inline void gen_op_mov_v_reg(TCGMemOp ot, TCGv t0, int reg)
{
if (ot == MO_8 && byte_reg_is_xH(reg)) {
tcg_gen_extract_tl(t0, cpu_regs[reg - 4], 8, 8);
} else {
tcg_gen_mov_tl(t0, cpu_regs[reg]);
}
}
static void gen_add_A0_im(DisasContext *s, int val)
{
tcg_gen_addi_tl(cpu_A0, cpu_A0, val);
if (!CODE64(s)) {
tcg_gen_ext32u_tl(cpu_A0, cpu_A0);
}
}
static inline void gen_op_jmp_v(TCGv dest)
{
tcg_gen_st_tl(dest, cpu_env, offsetof(CPUX86State, eip));
}
static inline void gen_op_add_reg_im(TCGMemOp size, int reg, int32_t val)
{
tcg_gen_addi_tl(cpu_tmp0, cpu_regs[reg], val);
gen_op_mov_reg_v(size, reg, cpu_tmp0);
}
static inline void gen_op_add_reg_T0(TCGMemOp size, int reg)
{
tcg_gen_add_tl(cpu_tmp0, cpu_regs[reg], cpu_T0);
gen_op_mov_reg_v(size, reg, cpu_tmp0);
}
static inline void gen_op_ld_v(DisasContext *s, int idx, TCGv t0, TCGv a0)
{
tcg_gen_qemu_ld_tl(t0, a0, s->mem_index, idx | MO_LE);
}
static inline void gen_op_st_v(DisasContext *s, int idx, TCGv t0, TCGv a0)
{
tcg_gen_qemu_st_tl(t0, a0, s->mem_index, idx | MO_LE);
}
static inline void gen_op_st_rm_T0_A0(DisasContext *s, int idx, int d)
{
if (d == OR_TMP0) {
gen_op_st_v(s, idx, cpu_T0, cpu_A0);
} else {
gen_op_mov_reg_v(idx, d, cpu_T0);
}
}
static inline void gen_jmp_im(target_ulong pc)
{
tcg_gen_movi_tl(cpu_tmp0, pc);
gen_op_jmp_v(cpu_tmp0);
}
/* Compute SEG:REG into A0. SEG is selected from the override segment
(OVR_SEG) and the default segment (DEF_SEG). OVR_SEG may be -1 to
indicate no override. */
static void gen_lea_v_seg(DisasContext *s, TCGMemOp aflag, TCGv a0,
int def_seg, int ovr_seg)
{
switch (aflag) {
#ifdef TARGET_X86_64
case MO_64:
if (ovr_seg < 0) {
tcg_gen_mov_tl(cpu_A0, a0);
return;
}
break;
#endif
case MO_32:
/* 32 bit address */
if (ovr_seg < 0 && s->addseg) {
ovr_seg = def_seg;
}
if (ovr_seg < 0) {
tcg_gen_ext32u_tl(cpu_A0, a0);
return;
}
break;
case MO_16:
/* 16 bit address */
tcg_gen_ext16u_tl(cpu_A0, a0);
a0 = cpu_A0;
if (ovr_seg < 0) {
if (s->addseg) {
ovr_seg = def_seg;
} else {
return;
}
}
break;
default:
tcg_abort();
}
if (ovr_seg >= 0) {
TCGv seg = cpu_seg_base[ovr_seg];
if (aflag == MO_64) {
tcg_gen_add_tl(cpu_A0, a0, seg);
} else if (CODE64(s)) {
tcg_gen_ext32u_tl(cpu_A0, a0);
tcg_gen_add_tl(cpu_A0, cpu_A0, seg);
} else {
tcg_gen_add_tl(cpu_A0, a0, seg);
tcg_gen_ext32u_tl(cpu_A0, cpu_A0);
}
}
}
static inline void gen_string_movl_A0_ESI(DisasContext *s)
{
gen_lea_v_seg(s, s->aflag, cpu_regs[R_ESI], R_DS, s->override);
}
static inline void gen_string_movl_A0_EDI(DisasContext *s)
{
gen_lea_v_seg(s, s->aflag, cpu_regs[R_EDI], R_ES, -1);
}
static inline void gen_op_movl_T0_Dshift(TCGMemOp ot)
{
tcg_gen_ld32s_tl(cpu_T0, cpu_env, offsetof(CPUX86State, df));
tcg_gen_shli_tl(cpu_T0, cpu_T0, ot);
};
static TCGv gen_ext_tl(TCGv dst, TCGv src, TCGMemOp size, bool sign)
{
switch (size) {
case MO_8:
if (sign) {
tcg_gen_ext8s_tl(dst, src);
} else {
tcg_gen_ext8u_tl(dst, src);
}
return dst;
case MO_16:
if (sign) {
tcg_gen_ext16s_tl(dst, src);
} else {
tcg_gen_ext16u_tl(dst, src);
}
return dst;
#ifdef TARGET_X86_64
case MO_32:
if (sign) {
tcg_gen_ext32s_tl(dst, src);
} else {
tcg_gen_ext32u_tl(dst, src);
}
return dst;
#endif
default:
return src;
}
}
static void gen_extu(TCGMemOp ot, TCGv reg)
{
gen_ext_tl(reg, reg, ot, false);
}
static void gen_exts(TCGMemOp ot, TCGv reg)
{
gen_ext_tl(reg, reg, ot, true);
}
static inline void gen_op_jnz_ecx(TCGMemOp size, TCGLabel *label1)
{
tcg_gen_mov_tl(cpu_tmp0, cpu_regs[R_ECX]);
gen_extu(size, cpu_tmp0);
tcg_gen_brcondi_tl(TCG_COND_NE, cpu_tmp0, 0, label1);
}
static inline void gen_op_jz_ecx(TCGMemOp size, TCGLabel *label1)
{
tcg_gen_mov_tl(cpu_tmp0, cpu_regs[R_ECX]);
gen_extu(size, cpu_tmp0);
tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_tmp0, 0, label1);
}
static void gen_helper_in_func(TCGMemOp ot, TCGv v, TCGv_i32 n)
{
switch (ot) {
case MO_8:
gen_helper_inb(v, cpu_env, n);
break;
case MO_16:
gen_helper_inw(v, cpu_env, n);
break;
case MO_32:
gen_helper_inl(v, cpu_env, n);
break;
default:
tcg_abort();
}
}
static void gen_helper_out_func(TCGMemOp ot, TCGv_i32 v, TCGv_i32 n)
{
switch (ot) {
case MO_8:
gen_helper_outb(cpu_env, v, n);
break;
case MO_16:
gen_helper_outw(cpu_env, v, n);
break;
case MO_32:
gen_helper_outl(cpu_env, v, n);
break;
default:
tcg_abort();
}
}
static void gen_check_io(DisasContext *s, TCGMemOp ot, target_ulong cur_eip,
uint32_t svm_flags)
{
target_ulong next_eip;
if (s->pe && (s->cpl > s->iopl || s->vm86)) {
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
switch (ot) {
case MO_8:
gen_helper_check_iob(cpu_env, cpu_tmp2_i32);
break;
case MO_16:
gen_helper_check_iow(cpu_env, cpu_tmp2_i32);
break;
case MO_32:
gen_helper_check_iol(cpu_env, cpu_tmp2_i32);
break;
default:
tcg_abort();
}
}
if(s->flags & HF_SVMI_MASK) {
gen_update_cc_op(s);
gen_jmp_im(cur_eip);
svm_flags |= (1 << (4 + ot));
next_eip = s->pc - s->cs_base;
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_svm_check_io(cpu_env, cpu_tmp2_i32,
tcg_const_i32(svm_flags),
tcg_const_i32(next_eip - cur_eip));
}
}
static inline void gen_movs(DisasContext *s, TCGMemOp ot)
{
gen_string_movl_A0_ESI(s);
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
gen_string_movl_A0_EDI(s);
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_ESI);
gen_op_add_reg_T0(s->aflag, R_EDI);
}
static void gen_op_update1_cc(void)
{
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
}
static void gen_op_update2_cc(void)
{
tcg_gen_mov_tl(cpu_cc_src, cpu_T1);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
}
static void gen_op_update3_cc(TCGv reg)
{
tcg_gen_mov_tl(cpu_cc_src2, reg);
tcg_gen_mov_tl(cpu_cc_src, cpu_T1);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
}
static inline void gen_op_testl_T0_T1_cc(void)
{
tcg_gen_and_tl(cpu_cc_dst, cpu_T0, cpu_T1);
}
static void gen_op_update_neg_cc(void)
{
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
tcg_gen_neg_tl(cpu_cc_src, cpu_T0);
tcg_gen_movi_tl(cpu_cc_srcT, 0);
}
/* compute all eflags to cc_src */
static void gen_compute_eflags(DisasContext *s)
{
TCGv zero, dst, src1, src2;
int live, dead;
if (s->cc_op == CC_OP_EFLAGS) {
return;
}
if (s->cc_op == CC_OP_CLR) {
tcg_gen_movi_tl(cpu_cc_src, CC_Z | CC_P);
set_cc_op(s, CC_OP_EFLAGS);
return;
}
TCGV_UNUSED(zero);
dst = cpu_cc_dst;
src1 = cpu_cc_src;
src2 = cpu_cc_src2;
/* Take care to not read values that are not live. */
live = cc_op_live[s->cc_op] & ~USES_CC_SRCT;
dead = live ^ (USES_CC_DST | USES_CC_SRC | USES_CC_SRC2);
if (dead) {
zero = tcg_const_tl(0);
if (dead & USES_CC_DST) {
dst = zero;
}
if (dead & USES_CC_SRC) {
src1 = zero;
}
if (dead & USES_CC_SRC2) {
src2 = zero;
}
}
gen_update_cc_op(s);
gen_helper_cc_compute_all(cpu_cc_src, dst, src1, src2, cpu_cc_op);
set_cc_op(s, CC_OP_EFLAGS);
if (dead) {
tcg_temp_free(zero);
}
}
typedef struct CCPrepare {
TCGCond cond;
TCGv reg;
TCGv reg2;
target_ulong imm;
target_ulong mask;
bool use_reg2;
bool no_setcond;
} CCPrepare;
/* compute eflags.C to reg */
static CCPrepare gen_prepare_eflags_c(DisasContext *s, TCGv reg)
{
TCGv t0, t1;
int size, shift;
switch (s->cc_op) {
case CC_OP_SUBB ... CC_OP_SUBQ:
/* (DATA_TYPE)CC_SRCT < (DATA_TYPE)CC_SRC */
size = s->cc_op - CC_OP_SUBB;
t1 = gen_ext_tl(cpu_tmp0, cpu_cc_src, size, false);
/* If no temporary was used, be careful not to alias t1 and t0. */
t0 = TCGV_EQUAL(t1, cpu_cc_src) ? cpu_tmp0 : reg;
tcg_gen_mov_tl(t0, cpu_cc_srcT);
gen_extu(size, t0);
goto add_sub;
case CC_OP_ADDB ... CC_OP_ADDQ:
/* (DATA_TYPE)CC_DST < (DATA_TYPE)CC_SRC */
size = s->cc_op - CC_OP_ADDB;
t1 = gen_ext_tl(cpu_tmp0, cpu_cc_src, size, false);
t0 = gen_ext_tl(reg, cpu_cc_dst, size, false);
add_sub:
return (CCPrepare) { .cond = TCG_COND_LTU, .reg = t0,
.reg2 = t1, .mask = -1, .use_reg2 = true };
case CC_OP_LOGICB ... CC_OP_LOGICQ:
case CC_OP_CLR:
case CC_OP_POPCNT:
return (CCPrepare) { .cond = TCG_COND_NEVER, .mask = -1 };
case CC_OP_INCB ... CC_OP_INCQ:
case CC_OP_DECB ... CC_OP_DECQ:
return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src,
.mask = -1, .no_setcond = true };
case CC_OP_SHLB ... CC_OP_SHLQ:
/* (CC_SRC >> (DATA_BITS - 1)) & 1 */
size = s->cc_op - CC_OP_SHLB;
shift = (8 << size) - 1;
return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src,
.mask = (target_ulong)1 << shift };
case CC_OP_MULB ... CC_OP_MULQ:
return (CCPrepare) { .cond = TCG_COND_NE,
.reg = cpu_cc_src, .mask = -1 };
case CC_OP_BMILGB ... CC_OP_BMILGQ:
size = s->cc_op - CC_OP_BMILGB;
t0 = gen_ext_tl(reg, cpu_cc_src, size, false);
return (CCPrepare) { .cond = TCG_COND_EQ, .reg = t0, .mask = -1 };
case CC_OP_ADCX:
case CC_OP_ADCOX:
return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_dst,
.mask = -1, .no_setcond = true };
case CC_OP_EFLAGS:
case CC_OP_SARB ... CC_OP_SARQ:
/* CC_SRC & 1 */
return (CCPrepare) { .cond = TCG_COND_NE,
.reg = cpu_cc_src, .mask = CC_C };
default:
/* The need to compute only C from CC_OP_DYNAMIC is important
in efficiently implementing e.g. INC at the start of a TB. */
gen_update_cc_op(s);
gen_helper_cc_compute_c(reg, cpu_cc_dst, cpu_cc_src,
cpu_cc_src2, cpu_cc_op);
return (CCPrepare) { .cond = TCG_COND_NE, .reg = reg,
.mask = -1, .no_setcond = true };
}
}
/* compute eflags.P to reg */
static CCPrepare gen_prepare_eflags_p(DisasContext *s, TCGv reg)
{
gen_compute_eflags(s);
return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src,
.mask = CC_P };
}
/* compute eflags.S to reg */
static CCPrepare gen_prepare_eflags_s(DisasContext *s, TCGv reg)
{
switch (s->cc_op) {
case CC_OP_DYNAMIC:
gen_compute_eflags(s);
/* FALLTHRU */
case CC_OP_EFLAGS:
case CC_OP_ADCX:
case CC_OP_ADOX:
case CC_OP_ADCOX:
return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src,
.mask = CC_S };
case CC_OP_CLR:
case CC_OP_POPCNT:
return (CCPrepare) { .cond = TCG_COND_NEVER, .mask = -1 };
default:
{
TCGMemOp size = (s->cc_op - CC_OP_ADDB) & 3;
TCGv t0 = gen_ext_tl(reg, cpu_cc_dst, size, true);
return (CCPrepare) { .cond = TCG_COND_LT, .reg = t0, .mask = -1 };
}
}
}
/* compute eflags.O to reg */
static CCPrepare gen_prepare_eflags_o(DisasContext *s, TCGv reg)
{
switch (s->cc_op) {
case CC_OP_ADOX:
case CC_OP_ADCOX:
return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src2,
.mask = -1, .no_setcond = true };
case CC_OP_CLR:
case CC_OP_POPCNT:
return (CCPrepare) { .cond = TCG_COND_NEVER, .mask = -1 };
default:
gen_compute_eflags(s);
return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src,
.mask = CC_O };
}
}
/* compute eflags.Z to reg */
static CCPrepare gen_prepare_eflags_z(DisasContext *s, TCGv reg)
{
switch (s->cc_op) {
case CC_OP_DYNAMIC:
gen_compute_eflags(s);
/* FALLTHRU */
case CC_OP_EFLAGS:
case CC_OP_ADCX:
case CC_OP_ADOX:
case CC_OP_ADCOX:
return (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src,
.mask = CC_Z };
case CC_OP_CLR:
return (CCPrepare) { .cond = TCG_COND_ALWAYS, .mask = -1 };
case CC_OP_POPCNT:
return (CCPrepare) { .cond = TCG_COND_EQ, .reg = cpu_cc_src,
.mask = -1 };
default:
{
TCGMemOp size = (s->cc_op - CC_OP_ADDB) & 3;
TCGv t0 = gen_ext_tl(reg, cpu_cc_dst, size, false);
return (CCPrepare) { .cond = TCG_COND_EQ, .reg = t0, .mask = -1 };
}
}
}
/* perform a conditional store into register 'reg' according to jump opcode
value 'b'. In the fast case, T0 is guaranted not to be used. */
static CCPrepare gen_prepare_cc(DisasContext *s, int b, TCGv reg)
{
int inv, jcc_op, cond;
TCGMemOp size;
CCPrepare cc;
TCGv t0;
inv = b & 1;
jcc_op = (b >> 1) & 7;
switch (s->cc_op) {
case CC_OP_SUBB ... CC_OP_SUBQ:
/* We optimize relational operators for the cmp/jcc case. */
size = s->cc_op - CC_OP_SUBB;
switch (jcc_op) {
case JCC_BE:
tcg_gen_mov_tl(cpu_tmp4, cpu_cc_srcT);
gen_extu(size, cpu_tmp4);
t0 = gen_ext_tl(cpu_tmp0, cpu_cc_src, size, false);
cc = (CCPrepare) { .cond = TCG_COND_LEU, .reg = cpu_tmp4,
.reg2 = t0, .mask = -1, .use_reg2 = true };
break;
case JCC_L:
cond = TCG_COND_LT;
goto fast_jcc_l;
case JCC_LE:
cond = TCG_COND_LE;
fast_jcc_l:
tcg_gen_mov_tl(cpu_tmp4, cpu_cc_srcT);
gen_exts(size, cpu_tmp4);
t0 = gen_ext_tl(cpu_tmp0, cpu_cc_src, size, true);
cc = (CCPrepare) { .cond = cond, .reg = cpu_tmp4,
.reg2 = t0, .mask = -1, .use_reg2 = true };
break;
default:
goto slow_jcc;
}
break;
default:
slow_jcc:
/* This actually generates good code for JC, JZ and JS. */
switch (jcc_op) {
case JCC_O:
cc = gen_prepare_eflags_o(s, reg);
break;
case JCC_B:
cc = gen_prepare_eflags_c(s, reg);
break;
case JCC_Z:
cc = gen_prepare_eflags_z(s, reg);
break;
case JCC_BE:
gen_compute_eflags(s);
cc = (CCPrepare) { .cond = TCG_COND_NE, .reg = cpu_cc_src,
.mask = CC_Z | CC_C };
break;
case JCC_S:
cc = gen_prepare_eflags_s(s, reg);
break;
case JCC_P:
cc = gen_prepare_eflags_p(s, reg);
break;
case JCC_L:
gen_compute_eflags(s);
if (TCGV_EQUAL(reg, cpu_cc_src)) {
reg = cpu_tmp0;
}
tcg_gen_shri_tl(reg, cpu_cc_src, 4); /* CC_O -> CC_S */
tcg_gen_xor_tl(reg, reg, cpu_cc_src);
cc = (CCPrepare) { .cond = TCG_COND_NE, .reg = reg,
.mask = CC_S };
break;
default:
case JCC_LE:
gen_compute_eflags(s);
if (TCGV_EQUAL(reg, cpu_cc_src)) {
reg = cpu_tmp0;
}
tcg_gen_shri_tl(reg, cpu_cc_src, 4); /* CC_O -> CC_S */
tcg_gen_xor_tl(reg, reg, cpu_cc_src);
cc = (CCPrepare) { .cond = TCG_COND_NE, .reg = reg,
.mask = CC_S | CC_Z };
break;
}
break;
}
if (inv) {
cc.cond = tcg_invert_cond(cc.cond);
}
return cc;
}
static void gen_setcc1(DisasContext *s, int b, TCGv reg)
{
CCPrepare cc = gen_prepare_cc(s, b, reg);
if (cc.no_setcond) {
if (cc.cond == TCG_COND_EQ) {
tcg_gen_xori_tl(reg, cc.reg, 1);
} else {
tcg_gen_mov_tl(reg, cc.reg);
}
return;
}
if (cc.cond == TCG_COND_NE && !cc.use_reg2 && cc.imm == 0 &&
cc.mask != 0 && (cc.mask & (cc.mask - 1)) == 0) {
tcg_gen_shri_tl(reg, cc.reg, ctztl(cc.mask));
tcg_gen_andi_tl(reg, reg, 1);
return;
}
if (cc.mask != -1) {
tcg_gen_andi_tl(reg, cc.reg, cc.mask);
cc.reg = reg;
}
if (cc.use_reg2) {
tcg_gen_setcond_tl(cc.cond, reg, cc.reg, cc.reg2);
} else {
tcg_gen_setcondi_tl(cc.cond, reg, cc.reg, cc.imm);
}
}
static inline void gen_compute_eflags_c(DisasContext *s, TCGv reg)
{
gen_setcc1(s, JCC_B << 1, reg);
}
/* generate a conditional jump to label 'l1' according to jump opcode
value 'b'. In the fast case, T0 is guaranted not to be used. */
static inline void gen_jcc1_noeob(DisasContext *s, int b, TCGLabel *l1)
{
CCPrepare cc = gen_prepare_cc(s, b, cpu_T0);
if (cc.mask != -1) {
tcg_gen_andi_tl(cpu_T0, cc.reg, cc.mask);
cc.reg = cpu_T0;
}
if (cc.use_reg2) {
tcg_gen_brcond_tl(cc.cond, cc.reg, cc.reg2, l1);
} else {
tcg_gen_brcondi_tl(cc.cond, cc.reg, cc.imm, l1);
}
}
/* Generate a conditional jump to label 'l1' according to jump opcode
value 'b'. In the fast case, T0 is guaranted not to be used.
A translation block must end soon. */
static inline void gen_jcc1(DisasContext *s, int b, TCGLabel *l1)
{
CCPrepare cc = gen_prepare_cc(s, b, cpu_T0);
gen_update_cc_op(s);
if (cc.mask != -1) {
tcg_gen_andi_tl(cpu_T0, cc.reg, cc.mask);
cc.reg = cpu_T0;
}
set_cc_op(s, CC_OP_DYNAMIC);
if (cc.use_reg2) {
tcg_gen_brcond_tl(cc.cond, cc.reg, cc.reg2, l1);
} else {
tcg_gen_brcondi_tl(cc.cond, cc.reg, cc.imm, l1);
}
}
/* XXX: does not work with gdbstub "ice" single step - not a
serious problem */
static TCGLabel *gen_jz_ecx_string(DisasContext *s, target_ulong next_eip)
{
TCGLabel *l1 = gen_new_label();
TCGLabel *l2 = gen_new_label();
gen_op_jnz_ecx(s->aflag, l1);
gen_set_label(l2);
gen_jmp_tb(s, next_eip, 1);
gen_set_label(l1);
return l2;
}
static inline void gen_stos(DisasContext *s, TCGMemOp ot)
{
gen_op_mov_v_reg(MO_32, cpu_T0, R_EAX);
gen_string_movl_A0_EDI(s);
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_EDI);
}
static inline void gen_lods(DisasContext *s, TCGMemOp ot)
{
gen_string_movl_A0_ESI(s);
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
gen_op_mov_reg_v(ot, R_EAX, cpu_T0);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_ESI);
}
static inline void gen_scas(DisasContext *s, TCGMemOp ot)
{
gen_string_movl_A0_EDI(s);
gen_op_ld_v(s, ot, cpu_T1, cpu_A0);
gen_op(s, OP_CMPL, ot, R_EAX);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_EDI);
}
static inline void gen_cmps(DisasContext *s, TCGMemOp ot)
{
gen_string_movl_A0_EDI(s);
gen_op_ld_v(s, ot, cpu_T1, cpu_A0);
gen_string_movl_A0_ESI(s);
gen_op(s, OP_CMPL, ot, OR_TMP0);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_ESI);
gen_op_add_reg_T0(s->aflag, R_EDI);
}
static void gen_bpt_io(DisasContext *s, TCGv_i32 t_port, int ot)
{
if (s->flags & HF_IOBPT_MASK) {
TCGv_i32 t_size = tcg_const_i32(1 << ot);
TCGv t_next = tcg_const_tl(s->pc - s->cs_base);
gen_helper_bpt_io(cpu_env, t_port, t_size, t_next);
tcg_temp_free_i32(t_size);
tcg_temp_free(t_next);
}
}
static inline void gen_ins(DisasContext *s, TCGMemOp ot)
{
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_start();
}
gen_string_movl_A0_EDI(s);
/* Note: we must do this dummy write first to be restartable in
case of page fault. */
tcg_gen_movi_tl(cpu_T0, 0);
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_EDX]);
tcg_gen_andi_i32(cpu_tmp2_i32, cpu_tmp2_i32, 0xffff);
gen_helper_in_func(ot, cpu_T0, cpu_tmp2_i32);
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_EDI);
gen_bpt_io(s, cpu_tmp2_i32, ot);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_end();
}
}
static inline void gen_outs(DisasContext *s, TCGMemOp ot)
{
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_start();
}
gen_string_movl_A0_ESI(s);
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_EDX]);
tcg_gen_andi_i32(cpu_tmp2_i32, cpu_tmp2_i32, 0xffff);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T0);
gen_helper_out_func(ot, cpu_tmp2_i32, cpu_tmp3_i32);
gen_op_movl_T0_Dshift(ot);
gen_op_add_reg_T0(s->aflag, R_ESI);
gen_bpt_io(s, cpu_tmp2_i32, ot);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_end();
}
}
/* same method as Valgrind : we generate jumps to current or next
instruction */
#define GEN_REPZ(op) \
static inline void gen_repz_ ## op(DisasContext *s, TCGMemOp ot, \
target_ulong cur_eip, target_ulong next_eip) \
{ \
TCGLabel *l2; \
gen_update_cc_op(s); \
l2 = gen_jz_ecx_string(s, next_eip); \
gen_ ## op(s, ot); \
gen_op_add_reg_im(s->aflag, R_ECX, -1); \
/* a loop would cause two single step exceptions if ECX = 1 \
before rep string_insn */ \
if (s->repz_opt) \
gen_op_jz_ecx(s->aflag, l2); \
gen_jmp(s, cur_eip); \
}
#define GEN_REPZ2(op) \
static inline void gen_repz_ ## op(DisasContext *s, TCGMemOp ot, \
target_ulong cur_eip, \
target_ulong next_eip, \
int nz) \
{ \
TCGLabel *l2; \
gen_update_cc_op(s); \
l2 = gen_jz_ecx_string(s, next_eip); \
gen_ ## op(s, ot); \
gen_op_add_reg_im(s->aflag, R_ECX, -1); \
gen_update_cc_op(s); \
gen_jcc1(s, (JCC_Z << 1) | (nz ^ 1), l2); \
if (s->repz_opt) \
gen_op_jz_ecx(s->aflag, l2); \
gen_jmp(s, cur_eip); \
}
GEN_REPZ(movs)
GEN_REPZ(stos)
GEN_REPZ(lods)
GEN_REPZ(ins)
GEN_REPZ(outs)
GEN_REPZ2(scas)
GEN_REPZ2(cmps)
static void gen_helper_fp_arith_ST0_FT0(int op)
{
switch (op) {
case 0:
gen_helper_fadd_ST0_FT0(cpu_env);
break;
case 1:
gen_helper_fmul_ST0_FT0(cpu_env);
break;
case 2:
gen_helper_fcom_ST0_FT0(cpu_env);
break;
case 3:
gen_helper_fcom_ST0_FT0(cpu_env);
break;
case 4:
gen_helper_fsub_ST0_FT0(cpu_env);
break;
case 5:
gen_helper_fsubr_ST0_FT0(cpu_env);
break;
case 6:
gen_helper_fdiv_ST0_FT0(cpu_env);
break;
case 7:
gen_helper_fdivr_ST0_FT0(cpu_env);
break;
}
}
/* NOTE the exception in "r" op ordering */
static void gen_helper_fp_arith_STN_ST0(int op, int opreg)
{
TCGv_i32 tmp = tcg_const_i32(opreg);
switch (op) {
case 0:
gen_helper_fadd_STN_ST0(cpu_env, tmp);
break;
case 1:
gen_helper_fmul_STN_ST0(cpu_env, tmp);
break;
case 4:
gen_helper_fsubr_STN_ST0(cpu_env, tmp);
break;
case 5:
gen_helper_fsub_STN_ST0(cpu_env, tmp);
break;
case 6:
gen_helper_fdivr_STN_ST0(cpu_env, tmp);
break;
case 7:
gen_helper_fdiv_STN_ST0(cpu_env, tmp);
break;
}
}
/* if d == OR_TMP0, it means memory operand (address in A0) */
static void gen_op(DisasContext *s1, int op, TCGMemOp ot, int d)
{
if (d != OR_TMP0) {
gen_op_mov_v_reg(ot, cpu_T0, d);
} else if (!(s1->prefix & PREFIX_LOCK)) {
gen_op_ld_v(s1, ot, cpu_T0, cpu_A0);
}
switch(op) {
case OP_ADCL:
gen_compute_eflags_c(s1, cpu_tmp4);
if (s1->prefix & PREFIX_LOCK) {
tcg_gen_add_tl(cpu_T0, cpu_tmp4, cpu_T1);
tcg_gen_atomic_add_fetch_tl(cpu_T0, cpu_A0, cpu_T0,
s1->mem_index, ot | MO_LE);
} else {
tcg_gen_add_tl(cpu_T0, cpu_T0, cpu_T1);
tcg_gen_add_tl(cpu_T0, cpu_T0, cpu_tmp4);
gen_op_st_rm_T0_A0(s1, ot, d);
}
gen_op_update3_cc(cpu_tmp4);
set_cc_op(s1, CC_OP_ADCB + ot);
break;
case OP_SBBL:
gen_compute_eflags_c(s1, cpu_tmp4);
if (s1->prefix & PREFIX_LOCK) {
tcg_gen_add_tl(cpu_T0, cpu_T1, cpu_tmp4);
tcg_gen_neg_tl(cpu_T0, cpu_T0);
tcg_gen_atomic_add_fetch_tl(cpu_T0, cpu_A0, cpu_T0,
s1->mem_index, ot | MO_LE);
} else {
tcg_gen_sub_tl(cpu_T0, cpu_T0, cpu_T1);
tcg_gen_sub_tl(cpu_T0, cpu_T0, cpu_tmp4);
gen_op_st_rm_T0_A0(s1, ot, d);
}
gen_op_update3_cc(cpu_tmp4);
set_cc_op(s1, CC_OP_SBBB + ot);
break;
case OP_ADDL:
if (s1->prefix & PREFIX_LOCK) {
tcg_gen_atomic_add_fetch_tl(cpu_T0, cpu_A0, cpu_T1,
s1->mem_index, ot | MO_LE);
} else {
tcg_gen_add_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_st_rm_T0_A0(s1, ot, d);
}
gen_op_update2_cc();
set_cc_op(s1, CC_OP_ADDB + ot);
break;
case OP_SUBL:
if (s1->prefix & PREFIX_LOCK) {
tcg_gen_neg_tl(cpu_T0, cpu_T1);
tcg_gen_atomic_fetch_add_tl(cpu_cc_srcT, cpu_A0, cpu_T0,
s1->mem_index, ot | MO_LE);
tcg_gen_sub_tl(cpu_T0, cpu_cc_srcT, cpu_T1);
} else {
tcg_gen_mov_tl(cpu_cc_srcT, cpu_T0);
tcg_gen_sub_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_st_rm_T0_A0(s1, ot, d);
}
gen_op_update2_cc();
set_cc_op(s1, CC_OP_SUBB + ot);
break;
default:
case OP_ANDL:
if (s1->prefix & PREFIX_LOCK) {
tcg_gen_atomic_and_fetch_tl(cpu_T0, cpu_A0, cpu_T1,
s1->mem_index, ot | MO_LE);
} else {
tcg_gen_and_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_st_rm_T0_A0(s1, ot, d);
}
gen_op_update1_cc();
set_cc_op(s1, CC_OP_LOGICB + ot);
break;
case OP_ORL:
if (s1->prefix & PREFIX_LOCK) {
tcg_gen_atomic_or_fetch_tl(cpu_T0, cpu_A0, cpu_T1,
s1->mem_index, ot | MO_LE);
} else {
tcg_gen_or_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_st_rm_T0_A0(s1, ot, d);
}
gen_op_update1_cc();
set_cc_op(s1, CC_OP_LOGICB + ot);
break;
case OP_XORL:
if (s1->prefix & PREFIX_LOCK) {
tcg_gen_atomic_xor_fetch_tl(cpu_T0, cpu_A0, cpu_T1,
s1->mem_index, ot | MO_LE);
} else {
tcg_gen_xor_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_st_rm_T0_A0(s1, ot, d);
}
gen_op_update1_cc();
set_cc_op(s1, CC_OP_LOGICB + ot);
break;
case OP_CMPL:
tcg_gen_mov_tl(cpu_cc_src, cpu_T1);
tcg_gen_mov_tl(cpu_cc_srcT, cpu_T0);
tcg_gen_sub_tl(cpu_cc_dst, cpu_T0, cpu_T1);
set_cc_op(s1, CC_OP_SUBB + ot);
break;
}
}
/* if d == OR_TMP0, it means memory operand (address in A0) */
static void gen_inc(DisasContext *s1, TCGMemOp ot, int d, int c)
{
if (s1->prefix & PREFIX_LOCK) {
tcg_gen_movi_tl(cpu_T0, c > 0 ? 1 : -1);
tcg_gen_atomic_add_fetch_tl(cpu_T0, cpu_A0, cpu_T0,
s1->mem_index, ot | MO_LE);
} else {
if (d != OR_TMP0) {
gen_op_mov_v_reg(ot, cpu_T0, d);
} else {
gen_op_ld_v(s1, ot, cpu_T0, cpu_A0);
}
tcg_gen_addi_tl(cpu_T0, cpu_T0, (c > 0 ? 1 : -1));
gen_op_st_rm_T0_A0(s1, ot, d);
}
gen_compute_eflags_c(s1, cpu_cc_src);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
set_cc_op(s1, (c > 0 ? CC_OP_INCB : CC_OP_DECB) + ot);
}
static void gen_shift_flags(DisasContext *s, TCGMemOp ot, TCGv result,
TCGv shm1, TCGv count, bool is_right)
{
TCGv_i32 z32, s32, oldop;
TCGv z_tl;
/* Store the results into the CC variables. If we know that the
variable must be dead, store unconditionally. Otherwise we'll
need to not disrupt the current contents. */
z_tl = tcg_const_tl(0);
if (cc_op_live[s->cc_op] & USES_CC_DST) {
tcg_gen_movcond_tl(TCG_COND_NE, cpu_cc_dst, count, z_tl,
result, cpu_cc_dst);
} else {
tcg_gen_mov_tl(cpu_cc_dst, result);
}
if (cc_op_live[s->cc_op] & USES_CC_SRC) {
tcg_gen_movcond_tl(TCG_COND_NE, cpu_cc_src, count, z_tl,
shm1, cpu_cc_src);
} else {
tcg_gen_mov_tl(cpu_cc_src, shm1);
}
tcg_temp_free(z_tl);
/* Get the two potential CC_OP values into temporaries. */
tcg_gen_movi_i32(cpu_tmp2_i32, (is_right ? CC_OP_SARB : CC_OP_SHLB) + ot);
if (s->cc_op == CC_OP_DYNAMIC) {
oldop = cpu_cc_op;
} else {
tcg_gen_movi_i32(cpu_tmp3_i32, s->cc_op);
oldop = cpu_tmp3_i32;
}
/* Conditionally store the CC_OP value. */
z32 = tcg_const_i32(0);
s32 = tcg_temp_new_i32();
tcg_gen_trunc_tl_i32(s32, count);
tcg_gen_movcond_i32(TCG_COND_NE, cpu_cc_op, s32, z32, cpu_tmp2_i32, oldop);
tcg_temp_free_i32(z32);
tcg_temp_free_i32(s32);
/* The CC_OP value is no longer predictable. */
set_cc_op(s, CC_OP_DYNAMIC);
}
static void gen_shift_rm_T1(DisasContext *s, TCGMemOp ot, int op1,
int is_right, int is_arith)
{
target_ulong mask = (ot == MO_64 ? 0x3f : 0x1f);
/* load */
if (op1 == OR_TMP0) {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_v_reg(ot, cpu_T0, op1);
}
tcg_gen_andi_tl(cpu_T1, cpu_T1, mask);
tcg_gen_subi_tl(cpu_tmp0, cpu_T1, 1);
if (is_right) {
if (is_arith) {
gen_exts(ot, cpu_T0);
tcg_gen_sar_tl(cpu_tmp0, cpu_T0, cpu_tmp0);
tcg_gen_sar_tl(cpu_T0, cpu_T0, cpu_T1);
} else {
gen_extu(ot, cpu_T0);
tcg_gen_shr_tl(cpu_tmp0, cpu_T0, cpu_tmp0);
tcg_gen_shr_tl(cpu_T0, cpu_T0, cpu_T1);
}
} else {
tcg_gen_shl_tl(cpu_tmp0, cpu_T0, cpu_tmp0);
tcg_gen_shl_tl(cpu_T0, cpu_T0, cpu_T1);
}
/* store */
gen_op_st_rm_T0_A0(s, ot, op1);
gen_shift_flags(s, ot, cpu_T0, cpu_tmp0, cpu_T1, is_right);
}
static void gen_shift_rm_im(DisasContext *s, TCGMemOp ot, int op1, int op2,
int is_right, int is_arith)
{
int mask = (ot == MO_64 ? 0x3f : 0x1f);
/* load */
if (op1 == OR_TMP0)
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
else
gen_op_mov_v_reg(ot, cpu_T0, op1);
op2 &= mask;
if (op2 != 0) {
if (is_right) {
if (is_arith) {
gen_exts(ot, cpu_T0);
tcg_gen_sari_tl(cpu_tmp4, cpu_T0, op2 - 1);
tcg_gen_sari_tl(cpu_T0, cpu_T0, op2);
} else {
gen_extu(ot, cpu_T0);
tcg_gen_shri_tl(cpu_tmp4, cpu_T0, op2 - 1);
tcg_gen_shri_tl(cpu_T0, cpu_T0, op2);
}
} else {
tcg_gen_shli_tl(cpu_tmp4, cpu_T0, op2 - 1);
tcg_gen_shli_tl(cpu_T0, cpu_T0, op2);
}
}
/* store */
gen_op_st_rm_T0_A0(s, ot, op1);
/* update eflags if non zero shift */
if (op2 != 0) {
tcg_gen_mov_tl(cpu_cc_src, cpu_tmp4);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
set_cc_op(s, (is_right ? CC_OP_SARB : CC_OP_SHLB) + ot);
}
}
static void gen_rot_rm_T1(DisasContext *s, TCGMemOp ot, int op1, int is_right)
{
target_ulong mask = (ot == MO_64 ? 0x3f : 0x1f);
TCGv_i32 t0, t1;
/* load */
if (op1 == OR_TMP0) {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_v_reg(ot, cpu_T0, op1);
}
tcg_gen_andi_tl(cpu_T1, cpu_T1, mask);
switch (ot) {
case MO_8:
/* Replicate the 8-bit input so that a 32-bit rotate works. */
tcg_gen_ext8u_tl(cpu_T0, cpu_T0);
tcg_gen_muli_tl(cpu_T0, cpu_T0, 0x01010101);
goto do_long;
case MO_16:
/* Replicate the 16-bit input so that a 32-bit rotate works. */
tcg_gen_deposit_tl(cpu_T0, cpu_T0, cpu_T0, 16, 16);
goto do_long;
do_long:
#ifdef TARGET_X86_64
case MO_32:
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T1);
if (is_right) {
tcg_gen_rotr_i32(cpu_tmp2_i32, cpu_tmp2_i32, cpu_tmp3_i32);
} else {
tcg_gen_rotl_i32(cpu_tmp2_i32, cpu_tmp2_i32, cpu_tmp3_i32);
}
tcg_gen_extu_i32_tl(cpu_T0, cpu_tmp2_i32);
break;
#endif
default:
if (is_right) {
tcg_gen_rotr_tl(cpu_T0, cpu_T0, cpu_T1);
} else {
tcg_gen_rotl_tl(cpu_T0, cpu_T0, cpu_T1);
}
break;
}
/* store */
gen_op_st_rm_T0_A0(s, ot, op1);
/* We'll need the flags computed into CC_SRC. */
gen_compute_eflags(s);
/* The value that was "rotated out" is now present at the other end
of the word. Compute C into CC_DST and O into CC_SRC2. Note that
since we've computed the flags into CC_SRC, these variables are
currently dead. */
if (is_right) {
tcg_gen_shri_tl(cpu_cc_src2, cpu_T0, mask - 1);
tcg_gen_shri_tl(cpu_cc_dst, cpu_T0, mask);
tcg_gen_andi_tl(cpu_cc_dst, cpu_cc_dst, 1);
} else {
tcg_gen_shri_tl(cpu_cc_src2, cpu_T0, mask);
tcg_gen_andi_tl(cpu_cc_dst, cpu_T0, 1);
}
tcg_gen_andi_tl(cpu_cc_src2, cpu_cc_src2, 1);
tcg_gen_xor_tl(cpu_cc_src2, cpu_cc_src2, cpu_cc_dst);
/* Now conditionally store the new CC_OP value. If the shift count
is 0 we keep the CC_OP_EFLAGS setting so that only CC_SRC is live.
Otherwise reuse CC_OP_ADCOX which have the C and O flags split out
exactly as we computed above. */
t0 = tcg_const_i32(0);
t1 = tcg_temp_new_i32();
tcg_gen_trunc_tl_i32(t1, cpu_T1);
tcg_gen_movi_i32(cpu_tmp2_i32, CC_OP_ADCOX);
tcg_gen_movi_i32(cpu_tmp3_i32, CC_OP_EFLAGS);
tcg_gen_movcond_i32(TCG_COND_NE, cpu_cc_op, t1, t0,
cpu_tmp2_i32, cpu_tmp3_i32);
tcg_temp_free_i32(t0);
tcg_temp_free_i32(t1);
/* The CC_OP value is no longer predictable. */
set_cc_op(s, CC_OP_DYNAMIC);
}
static void gen_rot_rm_im(DisasContext *s, TCGMemOp ot, int op1, int op2,
int is_right)
{
int mask = (ot == MO_64 ? 0x3f : 0x1f);
int shift;
/* load */
if (op1 == OR_TMP0) {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_v_reg(ot, cpu_T0, op1);
}
op2 &= mask;
if (op2 != 0) {
switch (ot) {
#ifdef TARGET_X86_64
case MO_32:
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
if (is_right) {
tcg_gen_rotri_i32(cpu_tmp2_i32, cpu_tmp2_i32, op2);
} else {
tcg_gen_rotli_i32(cpu_tmp2_i32, cpu_tmp2_i32, op2);
}
tcg_gen_extu_i32_tl(cpu_T0, cpu_tmp2_i32);
break;
#endif
default:
if (is_right) {
tcg_gen_rotri_tl(cpu_T0, cpu_T0, op2);
} else {
tcg_gen_rotli_tl(cpu_T0, cpu_T0, op2);
}
break;
case MO_8:
mask = 7;
goto do_shifts;
case MO_16:
mask = 15;
do_shifts:
shift = op2 & mask;
if (is_right) {
shift = mask + 1 - shift;
}
gen_extu(ot, cpu_T0);
tcg_gen_shli_tl(cpu_tmp0, cpu_T0, shift);
tcg_gen_shri_tl(cpu_T0, cpu_T0, mask + 1 - shift);
tcg_gen_or_tl(cpu_T0, cpu_T0, cpu_tmp0);
break;
}
}
/* store */
gen_op_st_rm_T0_A0(s, ot, op1);
if (op2 != 0) {
/* Compute the flags into CC_SRC. */
gen_compute_eflags(s);
/* The value that was "rotated out" is now present at the other end
of the word. Compute C into CC_DST and O into CC_SRC2. Note that
since we've computed the flags into CC_SRC, these variables are
currently dead. */
if (is_right) {
tcg_gen_shri_tl(cpu_cc_src2, cpu_T0, mask - 1);
tcg_gen_shri_tl(cpu_cc_dst, cpu_T0, mask);
tcg_gen_andi_tl(cpu_cc_dst, cpu_cc_dst, 1);
} else {
tcg_gen_shri_tl(cpu_cc_src2, cpu_T0, mask);
tcg_gen_andi_tl(cpu_cc_dst, cpu_T0, 1);
}
tcg_gen_andi_tl(cpu_cc_src2, cpu_cc_src2, 1);
tcg_gen_xor_tl(cpu_cc_src2, cpu_cc_src2, cpu_cc_dst);
set_cc_op(s, CC_OP_ADCOX);
}
}
/* XXX: add faster immediate = 1 case */
static void gen_rotc_rm_T1(DisasContext *s, TCGMemOp ot, int op1,
int is_right)
{
gen_compute_eflags(s);
assert(s->cc_op == CC_OP_EFLAGS);
/* load */
if (op1 == OR_TMP0)
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
else
gen_op_mov_v_reg(ot, cpu_T0, op1);
if (is_right) {
switch (ot) {
case MO_8:
gen_helper_rcrb(cpu_T0, cpu_env, cpu_T0, cpu_T1);
break;
case MO_16:
gen_helper_rcrw(cpu_T0, cpu_env, cpu_T0, cpu_T1);
break;
case MO_32:
gen_helper_rcrl(cpu_T0, cpu_env, cpu_T0, cpu_T1);
break;
#ifdef TARGET_X86_64
case MO_64:
gen_helper_rcrq(cpu_T0, cpu_env, cpu_T0, cpu_T1);
break;
#endif
default:
tcg_abort();
}
} else {
switch (ot) {
case MO_8:
gen_helper_rclb(cpu_T0, cpu_env, cpu_T0, cpu_T1);
break;
case MO_16:
gen_helper_rclw(cpu_T0, cpu_env, cpu_T0, cpu_T1);
break;
case MO_32:
gen_helper_rcll(cpu_T0, cpu_env, cpu_T0, cpu_T1);
break;
#ifdef TARGET_X86_64
case MO_64:
gen_helper_rclq(cpu_T0, cpu_env, cpu_T0, cpu_T1);
break;
#endif
default:
tcg_abort();
}
}
/* store */
gen_op_st_rm_T0_A0(s, ot, op1);
}
/* XXX: add faster immediate case */
static void gen_shiftd_rm_T1(DisasContext *s, TCGMemOp ot, int op1,
bool is_right, TCGv count_in)
{
target_ulong mask = (ot == MO_64 ? 63 : 31);
TCGv count;
/* load */
if (op1 == OR_TMP0) {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_v_reg(ot, cpu_T0, op1);
}
count = tcg_temp_new();
tcg_gen_andi_tl(count, count_in, mask);
switch (ot) {
case MO_16:
/* Note: we implement the Intel behaviour for shift count > 16.
This means "shrdw C, B, A" shifts A:B:A >> C. Build the B:A
portion by constructing it as a 32-bit value. */
if (is_right) {
tcg_gen_deposit_tl(cpu_tmp0, cpu_T0, cpu_T1, 16, 16);
tcg_gen_mov_tl(cpu_T1, cpu_T0);
tcg_gen_mov_tl(cpu_T0, cpu_tmp0);
} else {
tcg_gen_deposit_tl(cpu_T1, cpu_T0, cpu_T1, 16, 16);
}
/* FALLTHRU */
#ifdef TARGET_X86_64
case MO_32:
/* Concatenate the two 32-bit values and use a 64-bit shift. */
tcg_gen_subi_tl(cpu_tmp0, count, 1);
if (is_right) {
tcg_gen_concat_tl_i64(cpu_T0, cpu_T0, cpu_T1);
tcg_gen_shr_i64(cpu_tmp0, cpu_T0, cpu_tmp0);
tcg_gen_shr_i64(cpu_T0, cpu_T0, count);
} else {
tcg_gen_concat_tl_i64(cpu_T0, cpu_T1, cpu_T0);
tcg_gen_shl_i64(cpu_tmp0, cpu_T0, cpu_tmp0);
tcg_gen_shl_i64(cpu_T0, cpu_T0, count);
tcg_gen_shri_i64(cpu_tmp0, cpu_tmp0, 32);
tcg_gen_shri_i64(cpu_T0, cpu_T0, 32);
}
break;
#endif
default:
tcg_gen_subi_tl(cpu_tmp0, count, 1);
if (is_right) {
tcg_gen_shr_tl(cpu_tmp0, cpu_T0, cpu_tmp0);
tcg_gen_subfi_tl(cpu_tmp4, mask + 1, count);
tcg_gen_shr_tl(cpu_T0, cpu_T0, count);
tcg_gen_shl_tl(cpu_T1, cpu_T1, cpu_tmp4);
} else {
tcg_gen_shl_tl(cpu_tmp0, cpu_T0, cpu_tmp0);
if (ot == MO_16) {
/* Only needed if count > 16, for Intel behaviour. */
tcg_gen_subfi_tl(cpu_tmp4, 33, count);
tcg_gen_shr_tl(cpu_tmp4, cpu_T1, cpu_tmp4);
tcg_gen_or_tl(cpu_tmp0, cpu_tmp0, cpu_tmp4);
}
tcg_gen_subfi_tl(cpu_tmp4, mask + 1, count);
tcg_gen_shl_tl(cpu_T0, cpu_T0, count);
tcg_gen_shr_tl(cpu_T1, cpu_T1, cpu_tmp4);
}
tcg_gen_movi_tl(cpu_tmp4, 0);
tcg_gen_movcond_tl(TCG_COND_EQ, cpu_T1, count, cpu_tmp4,
cpu_tmp4, cpu_T1);
tcg_gen_or_tl(cpu_T0, cpu_T0, cpu_T1);
break;
}
/* store */
gen_op_st_rm_T0_A0(s, ot, op1);
gen_shift_flags(s, ot, cpu_T0, cpu_tmp0, count, is_right);
tcg_temp_free(count);
}
static void gen_shift(DisasContext *s1, int op, TCGMemOp ot, int d, int s)
{
if (s != OR_TMP1)
gen_op_mov_v_reg(ot, cpu_T1, s);
switch(op) {
case OP_ROL:
gen_rot_rm_T1(s1, ot, d, 0);
break;
case OP_ROR:
gen_rot_rm_T1(s1, ot, d, 1);
break;
case OP_SHL:
case OP_SHL1:
gen_shift_rm_T1(s1, ot, d, 0, 0);
break;
case OP_SHR:
gen_shift_rm_T1(s1, ot, d, 1, 0);
break;
case OP_SAR:
gen_shift_rm_T1(s1, ot, d, 1, 1);
break;
case OP_RCL:
gen_rotc_rm_T1(s1, ot, d, 0);
break;
case OP_RCR:
gen_rotc_rm_T1(s1, ot, d, 1);
break;
}
}
static void gen_shifti(DisasContext *s1, int op, TCGMemOp ot, int d, int c)
{
switch(op) {
case OP_ROL:
gen_rot_rm_im(s1, ot, d, c, 0);
break;
case OP_ROR:
gen_rot_rm_im(s1, ot, d, c, 1);
break;
case OP_SHL:
case OP_SHL1:
gen_shift_rm_im(s1, ot, d, c, 0, 0);
break;
case OP_SHR:
gen_shift_rm_im(s1, ot, d, c, 1, 0);
break;
case OP_SAR:
gen_shift_rm_im(s1, ot, d, c, 1, 1);
break;
default:
/* currently not optimized */
tcg_gen_movi_tl(cpu_T1, c);
gen_shift(s1, op, ot, d, OR_TMP1);
break;
}
}
/* Decompose an address. */
typedef struct AddressParts {
int def_seg;
int base;
int index;
int scale;
target_long disp;
} AddressParts;
static AddressParts gen_lea_modrm_0(CPUX86State *env, DisasContext *s,
int modrm)
{
int def_seg, base, index, scale, mod, rm;
target_long disp;
bool havesib;
def_seg = R_DS;
index = -1;
scale = 0;
disp = 0;
mod = (modrm >> 6) & 3;
rm = modrm & 7;
base = rm | REX_B(s);
if (mod == 3) {
/* Normally filtered out earlier, but including this path
simplifies multi-byte nop, as well as bndcl, bndcu, bndcn. */
goto done;
}
switch (s->aflag) {
case MO_64:
case MO_32:
havesib = 0;
if (rm == 4) {
int code = cpu_ldub_code(env, s->pc++);
scale = (code >> 6) & 3;
index = ((code >> 3) & 7) | REX_X(s);
if (index == 4) {
index = -1; /* no index */
}
base = (code & 7) | REX_B(s);
havesib = 1;
}
switch (mod) {
case 0:
if ((base & 7) == 5) {
base = -1;
disp = (int32_t)cpu_ldl_code(env, s->pc);
s->pc += 4;
if (CODE64(s) && !havesib) {
base = -2;
disp += s->pc + s->rip_offset;
}
}
break;
case 1:
disp = (int8_t)cpu_ldub_code(env, s->pc++);
break;
default:
case 2:
disp = (int32_t)cpu_ldl_code(env, s->pc);
s->pc += 4;
break;
}
/* For correct popl handling with esp. */
if (base == R_ESP && s->popl_esp_hack) {
disp += s->popl_esp_hack;
}
if (base == R_EBP || base == R_ESP) {
def_seg = R_SS;
}
break;
case MO_16:
if (mod == 0) {
if (rm == 6) {
base = -1;
disp = cpu_lduw_code(env, s->pc);
s->pc += 2;
break;
}
} else if (mod == 1) {
disp = (int8_t)cpu_ldub_code(env, s->pc++);
} else {
disp = (int16_t)cpu_lduw_code(env, s->pc);
s->pc += 2;
}
switch (rm) {
case 0:
base = R_EBX;
index = R_ESI;
break;
case 1:
base = R_EBX;
index = R_EDI;
break;
case 2:
base = R_EBP;
index = R_ESI;
def_seg = R_SS;
break;
case 3:
base = R_EBP;
index = R_EDI;
def_seg = R_SS;
break;
case 4:
base = R_ESI;
break;
case 5:
base = R_EDI;
break;
case 6:
base = R_EBP;
def_seg = R_SS;
break;
default:
case 7:
base = R_EBX;
break;
}
break;
default:
tcg_abort();
}
done:
return (AddressParts){ def_seg, base, index, scale, disp };
}
/* Compute the address, with a minimum number of TCG ops. */
static TCGv gen_lea_modrm_1(AddressParts a)
{
TCGv ea;
TCGV_UNUSED(ea);
if (a.index >= 0) {
if (a.scale == 0) {
ea = cpu_regs[a.index];
} else {
tcg_gen_shli_tl(cpu_A0, cpu_regs[a.index], a.scale);
ea = cpu_A0;
}
if (a.base >= 0) {
tcg_gen_add_tl(cpu_A0, ea, cpu_regs[a.base]);
ea = cpu_A0;
}
} else if (a.base >= 0) {
ea = cpu_regs[a.base];
}
if (TCGV_IS_UNUSED(ea)) {
tcg_gen_movi_tl(cpu_A0, a.disp);
ea = cpu_A0;
} else if (a.disp != 0) {
tcg_gen_addi_tl(cpu_A0, ea, a.disp);
ea = cpu_A0;
}
return ea;
}
static void gen_lea_modrm(CPUX86State *env, DisasContext *s, int modrm)
{
AddressParts a = gen_lea_modrm_0(env, s, modrm);
TCGv ea = gen_lea_modrm_1(a);
gen_lea_v_seg(s, s->aflag, ea, a.def_seg, s->override);
}
static void gen_nop_modrm(CPUX86State *env, DisasContext *s, int modrm)
{
(void)gen_lea_modrm_0(env, s, modrm);
}
/* Used for BNDCL, BNDCU, BNDCN. */
static void gen_bndck(CPUX86State *env, DisasContext *s, int modrm,
TCGCond cond, TCGv_i64 bndv)
{
TCGv ea = gen_lea_modrm_1(gen_lea_modrm_0(env, s, modrm));
tcg_gen_extu_tl_i64(cpu_tmp1_i64, ea);
if (!CODE64(s)) {
tcg_gen_ext32u_i64(cpu_tmp1_i64, cpu_tmp1_i64);
}
tcg_gen_setcond_i64(cond, cpu_tmp1_i64, cpu_tmp1_i64, bndv);
tcg_gen_extrl_i64_i32(cpu_tmp2_i32, cpu_tmp1_i64);
gen_helper_bndck(cpu_env, cpu_tmp2_i32);
}
/* used for LEA and MOV AX, mem */
static void gen_add_A0_ds_seg(DisasContext *s)
{
gen_lea_v_seg(s, s->aflag, cpu_A0, R_DS, s->override);
}
/* generate modrm memory load or store of 'reg'. TMP0 is used if reg ==
OR_TMP0 */
static void gen_ldst_modrm(CPUX86State *env, DisasContext *s, int modrm,
TCGMemOp ot, int reg, int is_store)
{
int mod, rm;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
if (mod == 3) {
if (is_store) {
if (reg != OR_TMP0)
gen_op_mov_v_reg(ot, cpu_T0, reg);
gen_op_mov_reg_v(ot, rm, cpu_T0);
} else {
gen_op_mov_v_reg(ot, cpu_T0, rm);
if (reg != OR_TMP0)
gen_op_mov_reg_v(ot, reg, cpu_T0);
}
} else {
gen_lea_modrm(env, s, modrm);
if (is_store) {
if (reg != OR_TMP0)
gen_op_mov_v_reg(ot, cpu_T0, reg);
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
if (reg != OR_TMP0)
gen_op_mov_reg_v(ot, reg, cpu_T0);
}
}
}
static inline uint32_t insn_get(CPUX86State *env, DisasContext *s, TCGMemOp ot)
{
uint32_t ret;
switch (ot) {
case MO_8:
ret = cpu_ldub_code(env, s->pc);
s->pc++;
break;
case MO_16:
ret = cpu_lduw_code(env, s->pc);
s->pc += 2;
break;
case MO_32:
#ifdef TARGET_X86_64
case MO_64:
#endif
ret = cpu_ldl_code(env, s->pc);
s->pc += 4;
break;
default:
tcg_abort();
}
return ret;
}
static inline int insn_const_size(TCGMemOp ot)
{
if (ot <= MO_32) {
return 1 << ot;
} else {
return 4;
}
}
static inline bool use_goto_tb(DisasContext *s, target_ulong pc)
{
#ifndef CONFIG_USER_ONLY
return (pc & TARGET_PAGE_MASK) == (s->tb->pc & TARGET_PAGE_MASK) ||
(pc & TARGET_PAGE_MASK) == (s->pc_start & TARGET_PAGE_MASK);
#else
return true;
#endif
}
static inline void gen_goto_tb(DisasContext *s, int tb_num, target_ulong eip)
{
target_ulong pc = s->cs_base + eip;
if (use_goto_tb(s, pc)) {
/* jump to same page: we can use a direct jump */
tcg_gen_goto_tb(tb_num);
gen_jmp_im(eip);
tcg_gen_exit_tb((uintptr_t)s->tb + tb_num);
} else {
/* jump to another page: currently not optimized */
gen_jmp_im(eip);
gen_eob(s);
}
}
static inline void gen_jcc(DisasContext *s, int b,
target_ulong val, target_ulong next_eip)
{
TCGLabel *l1, *l2;
if (s->jmp_opt) {
l1 = gen_new_label();
gen_jcc1(s, b, l1);
gen_goto_tb(s, 0, next_eip);
gen_set_label(l1);
gen_goto_tb(s, 1, val);
s->is_jmp = DISAS_TB_JUMP;
} else {
l1 = gen_new_label();
l2 = gen_new_label();
gen_jcc1(s, b, l1);
gen_jmp_im(next_eip);
tcg_gen_br(l2);
gen_set_label(l1);
gen_jmp_im(val);
gen_set_label(l2);
gen_eob(s);
}
}
static void gen_cmovcc1(CPUX86State *env, DisasContext *s, TCGMemOp ot, int b,
int modrm, int reg)
{
CCPrepare cc;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
cc = gen_prepare_cc(s, b, cpu_T1);
if (cc.mask != -1) {
TCGv t0 = tcg_temp_new();
tcg_gen_andi_tl(t0, cc.reg, cc.mask);
cc.reg = t0;
}
if (!cc.use_reg2) {
cc.reg2 = tcg_const_tl(cc.imm);
}
tcg_gen_movcond_tl(cc.cond, cpu_T0, cc.reg, cc.reg2,
cpu_T0, cpu_regs[reg]);
gen_op_mov_reg_v(ot, reg, cpu_T0);
if (cc.mask != -1) {
tcg_temp_free(cc.reg);
}
if (!cc.use_reg2) {
tcg_temp_free(cc.reg2);
}
}
static inline void gen_op_movl_T0_seg(int seg_reg)
{
tcg_gen_ld32u_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,segs[seg_reg].selector));
}
static inline void gen_op_movl_seg_T0_vm(int seg_reg)
{
tcg_gen_ext16u_tl(cpu_T0, cpu_T0);
tcg_gen_st32_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,segs[seg_reg].selector));
tcg_gen_shli_tl(cpu_seg_base[seg_reg], cpu_T0, 4);
}
/* move T0 to seg_reg and compute if the CPU state may change. Never
call this function with seg_reg == R_CS */
static void gen_movl_seg_T0(DisasContext *s, int seg_reg)
{
if (s->pe && !s->vm86) {
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_load_seg(cpu_env, tcg_const_i32(seg_reg), cpu_tmp2_i32);
/* abort translation because the addseg value may change or
because ss32 may change. For R_SS, translation must always
stop as a special handling must be done to disable hardware
interrupts for the next instruction */
if (seg_reg == R_SS || (s->code32 && seg_reg < R_FS))
s->is_jmp = DISAS_TB_JUMP;
} else {
gen_op_movl_seg_T0_vm(seg_reg);
if (seg_reg == R_SS)
s->is_jmp = DISAS_TB_JUMP;
}
}
static inline int svm_is_rep(int prefixes)
{
return ((prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) ? 8 : 0);
}
static inline void
gen_svm_check_intercept_param(DisasContext *s, target_ulong pc_start,
uint32_t type, uint64_t param)
{
/* no SVM activated; fast case */
if (likely(!(s->flags & HF_SVMI_MASK)))
return;
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_svm_check_intercept_param(cpu_env, tcg_const_i32(type),
tcg_const_i64(param));
}
static inline void
gen_svm_check_intercept(DisasContext *s, target_ulong pc_start, uint64_t type)
{
gen_svm_check_intercept_param(s, pc_start, type, 0);
}
static inline void gen_stack_update(DisasContext *s, int addend)
{
gen_op_add_reg_im(mo_stacksize(s), R_ESP, addend);
}
/* Generate a push. It depends on ss32, addseg and dflag. */
static void gen_push_v(DisasContext *s, TCGv val)
{
TCGMemOp d_ot = mo_pushpop(s, s->dflag);
TCGMemOp a_ot = mo_stacksize(s);
int size = 1 << d_ot;
TCGv new_esp = cpu_A0;
tcg_gen_subi_tl(cpu_A0, cpu_regs[R_ESP], size);
if (!CODE64(s)) {
if (s->addseg) {
new_esp = cpu_tmp4;
tcg_gen_mov_tl(new_esp, cpu_A0);
}
gen_lea_v_seg(s, a_ot, cpu_A0, R_SS, -1);
}
gen_op_st_v(s, d_ot, val, cpu_A0);
gen_op_mov_reg_v(a_ot, R_ESP, new_esp);
}
/* two step pop is necessary for precise exceptions */
static TCGMemOp gen_pop_T0(DisasContext *s)
{
TCGMemOp d_ot = mo_pushpop(s, s->dflag);
gen_lea_v_seg(s, mo_stacksize(s), cpu_regs[R_ESP], R_SS, -1);
gen_op_ld_v(s, d_ot, cpu_T0, cpu_A0);
return d_ot;
}
static inline void gen_pop_update(DisasContext *s, TCGMemOp ot)
{
gen_stack_update(s, 1 << ot);
}
static inline void gen_stack_A0(DisasContext *s)
{
gen_lea_v_seg(s, s->ss32 ? MO_32 : MO_16, cpu_regs[R_ESP], R_SS, -1);
}
static void gen_pusha(DisasContext *s)
{
TCGMemOp s_ot = s->ss32 ? MO_32 : MO_16;
TCGMemOp d_ot = s->dflag;
int size = 1 << d_ot;
int i;
for (i = 0; i < 8; i++) {
tcg_gen_addi_tl(cpu_A0, cpu_regs[R_ESP], (i - 8) * size);
gen_lea_v_seg(s, s_ot, cpu_A0, R_SS, -1);
gen_op_st_v(s, d_ot, cpu_regs[7 - i], cpu_A0);
}
gen_stack_update(s, -8 * size);
}
static void gen_popa(DisasContext *s)
{
TCGMemOp s_ot = s->ss32 ? MO_32 : MO_16;
TCGMemOp d_ot = s->dflag;
int size = 1 << d_ot;
int i;
for (i = 0; i < 8; i++) {
/* ESP is not reloaded */
if (7 - i == R_ESP) {
continue;
}
tcg_gen_addi_tl(cpu_A0, cpu_regs[R_ESP], i * size);
gen_lea_v_seg(s, s_ot, cpu_A0, R_SS, -1);
gen_op_ld_v(s, d_ot, cpu_T0, cpu_A0);
gen_op_mov_reg_v(d_ot, 7 - i, cpu_T0);
}
gen_stack_update(s, 8 * size);
}
static void gen_enter(DisasContext *s, int esp_addend, int level)
{
TCGMemOp d_ot = mo_pushpop(s, s->dflag);
TCGMemOp a_ot = CODE64(s) ? MO_64 : s->ss32 ? MO_32 : MO_16;
int size = 1 << d_ot;
/* Push BP; compute FrameTemp into T1. */
tcg_gen_subi_tl(cpu_T1, cpu_regs[R_ESP], size);
gen_lea_v_seg(s, a_ot, cpu_T1, R_SS, -1);
gen_op_st_v(s, d_ot, cpu_regs[R_EBP], cpu_A0);
level &= 31;
if (level != 0) {
int i;
/* Copy level-1 pointers from the previous frame. */
for (i = 1; i < level; ++i) {
tcg_gen_subi_tl(cpu_A0, cpu_regs[R_EBP], size * i);
gen_lea_v_seg(s, a_ot, cpu_A0, R_SS, -1);
gen_op_ld_v(s, d_ot, cpu_tmp0, cpu_A0);
tcg_gen_subi_tl(cpu_A0, cpu_T1, size * i);
gen_lea_v_seg(s, a_ot, cpu_A0, R_SS, -1);
gen_op_st_v(s, d_ot, cpu_tmp0, cpu_A0);
}
/* Push the current FrameTemp as the last level. */
tcg_gen_subi_tl(cpu_A0, cpu_T1, size * level);
gen_lea_v_seg(s, a_ot, cpu_A0, R_SS, -1);
gen_op_st_v(s, d_ot, cpu_T1, cpu_A0);
}
/* Copy the FrameTemp value to EBP. */
gen_op_mov_reg_v(a_ot, R_EBP, cpu_T1);
/* Compute the final value of ESP. */
tcg_gen_subi_tl(cpu_T1, cpu_T1, esp_addend + size * level);
gen_op_mov_reg_v(a_ot, R_ESP, cpu_T1);
}
static void gen_leave(DisasContext *s)
{
TCGMemOp d_ot = mo_pushpop(s, s->dflag);
TCGMemOp a_ot = mo_stacksize(s);
gen_lea_v_seg(s, a_ot, cpu_regs[R_EBP], R_SS, -1);
gen_op_ld_v(s, d_ot, cpu_T0, cpu_A0);
tcg_gen_addi_tl(cpu_T1, cpu_regs[R_EBP], 1 << d_ot);
gen_op_mov_reg_v(d_ot, R_EBP, cpu_T0);
gen_op_mov_reg_v(a_ot, R_ESP, cpu_T1);
}
static void gen_exception(DisasContext *s, int trapno, target_ulong cur_eip)
{
gen_update_cc_op(s);
gen_jmp_im(cur_eip);
gen_helper_raise_exception(cpu_env, tcg_const_i32(trapno));
s->is_jmp = DISAS_TB_JUMP;
}
/* Generate #UD for the current instruction. The assumption here is that
the instruction is known, but it isn't allowed in the current cpu mode. */
static void gen_illegal_opcode(DisasContext *s)
{
gen_exception(s, EXCP06_ILLOP, s->pc_start - s->cs_base);
}
/* Similarly, except that the assumption here is that we don't decode
the instruction at all -- either a missing opcode, an unimplemented
feature, or just a bogus instruction stream. */
static void gen_unknown_opcode(CPUX86State *env, DisasContext *s)
{
gen_illegal_opcode(s);
if (qemu_loglevel_mask(LOG_UNIMP)) {
target_ulong pc = s->pc_start, end = s->pc;
qemu_log_lock();
qemu_log("ILLOPC: " TARGET_FMT_lx ":", pc);
for (; pc < end; ++pc) {
qemu_log(" %02x", cpu_ldub_code(env, pc));
}
qemu_log("\n");
qemu_log_unlock();
}
}
/* an interrupt is different from an exception because of the
privilege checks */
static void gen_interrupt(DisasContext *s, int intno,
target_ulong cur_eip, target_ulong next_eip)
{
gen_update_cc_op(s);
gen_jmp_im(cur_eip);
gen_helper_raise_interrupt(cpu_env, tcg_const_i32(intno),
tcg_const_i32(next_eip - cur_eip));
s->is_jmp = DISAS_TB_JUMP;
}
static void gen_debug(DisasContext *s, target_ulong cur_eip)
{
gen_update_cc_op(s);
gen_jmp_im(cur_eip);
gen_helper_debug(cpu_env);
s->is_jmp = DISAS_TB_JUMP;
}
static void gen_set_hflag(DisasContext *s, uint32_t mask)
{
if ((s->flags & mask) == 0) {
TCGv_i32 t = tcg_temp_new_i32();
tcg_gen_ld_i32(t, cpu_env, offsetof(CPUX86State, hflags));
tcg_gen_ori_i32(t, t, mask);
tcg_gen_st_i32(t, cpu_env, offsetof(CPUX86State, hflags));
tcg_temp_free_i32(t);
s->flags |= mask;
}
}
static void gen_reset_hflag(DisasContext *s, uint32_t mask)
{
if (s->flags & mask) {
TCGv_i32 t = tcg_temp_new_i32();
tcg_gen_ld_i32(t, cpu_env, offsetof(CPUX86State, hflags));
tcg_gen_andi_i32(t, t, ~mask);
tcg_gen_st_i32(t, cpu_env, offsetof(CPUX86State, hflags));
tcg_temp_free_i32(t);
s->flags &= ~mask;
}
}
/* Clear BND registers during legacy branches. */
static void gen_bnd_jmp(DisasContext *s)
{
/* Clear the registers only if BND prefix is missing, MPX is enabled,
and if the BNDREGs are known to be in use (non-zero) already.
The helper itself will check BNDPRESERVE at runtime. */
if ((s->prefix & PREFIX_REPNZ) == 0
&& (s->flags & HF_MPX_EN_MASK) != 0
&& (s->flags & HF_MPX_IU_MASK) != 0) {
gen_helper_bnd_jmp(cpu_env);
}
}
/* Generate an end of block. Trace exception is also generated if needed.
If INHIBIT, set HF_INHIBIT_IRQ_MASK if it isn't already set.
If RECHECK_TF, emit a rechecking helper for #DB, ignoring the state of
S->TF. This is used by the syscall/sysret insns. */
static void gen_eob_worker(DisasContext *s, bool inhibit, bool recheck_tf)
{
gen_update_cc_op(s);
/* If several instructions disable interrupts, only the first does it. */
if (inhibit && !(s->flags & HF_INHIBIT_IRQ_MASK)) {
gen_set_hflag(s, HF_INHIBIT_IRQ_MASK);
} else {
gen_reset_hflag(s, HF_INHIBIT_IRQ_MASK);
}
if (s->tb->flags & HF_RF_MASK) {
gen_helper_reset_rf(cpu_env);
}
if (s->singlestep_enabled) {
gen_helper_debug(cpu_env);
} else if (recheck_tf) {
gen_helper_rechecking_single_step(cpu_env);
tcg_gen_exit_tb(0);
} else if (s->tf) {
gen_helper_single_step(cpu_env);
} else {
tcg_gen_exit_tb(0);
}
s->is_jmp = DISAS_TB_JUMP;
}
/* End of block.
If INHIBIT, set HF_INHIBIT_IRQ_MASK if it isn't already set. */
static void gen_eob_inhibit_irq(DisasContext *s, bool inhibit)
{
gen_eob_worker(s, inhibit, false);
}
/* End of block, resetting the inhibit irq flag. */
static void gen_eob(DisasContext *s)
{
gen_eob_worker(s, false, false);
}
/* generate a jump to eip. No segment change must happen before as a
direct call to the next block may occur */
static void gen_jmp_tb(DisasContext *s, target_ulong eip, int tb_num)
{
gen_update_cc_op(s);
set_cc_op(s, CC_OP_DYNAMIC);
if (s->jmp_opt) {
gen_goto_tb(s, tb_num, eip);
s->is_jmp = DISAS_TB_JUMP;
} else {
gen_jmp_im(eip);
gen_eob(s);
}
}
static void gen_jmp(DisasContext *s, target_ulong eip)
{
gen_jmp_tb(s, eip, 0);
}
static inline void gen_ldq_env_A0(DisasContext *s, int offset)
{
tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_A0, s->mem_index, MO_LEQ);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, offset);
}
static inline void gen_stq_env_A0(DisasContext *s, int offset)
{
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, offset);
tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_A0, s->mem_index, MO_LEQ);
}
static inline void gen_ldo_env_A0(DisasContext *s, int offset)
{
int mem_index = s->mem_index;
tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_A0, mem_index, MO_LEQ);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, offset + offsetof(ZMMReg, ZMM_Q(0)));
tcg_gen_addi_tl(cpu_tmp0, cpu_A0, 8);
tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_tmp0, mem_index, MO_LEQ);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, offset + offsetof(ZMMReg, ZMM_Q(1)));
}
static inline void gen_sto_env_A0(DisasContext *s, int offset)
{
int mem_index = s->mem_index;
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, offset + offsetof(ZMMReg, ZMM_Q(0)));
tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_A0, mem_index, MO_LEQ);
tcg_gen_addi_tl(cpu_tmp0, cpu_A0, 8);
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, offset + offsetof(ZMMReg, ZMM_Q(1)));
tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_tmp0, mem_index, MO_LEQ);
}
static inline void gen_op_movo(int d_offset, int s_offset)
{
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, s_offset + offsetof(ZMMReg, ZMM_Q(0)));
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, d_offset + offsetof(ZMMReg, ZMM_Q(0)));
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, s_offset + offsetof(ZMMReg, ZMM_Q(1)));
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, d_offset + offsetof(ZMMReg, ZMM_Q(1)));
}
static inline void gen_op_movq(int d_offset, int s_offset)
{
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, s_offset);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, d_offset);
}
static inline void gen_op_movl(int d_offset, int s_offset)
{
tcg_gen_ld_i32(cpu_tmp2_i32, cpu_env, s_offset);
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, d_offset);
}
static inline void gen_op_movq_env_0(int d_offset)
{
tcg_gen_movi_i64(cpu_tmp1_i64, 0);
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, d_offset);
}
typedef void (*SSEFunc_i_ep)(TCGv_i32 val, TCGv_ptr env, TCGv_ptr reg);
typedef void (*SSEFunc_l_ep)(TCGv_i64 val, TCGv_ptr env, TCGv_ptr reg);
typedef void (*SSEFunc_0_epi)(TCGv_ptr env, TCGv_ptr reg, TCGv_i32 val);
typedef void (*SSEFunc_0_epl)(TCGv_ptr env, TCGv_ptr reg, TCGv_i64 val);
typedef void (*SSEFunc_0_epp)(TCGv_ptr env, TCGv_ptr reg_a, TCGv_ptr reg_b);
typedef void (*SSEFunc_0_eppi)(TCGv_ptr env, TCGv_ptr reg_a, TCGv_ptr reg_b,
TCGv_i32 val);
typedef void (*SSEFunc_0_ppi)(TCGv_ptr reg_a, TCGv_ptr reg_b, TCGv_i32 val);
typedef void (*SSEFunc_0_eppt)(TCGv_ptr env, TCGv_ptr reg_a, TCGv_ptr reg_b,
TCGv val);
#define SSE_SPECIAL ((void *)1)
#define SSE_DUMMY ((void *)2)
#define MMX_OP2(x) { gen_helper_ ## x ## _mmx, gen_helper_ ## x ## _xmm }
#define SSE_FOP(x) { gen_helper_ ## x ## ps, gen_helper_ ## x ## pd, \
gen_helper_ ## x ## ss, gen_helper_ ## x ## sd, }
static const SSEFunc_0_epp sse_op_table1[256][4] = {
/* 3DNow! extensions */
[0x0e] = { SSE_DUMMY }, /* femms */
[0x0f] = { SSE_DUMMY }, /* pf... */
/* pure SSE operations */
[0x10] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movups, movupd, movss, movsd */
[0x11] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movups, movupd, movss, movsd */
[0x12] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movlps, movlpd, movsldup, movddup */
[0x13] = { SSE_SPECIAL, SSE_SPECIAL }, /* movlps, movlpd */
[0x14] = { gen_helper_punpckldq_xmm, gen_helper_punpcklqdq_xmm },
[0x15] = { gen_helper_punpckhdq_xmm, gen_helper_punpckhqdq_xmm },
[0x16] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movhps, movhpd, movshdup */
[0x17] = { SSE_SPECIAL, SSE_SPECIAL }, /* movhps, movhpd */
[0x28] = { SSE_SPECIAL, SSE_SPECIAL }, /* movaps, movapd */
[0x29] = { SSE_SPECIAL, SSE_SPECIAL }, /* movaps, movapd */
[0x2a] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* cvtpi2ps, cvtpi2pd, cvtsi2ss, cvtsi2sd */
[0x2b] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movntps, movntpd, movntss, movntsd */
[0x2c] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* cvttps2pi, cvttpd2pi, cvttsd2si, cvttss2si */
[0x2d] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* cvtps2pi, cvtpd2pi, cvtsd2si, cvtss2si */
[0x2e] = { gen_helper_ucomiss, gen_helper_ucomisd },
[0x2f] = { gen_helper_comiss, gen_helper_comisd },
[0x50] = { SSE_SPECIAL, SSE_SPECIAL }, /* movmskps, movmskpd */
[0x51] = SSE_FOP(sqrt),
[0x52] = { gen_helper_rsqrtps, NULL, gen_helper_rsqrtss, NULL },
[0x53] = { gen_helper_rcpps, NULL, gen_helper_rcpss, NULL },
[0x54] = { gen_helper_pand_xmm, gen_helper_pand_xmm }, /* andps, andpd */
[0x55] = { gen_helper_pandn_xmm, gen_helper_pandn_xmm }, /* andnps, andnpd */
[0x56] = { gen_helper_por_xmm, gen_helper_por_xmm }, /* orps, orpd */
[0x57] = { gen_helper_pxor_xmm, gen_helper_pxor_xmm }, /* xorps, xorpd */
[0x58] = SSE_FOP(add),
[0x59] = SSE_FOP(mul),
[0x5a] = { gen_helper_cvtps2pd, gen_helper_cvtpd2ps,
gen_helper_cvtss2sd, gen_helper_cvtsd2ss },
[0x5b] = { gen_helper_cvtdq2ps, gen_helper_cvtps2dq, gen_helper_cvttps2dq },
[0x5c] = SSE_FOP(sub),
[0x5d] = SSE_FOP(min),
[0x5e] = SSE_FOP(div),
[0x5f] = SSE_FOP(max),
[0xc2] = SSE_FOP(cmpeq),
[0xc6] = { (SSEFunc_0_epp)gen_helper_shufps,
(SSEFunc_0_epp)gen_helper_shufpd }, /* XXX: casts */
/* SSSE3, SSE4, MOVBE, CRC32, BMI1, BMI2, ADX. */
[0x38] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL },
[0x3a] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL },
/* MMX ops and their SSE extensions */
[0x60] = MMX_OP2(punpcklbw),
[0x61] = MMX_OP2(punpcklwd),
[0x62] = MMX_OP2(punpckldq),
[0x63] = MMX_OP2(packsswb),
[0x64] = MMX_OP2(pcmpgtb),
[0x65] = MMX_OP2(pcmpgtw),
[0x66] = MMX_OP2(pcmpgtl),
[0x67] = MMX_OP2(packuswb),
[0x68] = MMX_OP2(punpckhbw),
[0x69] = MMX_OP2(punpckhwd),
[0x6a] = MMX_OP2(punpckhdq),
[0x6b] = MMX_OP2(packssdw),
[0x6c] = { NULL, gen_helper_punpcklqdq_xmm },
[0x6d] = { NULL, gen_helper_punpckhqdq_xmm },
[0x6e] = { SSE_SPECIAL, SSE_SPECIAL }, /* movd mm, ea */
[0x6f] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movq, movdqa, , movqdu */
[0x70] = { (SSEFunc_0_epp)gen_helper_pshufw_mmx,
(SSEFunc_0_epp)gen_helper_pshufd_xmm,
(SSEFunc_0_epp)gen_helper_pshufhw_xmm,
(SSEFunc_0_epp)gen_helper_pshuflw_xmm }, /* XXX: casts */
[0x71] = { SSE_SPECIAL, SSE_SPECIAL }, /* shiftw */
[0x72] = { SSE_SPECIAL, SSE_SPECIAL }, /* shiftd */
[0x73] = { SSE_SPECIAL, SSE_SPECIAL }, /* shiftq */
[0x74] = MMX_OP2(pcmpeqb),
[0x75] = MMX_OP2(pcmpeqw),
[0x76] = MMX_OP2(pcmpeql),
[0x77] = { SSE_DUMMY }, /* emms */
[0x78] = { NULL, SSE_SPECIAL, NULL, SSE_SPECIAL }, /* extrq_i, insertq_i */
[0x79] = { NULL, gen_helper_extrq_r, NULL, gen_helper_insertq_r },
[0x7c] = { NULL, gen_helper_haddpd, NULL, gen_helper_haddps },
[0x7d] = { NULL, gen_helper_hsubpd, NULL, gen_helper_hsubps },
[0x7e] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movd, movd, , movq */
[0x7f] = { SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL }, /* movq, movdqa, movdqu */
[0xc4] = { SSE_SPECIAL, SSE_SPECIAL }, /* pinsrw */
[0xc5] = { SSE_SPECIAL, SSE_SPECIAL }, /* pextrw */
[0xd0] = { NULL, gen_helper_addsubpd, NULL, gen_helper_addsubps },
[0xd1] = MMX_OP2(psrlw),
[0xd2] = MMX_OP2(psrld),
[0xd3] = MMX_OP2(psrlq),
[0xd4] = MMX_OP2(paddq),
[0xd5] = MMX_OP2(pmullw),
[0xd6] = { NULL, SSE_SPECIAL, SSE_SPECIAL, SSE_SPECIAL },
[0xd7] = { SSE_SPECIAL, SSE_SPECIAL }, /* pmovmskb */
[0xd8] = MMX_OP2(psubusb),
[0xd9] = MMX_OP2(psubusw),
[0xda] = MMX_OP2(pminub),
[0xdb] = MMX_OP2(pand),
[0xdc] = MMX_OP2(paddusb),
[0xdd] = MMX_OP2(paddusw),
[0xde] = MMX_OP2(pmaxub),
[0xdf] = MMX_OP2(pandn),
[0xe0] = MMX_OP2(pavgb),
[0xe1] = MMX_OP2(psraw),
[0xe2] = MMX_OP2(psrad),
[0xe3] = MMX_OP2(pavgw),
[0xe4] = MMX_OP2(pmulhuw),
[0xe5] = MMX_OP2(pmulhw),
[0xe6] = { NULL, gen_helper_cvttpd2dq, gen_helper_cvtdq2pd, gen_helper_cvtpd2dq },
[0xe7] = { SSE_SPECIAL , SSE_SPECIAL }, /* movntq, movntq */
[0xe8] = MMX_OP2(psubsb),
[0xe9] = MMX_OP2(psubsw),
[0xea] = MMX_OP2(pminsw),
[0xeb] = MMX_OP2(por),
[0xec] = MMX_OP2(paddsb),
[0xed] = MMX_OP2(paddsw),
[0xee] = MMX_OP2(pmaxsw),
[0xef] = MMX_OP2(pxor),
[0xf0] = { NULL, NULL, NULL, SSE_SPECIAL }, /* lddqu */
[0xf1] = MMX_OP2(psllw),
[0xf2] = MMX_OP2(pslld),
[0xf3] = MMX_OP2(psllq),
[0xf4] = MMX_OP2(pmuludq),
[0xf5] = MMX_OP2(pmaddwd),
[0xf6] = MMX_OP2(psadbw),
[0xf7] = { (SSEFunc_0_epp)gen_helper_maskmov_mmx,
(SSEFunc_0_epp)gen_helper_maskmov_xmm }, /* XXX: casts */
[0xf8] = MMX_OP2(psubb),
[0xf9] = MMX_OP2(psubw),
[0xfa] = MMX_OP2(psubl),
[0xfb] = MMX_OP2(psubq),
[0xfc] = MMX_OP2(paddb),
[0xfd] = MMX_OP2(paddw),
[0xfe] = MMX_OP2(paddl),
};
static const SSEFunc_0_epp sse_op_table2[3 * 8][2] = {
[0 + 2] = MMX_OP2(psrlw),
[0 + 4] = MMX_OP2(psraw),
[0 + 6] = MMX_OP2(psllw),
[8 + 2] = MMX_OP2(psrld),
[8 + 4] = MMX_OP2(psrad),
[8 + 6] = MMX_OP2(pslld),
[16 + 2] = MMX_OP2(psrlq),
[16 + 3] = { NULL, gen_helper_psrldq_xmm },
[16 + 6] = MMX_OP2(psllq),
[16 + 7] = { NULL, gen_helper_pslldq_xmm },
};
static const SSEFunc_0_epi sse_op_table3ai[] = {
gen_helper_cvtsi2ss,
gen_helper_cvtsi2sd
};
#ifdef TARGET_X86_64
static const SSEFunc_0_epl sse_op_table3aq[] = {
gen_helper_cvtsq2ss,
gen_helper_cvtsq2sd
};
#endif
static const SSEFunc_i_ep sse_op_table3bi[] = {
gen_helper_cvttss2si,
gen_helper_cvtss2si,
gen_helper_cvttsd2si,
gen_helper_cvtsd2si
};
#ifdef TARGET_X86_64
static const SSEFunc_l_ep sse_op_table3bq[] = {
gen_helper_cvttss2sq,
gen_helper_cvtss2sq,
gen_helper_cvttsd2sq,
gen_helper_cvtsd2sq
};
#endif
static const SSEFunc_0_epp sse_op_table4[8][4] = {
SSE_FOP(cmpeq),
SSE_FOP(cmplt),
SSE_FOP(cmple),
SSE_FOP(cmpunord),
SSE_FOP(cmpneq),
SSE_FOP(cmpnlt),
SSE_FOP(cmpnle),
SSE_FOP(cmpord),
};
static const SSEFunc_0_epp sse_op_table5[256] = {
[0x0c] = gen_helper_pi2fw,
[0x0d] = gen_helper_pi2fd,
[0x1c] = gen_helper_pf2iw,
[0x1d] = gen_helper_pf2id,
[0x8a] = gen_helper_pfnacc,
[0x8e] = gen_helper_pfpnacc,
[0x90] = gen_helper_pfcmpge,
[0x94] = gen_helper_pfmin,
[0x96] = gen_helper_pfrcp,
[0x97] = gen_helper_pfrsqrt,
[0x9a] = gen_helper_pfsub,
[0x9e] = gen_helper_pfadd,
[0xa0] = gen_helper_pfcmpgt,
[0xa4] = gen_helper_pfmax,
[0xa6] = gen_helper_movq, /* pfrcpit1; no need to actually increase precision */
[0xa7] = gen_helper_movq, /* pfrsqit1 */
[0xaa] = gen_helper_pfsubr,
[0xae] = gen_helper_pfacc,
[0xb0] = gen_helper_pfcmpeq,
[0xb4] = gen_helper_pfmul,
[0xb6] = gen_helper_movq, /* pfrcpit2 */
[0xb7] = gen_helper_pmulhrw_mmx,
[0xbb] = gen_helper_pswapd,
[0xbf] = gen_helper_pavgb_mmx /* pavgusb */
};
struct SSEOpHelper_epp {
SSEFunc_0_epp op[2];
uint32_t ext_mask;
};
struct SSEOpHelper_eppi {
SSEFunc_0_eppi op[2];
uint32_t ext_mask;
};
#define SSSE3_OP(x) { MMX_OP2(x), CPUID_EXT_SSSE3 }
#define SSE41_OP(x) { { NULL, gen_helper_ ## x ## _xmm }, CPUID_EXT_SSE41 }
#define SSE42_OP(x) { { NULL, gen_helper_ ## x ## _xmm }, CPUID_EXT_SSE42 }
#define SSE41_SPECIAL { { NULL, SSE_SPECIAL }, CPUID_EXT_SSE41 }
#define PCLMULQDQ_OP(x) { { NULL, gen_helper_ ## x ## _xmm }, \
CPUID_EXT_PCLMULQDQ }
#define AESNI_OP(x) { { NULL, gen_helper_ ## x ## _xmm }, CPUID_EXT_AES }
static const struct SSEOpHelper_epp sse_op_table6[256] = {
[0x00] = SSSE3_OP(pshufb),
[0x01] = SSSE3_OP(phaddw),
[0x02] = SSSE3_OP(phaddd),
[0x03] = SSSE3_OP(phaddsw),
[0x04] = SSSE3_OP(pmaddubsw),
[0x05] = SSSE3_OP(phsubw),
[0x06] = SSSE3_OP(phsubd),
[0x07] = SSSE3_OP(phsubsw),
[0x08] = SSSE3_OP(psignb),
[0x09] = SSSE3_OP(psignw),
[0x0a] = SSSE3_OP(psignd),
[0x0b] = SSSE3_OP(pmulhrsw),
[0x10] = SSE41_OP(pblendvb),
[0x14] = SSE41_OP(blendvps),
[0x15] = SSE41_OP(blendvpd),
[0x17] = SSE41_OP(ptest),
[0x1c] = SSSE3_OP(pabsb),
[0x1d] = SSSE3_OP(pabsw),
[0x1e] = SSSE3_OP(pabsd),
[0x20] = SSE41_OP(pmovsxbw),
[0x21] = SSE41_OP(pmovsxbd),
[0x22] = SSE41_OP(pmovsxbq),
[0x23] = SSE41_OP(pmovsxwd),
[0x24] = SSE41_OP(pmovsxwq),
[0x25] = SSE41_OP(pmovsxdq),
[0x28] = SSE41_OP(pmuldq),
[0x29] = SSE41_OP(pcmpeqq),
[0x2a] = SSE41_SPECIAL, /* movntqda */
[0x2b] = SSE41_OP(packusdw),
[0x30] = SSE41_OP(pmovzxbw),
[0x31] = SSE41_OP(pmovzxbd),
[0x32] = SSE41_OP(pmovzxbq),
[0x33] = SSE41_OP(pmovzxwd),
[0x34] = SSE41_OP(pmovzxwq),
[0x35] = SSE41_OP(pmovzxdq),
[0x37] = SSE42_OP(pcmpgtq),
[0x38] = SSE41_OP(pminsb),
[0x39] = SSE41_OP(pminsd),
[0x3a] = SSE41_OP(pminuw),
[0x3b] = SSE41_OP(pminud),
[0x3c] = SSE41_OP(pmaxsb),
[0x3d] = SSE41_OP(pmaxsd),
[0x3e] = SSE41_OP(pmaxuw),
[0x3f] = SSE41_OP(pmaxud),
[0x40] = SSE41_OP(pmulld),
[0x41] = SSE41_OP(phminposuw),
[0xdb] = AESNI_OP(aesimc),
[0xdc] = AESNI_OP(aesenc),
[0xdd] = AESNI_OP(aesenclast),
[0xde] = AESNI_OP(aesdec),
[0xdf] = AESNI_OP(aesdeclast),
};
static const struct SSEOpHelper_eppi sse_op_table7[256] = {
[0x08] = SSE41_OP(roundps),
[0x09] = SSE41_OP(roundpd),
[0x0a] = SSE41_OP(roundss),
[0x0b] = SSE41_OP(roundsd),
[0x0c] = SSE41_OP(blendps),
[0x0d] = SSE41_OP(blendpd),
[0x0e] = SSE41_OP(pblendw),
[0x0f] = SSSE3_OP(palignr),
[0x14] = SSE41_SPECIAL, /* pextrb */
[0x15] = SSE41_SPECIAL, /* pextrw */
[0x16] = SSE41_SPECIAL, /* pextrd/pextrq */
[0x17] = SSE41_SPECIAL, /* extractps */
[0x20] = SSE41_SPECIAL, /* pinsrb */
[0x21] = SSE41_SPECIAL, /* insertps */
[0x22] = SSE41_SPECIAL, /* pinsrd/pinsrq */
[0x40] = SSE41_OP(dpps),
[0x41] = SSE41_OP(dppd),
[0x42] = SSE41_OP(mpsadbw),
[0x44] = PCLMULQDQ_OP(pclmulqdq),
[0x60] = SSE42_OP(pcmpestrm),
[0x61] = SSE42_OP(pcmpestri),
[0x62] = SSE42_OP(pcmpistrm),
[0x63] = SSE42_OP(pcmpistri),
[0xdf] = AESNI_OP(aeskeygenassist),
};
static void gen_sse(CPUX86State *env, DisasContext *s, int b,
target_ulong pc_start, int rex_r)
{
int b1, op1_offset, op2_offset, is_xmm, val;
int modrm, mod, rm, reg;
SSEFunc_0_epp sse_fn_epp;
SSEFunc_0_eppi sse_fn_eppi;
SSEFunc_0_ppi sse_fn_ppi;
SSEFunc_0_eppt sse_fn_eppt;
TCGMemOp ot;
b &= 0xff;
if (s->prefix & PREFIX_DATA)
b1 = 1;
else if (s->prefix & PREFIX_REPZ)
b1 = 2;
else if (s->prefix & PREFIX_REPNZ)
b1 = 3;
else
b1 = 0;
sse_fn_epp = sse_op_table1[b][b1];
if (!sse_fn_epp) {
goto unknown_op;
}
if ((b <= 0x5f && b >= 0x10) || b == 0xc6 || b == 0xc2) {
is_xmm = 1;
} else {
if (b1 == 0) {
/* MMX case */
is_xmm = 0;
} else {
is_xmm = 1;
}
}
/* simple MMX/SSE operation */
if (s->flags & HF_TS_MASK) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
return;
}
if (s->flags & HF_EM_MASK) {
illegal_op:
gen_illegal_opcode(s);
return;
}
if (is_xmm
&& !(s->flags & HF_OSFXSR_MASK)
&& ((b != 0x38 && b != 0x3a) || (s->prefix & PREFIX_DATA))) {
goto unknown_op;
}
if (b == 0x0e) {
if (!(s->cpuid_ext2_features & CPUID_EXT2_3DNOW)) {
/* If we were fully decoding this we might use illegal_op. */
goto unknown_op;
}
/* femms */
gen_helper_emms(cpu_env);
return;
}
if (b == 0x77) {
/* emms */
gen_helper_emms(cpu_env);
return;
}
/* prepare MMX state (XXX: optimize by storing fptt and fptags in
the static cpu state) */
if (!is_xmm) {
gen_helper_enter_mmx(cpu_env);
}
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7);
if (is_xmm)
reg |= rex_r;
mod = (modrm >> 6) & 3;
if (sse_fn_epp == SSE_SPECIAL) {
b |= (b1 << 8);
switch(b) {
case 0x0e7: /* movntq */
if (mod == 3) {
goto illegal_op;
}
gen_lea_modrm(env, s, modrm);
gen_stq_env_A0(s, offsetof(CPUX86State, fpregs[reg].mmx));
break;
case 0x1e7: /* movntdq */
case 0x02b: /* movntps */
case 0x12b: /* movntps */
if (mod == 3)
goto illegal_op;
gen_lea_modrm(env, s, modrm);
gen_sto_env_A0(s, offsetof(CPUX86State, xmm_regs[reg]));
break;
case 0x3f0: /* lddqu */
if (mod == 3)
goto illegal_op;
gen_lea_modrm(env, s, modrm);
gen_ldo_env_A0(s, offsetof(CPUX86State, xmm_regs[reg]));
break;
case 0x22b: /* movntss */
case 0x32b: /* movntsd */
if (mod == 3)
goto illegal_op;
gen_lea_modrm(env, s, modrm);
if (b1 & 1) {
gen_stq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(0)));
} else {
tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_L(0)));
gen_op_st_v(s, MO_32, cpu_T0, cpu_A0);
}
break;
case 0x6e: /* movd mm, ea */
#ifdef TARGET_X86_64
if (s->dflag == MO_64) {
gen_ldst_modrm(env, s, modrm, MO_64, OR_TMP0, 0);
tcg_gen_st_tl(cpu_T0, cpu_env, offsetof(CPUX86State,fpregs[reg].mmx));
} else
#endif
{
gen_ldst_modrm(env, s, modrm, MO_32, OR_TMP0, 0);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,fpregs[reg].mmx));
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_movl_mm_T0_mmx(cpu_ptr0, cpu_tmp2_i32);
}
break;
case 0x16e: /* movd xmm, ea */
#ifdef TARGET_X86_64
if (s->dflag == MO_64) {
gen_ldst_modrm(env, s, modrm, MO_64, OR_TMP0, 0);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,xmm_regs[reg]));
gen_helper_movq_mm_T0_xmm(cpu_ptr0, cpu_T0);
} else
#endif
{
gen_ldst_modrm(env, s, modrm, MO_32, OR_TMP0, 0);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,xmm_regs[reg]));
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_movl_mm_T0_xmm(cpu_ptr0, cpu_tmp2_i32);
}
break;
case 0x6f: /* movq mm, ea */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldq_env_A0(s, offsetof(CPUX86State, fpregs[reg].mmx));
} else {
rm = (modrm & 7);
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env,
offsetof(CPUX86State,fpregs[rm].mmx));
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env,
offsetof(CPUX86State,fpregs[reg].mmx));
}
break;
case 0x010: /* movups */
case 0x110: /* movupd */
case 0x028: /* movaps */
case 0x128: /* movapd */
case 0x16f: /* movdqa xmm, ea */
case 0x26f: /* movdqu xmm, ea */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldo_env_A0(s, offsetof(CPUX86State, xmm_regs[reg]));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movo(offsetof(CPUX86State,xmm_regs[reg]),
offsetof(CPUX86State,xmm_regs[rm]));
}
break;
case 0x210: /* movss xmm, ea */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, MO_32, cpu_T0, cpu_A0);
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)));
tcg_gen_movi_tl(cpu_T0, 0);
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(1)));
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(2)));
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(3)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_L(0)));
}
break;
case 0x310: /* movsd xmm, ea */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(0)));
tcg_gen_movi_tl(cpu_T0, 0);
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(2)));
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(3)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0)));
}
break;
case 0x012: /* movlps */
case 0x112: /* movlpd */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(0)));
} else {
/* movhlps */
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(1)));
}
break;
case 0x212: /* movsldup */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldo_env_A0(s, offsetof(CPUX86State, xmm_regs[reg]));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_L(0)));
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(2)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_L(2)));
}
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(1)),
offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)));
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(3)),
offsetof(CPUX86State,xmm_regs[reg].ZMM_L(2)));
break;
case 0x312: /* movddup */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(0)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0)));
}
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(1)),
offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)));
break;
case 0x016: /* movhps */
case 0x116: /* movhpd */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(1)));
} else {
/* movlhps */
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(1)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0)));
}
break;
case 0x216: /* movshdup */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldo_env_A0(s, offsetof(CPUX86State, xmm_regs[reg]));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(1)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_L(1)));
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(3)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_L(3)));
}
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)),
offsetof(CPUX86State,xmm_regs[reg].ZMM_L(1)));
gen_op_movl(offsetof(CPUX86State,xmm_regs[reg].ZMM_L(2)),
offsetof(CPUX86State,xmm_regs[reg].ZMM_L(3)));
break;
case 0x178:
case 0x378:
{
int bit_index, field_length;
if (b1 == 1 && reg != 0)
goto illegal_op;
field_length = cpu_ldub_code(env, s->pc++) & 0x3F;
bit_index = cpu_ldub_code(env, s->pc++) & 0x3F;
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,xmm_regs[reg]));
if (b1 == 1)
gen_helper_extrq_i(cpu_env, cpu_ptr0,
tcg_const_i32(bit_index),
tcg_const_i32(field_length));
else
gen_helper_insertq_i(cpu_env, cpu_ptr0,
tcg_const_i32(bit_index),
tcg_const_i32(field_length));
}
break;
case 0x7e: /* movd ea, mm */
#ifdef TARGET_X86_64
if (s->dflag == MO_64) {
tcg_gen_ld_i64(cpu_T0, cpu_env,
offsetof(CPUX86State,fpregs[reg].mmx));
gen_ldst_modrm(env, s, modrm, MO_64, OR_TMP0, 1);
} else
#endif
{
tcg_gen_ld32u_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,fpregs[reg].mmx.MMX_L(0)));
gen_ldst_modrm(env, s, modrm, MO_32, OR_TMP0, 1);
}
break;
case 0x17e: /* movd ea, xmm */
#ifdef TARGET_X86_64
if (s->dflag == MO_64) {
tcg_gen_ld_i64(cpu_T0, cpu_env,
offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)));
gen_ldst_modrm(env, s, modrm, MO_64, OR_TMP0, 1);
} else
#endif
{
tcg_gen_ld32u_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)));
gen_ldst_modrm(env, s, modrm, MO_32, OR_TMP0, 1);
}
break;
case 0x27e: /* movq xmm, ea */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_ldq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(0)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)),
offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0)));
}
gen_op_movq_env_0(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(1)));
break;
case 0x7f: /* movq ea, mm */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_stq_env_A0(s, offsetof(CPUX86State, fpregs[reg].mmx));
} else {
rm = (modrm & 7);
gen_op_movq(offsetof(CPUX86State,fpregs[rm].mmx),
offsetof(CPUX86State,fpregs[reg].mmx));
}
break;
case 0x011: /* movups */
case 0x111: /* movupd */
case 0x029: /* movaps */
case 0x129: /* movapd */
case 0x17f: /* movdqa ea, xmm */
case 0x27f: /* movdqu ea, xmm */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_sto_env_A0(s, offsetof(CPUX86State, xmm_regs[reg]));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movo(offsetof(CPUX86State,xmm_regs[rm]),
offsetof(CPUX86State,xmm_regs[reg]));
}
break;
case 0x211: /* movss ea, xmm */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)));
gen_op_st_v(s, MO_32, cpu_T0, cpu_A0);
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movl(offsetof(CPUX86State,xmm_regs[rm].ZMM_L(0)),
offsetof(CPUX86State,xmm_regs[reg].ZMM_L(0)));
}
break;
case 0x311: /* movsd ea, xmm */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_stq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(0)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0)),
offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)));
}
break;
case 0x013: /* movlps */
case 0x113: /* movlpd */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_stq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(0)));
} else {
goto illegal_op;
}
break;
case 0x017: /* movhps */
case 0x117: /* movhpd */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_stq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(1)));
} else {
goto illegal_op;
}
break;
case 0x71: /* shift mm, im */
case 0x72:
case 0x73:
case 0x171: /* shift xmm, im */
case 0x172:
case 0x173:
if (b1 >= 2) {
goto unknown_op;
}
val = cpu_ldub_code(env, s->pc++);
if (is_xmm) {
tcg_gen_movi_tl(cpu_T0, val);
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_t0.ZMM_L(0)));
tcg_gen_movi_tl(cpu_T0, 0);
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_t0.ZMM_L(1)));
op1_offset = offsetof(CPUX86State,xmm_t0);
} else {
tcg_gen_movi_tl(cpu_T0, val);
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,mmx_t0.MMX_L(0)));
tcg_gen_movi_tl(cpu_T0, 0);
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,mmx_t0.MMX_L(1)));
op1_offset = offsetof(CPUX86State,mmx_t0);
}
sse_fn_epp = sse_op_table2[((b - 1) & 3) * 8 +
(((modrm >> 3)) & 7)][b1];
if (!sse_fn_epp) {
goto unknown_op;
}
if (is_xmm) {
rm = (modrm & 7) | REX_B(s);
op2_offset = offsetof(CPUX86State,xmm_regs[rm]);
} else {
rm = (modrm & 7);
op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);
}
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op2_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op1_offset);
sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1);
break;
case 0x050: /* movmskps */
rm = (modrm & 7) | REX_B(s);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,xmm_regs[rm]));
gen_helper_movmskps(cpu_tmp2_i32, cpu_env, cpu_ptr0);
tcg_gen_extu_i32_tl(cpu_regs[reg], cpu_tmp2_i32);
break;
case 0x150: /* movmskpd */
rm = (modrm & 7) | REX_B(s);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env,
offsetof(CPUX86State,xmm_regs[rm]));
gen_helper_movmskpd(cpu_tmp2_i32, cpu_env, cpu_ptr0);
tcg_gen_extu_i32_tl(cpu_regs[reg], cpu_tmp2_i32);
break;
case 0x02a: /* cvtpi2ps */
case 0x12a: /* cvtpi2pd */
gen_helper_enter_mmx(cpu_env);
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
op2_offset = offsetof(CPUX86State,mmx_t0);
gen_ldq_env_A0(s, op2_offset);
} else {
rm = (modrm & 7);
op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);
}
op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
switch(b >> 8) {
case 0x0:
gen_helper_cvtpi2ps(cpu_env, cpu_ptr0, cpu_ptr1);
break;
default:
case 0x1:
gen_helper_cvtpi2pd(cpu_env, cpu_ptr0, cpu_ptr1);
break;
}
break;
case 0x22a: /* cvtsi2ss */
case 0x32a: /* cvtsi2sd */
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
if (ot == MO_32) {
SSEFunc_0_epi sse_fn_epi = sse_op_table3ai[(b >> 8) & 1];
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
sse_fn_epi(cpu_env, cpu_ptr0, cpu_tmp2_i32);
} else {
#ifdef TARGET_X86_64
SSEFunc_0_epl sse_fn_epl = sse_op_table3aq[(b >> 8) & 1];
sse_fn_epl(cpu_env, cpu_ptr0, cpu_T0);
#else
goto illegal_op;
#endif
}
break;
case 0x02c: /* cvttps2pi */
case 0x12c: /* cvttpd2pi */
case 0x02d: /* cvtps2pi */
case 0x12d: /* cvtpd2pi */
gen_helper_enter_mmx(cpu_env);
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
op2_offset = offsetof(CPUX86State,xmm_t0);
gen_ldo_env_A0(s, op2_offset);
} else {
rm = (modrm & 7) | REX_B(s);
op2_offset = offsetof(CPUX86State,xmm_regs[rm]);
}
op1_offset = offsetof(CPUX86State,fpregs[reg & 7].mmx);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
switch(b) {
case 0x02c:
gen_helper_cvttps2pi(cpu_env, cpu_ptr0, cpu_ptr1);
break;
case 0x12c:
gen_helper_cvttpd2pi(cpu_env, cpu_ptr0, cpu_ptr1);
break;
case 0x02d:
gen_helper_cvtps2pi(cpu_env, cpu_ptr0, cpu_ptr1);
break;
case 0x12d:
gen_helper_cvtpd2pi(cpu_env, cpu_ptr0, cpu_ptr1);
break;
}
break;
case 0x22c: /* cvttss2si */
case 0x32c: /* cvttsd2si */
case 0x22d: /* cvtss2si */
case 0x32d: /* cvtsd2si */
ot = mo_64_32(s->dflag);
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
if ((b >> 8) & 1) {
gen_ldq_env_A0(s, offsetof(CPUX86State, xmm_t0.ZMM_Q(0)));
} else {
gen_op_ld_v(s, MO_32, cpu_T0, cpu_A0);
tcg_gen_st32_tl(cpu_T0, cpu_env, offsetof(CPUX86State,xmm_t0.ZMM_L(0)));
}
op2_offset = offsetof(CPUX86State,xmm_t0);
} else {
rm = (modrm & 7) | REX_B(s);
op2_offset = offsetof(CPUX86State,xmm_regs[rm]);
}
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op2_offset);
if (ot == MO_32) {
SSEFunc_i_ep sse_fn_i_ep =
sse_op_table3bi[((b >> 7) & 2) | (b & 1)];
sse_fn_i_ep(cpu_tmp2_i32, cpu_env, cpu_ptr0);
tcg_gen_extu_i32_tl(cpu_T0, cpu_tmp2_i32);
} else {
#ifdef TARGET_X86_64
SSEFunc_l_ep sse_fn_l_ep =
sse_op_table3bq[((b >> 7) & 2) | (b & 1)];
sse_fn_l_ep(cpu_T0, cpu_env, cpu_ptr0);
#else
goto illegal_op;
#endif
}
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
case 0xc4: /* pinsrw */
case 0x1c4:
s->rip_offset = 1;
gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0);
val = cpu_ldub_code(env, s->pc++);
if (b1) {
val &= 7;
tcg_gen_st16_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,xmm_regs[reg].ZMM_W(val)));
} else {
val &= 3;
tcg_gen_st16_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,fpregs[reg].mmx.MMX_W(val)));
}
break;
case 0xc5: /* pextrw */
case 0x1c5:
if (mod != 3)
goto illegal_op;
ot = mo_64_32(s->dflag);
val = cpu_ldub_code(env, s->pc++);
if (b1) {
val &= 7;
rm = (modrm & 7) | REX_B(s);
tcg_gen_ld16u_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,xmm_regs[rm].ZMM_W(val)));
} else {
val &= 3;
rm = (modrm & 7);
tcg_gen_ld16u_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,fpregs[rm].mmx.MMX_W(val)));
}
reg = ((modrm >> 3) & 7) | rex_r;
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
case 0x1d6: /* movq ea, xmm */
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_stq_env_A0(s, offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(0)));
} else {
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0)),
offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)));
gen_op_movq_env_0(offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(1)));
}
break;
case 0x2d6: /* movq2dq */
gen_helper_enter_mmx(cpu_env);
rm = (modrm & 7);
gen_op_movq(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(0)),
offsetof(CPUX86State,fpregs[rm].mmx));
gen_op_movq_env_0(offsetof(CPUX86State,xmm_regs[reg].ZMM_Q(1)));
break;
case 0x3d6: /* movdq2q */
gen_helper_enter_mmx(cpu_env);
rm = (modrm & 7) | REX_B(s);
gen_op_movq(offsetof(CPUX86State,fpregs[reg & 7].mmx),
offsetof(CPUX86State,xmm_regs[rm].ZMM_Q(0)));
break;
case 0xd7: /* pmovmskb */
case 0x1d7:
if (mod != 3)
goto illegal_op;
if (b1) {
rm = (modrm & 7) | REX_B(s);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, offsetof(CPUX86State,xmm_regs[rm]));
gen_helper_pmovmskb_xmm(cpu_tmp2_i32, cpu_env, cpu_ptr0);
} else {
rm = (modrm & 7);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, offsetof(CPUX86State,fpregs[rm].mmx));
gen_helper_pmovmskb_mmx(cpu_tmp2_i32, cpu_env, cpu_ptr0);
}
reg = ((modrm >> 3) & 7) | rex_r;
tcg_gen_extu_i32_tl(cpu_regs[reg], cpu_tmp2_i32);
break;
case 0x138:
case 0x038:
b = modrm;
if ((b & 0xf0) == 0xf0) {
goto do_0f_38_fx;
}
modrm = cpu_ldub_code(env, s->pc++);
rm = modrm & 7;
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
if (b1 >= 2) {
goto unknown_op;
}
sse_fn_epp = sse_op_table6[b].op[b1];
if (!sse_fn_epp) {
goto unknown_op;
}
if (!(s->cpuid_ext_features & sse_op_table6[b].ext_mask))
goto illegal_op;
if (b1) {
op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
if (mod == 3) {
op2_offset = offsetof(CPUX86State,xmm_regs[rm | REX_B(s)]);
} else {
op2_offset = offsetof(CPUX86State,xmm_t0);
gen_lea_modrm(env, s, modrm);
switch (b) {
case 0x20: case 0x30: /* pmovsxbw, pmovzxbw */
case 0x23: case 0x33: /* pmovsxwd, pmovzxwd */
case 0x25: case 0x35: /* pmovsxdq, pmovzxdq */
gen_ldq_env_A0(s, op2_offset +
offsetof(ZMMReg, ZMM_Q(0)));
break;
case 0x21: case 0x31: /* pmovsxbd, pmovzxbd */
case 0x24: case 0x34: /* pmovsxwq, pmovzxwq */
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, op2_offset +
offsetof(ZMMReg, ZMM_L(0)));
break;
case 0x22: case 0x32: /* pmovsxbq, pmovzxbq */
tcg_gen_qemu_ld_tl(cpu_tmp0, cpu_A0,
s->mem_index, MO_LEUW);
tcg_gen_st16_tl(cpu_tmp0, cpu_env, op2_offset +
offsetof(ZMMReg, ZMM_W(0)));
break;
case 0x2a: /* movntqda */
gen_ldo_env_A0(s, op1_offset);
return;
default:
gen_ldo_env_A0(s, op2_offset);
}
}
} else {
op1_offset = offsetof(CPUX86State,fpregs[reg].mmx);
if (mod == 3) {
op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);
} else {
op2_offset = offsetof(CPUX86State,mmx_t0);
gen_lea_modrm(env, s, modrm);
gen_ldq_env_A0(s, op2_offset);
}
}
if (sse_fn_epp == SSE_SPECIAL) {
goto unknown_op;
}
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1);
if (b == 0x17) {
set_cc_op(s, CC_OP_EFLAGS);
}
break;
case 0x238:
case 0x338:
do_0f_38_fx:
/* Various integer extensions at 0f 38 f[0-f]. */
b = modrm | (b1 << 8);
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
switch (b) {
case 0x3f0: /* crc32 Gd,Eb */
case 0x3f1: /* crc32 Gd,Ey */
do_crc32:
if (!(s->cpuid_ext_features & CPUID_EXT_SSE42)) {
goto illegal_op;
}
if ((b & 0xff) == 0xf0) {
ot = MO_8;
} else if (s->dflag != MO_64) {
ot = (s->prefix & PREFIX_DATA ? MO_16 : MO_32);
} else {
ot = MO_64;
}
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[reg]);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
gen_helper_crc32(cpu_T0, cpu_tmp2_i32,
cpu_T0, tcg_const_i32(8 << ot));
ot = mo_64_32(s->dflag);
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
case 0x1f0: /* crc32 or movbe */
case 0x1f1:
/* For these insns, the f3 prefix is supposed to have priority
over the 66 prefix, but that's not what we implement above
setting b1. */
if (s->prefix & PREFIX_REPNZ) {
goto do_crc32;
}
/* FALLTHRU */
case 0x0f0: /* movbe Gy,My */
case 0x0f1: /* movbe My,Gy */
if (!(s->cpuid_ext_features & CPUID_EXT_MOVBE)) {
goto illegal_op;
}
if (s->dflag != MO_64) {
ot = (s->prefix & PREFIX_DATA ? MO_16 : MO_32);
} else {
ot = MO_64;
}
gen_lea_modrm(env, s, modrm);
if ((b & 1) == 0) {
tcg_gen_qemu_ld_tl(cpu_T0, cpu_A0,
s->mem_index, ot | MO_BE);
gen_op_mov_reg_v(ot, reg, cpu_T0);
} else {
tcg_gen_qemu_st_tl(cpu_regs[reg], cpu_A0,
s->mem_index, ot | MO_BE);
}
break;
case 0x0f2: /* andn Gy, By, Ey */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI1)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
tcg_gen_andc_tl(cpu_T0, cpu_regs[s->vex_v], cpu_T0);
gen_op_mov_reg_v(ot, reg, cpu_T0);
gen_op_update1_cc();
set_cc_op(s, CC_OP_LOGICB + ot);
break;
case 0x0f7: /* bextr Gy, Ey, By */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI1)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
{
TCGv bound, zero;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
/* Extract START, and shift the operand.
Shifts larger than operand size get zeros. */
tcg_gen_ext8u_tl(cpu_A0, cpu_regs[s->vex_v]);
tcg_gen_shr_tl(cpu_T0, cpu_T0, cpu_A0);
bound = tcg_const_tl(ot == MO_64 ? 63 : 31);
zero = tcg_const_tl(0);
tcg_gen_movcond_tl(TCG_COND_LEU, cpu_T0, cpu_A0, bound,
cpu_T0, zero);
tcg_temp_free(zero);
/* Extract the LEN into a mask. Lengths larger than
operand size get all ones. */
tcg_gen_extract_tl(cpu_A0, cpu_regs[s->vex_v], 8, 8);
tcg_gen_movcond_tl(TCG_COND_LEU, cpu_A0, cpu_A0, bound,
cpu_A0, bound);
tcg_temp_free(bound);
tcg_gen_movi_tl(cpu_T1, 1);
tcg_gen_shl_tl(cpu_T1, cpu_T1, cpu_A0);
tcg_gen_subi_tl(cpu_T1, cpu_T1, 1);
tcg_gen_and_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_mov_reg_v(ot, reg, cpu_T0);
gen_op_update1_cc();
set_cc_op(s, CC_OP_LOGICB + ot);
}
break;
case 0x0f5: /* bzhi Gy, Ey, By */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
tcg_gen_ext8u_tl(cpu_T1, cpu_regs[s->vex_v]);
{
TCGv bound = tcg_const_tl(ot == MO_64 ? 63 : 31);
/* Note that since we're using BMILG (in order to get O
cleared) we need to store the inverse into C. */
tcg_gen_setcond_tl(TCG_COND_LT, cpu_cc_src,
cpu_T1, bound);
tcg_gen_movcond_tl(TCG_COND_GT, cpu_T1, cpu_T1,
bound, bound, cpu_T1);
tcg_temp_free(bound);
}
tcg_gen_movi_tl(cpu_A0, -1);
tcg_gen_shl_tl(cpu_A0, cpu_A0, cpu_T1);
tcg_gen_andc_tl(cpu_T0, cpu_T0, cpu_A0);
gen_op_mov_reg_v(ot, reg, cpu_T0);
gen_op_update1_cc();
set_cc_op(s, CC_OP_BMILGB + ot);
break;
case 0x3f6: /* mulx By, Gy, rdx, Ey */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
switch (ot) {
default:
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_regs[R_EDX]);
tcg_gen_mulu2_i32(cpu_tmp2_i32, cpu_tmp3_i32,
cpu_tmp2_i32, cpu_tmp3_i32);
tcg_gen_extu_i32_tl(cpu_regs[s->vex_v], cpu_tmp2_i32);
tcg_gen_extu_i32_tl(cpu_regs[reg], cpu_tmp3_i32);
break;
#ifdef TARGET_X86_64
case MO_64:
tcg_gen_mulu2_i64(cpu_T0, cpu_T1,
cpu_T0, cpu_regs[R_EDX]);
tcg_gen_mov_i64(cpu_regs[s->vex_v], cpu_T0);
tcg_gen_mov_i64(cpu_regs[reg], cpu_T1);
break;
#endif
}
break;
case 0x3f5: /* pdep Gy, By, Ey */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
/* Note that by zero-extending the mask operand, we
automatically handle zero-extending the result. */
if (ot == MO_64) {
tcg_gen_mov_tl(cpu_T1, cpu_regs[s->vex_v]);
} else {
tcg_gen_ext32u_tl(cpu_T1, cpu_regs[s->vex_v]);
}
gen_helper_pdep(cpu_regs[reg], cpu_T0, cpu_T1);
break;
case 0x2f5: /* pext Gy, By, Ey */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
/* Note that by zero-extending the mask operand, we
automatically handle zero-extending the result. */
if (ot == MO_64) {
tcg_gen_mov_tl(cpu_T1, cpu_regs[s->vex_v]);
} else {
tcg_gen_ext32u_tl(cpu_T1, cpu_regs[s->vex_v]);
}
gen_helper_pext(cpu_regs[reg], cpu_T0, cpu_T1);
break;
case 0x1f6: /* adcx Gy, Ey */
case 0x2f6: /* adox Gy, Ey */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_ADX)) {
goto illegal_op;
} else {
TCGv carry_in, carry_out, zero;
int end_op;
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
/* Re-use the carry-out from a previous round. */
TCGV_UNUSED(carry_in);
carry_out = (b == 0x1f6 ? cpu_cc_dst : cpu_cc_src2);
switch (s->cc_op) {
case CC_OP_ADCX:
if (b == 0x1f6) {
carry_in = cpu_cc_dst;
end_op = CC_OP_ADCX;
} else {
end_op = CC_OP_ADCOX;
}
break;
case CC_OP_ADOX:
if (b == 0x1f6) {
end_op = CC_OP_ADCOX;
} else {
carry_in = cpu_cc_src2;
end_op = CC_OP_ADOX;
}
break;
case CC_OP_ADCOX:
end_op = CC_OP_ADCOX;
carry_in = carry_out;
break;
default:
end_op = (b == 0x1f6 ? CC_OP_ADCX : CC_OP_ADOX);
break;
}
/* If we can't reuse carry-out, get it out of EFLAGS. */
if (TCGV_IS_UNUSED(carry_in)) {
if (s->cc_op != CC_OP_ADCX && s->cc_op != CC_OP_ADOX) {
gen_compute_eflags(s);
}
carry_in = cpu_tmp0;
tcg_gen_extract_tl(carry_in, cpu_cc_src,
ctz32(b == 0x1f6 ? CC_C : CC_O), 1);
}
switch (ot) {
#ifdef TARGET_X86_64
case MO_32:
/* If we know TL is 64-bit, and we want a 32-bit
result, just do everything in 64-bit arithmetic. */
tcg_gen_ext32u_i64(cpu_regs[reg], cpu_regs[reg]);
tcg_gen_ext32u_i64(cpu_T0, cpu_T0);
tcg_gen_add_i64(cpu_T0, cpu_T0, cpu_regs[reg]);
tcg_gen_add_i64(cpu_T0, cpu_T0, carry_in);
tcg_gen_ext32u_i64(cpu_regs[reg], cpu_T0);
tcg_gen_shri_i64(carry_out, cpu_T0, 32);
break;
#endif
default:
/* Otherwise compute the carry-out in two steps. */
zero = tcg_const_tl(0);
tcg_gen_add2_tl(cpu_T0, carry_out,
cpu_T0, zero,
carry_in, zero);
tcg_gen_add2_tl(cpu_regs[reg], carry_out,
cpu_regs[reg], carry_out,
cpu_T0, zero);
tcg_temp_free(zero);
break;
}
set_cc_op(s, end_op);
}
break;
case 0x1f7: /* shlx Gy, Ey, By */
case 0x2f7: /* sarx Gy, Ey, By */
case 0x3f7: /* shrx Gy, Ey, By */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
if (ot == MO_64) {
tcg_gen_andi_tl(cpu_T1, cpu_regs[s->vex_v], 63);
} else {
tcg_gen_andi_tl(cpu_T1, cpu_regs[s->vex_v], 31);
}
if (b == 0x1f7) {
tcg_gen_shl_tl(cpu_T0, cpu_T0, cpu_T1);
} else if (b == 0x2f7) {
if (ot != MO_64) {
tcg_gen_ext32s_tl(cpu_T0, cpu_T0);
}
tcg_gen_sar_tl(cpu_T0, cpu_T0, cpu_T1);
} else {
if (ot != MO_64) {
tcg_gen_ext32u_tl(cpu_T0, cpu_T0);
}
tcg_gen_shr_tl(cpu_T0, cpu_T0, cpu_T1);
}
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
case 0x0f3:
case 0x1f3:
case 0x2f3:
case 0x3f3: /* Group 17 */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI1)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
switch (reg & 7) {
case 1: /* blsr By,Ey */
tcg_gen_neg_tl(cpu_T1, cpu_T0);
tcg_gen_and_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_mov_reg_v(ot, s->vex_v, cpu_T0);
gen_op_update2_cc();
set_cc_op(s, CC_OP_BMILGB + ot);
break;
case 2: /* blsmsk By,Ey */
tcg_gen_mov_tl(cpu_cc_src, cpu_T0);
tcg_gen_subi_tl(cpu_T0, cpu_T0, 1);
tcg_gen_xor_tl(cpu_T0, cpu_T0, cpu_cc_src);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
set_cc_op(s, CC_OP_BMILGB + ot);
break;
case 3: /* blsi By, Ey */
tcg_gen_mov_tl(cpu_cc_src, cpu_T0);
tcg_gen_subi_tl(cpu_T0, cpu_T0, 1);
tcg_gen_and_tl(cpu_T0, cpu_T0, cpu_cc_src);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
set_cc_op(s, CC_OP_BMILGB + ot);
break;
default:
goto unknown_op;
}
break;
default:
goto unknown_op;
}
break;
case 0x03a:
case 0x13a:
b = modrm;
modrm = cpu_ldub_code(env, s->pc++);
rm = modrm & 7;
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
if (b1 >= 2) {
goto unknown_op;
}
sse_fn_eppi = sse_op_table7[b].op[b1];
if (!sse_fn_eppi) {
goto unknown_op;
}
if (!(s->cpuid_ext_features & sse_op_table7[b].ext_mask))
goto illegal_op;
if (sse_fn_eppi == SSE_SPECIAL) {
ot = mo_64_32(s->dflag);
rm = (modrm & 7) | REX_B(s);
if (mod != 3)
gen_lea_modrm(env, s, modrm);
reg = ((modrm >> 3) & 7) | rex_r;
val = cpu_ldub_code(env, s->pc++);
switch (b) {
case 0x14: /* pextrb */
tcg_gen_ld8u_tl(cpu_T0, cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_B(val & 15)));
if (mod == 3) {
gen_op_mov_reg_v(ot, rm, cpu_T0);
} else {
tcg_gen_qemu_st_tl(cpu_T0, cpu_A0,
s->mem_index, MO_UB);
}
break;
case 0x15: /* pextrw */
tcg_gen_ld16u_tl(cpu_T0, cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_W(val & 7)));
if (mod == 3) {
gen_op_mov_reg_v(ot, rm, cpu_T0);
} else {
tcg_gen_qemu_st_tl(cpu_T0, cpu_A0,
s->mem_index, MO_LEUW);
}
break;
case 0x16:
if (ot == MO_32) { /* pextrd */
tcg_gen_ld_i32(cpu_tmp2_i32, cpu_env,
offsetof(CPUX86State,
xmm_regs[reg].ZMM_L(val & 3)));
if (mod == 3) {
tcg_gen_extu_i32_tl(cpu_regs[rm], cpu_tmp2_i32);
} else {
tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
}
} else { /* pextrq */
#ifdef TARGET_X86_64
tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env,
offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(val & 1)));
if (mod == 3) {
tcg_gen_mov_i64(cpu_regs[rm], cpu_tmp1_i64);
} else {
tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_A0,
s->mem_index, MO_LEQ);
}
#else
goto illegal_op;
#endif
}
break;
case 0x17: /* extractps */
tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_L(val & 3)));
if (mod == 3) {
gen_op_mov_reg_v(ot, rm, cpu_T0);
} else {
tcg_gen_qemu_st_tl(cpu_T0, cpu_A0,
s->mem_index, MO_LEUL);
}
break;
case 0x20: /* pinsrb */
if (mod == 3) {
gen_op_mov_v_reg(MO_32, cpu_T0, rm);
} else {
tcg_gen_qemu_ld_tl(cpu_T0, cpu_A0,
s->mem_index, MO_UB);
}
tcg_gen_st8_tl(cpu_T0, cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_B(val & 15)));
break;
case 0x21: /* insertps */
if (mod == 3) {
tcg_gen_ld_i32(cpu_tmp2_i32, cpu_env,
offsetof(CPUX86State,xmm_regs[rm]
.ZMM_L((val >> 6) & 3)));
} else {
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
}
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env,
offsetof(CPUX86State,xmm_regs[reg]
.ZMM_L((val >> 4) & 3)));
if ((val >> 0) & 1)
tcg_gen_st_i32(tcg_const_i32(0 /*float32_zero*/),
cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_L(0)));
if ((val >> 1) & 1)
tcg_gen_st_i32(tcg_const_i32(0 /*float32_zero*/),
cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_L(1)));
if ((val >> 2) & 1)
tcg_gen_st_i32(tcg_const_i32(0 /*float32_zero*/),
cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_L(2)));
if ((val >> 3) & 1)
tcg_gen_st_i32(tcg_const_i32(0 /*float32_zero*/),
cpu_env, offsetof(CPUX86State,
xmm_regs[reg].ZMM_L(3)));
break;
case 0x22:
if (ot == MO_32) { /* pinsrd */
if (mod == 3) {
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[rm]);
} else {
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
}
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env,
offsetof(CPUX86State,
xmm_regs[reg].ZMM_L(val & 3)));
} else { /* pinsrq */
#ifdef TARGET_X86_64
if (mod == 3) {
gen_op_mov_v_reg(ot, cpu_tmp1_i64, rm);
} else {
tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_A0,
s->mem_index, MO_LEQ);
}
tcg_gen_st_i64(cpu_tmp1_i64, cpu_env,
offsetof(CPUX86State,
xmm_regs[reg].ZMM_Q(val & 1)));
#else
goto illegal_op;
#endif
}
break;
}
return;
}
if (b1) {
op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
if (mod == 3) {
op2_offset = offsetof(CPUX86State,xmm_regs[rm | REX_B(s)]);
} else {
op2_offset = offsetof(CPUX86State,xmm_t0);
gen_lea_modrm(env, s, modrm);
gen_ldo_env_A0(s, op2_offset);
}
} else {
op1_offset = offsetof(CPUX86State,fpregs[reg].mmx);
if (mod == 3) {
op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);
} else {
op2_offset = offsetof(CPUX86State,mmx_t0);
gen_lea_modrm(env, s, modrm);
gen_ldq_env_A0(s, op2_offset);
}
}
val = cpu_ldub_code(env, s->pc++);
if ((b & 0xfc) == 0x60) { /* pcmpXstrX */
set_cc_op(s, CC_OP_EFLAGS);
if (s->dflag == MO_64) {
/* The helper must use entire 64-bit gp registers */
val |= 1 << 8;
}
}
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
sse_fn_eppi(cpu_env, cpu_ptr0, cpu_ptr1, tcg_const_i32(val));
break;
case 0x33a:
/* Various integer extensions at 0f 3a f[0-f]. */
b = modrm | (b1 << 8);
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
switch (b) {
case 0x3f0: /* rorx Gy,Ey, Ib */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI2)
|| !(s->prefix & PREFIX_VEX)
|| s->vex_l != 0) {
goto illegal_op;
}
ot = mo_64_32(s->dflag);
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
b = cpu_ldub_code(env, s->pc++);
if (ot == MO_64) {
tcg_gen_rotri_tl(cpu_T0, cpu_T0, b & 63);
} else {
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
tcg_gen_rotri_i32(cpu_tmp2_i32, cpu_tmp2_i32, b & 31);
tcg_gen_extu_i32_tl(cpu_T0, cpu_tmp2_i32);
}
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
default:
goto unknown_op;
}
break;
default:
unknown_op:
gen_unknown_opcode(env, s);
return;
}
} else {
/* generic MMX or SSE operation */
switch(b) {
case 0x70: /* pshufx insn */
case 0xc6: /* pshufx insn */
case 0xc2: /* compare insns */
s->rip_offset = 1;
break;
default:
break;
}
if (is_xmm) {
op1_offset = offsetof(CPUX86State,xmm_regs[reg]);
if (mod != 3) {
int sz = 4;
gen_lea_modrm(env, s, modrm);
op2_offset = offsetof(CPUX86State,xmm_t0);
switch (b) {
case 0x50 ... 0x5a:
case 0x5c ... 0x5f:
case 0xc2:
/* Most sse scalar operations. */
if (b1 == 2) {
sz = 2;
} else if (b1 == 3) {
sz = 3;
}
break;
case 0x2e: /* ucomis[sd] */
case 0x2f: /* comis[sd] */
if (b1 == 0) {
sz = 2;
} else {
sz = 3;
}
break;
}
switch (sz) {
case 2:
/* 32 bit access */
gen_op_ld_v(s, MO_32, cpu_T0, cpu_A0);
tcg_gen_st32_tl(cpu_T0, cpu_env,
offsetof(CPUX86State,xmm_t0.ZMM_L(0)));
break;
case 3:
/* 64 bit access */
gen_ldq_env_A0(s, offsetof(CPUX86State, xmm_t0.ZMM_D(0)));
break;
default:
/* 128 bit access */
gen_ldo_env_A0(s, op2_offset);
break;
}
} else {
rm = (modrm & 7) | REX_B(s);
op2_offset = offsetof(CPUX86State,xmm_regs[rm]);
}
} else {
op1_offset = offsetof(CPUX86State,fpregs[reg].mmx);
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
op2_offset = offsetof(CPUX86State,mmx_t0);
gen_ldq_env_A0(s, op2_offset);
} else {
rm = (modrm & 7);
op2_offset = offsetof(CPUX86State,fpregs[rm].mmx);
}
}
switch(b) {
case 0x0f: /* 3DNow! data insns */
val = cpu_ldub_code(env, s->pc++);
sse_fn_epp = sse_op_table5[val];
if (!sse_fn_epp) {
goto unknown_op;
}
if (!(s->cpuid_ext2_features & CPUID_EXT2_3DNOW)) {
goto illegal_op;
}
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1);
break;
case 0x70: /* pshufx insn */
case 0xc6: /* pshufx insn */
val = cpu_ldub_code(env, s->pc++);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
/* XXX: introduce a new table? */
sse_fn_ppi = (SSEFunc_0_ppi)sse_fn_epp;
sse_fn_ppi(cpu_ptr0, cpu_ptr1, tcg_const_i32(val));
break;
case 0xc2:
/* compare insns */
val = cpu_ldub_code(env, s->pc++);
if (val >= 8)
goto unknown_op;
sse_fn_epp = sse_op_table4[val][b1];
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1);
break;
case 0xf7:
/* maskmov : we must prepare A0 */
if (mod != 3)
goto illegal_op;
tcg_gen_mov_tl(cpu_A0, cpu_regs[R_EDI]);
gen_extu(s->aflag, cpu_A0);
gen_add_A0_ds_seg(s);
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
/* XXX: introduce a new table? */
sse_fn_eppt = (SSEFunc_0_eppt)sse_fn_epp;
sse_fn_eppt(cpu_env, cpu_ptr0, cpu_ptr1, cpu_A0);
break;
default:
tcg_gen_addi_ptr(cpu_ptr0, cpu_env, op1_offset);
tcg_gen_addi_ptr(cpu_ptr1, cpu_env, op2_offset);
sse_fn_epp(cpu_env, cpu_ptr0, cpu_ptr1);
break;
}
if (b == 0x2e || b == 0x2f) {
set_cc_op(s, CC_OP_EFLAGS);
}
}
}
/* convert one instruction. s->is_jmp is set if the translation must
be stopped. Return the next pc value */
static target_ulong disas_insn(CPUX86State *env, DisasContext *s,
target_ulong pc_start)
{
int b, prefixes;
int shift;
TCGMemOp ot, aflag, dflag;
int modrm, reg, rm, mod, op, opreg, val;
target_ulong next_eip, tval;
int rex_w, rex_r;
s->pc_start = s->pc = pc_start;
prefixes = 0;
s->override = -1;
rex_w = -1;
rex_r = 0;
#ifdef TARGET_X86_64
s->rex_x = 0;
s->rex_b = 0;
x86_64_hregs = 0;
#endif
s->rip_offset = 0; /* for relative ip address */
s->vex_l = 0;
s->vex_v = 0;
next_byte:
b = cpu_ldub_code(env, s->pc);
s->pc++;
/* Collect prefixes. */
switch (b) {
case 0xf3:
prefixes |= PREFIX_REPZ;
goto next_byte;
case 0xf2:
prefixes |= PREFIX_REPNZ;
goto next_byte;
case 0xf0:
prefixes |= PREFIX_LOCK;
goto next_byte;
case 0x2e:
s->override = R_CS;
goto next_byte;
case 0x36:
s->override = R_SS;
goto next_byte;
case 0x3e:
s->override = R_DS;
goto next_byte;
case 0x26:
s->override = R_ES;
goto next_byte;
case 0x64:
s->override = R_FS;
goto next_byte;
case 0x65:
s->override = R_GS;
goto next_byte;
case 0x66:
prefixes |= PREFIX_DATA;
goto next_byte;
case 0x67:
prefixes |= PREFIX_ADR;
goto next_byte;
#ifdef TARGET_X86_64
case 0x40 ... 0x4f:
if (CODE64(s)) {
/* REX prefix */
rex_w = (b >> 3) & 1;
rex_r = (b & 0x4) << 1;
s->rex_x = (b & 0x2) << 2;
REX_B(s) = (b & 0x1) << 3;
x86_64_hregs = 1; /* select uniform byte register addressing */
goto next_byte;
}
break;
#endif
case 0xc5: /* 2-byte VEX */
case 0xc4: /* 3-byte VEX */
/* VEX prefixes cannot be used except in 32-bit mode.
Otherwise the instruction is LES or LDS. */
if (s->code32 && !s->vm86) {
static const int pp_prefix[4] = {
0, PREFIX_DATA, PREFIX_REPZ, PREFIX_REPNZ
};
int vex3, vex2 = cpu_ldub_code(env, s->pc);
if (!CODE64(s) && (vex2 & 0xc0) != 0xc0) {
/* 4.1.4.6: In 32-bit mode, bits [7:6] must be 11b,
otherwise the instruction is LES or LDS. */
break;
}
s->pc++;
/* 4.1.1-4.1.3: No preceding lock, 66, f2, f3, or rex prefixes. */
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ
| PREFIX_LOCK | PREFIX_DATA)) {
goto illegal_op;
}
#ifdef TARGET_X86_64
if (x86_64_hregs) {
goto illegal_op;
}
#endif
rex_r = (~vex2 >> 4) & 8;
if (b == 0xc5) {
vex3 = vex2;
b = cpu_ldub_code(env, s->pc++);
} else {
#ifdef TARGET_X86_64
s->rex_x = (~vex2 >> 3) & 8;
s->rex_b = (~vex2 >> 2) & 8;
#endif
vex3 = cpu_ldub_code(env, s->pc++);
rex_w = (vex3 >> 7) & 1;
switch (vex2 & 0x1f) {
case 0x01: /* Implied 0f leading opcode bytes. */
b = cpu_ldub_code(env, s->pc++) | 0x100;
break;
case 0x02: /* Implied 0f 38 leading opcode bytes. */
b = 0x138;
break;
case 0x03: /* Implied 0f 3a leading opcode bytes. */
b = 0x13a;
break;
default: /* Reserved for future use. */
goto unknown_op;
}
}
s->vex_v = (~vex3 >> 3) & 0xf;
s->vex_l = (vex3 >> 2) & 1;
prefixes |= pp_prefix[vex3 & 3] | PREFIX_VEX;
}
break;
}
/* Post-process prefixes. */
if (CODE64(s)) {
/* In 64-bit mode, the default data size is 32-bit. Select 64-bit
data with rex_w, and 16-bit data with 0x66; rex_w takes precedence
over 0x66 if both are present. */
dflag = (rex_w > 0 ? MO_64 : prefixes & PREFIX_DATA ? MO_16 : MO_32);
/* In 64-bit mode, 0x67 selects 32-bit addressing. */
aflag = (prefixes & PREFIX_ADR ? MO_32 : MO_64);
} else {
/* In 16/32-bit mode, 0x66 selects the opposite data size. */
if (s->code32 ^ ((prefixes & PREFIX_DATA) != 0)) {
dflag = MO_32;
} else {
dflag = MO_16;
}
/* In 16/32-bit mode, 0x67 selects the opposite addressing. */
if (s->code32 ^ ((prefixes & PREFIX_ADR) != 0)) {
aflag = MO_32;
} else {
aflag = MO_16;
}
}
s->prefix = prefixes;
s->aflag = aflag;
s->dflag = dflag;
/* now check op code */
reswitch:
switch(b) {
case 0x0f:
/**************************/
/* extended op code */
b = cpu_ldub_code(env, s->pc++) | 0x100;
goto reswitch;
/**************************/
/* arith & logic */
case 0x00 ... 0x05:
case 0x08 ... 0x0d:
case 0x10 ... 0x15:
case 0x18 ... 0x1d:
case 0x20 ... 0x25:
case 0x28 ... 0x2d:
case 0x30 ... 0x35:
case 0x38 ... 0x3d:
{
int op, f, val;
op = (b >> 3) & 7;
f = (b >> 1) & 3;
ot = mo_b_d(b, dflag);
switch(f) {
case 0: /* OP Ev, Gv */
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
opreg = OR_TMP0;
} else if (op == OP_XORL && rm == reg) {
xor_zero:
/* xor reg, reg optimisation */
set_cc_op(s, CC_OP_CLR);
tcg_gen_movi_tl(cpu_T0, 0);
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
} else {
opreg = rm;
}
gen_op_mov_v_reg(ot, cpu_T1, reg);
gen_op(s, op, ot, opreg);
break;
case 1: /* OP Gv, Ev */
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
reg = ((modrm >> 3) & 7) | rex_r;
rm = (modrm & 7) | REX_B(s);
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, ot, cpu_T1, cpu_A0);
} else if (op == OP_XORL && rm == reg) {
goto xor_zero;
} else {
gen_op_mov_v_reg(ot, cpu_T1, rm);
}
gen_op(s, op, ot, reg);
break;
case 2: /* OP A, Iv */
val = insn_get(env, s, ot);
tcg_gen_movi_tl(cpu_T1, val);
gen_op(s, op, ot, OR_EAX);
break;
}
}
break;
case 0x82:
if (CODE64(s))
goto illegal_op;
case 0x80: /* GRP1 */
case 0x81:
case 0x83:
{
int val;
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
op = (modrm >> 3) & 7;
if (mod != 3) {
if (b == 0x83)
s->rip_offset = 1;
else
s->rip_offset = insn_const_size(ot);
gen_lea_modrm(env, s, modrm);
opreg = OR_TMP0;
} else {
opreg = rm;
}
switch(b) {
default:
case 0x80:
case 0x81:
case 0x82:
val = insn_get(env, s, ot);
break;
case 0x83:
val = (int8_t)insn_get(env, s, MO_8);
break;
}
tcg_gen_movi_tl(cpu_T1, val);
gen_op(s, op, ot, opreg);
}
break;
/**************************/
/* inc, dec, and other misc arith */
case 0x40 ... 0x47: /* inc Gv */
ot = dflag;
gen_inc(s, ot, OR_EAX + (b & 7), 1);
break;
case 0x48 ... 0x4f: /* dec Gv */
ot = dflag;
gen_inc(s, ot, OR_EAX + (b & 7), -1);
break;
case 0xf6: /* GRP3 */
case 0xf7:
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
op = (modrm >> 3) & 7;
if (mod != 3) {
if (op == 0) {
s->rip_offset = insn_const_size(ot);
}
gen_lea_modrm(env, s, modrm);
/* For those below that handle locked memory, don't load here. */
if (!(s->prefix & PREFIX_LOCK)
|| op != 2) {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
}
} else {
gen_op_mov_v_reg(ot, cpu_T0, rm);
}
switch(op) {
case 0: /* test */
val = insn_get(env, s, ot);
tcg_gen_movi_tl(cpu_T1, val);
gen_op_testl_T0_T1_cc();
set_cc_op(s, CC_OP_LOGICB + ot);
break;
case 2: /* not */
if (s->prefix & PREFIX_LOCK) {
if (mod == 3) {
goto illegal_op;
}
tcg_gen_movi_tl(cpu_T0, ~0);
tcg_gen_atomic_xor_fetch_tl(cpu_T0, cpu_A0, cpu_T0,
s->mem_index, ot | MO_LE);
} else {
tcg_gen_not_tl(cpu_T0, cpu_T0);
if (mod != 3) {
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_reg_v(ot, rm, cpu_T0);
}
}
break;
case 3: /* neg */
if (s->prefix & PREFIX_LOCK) {
TCGLabel *label1;
TCGv a0, t0, t1, t2;
if (mod == 3) {
goto illegal_op;
}
a0 = tcg_temp_local_new();
t0 = tcg_temp_local_new();
label1 = gen_new_label();
tcg_gen_mov_tl(a0, cpu_A0);
tcg_gen_mov_tl(t0, cpu_T0);
gen_set_label(label1);
t1 = tcg_temp_new();
t2 = tcg_temp_new();
tcg_gen_mov_tl(t2, t0);
tcg_gen_neg_tl(t1, t0);
tcg_gen_atomic_cmpxchg_tl(t0, a0, t0, t1,
s->mem_index, ot | MO_LE);
tcg_temp_free(t1);
tcg_gen_brcond_tl(TCG_COND_NE, t0, t2, label1);
tcg_temp_free(t2);
tcg_temp_free(a0);
tcg_gen_mov_tl(cpu_T0, t0);
tcg_temp_free(t0);
} else {
tcg_gen_neg_tl(cpu_T0, cpu_T0);
if (mod != 3) {
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_reg_v(ot, rm, cpu_T0);
}
}
gen_op_update_neg_cc();
set_cc_op(s, CC_OP_SUBB + ot);
break;
case 4: /* mul */
switch(ot) {
case MO_8:
gen_op_mov_v_reg(MO_8, cpu_T1, R_EAX);
tcg_gen_ext8u_tl(cpu_T0, cpu_T0);
tcg_gen_ext8u_tl(cpu_T1, cpu_T1);
/* XXX: use 32 bit mul which could be faster */
tcg_gen_mul_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
tcg_gen_andi_tl(cpu_cc_src, cpu_T0, 0xff00);
set_cc_op(s, CC_OP_MULB);
break;
case MO_16:
gen_op_mov_v_reg(MO_16, cpu_T1, R_EAX);
tcg_gen_ext16u_tl(cpu_T0, cpu_T0);
tcg_gen_ext16u_tl(cpu_T1, cpu_T1);
/* XXX: use 32 bit mul which could be faster */
tcg_gen_mul_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
tcg_gen_shri_tl(cpu_T0, cpu_T0, 16);
gen_op_mov_reg_v(MO_16, R_EDX, cpu_T0);
tcg_gen_mov_tl(cpu_cc_src, cpu_T0);
set_cc_op(s, CC_OP_MULW);
break;
default:
case MO_32:
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_regs[R_EAX]);
tcg_gen_mulu2_i32(cpu_tmp2_i32, cpu_tmp3_i32,
cpu_tmp2_i32, cpu_tmp3_i32);
tcg_gen_extu_i32_tl(cpu_regs[R_EAX], cpu_tmp2_i32);
tcg_gen_extu_i32_tl(cpu_regs[R_EDX], cpu_tmp3_i32);
tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[R_EAX]);
tcg_gen_mov_tl(cpu_cc_src, cpu_regs[R_EDX]);
set_cc_op(s, CC_OP_MULL);
break;
#ifdef TARGET_X86_64
case MO_64:
tcg_gen_mulu2_i64(cpu_regs[R_EAX], cpu_regs[R_EDX],
cpu_T0, cpu_regs[R_EAX]);
tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[R_EAX]);
tcg_gen_mov_tl(cpu_cc_src, cpu_regs[R_EDX]);
set_cc_op(s, CC_OP_MULQ);
break;
#endif
}
break;
case 5: /* imul */
switch(ot) {
case MO_8:
gen_op_mov_v_reg(MO_8, cpu_T1, R_EAX);
tcg_gen_ext8s_tl(cpu_T0, cpu_T0);
tcg_gen_ext8s_tl(cpu_T1, cpu_T1);
/* XXX: use 32 bit mul which could be faster */
tcg_gen_mul_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
tcg_gen_ext8s_tl(cpu_tmp0, cpu_T0);
tcg_gen_sub_tl(cpu_cc_src, cpu_T0, cpu_tmp0);
set_cc_op(s, CC_OP_MULB);
break;
case MO_16:
gen_op_mov_v_reg(MO_16, cpu_T1, R_EAX);
tcg_gen_ext16s_tl(cpu_T0, cpu_T0);
tcg_gen_ext16s_tl(cpu_T1, cpu_T1);
/* XXX: use 32 bit mul which could be faster */
tcg_gen_mul_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
tcg_gen_ext16s_tl(cpu_tmp0, cpu_T0);
tcg_gen_sub_tl(cpu_cc_src, cpu_T0, cpu_tmp0);
tcg_gen_shri_tl(cpu_T0, cpu_T0, 16);
gen_op_mov_reg_v(MO_16, R_EDX, cpu_T0);
set_cc_op(s, CC_OP_MULW);
break;
default:
case MO_32:
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_regs[R_EAX]);
tcg_gen_muls2_i32(cpu_tmp2_i32, cpu_tmp3_i32,
cpu_tmp2_i32, cpu_tmp3_i32);
tcg_gen_extu_i32_tl(cpu_regs[R_EAX], cpu_tmp2_i32);
tcg_gen_extu_i32_tl(cpu_regs[R_EDX], cpu_tmp3_i32);
tcg_gen_sari_i32(cpu_tmp2_i32, cpu_tmp2_i32, 31);
tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[R_EAX]);
tcg_gen_sub_i32(cpu_tmp2_i32, cpu_tmp2_i32, cpu_tmp3_i32);
tcg_gen_extu_i32_tl(cpu_cc_src, cpu_tmp2_i32);
set_cc_op(s, CC_OP_MULL);
break;
#ifdef TARGET_X86_64
case MO_64:
tcg_gen_muls2_i64(cpu_regs[R_EAX], cpu_regs[R_EDX],
cpu_T0, cpu_regs[R_EAX]);
tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[R_EAX]);
tcg_gen_sari_tl(cpu_cc_src, cpu_regs[R_EAX], 63);
tcg_gen_sub_tl(cpu_cc_src, cpu_cc_src, cpu_regs[R_EDX]);
set_cc_op(s, CC_OP_MULQ);
break;
#endif
}
break;
case 6: /* div */
switch(ot) {
case MO_8:
gen_helper_divb_AL(cpu_env, cpu_T0);
break;
case MO_16:
gen_helper_divw_AX(cpu_env, cpu_T0);
break;
default:
case MO_32:
gen_helper_divl_EAX(cpu_env, cpu_T0);
break;
#ifdef TARGET_X86_64
case MO_64:
gen_helper_divq_EAX(cpu_env, cpu_T0);
break;
#endif
}
break;
case 7: /* idiv */
switch(ot) {
case MO_8:
gen_helper_idivb_AL(cpu_env, cpu_T0);
break;
case MO_16:
gen_helper_idivw_AX(cpu_env, cpu_T0);
break;
default:
case MO_32:
gen_helper_idivl_EAX(cpu_env, cpu_T0);
break;
#ifdef TARGET_X86_64
case MO_64:
gen_helper_idivq_EAX(cpu_env, cpu_T0);
break;
#endif
}
break;
default:
goto unknown_op;
}
break;
case 0xfe: /* GRP4 */
case 0xff: /* GRP5 */
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
op = (modrm >> 3) & 7;
if (op >= 2 && b == 0xfe) {
goto unknown_op;
}
if (CODE64(s)) {
if (op == 2 || op == 4) {
/* operand size for jumps is 64 bit */
ot = MO_64;
} else if (op == 3 || op == 5) {
ot = dflag != MO_16 ? MO_32 + (rex_w == 1) : MO_16;
} else if (op == 6) {
/* default push size is 64 bit */
ot = mo_pushpop(s, dflag);
}
}
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
if (op >= 2 && op != 3 && op != 5)
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_v_reg(ot, cpu_T0, rm);
}
switch(op) {
case 0: /* inc Ev */
if (mod != 3)
opreg = OR_TMP0;
else
opreg = rm;
gen_inc(s, ot, opreg, 1);
break;
case 1: /* dec Ev */
if (mod != 3)
opreg = OR_TMP0;
else
opreg = rm;
gen_inc(s, ot, opreg, -1);
break;
case 2: /* call Ev */
/* XXX: optimize if memory (no 'and' is necessary) */
if (dflag == MO_16) {
tcg_gen_ext16u_tl(cpu_T0, cpu_T0);
}
next_eip = s->pc - s->cs_base;
tcg_gen_movi_tl(cpu_T1, next_eip);
gen_push_v(s, cpu_T1);
gen_op_jmp_v(cpu_T0);
gen_bnd_jmp(s);
gen_eob(s);
break;
case 3: /* lcall Ev */
gen_op_ld_v(s, ot, cpu_T1, cpu_A0);
gen_add_A0_im(s, 1 << ot);
gen_op_ld_v(s, MO_16, cpu_T0, cpu_A0);
do_lcall:
if (s->pe && !s->vm86) {
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_lcall_protected(cpu_env, cpu_tmp2_i32, cpu_T1,
tcg_const_i32(dflag - 1),
tcg_const_tl(s->pc - s->cs_base));
} else {
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_lcall_real(cpu_env, cpu_tmp2_i32, cpu_T1,
tcg_const_i32(dflag - 1),
tcg_const_i32(s->pc - s->cs_base));
}
gen_eob(s);
break;
case 4: /* jmp Ev */
if (dflag == MO_16) {
tcg_gen_ext16u_tl(cpu_T0, cpu_T0);
}
gen_op_jmp_v(cpu_T0);
gen_bnd_jmp(s);
gen_eob(s);
break;
case 5: /* ljmp Ev */
gen_op_ld_v(s, ot, cpu_T1, cpu_A0);
gen_add_A0_im(s, 1 << ot);
gen_op_ld_v(s, MO_16, cpu_T0, cpu_A0);
do_ljmp:
if (s->pe && !s->vm86) {
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_ljmp_protected(cpu_env, cpu_tmp2_i32, cpu_T1,
tcg_const_tl(s->pc - s->cs_base));
} else {
gen_op_movl_seg_T0_vm(R_CS);
gen_op_jmp_v(cpu_T1);
}
gen_eob(s);
break;
case 6: /* push Ev */
gen_push_v(s, cpu_T0);
break;
default:
goto unknown_op;
}
break;
case 0x84: /* test Ev, Gv */
case 0x85:
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
gen_op_mov_v_reg(ot, cpu_T1, reg);
gen_op_testl_T0_T1_cc();
set_cc_op(s, CC_OP_LOGICB + ot);
break;
case 0xa8: /* test eAX, Iv */
case 0xa9:
ot = mo_b_d(b, dflag);
val = insn_get(env, s, ot);
gen_op_mov_v_reg(ot, cpu_T0, OR_EAX);
tcg_gen_movi_tl(cpu_T1, val);
gen_op_testl_T0_T1_cc();
set_cc_op(s, CC_OP_LOGICB + ot);
break;
case 0x98: /* CWDE/CBW */
switch (dflag) {
#ifdef TARGET_X86_64
case MO_64:
gen_op_mov_v_reg(MO_32, cpu_T0, R_EAX);
tcg_gen_ext32s_tl(cpu_T0, cpu_T0);
gen_op_mov_reg_v(MO_64, R_EAX, cpu_T0);
break;
#endif
case MO_32:
gen_op_mov_v_reg(MO_16, cpu_T0, R_EAX);
tcg_gen_ext16s_tl(cpu_T0, cpu_T0);
gen_op_mov_reg_v(MO_32, R_EAX, cpu_T0);
break;
case MO_16:
gen_op_mov_v_reg(MO_8, cpu_T0, R_EAX);
tcg_gen_ext8s_tl(cpu_T0, cpu_T0);
gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0);
break;
default:
tcg_abort();
}
break;
case 0x99: /* CDQ/CWD */
switch (dflag) {
#ifdef TARGET_X86_64
case MO_64:
gen_op_mov_v_reg(MO_64, cpu_T0, R_EAX);
tcg_gen_sari_tl(cpu_T0, cpu_T0, 63);
gen_op_mov_reg_v(MO_64, R_EDX, cpu_T0);
break;
#endif
case MO_32:
gen_op_mov_v_reg(MO_32, cpu_T0, R_EAX);
tcg_gen_ext32s_tl(cpu_T0, cpu_T0);
tcg_gen_sari_tl(cpu_T0, cpu_T0, 31);
gen_op_mov_reg_v(MO_32, R_EDX, cpu_T0);
break;
case MO_16:
gen_op_mov_v_reg(MO_16, cpu_T0, R_EAX);
tcg_gen_ext16s_tl(cpu_T0, cpu_T0);
tcg_gen_sari_tl(cpu_T0, cpu_T0, 15);
gen_op_mov_reg_v(MO_16, R_EDX, cpu_T0);
break;
default:
tcg_abort();
}
break;
case 0x1af: /* imul Gv, Ev */
case 0x69: /* imul Gv, Ev, I */
case 0x6b:
ot = dflag;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
if (b == 0x69)
s->rip_offset = insn_const_size(ot);
else if (b == 0x6b)
s->rip_offset = 1;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
if (b == 0x69) {
val = insn_get(env, s, ot);
tcg_gen_movi_tl(cpu_T1, val);
} else if (b == 0x6b) {
val = (int8_t)insn_get(env, s, MO_8);
tcg_gen_movi_tl(cpu_T1, val);
} else {
gen_op_mov_v_reg(ot, cpu_T1, reg);
}
switch (ot) {
#ifdef TARGET_X86_64
case MO_64:
tcg_gen_muls2_i64(cpu_regs[reg], cpu_T1, cpu_T0, cpu_T1);
tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[reg]);
tcg_gen_sari_tl(cpu_cc_src, cpu_cc_dst, 63);
tcg_gen_sub_tl(cpu_cc_src, cpu_cc_src, cpu_T1);
break;
#endif
case MO_32:
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T1);
tcg_gen_muls2_i32(cpu_tmp2_i32, cpu_tmp3_i32,
cpu_tmp2_i32, cpu_tmp3_i32);
tcg_gen_extu_i32_tl(cpu_regs[reg], cpu_tmp2_i32);
tcg_gen_sari_i32(cpu_tmp2_i32, cpu_tmp2_i32, 31);
tcg_gen_mov_tl(cpu_cc_dst, cpu_regs[reg]);
tcg_gen_sub_i32(cpu_tmp2_i32, cpu_tmp2_i32, cpu_tmp3_i32);
tcg_gen_extu_i32_tl(cpu_cc_src, cpu_tmp2_i32);
break;
default:
tcg_gen_ext16s_tl(cpu_T0, cpu_T0);
tcg_gen_ext16s_tl(cpu_T1, cpu_T1);
/* XXX: use 32 bit mul which could be faster */
tcg_gen_mul_tl(cpu_T0, cpu_T0, cpu_T1);
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
tcg_gen_ext16s_tl(cpu_tmp0, cpu_T0);
tcg_gen_sub_tl(cpu_cc_src, cpu_T0, cpu_tmp0);
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
}
set_cc_op(s, CC_OP_MULB + ot);
break;
case 0x1c0:
case 0x1c1: /* xadd Ev, Gv */
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
gen_op_mov_v_reg(ot, cpu_T0, reg);
if (mod == 3) {
rm = (modrm & 7) | REX_B(s);
gen_op_mov_v_reg(ot, cpu_T1, rm);
tcg_gen_add_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_mov_reg_v(ot, reg, cpu_T1);
gen_op_mov_reg_v(ot, rm, cpu_T0);
} else {
gen_lea_modrm(env, s, modrm);
if (s->prefix & PREFIX_LOCK) {
tcg_gen_atomic_fetch_add_tl(cpu_T1, cpu_A0, cpu_T0,
s->mem_index, ot | MO_LE);
tcg_gen_add_tl(cpu_T0, cpu_T0, cpu_T1);
} else {
gen_op_ld_v(s, ot, cpu_T1, cpu_A0);
tcg_gen_add_tl(cpu_T0, cpu_T0, cpu_T1);
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
}
gen_op_mov_reg_v(ot, reg, cpu_T1);
}
gen_op_update2_cc();
set_cc_op(s, CC_OP_ADDB + ot);
break;
case 0x1b0:
case 0x1b1: /* cmpxchg Ev, Gv */
{
TCGv oldv, newv, cmpv;
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
oldv = tcg_temp_new();
newv = tcg_temp_new();
cmpv = tcg_temp_new();
gen_op_mov_v_reg(ot, newv, reg);
tcg_gen_mov_tl(cmpv, cpu_regs[R_EAX]);
if (s->prefix & PREFIX_LOCK) {
if (mod == 3) {
goto illegal_op;
}
gen_lea_modrm(env, s, modrm);
tcg_gen_atomic_cmpxchg_tl(oldv, cpu_A0, cmpv, newv,
s->mem_index, ot | MO_LE);
gen_op_mov_reg_v(ot, R_EAX, oldv);
} else {
if (mod == 3) {
rm = (modrm & 7) | REX_B(s);
gen_op_mov_v_reg(ot, oldv, rm);
} else {
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, ot, oldv, cpu_A0);
rm = 0; /* avoid warning */
}
gen_extu(ot, oldv);
gen_extu(ot, cmpv);
/* store value = (old == cmp ? new : old); */
tcg_gen_movcond_tl(TCG_COND_EQ, newv, oldv, cmpv, newv, oldv);
if (mod == 3) {
gen_op_mov_reg_v(ot, R_EAX, oldv);
gen_op_mov_reg_v(ot, rm, newv);
} else {
/* Perform an unconditional store cycle like physical cpu;
must be before changing accumulator to ensure
idempotency if the store faults and the instruction
is restarted */
gen_op_st_v(s, ot, newv, cpu_A0);
gen_op_mov_reg_v(ot, R_EAX, oldv);
}
}
tcg_gen_mov_tl(cpu_cc_src, oldv);
tcg_gen_mov_tl(cpu_cc_srcT, cmpv);
tcg_gen_sub_tl(cpu_cc_dst, cmpv, oldv);
set_cc_op(s, CC_OP_SUBB + ot);
tcg_temp_free(oldv);
tcg_temp_free(newv);
tcg_temp_free(cmpv);
}
break;
case 0x1c7: /* cmpxchg8b */
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
if ((mod == 3) || ((modrm & 0x38) != 0x8))
goto illegal_op;
#ifdef TARGET_X86_64
if (dflag == MO_64) {
if (!(s->cpuid_ext_features & CPUID_EXT_CX16))
goto illegal_op;
gen_lea_modrm(env, s, modrm);
if ((s->prefix & PREFIX_LOCK) && parallel_cpus) {
gen_helper_cmpxchg16b(cpu_env, cpu_A0);
} else {
gen_helper_cmpxchg16b_unlocked(cpu_env, cpu_A0);
}
} else
#endif
{
if (!(s->cpuid_features & CPUID_CX8))
goto illegal_op;
gen_lea_modrm(env, s, modrm);
if ((s->prefix & PREFIX_LOCK) && parallel_cpus) {
gen_helper_cmpxchg8b(cpu_env, cpu_A0);
} else {
gen_helper_cmpxchg8b_unlocked(cpu_env, cpu_A0);
}
}
set_cc_op(s, CC_OP_EFLAGS);
break;
/**************************/
/* push/pop */
case 0x50 ... 0x57: /* push */
gen_op_mov_v_reg(MO_32, cpu_T0, (b & 7) | REX_B(s));
gen_push_v(s, cpu_T0);
break;
case 0x58 ... 0x5f: /* pop */
ot = gen_pop_T0(s);
/* NOTE: order is important for pop %sp */
gen_pop_update(s, ot);
gen_op_mov_reg_v(ot, (b & 7) | REX_B(s), cpu_T0);
break;
case 0x60: /* pusha */
if (CODE64(s))
goto illegal_op;
gen_pusha(s);
break;
case 0x61: /* popa */
if (CODE64(s))
goto illegal_op;
gen_popa(s);
break;
case 0x68: /* push Iv */
case 0x6a:
ot = mo_pushpop(s, dflag);
if (b == 0x68)
val = insn_get(env, s, ot);
else
val = (int8_t)insn_get(env, s, MO_8);
tcg_gen_movi_tl(cpu_T0, val);
gen_push_v(s, cpu_T0);
break;
case 0x8f: /* pop Ev */
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
ot = gen_pop_T0(s);
if (mod == 3) {
/* NOTE: order is important for pop %sp */
gen_pop_update(s, ot);
rm = (modrm & 7) | REX_B(s);
gen_op_mov_reg_v(ot, rm, cpu_T0);
} else {
/* NOTE: order is important too for MMU exceptions */
s->popl_esp_hack = 1 << ot;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 1);
s->popl_esp_hack = 0;
gen_pop_update(s, ot);
}
break;
case 0xc8: /* enter */
{
int level;
val = cpu_lduw_code(env, s->pc);
s->pc += 2;
level = cpu_ldub_code(env, s->pc++);
gen_enter(s, val, level);
}
break;
case 0xc9: /* leave */
gen_leave(s);
break;
case 0x06: /* push es */
case 0x0e: /* push cs */
case 0x16: /* push ss */
case 0x1e: /* push ds */
if (CODE64(s))
goto illegal_op;
gen_op_movl_T0_seg(b >> 3);
gen_push_v(s, cpu_T0);
break;
case 0x1a0: /* push fs */
case 0x1a8: /* push gs */
gen_op_movl_T0_seg((b >> 3) & 7);
gen_push_v(s, cpu_T0);
break;
case 0x07: /* pop es */
case 0x17: /* pop ss */
case 0x1f: /* pop ds */
if (CODE64(s))
goto illegal_op;
reg = b >> 3;
ot = gen_pop_T0(s);
gen_movl_seg_T0(s, reg);
gen_pop_update(s, ot);
/* Note that reg == R_SS in gen_movl_seg_T0 always sets is_jmp. */
if (s->is_jmp) {
gen_jmp_im(s->pc - s->cs_base);
if (reg == R_SS) {
s->tf = 0;
gen_eob_inhibit_irq(s, true);
} else {
gen_eob(s);
}
}
break;
case 0x1a1: /* pop fs */
case 0x1a9: /* pop gs */
ot = gen_pop_T0(s);
gen_movl_seg_T0(s, (b >> 3) & 7);
gen_pop_update(s, ot);
if (s->is_jmp) {
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
}
break;
/**************************/
/* mov */
case 0x88:
case 0x89: /* mov Gv, Ev */
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
/* generate a generic store */
gen_ldst_modrm(env, s, modrm, ot, reg, 1);
break;
case 0xc6:
case 0xc7: /* mov Ev, Iv */
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
if (mod != 3) {
s->rip_offset = insn_const_size(ot);
gen_lea_modrm(env, s, modrm);
}
val = insn_get(env, s, ot);
tcg_gen_movi_tl(cpu_T0, val);
if (mod != 3) {
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_reg_v(ot, (modrm & 7) | REX_B(s), cpu_T0);
}
break;
case 0x8a:
case 0x8b: /* mov Ev, Gv */
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
case 0x8e: /* mov seg, Gv */
modrm = cpu_ldub_code(env, s->pc++);
reg = (modrm >> 3) & 7;
if (reg >= 6 || reg == R_CS)
goto illegal_op;
gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0);
gen_movl_seg_T0(s, reg);
/* Note that reg == R_SS in gen_movl_seg_T0 always sets is_jmp. */
if (s->is_jmp) {
gen_jmp_im(s->pc - s->cs_base);
if (reg == R_SS) {
s->tf = 0;
gen_eob_inhibit_irq(s, true);
} else {
gen_eob(s);
}
}
break;
case 0x8c: /* mov Gv, seg */
modrm = cpu_ldub_code(env, s->pc++);
reg = (modrm >> 3) & 7;
mod = (modrm >> 6) & 3;
if (reg >= 6)
goto illegal_op;
gen_op_movl_T0_seg(reg);
ot = mod == 3 ? dflag : MO_16;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 1);
break;
case 0x1b6: /* movzbS Gv, Eb */
case 0x1b7: /* movzwS Gv, Eb */
case 0x1be: /* movsbS Gv, Eb */
case 0x1bf: /* movswS Gv, Eb */
{
TCGMemOp d_ot;
TCGMemOp s_ot;
/* d_ot is the size of destination */
d_ot = dflag;
/* ot is the size of source */
ot = (b & 1) + MO_8;
/* s_ot is the sign+size of source */
s_ot = b & 8 ? MO_SIGN | ot : ot;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
if (mod == 3) {
if (s_ot == MO_SB && byte_reg_is_xH(rm)) {
tcg_gen_sextract_tl(cpu_T0, cpu_regs[rm - 4], 8, 8);
} else {
gen_op_mov_v_reg(ot, cpu_T0, rm);
switch (s_ot) {
case MO_UB:
tcg_gen_ext8u_tl(cpu_T0, cpu_T0);
break;
case MO_SB:
tcg_gen_ext8s_tl(cpu_T0, cpu_T0);
break;
case MO_UW:
tcg_gen_ext16u_tl(cpu_T0, cpu_T0);
break;
default:
case MO_SW:
tcg_gen_ext16s_tl(cpu_T0, cpu_T0);
break;
}
}
gen_op_mov_reg_v(d_ot, reg, cpu_T0);
} else {
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, s_ot, cpu_T0, cpu_A0);
gen_op_mov_reg_v(d_ot, reg, cpu_T0);
}
}
break;
case 0x8d: /* lea */
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
if (mod == 3)
goto illegal_op;
reg = ((modrm >> 3) & 7) | rex_r;
{
AddressParts a = gen_lea_modrm_0(env, s, modrm);
TCGv ea = gen_lea_modrm_1(a);
gen_lea_v_seg(s, s->aflag, ea, -1, -1);
gen_op_mov_reg_v(dflag, reg, cpu_A0);
}
break;
case 0xa0: /* mov EAX, Ov */
case 0xa1:
case 0xa2: /* mov Ov, EAX */
case 0xa3:
{
target_ulong offset_addr;
ot = mo_b_d(b, dflag);
switch (s->aflag) {
#ifdef TARGET_X86_64
case MO_64:
offset_addr = cpu_ldq_code(env, s->pc);
s->pc += 8;
break;
#endif
default:
offset_addr = insn_get(env, s, s->aflag);
break;
}
tcg_gen_movi_tl(cpu_A0, offset_addr);
gen_add_A0_ds_seg(s);
if ((b & 2) == 0) {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
gen_op_mov_reg_v(ot, R_EAX, cpu_T0);
} else {
gen_op_mov_v_reg(ot, cpu_T0, R_EAX);
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
}
}
break;
case 0xd7: /* xlat */
tcg_gen_mov_tl(cpu_A0, cpu_regs[R_EBX]);
tcg_gen_ext8u_tl(cpu_T0, cpu_regs[R_EAX]);
tcg_gen_add_tl(cpu_A0, cpu_A0, cpu_T0);
gen_extu(s->aflag, cpu_A0);
gen_add_A0_ds_seg(s);
gen_op_ld_v(s, MO_8, cpu_T0, cpu_A0);
gen_op_mov_reg_v(MO_8, R_EAX, cpu_T0);
break;
case 0xb0 ... 0xb7: /* mov R, Ib */
val = insn_get(env, s, MO_8);
tcg_gen_movi_tl(cpu_T0, val);
gen_op_mov_reg_v(MO_8, (b & 7) | REX_B(s), cpu_T0);
break;
case 0xb8 ... 0xbf: /* mov R, Iv */
#ifdef TARGET_X86_64
if (dflag == MO_64) {
uint64_t tmp;
/* 64 bit case */
tmp = cpu_ldq_code(env, s->pc);
s->pc += 8;
reg = (b & 7) | REX_B(s);
tcg_gen_movi_tl(cpu_T0, tmp);
gen_op_mov_reg_v(MO_64, reg, cpu_T0);
} else
#endif
{
ot = dflag;
val = insn_get(env, s, ot);
reg = (b & 7) | REX_B(s);
tcg_gen_movi_tl(cpu_T0, val);
gen_op_mov_reg_v(ot, reg, cpu_T0);
}
break;
case 0x91 ... 0x97: /* xchg R, EAX */
do_xchg_reg_eax:
ot = dflag;
reg = (b & 7) | REX_B(s);
rm = R_EAX;
goto do_xchg_reg;
case 0x86:
case 0x87: /* xchg Ev, Gv */
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
if (mod == 3) {
rm = (modrm & 7) | REX_B(s);
do_xchg_reg:
gen_op_mov_v_reg(ot, cpu_T0, reg);
gen_op_mov_v_reg(ot, cpu_T1, rm);
gen_op_mov_reg_v(ot, rm, cpu_T0);
gen_op_mov_reg_v(ot, reg, cpu_T1);
} else {
gen_lea_modrm(env, s, modrm);
gen_op_mov_v_reg(ot, cpu_T0, reg);
/* for xchg, lock is implicit */
tcg_gen_atomic_xchg_tl(cpu_T1, cpu_A0, cpu_T0,
s->mem_index, ot | MO_LE);
gen_op_mov_reg_v(ot, reg, cpu_T1);
}
break;
case 0xc4: /* les Gv */
/* In CODE64 this is VEX3; see above. */
op = R_ES;
goto do_lxx;
case 0xc5: /* lds Gv */
/* In CODE64 this is VEX2; see above. */
op = R_DS;
goto do_lxx;
case 0x1b2: /* lss Gv */
op = R_SS;
goto do_lxx;
case 0x1b4: /* lfs Gv */
op = R_FS;
goto do_lxx;
case 0x1b5: /* lgs Gv */
op = R_GS;
do_lxx:
ot = dflag != MO_16 ? MO_32 : MO_16;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
if (mod == 3)
goto illegal_op;
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, ot, cpu_T1, cpu_A0);
gen_add_A0_im(s, 1 << ot);
/* load the segment first to handle exceptions properly */
gen_op_ld_v(s, MO_16, cpu_T0, cpu_A0);
gen_movl_seg_T0(s, op);
/* then put the data */
gen_op_mov_reg_v(ot, reg, cpu_T1);
if (s->is_jmp) {
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
}
break;
/************************/
/* shifts */
case 0xc0:
case 0xc1:
/* shift Ev,Ib */
shift = 2;
grp2:
{
ot = mo_b_d(b, dflag);
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
op = (modrm >> 3) & 7;
if (mod != 3) {
if (shift == 2) {
s->rip_offset = 1;
}
gen_lea_modrm(env, s, modrm);
opreg = OR_TMP0;
} else {
opreg = (modrm & 7) | REX_B(s);
}
/* simpler op */
if (shift == 0) {
gen_shift(s, op, ot, opreg, OR_ECX);
} else {
if (shift == 2) {
shift = cpu_ldub_code(env, s->pc++);
}
gen_shifti(s, op, ot, opreg, shift);
}
}
break;
case 0xd0:
case 0xd1:
/* shift Ev,1 */
shift = 1;
goto grp2;
case 0xd2:
case 0xd3:
/* shift Ev,cl */
shift = 0;
goto grp2;
case 0x1a4: /* shld imm */
op = 0;
shift = 1;
goto do_shiftd;
case 0x1a5: /* shld cl */
op = 0;
shift = 0;
goto do_shiftd;
case 0x1ac: /* shrd imm */
op = 1;
shift = 1;
goto do_shiftd;
case 0x1ad: /* shrd cl */
op = 1;
shift = 0;
do_shiftd:
ot = dflag;
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
reg = ((modrm >> 3) & 7) | rex_r;
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
opreg = OR_TMP0;
} else {
opreg = rm;
}
gen_op_mov_v_reg(ot, cpu_T1, reg);
if (shift) {
TCGv imm = tcg_const_tl(cpu_ldub_code(env, s->pc++));
gen_shiftd_rm_T1(s, ot, opreg, op, imm);
tcg_temp_free(imm);
} else {
gen_shiftd_rm_T1(s, ot, opreg, op, cpu_regs[R_ECX]);
}
break;
/************************/
/* floats */
case 0xd8 ... 0xdf:
if (s->flags & (HF_EM_MASK | HF_TS_MASK)) {
/* if CR0.EM or CR0.TS are set, generate an FPU exception */
/* XXX: what to do if illegal op ? */
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
break;
}
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
rm = modrm & 7;
op = ((b & 7) << 3) | ((modrm >> 3) & 7);
if (mod != 3) {
/* memory op */
gen_lea_modrm(env, s, modrm);
switch(op) {
case 0x00 ... 0x07: /* fxxxs */
case 0x10 ... 0x17: /* fixxxl */
case 0x20 ... 0x27: /* fxxxl */
case 0x30 ... 0x37: /* fixxx */
{
int op1;
op1 = op & 7;
switch(op >> 4) {
case 0:
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
gen_helper_flds_FT0(cpu_env, cpu_tmp2_i32);
break;
case 1:
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
gen_helper_fildl_FT0(cpu_env, cpu_tmp2_i32);
break;
case 2:
tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_A0,
s->mem_index, MO_LEQ);
gen_helper_fldl_FT0(cpu_env, cpu_tmp1_i64);
break;
case 3:
default:
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LESW);
gen_helper_fildl_FT0(cpu_env, cpu_tmp2_i32);
break;
}
gen_helper_fp_arith_ST0_FT0(op1);
if (op1 == 3) {
/* fcomp needs pop */
gen_helper_fpop(cpu_env);
}
}
break;
case 0x08: /* flds */
case 0x0a: /* fsts */
case 0x0b: /* fstps */
case 0x18 ... 0x1b: /* fildl, fisttpl, fistl, fistpl */
case 0x28 ... 0x2b: /* fldl, fisttpll, fstl, fstpl */
case 0x38 ... 0x3b: /* filds, fisttps, fists, fistps */
switch(op & 7) {
case 0:
switch(op >> 4) {
case 0:
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
gen_helper_flds_ST0(cpu_env, cpu_tmp2_i32);
break;
case 1:
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
gen_helper_fildl_ST0(cpu_env, cpu_tmp2_i32);
break;
case 2:
tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_A0,
s->mem_index, MO_LEQ);
gen_helper_fldl_ST0(cpu_env, cpu_tmp1_i64);
break;
case 3:
default:
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LESW);
gen_helper_fildl_ST0(cpu_env, cpu_tmp2_i32);
break;
}
break;
case 1:
/* XXX: the corresponding CPUID bit must be tested ! */
switch(op >> 4) {
case 1:
gen_helper_fisttl_ST0(cpu_tmp2_i32, cpu_env);
tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
break;
case 2:
gen_helper_fisttll_ST0(cpu_tmp1_i64, cpu_env);
tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_A0,
s->mem_index, MO_LEQ);
break;
case 3:
default:
gen_helper_fistt_ST0(cpu_tmp2_i32, cpu_env);
tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUW);
break;
}
gen_helper_fpop(cpu_env);
break;
default:
switch(op >> 4) {
case 0:
gen_helper_fsts_ST0(cpu_tmp2_i32, cpu_env);
tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
break;
case 1:
gen_helper_fistl_ST0(cpu_tmp2_i32, cpu_env);
tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUL);
break;
case 2:
gen_helper_fstl_ST0(cpu_tmp1_i64, cpu_env);
tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_A0,
s->mem_index, MO_LEQ);
break;
case 3:
default:
gen_helper_fist_ST0(cpu_tmp2_i32, cpu_env);
tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUW);
break;
}
if ((op & 7) == 3)
gen_helper_fpop(cpu_env);
break;
}
break;
case 0x0c: /* fldenv mem */
gen_helper_fldenv(cpu_env, cpu_A0, tcg_const_i32(dflag - 1));
break;
case 0x0d: /* fldcw mem */
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUW);
gen_helper_fldcw(cpu_env, cpu_tmp2_i32);
break;
case 0x0e: /* fnstenv mem */
gen_helper_fstenv(cpu_env, cpu_A0, tcg_const_i32(dflag - 1));
break;
case 0x0f: /* fnstcw mem */
gen_helper_fnstcw(cpu_tmp2_i32, cpu_env);
tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUW);
break;
case 0x1d: /* fldt mem */
gen_helper_fldt_ST0(cpu_env, cpu_A0);
break;
case 0x1f: /* fstpt mem */
gen_helper_fstt_ST0(cpu_env, cpu_A0);
gen_helper_fpop(cpu_env);
break;
case 0x2c: /* frstor mem */
gen_helper_frstor(cpu_env, cpu_A0, tcg_const_i32(dflag - 1));
break;
case 0x2e: /* fnsave mem */
gen_helper_fsave(cpu_env, cpu_A0, tcg_const_i32(dflag - 1));
break;
case 0x2f: /* fnstsw mem */
gen_helper_fnstsw(cpu_tmp2_i32, cpu_env);
tcg_gen_qemu_st_i32(cpu_tmp2_i32, cpu_A0,
s->mem_index, MO_LEUW);
break;
case 0x3c: /* fbld */
gen_helper_fbld_ST0(cpu_env, cpu_A0);
break;
case 0x3e: /* fbstp */
gen_helper_fbst_ST0(cpu_env, cpu_A0);
gen_helper_fpop(cpu_env);
break;
case 0x3d: /* fildll */
tcg_gen_qemu_ld_i64(cpu_tmp1_i64, cpu_A0, s->mem_index, MO_LEQ);
gen_helper_fildll_ST0(cpu_env, cpu_tmp1_i64);
break;
case 0x3f: /* fistpll */
gen_helper_fistll_ST0(cpu_tmp1_i64, cpu_env);
tcg_gen_qemu_st_i64(cpu_tmp1_i64, cpu_A0, s->mem_index, MO_LEQ);
gen_helper_fpop(cpu_env);
break;
default:
goto unknown_op;
}
} else {
/* register float ops */
opreg = rm;
switch(op) {
case 0x08: /* fld sti */
gen_helper_fpush(cpu_env);
gen_helper_fmov_ST0_STN(cpu_env,
tcg_const_i32((opreg + 1) & 7));
break;
case 0x09: /* fxchg sti */
case 0x29: /* fxchg4 sti, undocumented op */
case 0x39: /* fxchg7 sti, undocumented op */
gen_helper_fxchg_ST0_STN(cpu_env, tcg_const_i32(opreg));
break;
case 0x0a: /* grp d9/2 */
switch(rm) {
case 0: /* fnop */
/* check exceptions (FreeBSD FPU probe) */
gen_helper_fwait(cpu_env);
break;
default:
goto unknown_op;
}
break;
case 0x0c: /* grp d9/4 */
switch(rm) {
case 0: /* fchs */
gen_helper_fchs_ST0(cpu_env);
break;
case 1: /* fabs */
gen_helper_fabs_ST0(cpu_env);
break;
case 4: /* ftst */
gen_helper_fldz_FT0(cpu_env);
gen_helper_fcom_ST0_FT0(cpu_env);
break;
case 5: /* fxam */
gen_helper_fxam_ST0(cpu_env);
break;
default:
goto unknown_op;
}
break;
case 0x0d: /* grp d9/5 */
{
switch(rm) {
case 0:
gen_helper_fpush(cpu_env);
gen_helper_fld1_ST0(cpu_env);
break;
case 1:
gen_helper_fpush(cpu_env);
gen_helper_fldl2t_ST0(cpu_env);
break;
case 2:
gen_helper_fpush(cpu_env);
gen_helper_fldl2e_ST0(cpu_env);
break;
case 3:
gen_helper_fpush(cpu_env);
gen_helper_fldpi_ST0(cpu_env);
break;
case 4:
gen_helper_fpush(cpu_env);
gen_helper_fldlg2_ST0(cpu_env);
break;
case 5:
gen_helper_fpush(cpu_env);
gen_helper_fldln2_ST0(cpu_env);
break;
case 6:
gen_helper_fpush(cpu_env);
gen_helper_fldz_ST0(cpu_env);
break;
default:
goto unknown_op;
}
}
break;
case 0x0e: /* grp d9/6 */
switch(rm) {
case 0: /* f2xm1 */
gen_helper_f2xm1(cpu_env);
break;
case 1: /* fyl2x */
gen_helper_fyl2x(cpu_env);
break;
case 2: /* fptan */
gen_helper_fptan(cpu_env);
break;
case 3: /* fpatan */
gen_helper_fpatan(cpu_env);
break;
case 4: /* fxtract */
gen_helper_fxtract(cpu_env);
break;
case 5: /* fprem1 */
gen_helper_fprem1(cpu_env);
break;
case 6: /* fdecstp */
gen_helper_fdecstp(cpu_env);
break;
default:
case 7: /* fincstp */
gen_helper_fincstp(cpu_env);
break;
}
break;
case 0x0f: /* grp d9/7 */
switch(rm) {
case 0: /* fprem */
gen_helper_fprem(cpu_env);
break;
case 1: /* fyl2xp1 */
gen_helper_fyl2xp1(cpu_env);
break;
case 2: /* fsqrt */
gen_helper_fsqrt(cpu_env);
break;
case 3: /* fsincos */
gen_helper_fsincos(cpu_env);
break;
case 5: /* fscale */
gen_helper_fscale(cpu_env);
break;
case 4: /* frndint */
gen_helper_frndint(cpu_env);
break;
case 6: /* fsin */
gen_helper_fsin(cpu_env);
break;
default:
case 7: /* fcos */
gen_helper_fcos(cpu_env);
break;
}
break;
case 0x00: case 0x01: case 0x04 ... 0x07: /* fxxx st, sti */
case 0x20: case 0x21: case 0x24 ... 0x27: /* fxxx sti, st */
case 0x30: case 0x31: case 0x34 ... 0x37: /* fxxxp sti, st */
{
int op1;
op1 = op & 7;
if (op >= 0x20) {
gen_helper_fp_arith_STN_ST0(op1, opreg);
if (op >= 0x30)
gen_helper_fpop(cpu_env);
} else {
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fp_arith_ST0_FT0(op1);
}
}
break;
case 0x02: /* fcom */
case 0x22: /* fcom2, undocumented op */
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fcom_ST0_FT0(cpu_env);
break;
case 0x03: /* fcomp */
case 0x23: /* fcomp3, undocumented op */
case 0x32: /* fcomp5, undocumented op */
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fcom_ST0_FT0(cpu_env);
gen_helper_fpop(cpu_env);
break;
case 0x15: /* da/5 */
switch(rm) {
case 1: /* fucompp */
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(1));
gen_helper_fucom_ST0_FT0(cpu_env);
gen_helper_fpop(cpu_env);
gen_helper_fpop(cpu_env);
break;
default:
goto unknown_op;
}
break;
case 0x1c:
switch(rm) {
case 0: /* feni (287 only, just do nop here) */
break;
case 1: /* fdisi (287 only, just do nop here) */
break;
case 2: /* fclex */
gen_helper_fclex(cpu_env);
break;
case 3: /* fninit */
gen_helper_fninit(cpu_env);
break;
case 4: /* fsetpm (287 only, just do nop here) */
break;
default:
goto unknown_op;
}
break;
case 0x1d: /* fucomi */
if (!(s->cpuid_features & CPUID_CMOV)) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fucomi_ST0_FT0(cpu_env);
set_cc_op(s, CC_OP_EFLAGS);
break;
case 0x1e: /* fcomi */
if (!(s->cpuid_features & CPUID_CMOV)) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fcomi_ST0_FT0(cpu_env);
set_cc_op(s, CC_OP_EFLAGS);
break;
case 0x28: /* ffree sti */
gen_helper_ffree_STN(cpu_env, tcg_const_i32(opreg));
break;
case 0x2a: /* fst sti */
gen_helper_fmov_STN_ST0(cpu_env, tcg_const_i32(opreg));
break;
case 0x2b: /* fstp sti */
case 0x0b: /* fstp1 sti, undocumented op */
case 0x3a: /* fstp8 sti, undocumented op */
case 0x3b: /* fstp9 sti, undocumented op */
gen_helper_fmov_STN_ST0(cpu_env, tcg_const_i32(opreg));
gen_helper_fpop(cpu_env);
break;
case 0x2c: /* fucom st(i) */
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fucom_ST0_FT0(cpu_env);
break;
case 0x2d: /* fucomp st(i) */
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fucom_ST0_FT0(cpu_env);
gen_helper_fpop(cpu_env);
break;
case 0x33: /* de/3 */
switch(rm) {
case 1: /* fcompp */
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(1));
gen_helper_fcom_ST0_FT0(cpu_env);
gen_helper_fpop(cpu_env);
gen_helper_fpop(cpu_env);
break;
default:
goto unknown_op;
}
break;
case 0x38: /* ffreep sti, undocumented op */
gen_helper_ffree_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fpop(cpu_env);
break;
case 0x3c: /* df/4 */
switch(rm) {
case 0:
gen_helper_fnstsw(cpu_tmp2_i32, cpu_env);
tcg_gen_extu_i32_tl(cpu_T0, cpu_tmp2_i32);
gen_op_mov_reg_v(MO_16, R_EAX, cpu_T0);
break;
default:
goto unknown_op;
}
break;
case 0x3d: /* fucomip */
if (!(s->cpuid_features & CPUID_CMOV)) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fucomi_ST0_FT0(cpu_env);
gen_helper_fpop(cpu_env);
set_cc_op(s, CC_OP_EFLAGS);
break;
case 0x3e: /* fcomip */
if (!(s->cpuid_features & CPUID_CMOV)) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_helper_fmov_FT0_STN(cpu_env, tcg_const_i32(opreg));
gen_helper_fcomi_ST0_FT0(cpu_env);
gen_helper_fpop(cpu_env);
set_cc_op(s, CC_OP_EFLAGS);
break;
case 0x10 ... 0x13: /* fcmovxx */
case 0x18 ... 0x1b:
{
int op1;
TCGLabel *l1;
static const uint8_t fcmov_cc[8] = {
(JCC_B << 1),
(JCC_Z << 1),
(JCC_BE << 1),
(JCC_P << 1),
};
if (!(s->cpuid_features & CPUID_CMOV)) {
goto illegal_op;
}
op1 = fcmov_cc[op & 3] | (((op >> 3) & 1) ^ 1);
l1 = gen_new_label();
gen_jcc1_noeob(s, op1, l1);
gen_helper_fmov_ST0_STN(cpu_env, tcg_const_i32(opreg));
gen_set_label(l1);
}
break;
default:
goto unknown_op;
}
}
break;
/************************/
/* string ops */
case 0xa4: /* movsS */
case 0xa5:
ot = mo_b_d(b, dflag);
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) {
gen_repz_movs(s, ot, pc_start - s->cs_base, s->pc - s->cs_base);
} else {
gen_movs(s, ot);
}
break;
case 0xaa: /* stosS */
case 0xab:
ot = mo_b_d(b, dflag);
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) {
gen_repz_stos(s, ot, pc_start - s->cs_base, s->pc - s->cs_base);
} else {
gen_stos(s, ot);
}
break;
case 0xac: /* lodsS */
case 0xad:
ot = mo_b_d(b, dflag);
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) {
gen_repz_lods(s, ot, pc_start - s->cs_base, s->pc - s->cs_base);
} else {
gen_lods(s, ot);
}
break;
case 0xae: /* scasS */
case 0xaf:
ot = mo_b_d(b, dflag);
if (prefixes & PREFIX_REPNZ) {
gen_repz_scas(s, ot, pc_start - s->cs_base, s->pc - s->cs_base, 1);
} else if (prefixes & PREFIX_REPZ) {
gen_repz_scas(s, ot, pc_start - s->cs_base, s->pc - s->cs_base, 0);
} else {
gen_scas(s, ot);
}
break;
case 0xa6: /* cmpsS */
case 0xa7:
ot = mo_b_d(b, dflag);
if (prefixes & PREFIX_REPNZ) {
gen_repz_cmps(s, ot, pc_start - s->cs_base, s->pc - s->cs_base, 1);
} else if (prefixes & PREFIX_REPZ) {
gen_repz_cmps(s, ot, pc_start - s->cs_base, s->pc - s->cs_base, 0);
} else {
gen_cmps(s, ot);
}
break;
case 0x6c: /* insS */
case 0x6d:
ot = mo_b_d32(b, dflag);
tcg_gen_ext16u_tl(cpu_T0, cpu_regs[R_EDX]);
gen_check_io(s, ot, pc_start - s->cs_base,
SVM_IOIO_TYPE_MASK | svm_is_rep(prefixes) | 4);
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) {
gen_repz_ins(s, ot, pc_start - s->cs_base, s->pc - s->cs_base);
} else {
gen_ins(s, ot);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_jmp(s, s->pc - s->cs_base);
}
}
break;
case 0x6e: /* outsS */
case 0x6f:
ot = mo_b_d32(b, dflag);
tcg_gen_ext16u_tl(cpu_T0, cpu_regs[R_EDX]);
gen_check_io(s, ot, pc_start - s->cs_base,
svm_is_rep(prefixes) | 4);
if (prefixes & (PREFIX_REPZ | PREFIX_REPNZ)) {
gen_repz_outs(s, ot, pc_start - s->cs_base, s->pc - s->cs_base);
} else {
gen_outs(s, ot);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_jmp(s, s->pc - s->cs_base);
}
}
break;
/************************/
/* port I/O */
case 0xe4:
case 0xe5:
ot = mo_b_d32(b, dflag);
val = cpu_ldub_code(env, s->pc++);
tcg_gen_movi_tl(cpu_T0, val);
gen_check_io(s, ot, pc_start - s->cs_base,
SVM_IOIO_TYPE_MASK | svm_is_rep(prefixes));
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_start();
}
tcg_gen_movi_i32(cpu_tmp2_i32, val);
gen_helper_in_func(ot, cpu_T1, cpu_tmp2_i32);
gen_op_mov_reg_v(ot, R_EAX, cpu_T1);
gen_bpt_io(s, cpu_tmp2_i32, ot);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
case 0xe6:
case 0xe7:
ot = mo_b_d32(b, dflag);
val = cpu_ldub_code(env, s->pc++);
tcg_gen_movi_tl(cpu_T0, val);
gen_check_io(s, ot, pc_start - s->cs_base,
svm_is_rep(prefixes));
gen_op_mov_v_reg(ot, cpu_T1, R_EAX);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_start();
}
tcg_gen_movi_i32(cpu_tmp2_i32, val);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T1);
gen_helper_out_func(ot, cpu_tmp2_i32, cpu_tmp3_i32);
gen_bpt_io(s, cpu_tmp2_i32, ot);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
case 0xec:
case 0xed:
ot = mo_b_d32(b, dflag);
tcg_gen_ext16u_tl(cpu_T0, cpu_regs[R_EDX]);
gen_check_io(s, ot, pc_start - s->cs_base,
SVM_IOIO_TYPE_MASK | svm_is_rep(prefixes));
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_start();
}
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_in_func(ot, cpu_T1, cpu_tmp2_i32);
gen_op_mov_reg_v(ot, R_EAX, cpu_T1);
gen_bpt_io(s, cpu_tmp2_i32, ot);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
case 0xee:
case 0xef:
ot = mo_b_d32(b, dflag);
tcg_gen_ext16u_tl(cpu_T0, cpu_regs[R_EDX]);
gen_check_io(s, ot, pc_start - s->cs_base,
svm_is_rep(prefixes));
gen_op_mov_v_reg(ot, cpu_T1, R_EAX);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_start();
}
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T1);
gen_helper_out_func(ot, cpu_tmp2_i32, cpu_tmp3_i32);
gen_bpt_io(s, cpu_tmp2_i32, ot);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
/************************/
/* control */
case 0xc2: /* ret im */
val = cpu_ldsw_code(env, s->pc);
s->pc += 2;
ot = gen_pop_T0(s);
gen_stack_update(s, val + (1 << ot));
/* Note that gen_pop_T0 uses a zero-extending load. */
gen_op_jmp_v(cpu_T0);
gen_bnd_jmp(s);
gen_eob(s);
break;
case 0xc3: /* ret */
ot = gen_pop_T0(s);
gen_pop_update(s, ot);
/* Note that gen_pop_T0 uses a zero-extending load. */
gen_op_jmp_v(cpu_T0);
gen_bnd_jmp(s);
gen_eob(s);
break;
case 0xca: /* lret im */
val = cpu_ldsw_code(env, s->pc);
s->pc += 2;
do_lret:
if (s->pe && !s->vm86) {
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_lret_protected(cpu_env, tcg_const_i32(dflag - 1),
tcg_const_i32(val));
} else {
gen_stack_A0(s);
/* pop offset */
gen_op_ld_v(s, dflag, cpu_T0, cpu_A0);
/* NOTE: keeping EIP updated is not a problem in case of
exception */
gen_op_jmp_v(cpu_T0);
/* pop selector */
gen_add_A0_im(s, 1 << dflag);
gen_op_ld_v(s, dflag, cpu_T0, cpu_A0);
gen_op_movl_seg_T0_vm(R_CS);
/* add stack offset */
gen_stack_update(s, val + (2 << dflag));
}
gen_eob(s);
break;
case 0xcb: /* lret */
val = 0;
goto do_lret;
case 0xcf: /* iret */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_IRET);
if (!s->pe) {
/* real mode */
gen_helper_iret_real(cpu_env, tcg_const_i32(dflag - 1));
set_cc_op(s, CC_OP_EFLAGS);
} else if (s->vm86) {
if (s->iopl != 3) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_helper_iret_real(cpu_env, tcg_const_i32(dflag - 1));
set_cc_op(s, CC_OP_EFLAGS);
}
} else {
gen_helper_iret_protected(cpu_env, tcg_const_i32(dflag - 1),
tcg_const_i32(s->pc - s->cs_base));
set_cc_op(s, CC_OP_EFLAGS);
}
gen_eob(s);
break;
case 0xe8: /* call im */
{
if (dflag != MO_16) {
tval = (int32_t)insn_get(env, s, MO_32);
} else {
tval = (int16_t)insn_get(env, s, MO_16);
}
next_eip = s->pc - s->cs_base;
tval += next_eip;
if (dflag == MO_16) {
tval &= 0xffff;
} else if (!CODE64(s)) {
tval &= 0xffffffff;
}
tcg_gen_movi_tl(cpu_T0, next_eip);
gen_push_v(s, cpu_T0);
gen_bnd_jmp(s);
gen_jmp(s, tval);
}
break;
case 0x9a: /* lcall im */
{
unsigned int selector, offset;
if (CODE64(s))
goto illegal_op;
ot = dflag;
offset = insn_get(env, s, ot);
selector = insn_get(env, s, MO_16);
tcg_gen_movi_tl(cpu_T0, selector);
tcg_gen_movi_tl(cpu_T1, offset);
}
goto do_lcall;
case 0xe9: /* jmp im */
if (dflag != MO_16) {
tval = (int32_t)insn_get(env, s, MO_32);
} else {
tval = (int16_t)insn_get(env, s, MO_16);
}
tval += s->pc - s->cs_base;
if (dflag == MO_16) {
tval &= 0xffff;
} else if (!CODE64(s)) {
tval &= 0xffffffff;
}
gen_bnd_jmp(s);
gen_jmp(s, tval);
break;
case 0xea: /* ljmp im */
{
unsigned int selector, offset;
if (CODE64(s))
goto illegal_op;
ot = dflag;
offset = insn_get(env, s, ot);
selector = insn_get(env, s, MO_16);
tcg_gen_movi_tl(cpu_T0, selector);
tcg_gen_movi_tl(cpu_T1, offset);
}
goto do_ljmp;
case 0xeb: /* jmp Jb */
tval = (int8_t)insn_get(env, s, MO_8);
tval += s->pc - s->cs_base;
if (dflag == MO_16) {
tval &= 0xffff;
}
gen_jmp(s, tval);
break;
case 0x70 ... 0x7f: /* jcc Jb */
tval = (int8_t)insn_get(env, s, MO_8);
goto do_jcc;
case 0x180 ... 0x18f: /* jcc Jv */
if (dflag != MO_16) {
tval = (int32_t)insn_get(env, s, MO_32);
} else {
tval = (int16_t)insn_get(env, s, MO_16);
}
do_jcc:
next_eip = s->pc - s->cs_base;
tval += next_eip;
if (dflag == MO_16) {
tval &= 0xffff;
}
gen_bnd_jmp(s);
gen_jcc(s, b, tval, next_eip);
break;
case 0x190 ... 0x19f: /* setcc Gv */
modrm = cpu_ldub_code(env, s->pc++);
gen_setcc1(s, b, cpu_T0);
gen_ldst_modrm(env, s, modrm, MO_8, OR_TMP0, 1);
break;
case 0x140 ... 0x14f: /* cmov Gv, Ev */
if (!(s->cpuid_features & CPUID_CMOV)) {
goto illegal_op;
}
ot = dflag;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
gen_cmovcc1(env, s, ot, b, modrm, reg);
break;
/************************/
/* flags */
case 0x9c: /* pushf */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_PUSHF);
if (s->vm86 && s->iopl != 3) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_update_cc_op(s);
gen_helper_read_eflags(cpu_T0, cpu_env);
gen_push_v(s, cpu_T0);
}
break;
case 0x9d: /* popf */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_POPF);
if (s->vm86 && s->iopl != 3) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
ot = gen_pop_T0(s);
if (s->cpl == 0) {
if (dflag != MO_16) {
gen_helper_write_eflags(cpu_env, cpu_T0,
tcg_const_i32((TF_MASK | AC_MASK |
ID_MASK | NT_MASK |
IF_MASK |
IOPL_MASK)));
} else {
gen_helper_write_eflags(cpu_env, cpu_T0,
tcg_const_i32((TF_MASK | AC_MASK |
ID_MASK | NT_MASK |
IF_MASK | IOPL_MASK)
& 0xffff));
}
} else {
if (s->cpl <= s->iopl) {
if (dflag != MO_16) {
gen_helper_write_eflags(cpu_env, cpu_T0,
tcg_const_i32((TF_MASK |
AC_MASK |
ID_MASK |
NT_MASK |
IF_MASK)));
} else {
gen_helper_write_eflags(cpu_env, cpu_T0,
tcg_const_i32((TF_MASK |
AC_MASK |
ID_MASK |
NT_MASK |
IF_MASK)
& 0xffff));
}
} else {
if (dflag != MO_16) {
gen_helper_write_eflags(cpu_env, cpu_T0,
tcg_const_i32((TF_MASK | AC_MASK |
ID_MASK | NT_MASK)));
} else {
gen_helper_write_eflags(cpu_env, cpu_T0,
tcg_const_i32((TF_MASK | AC_MASK |
ID_MASK | NT_MASK)
& 0xffff));
}
}
}
gen_pop_update(s, ot);
set_cc_op(s, CC_OP_EFLAGS);
/* abort translation because TF/AC flag may change */
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
}
break;
case 0x9e: /* sahf */
if (CODE64(s) && !(s->cpuid_ext3_features & CPUID_EXT3_LAHF_LM))
goto illegal_op;
gen_op_mov_v_reg(MO_8, cpu_T0, R_AH);
gen_compute_eflags(s);
tcg_gen_andi_tl(cpu_cc_src, cpu_cc_src, CC_O);
tcg_gen_andi_tl(cpu_T0, cpu_T0, CC_S | CC_Z | CC_A | CC_P | CC_C);
tcg_gen_or_tl(cpu_cc_src, cpu_cc_src, cpu_T0);
break;
case 0x9f: /* lahf */
if (CODE64(s) && !(s->cpuid_ext3_features & CPUID_EXT3_LAHF_LM))
goto illegal_op;
gen_compute_eflags(s);
/* Note: gen_compute_eflags() only gives the condition codes */
tcg_gen_ori_tl(cpu_T0, cpu_cc_src, 0x02);
gen_op_mov_reg_v(MO_8, R_AH, cpu_T0);
break;
case 0xf5: /* cmc */
gen_compute_eflags(s);
tcg_gen_xori_tl(cpu_cc_src, cpu_cc_src, CC_C);
break;
case 0xf8: /* clc */
gen_compute_eflags(s);
tcg_gen_andi_tl(cpu_cc_src, cpu_cc_src, ~CC_C);
break;
case 0xf9: /* stc */
gen_compute_eflags(s);
tcg_gen_ori_tl(cpu_cc_src, cpu_cc_src, CC_C);
break;
case 0xfc: /* cld */
tcg_gen_movi_i32(cpu_tmp2_i32, 1);
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, offsetof(CPUX86State, df));
break;
case 0xfd: /* std */
tcg_gen_movi_i32(cpu_tmp2_i32, -1);
tcg_gen_st_i32(cpu_tmp2_i32, cpu_env, offsetof(CPUX86State, df));
break;
/************************/
/* bit operations */
case 0x1ba: /* bt/bts/btr/btc Gv, im */
ot = dflag;
modrm = cpu_ldub_code(env, s->pc++);
op = (modrm >> 3) & 7;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
if (mod != 3) {
s->rip_offset = 1;
gen_lea_modrm(env, s, modrm);
if (!(s->prefix & PREFIX_LOCK)) {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
}
} else {
gen_op_mov_v_reg(ot, cpu_T0, rm);
}
/* load shift */
val = cpu_ldub_code(env, s->pc++);
tcg_gen_movi_tl(cpu_T1, val);
if (op < 4)
goto unknown_op;
op -= 4;
goto bt_op;
case 0x1a3: /* bt Gv, Ev */
op = 0;
goto do_btx;
case 0x1ab: /* bts */
op = 1;
goto do_btx;
case 0x1b3: /* btr */
op = 2;
goto do_btx;
case 0x1bb: /* btc */
op = 3;
do_btx:
ot = dflag;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
gen_op_mov_v_reg(MO_32, cpu_T1, reg);
if (mod != 3) {
AddressParts a = gen_lea_modrm_0(env, s, modrm);
/* specific case: we need to add a displacement */
gen_exts(ot, cpu_T1);
tcg_gen_sari_tl(cpu_tmp0, cpu_T1, 3 + ot);
tcg_gen_shli_tl(cpu_tmp0, cpu_tmp0, ot);
tcg_gen_add_tl(cpu_A0, gen_lea_modrm_1(a), cpu_tmp0);
gen_lea_v_seg(s, s->aflag, cpu_A0, a.def_seg, s->override);
if (!(s->prefix & PREFIX_LOCK)) {
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
}
} else {
gen_op_mov_v_reg(ot, cpu_T0, rm);
}
bt_op:
tcg_gen_andi_tl(cpu_T1, cpu_T1, (1 << (3 + ot)) - 1);
tcg_gen_movi_tl(cpu_tmp0, 1);
tcg_gen_shl_tl(cpu_tmp0, cpu_tmp0, cpu_T1);
if (s->prefix & PREFIX_LOCK) {
switch (op) {
case 0: /* bt */
/* Needs no atomic ops; we surpressed the normal
memory load for LOCK above so do it now. */
gen_op_ld_v(s, ot, cpu_T0, cpu_A0);
break;
case 1: /* bts */
tcg_gen_atomic_fetch_or_tl(cpu_T0, cpu_A0, cpu_tmp0,
s->mem_index, ot | MO_LE);
break;
case 2: /* btr */
tcg_gen_not_tl(cpu_tmp0, cpu_tmp0);
tcg_gen_atomic_fetch_and_tl(cpu_T0, cpu_A0, cpu_tmp0,
s->mem_index, ot | MO_LE);
break;
default:
case 3: /* btc */
tcg_gen_atomic_fetch_xor_tl(cpu_T0, cpu_A0, cpu_tmp0,
s->mem_index, ot | MO_LE);
break;
}
tcg_gen_shr_tl(cpu_tmp4, cpu_T0, cpu_T1);
} else {
tcg_gen_shr_tl(cpu_tmp4, cpu_T0, cpu_T1);
switch (op) {
case 0: /* bt */
/* Data already loaded; nothing to do. */
break;
case 1: /* bts */
tcg_gen_or_tl(cpu_T0, cpu_T0, cpu_tmp0);
break;
case 2: /* btr */
tcg_gen_andc_tl(cpu_T0, cpu_T0, cpu_tmp0);
break;
default:
case 3: /* btc */
tcg_gen_xor_tl(cpu_T0, cpu_T0, cpu_tmp0);
break;
}
if (op != 0) {
if (mod != 3) {
gen_op_st_v(s, ot, cpu_T0, cpu_A0);
} else {
gen_op_mov_reg_v(ot, rm, cpu_T0);
}
}
}
/* Delay all CC updates until after the store above. Note that
C is the result of the test, Z is unchanged, and the others
are all undefined. */
switch (s->cc_op) {
case CC_OP_MULB ... CC_OP_MULQ:
case CC_OP_ADDB ... CC_OP_ADDQ:
case CC_OP_ADCB ... CC_OP_ADCQ:
case CC_OP_SUBB ... CC_OP_SUBQ:
case CC_OP_SBBB ... CC_OP_SBBQ:
case CC_OP_LOGICB ... CC_OP_LOGICQ:
case CC_OP_INCB ... CC_OP_INCQ:
case CC_OP_DECB ... CC_OP_DECQ:
case CC_OP_SHLB ... CC_OP_SHLQ:
case CC_OP_SARB ... CC_OP_SARQ:
case CC_OP_BMILGB ... CC_OP_BMILGQ:
/* Z was going to be computed from the non-zero status of CC_DST.
We can get that same Z value (and the new C value) by leaving
CC_DST alone, setting CC_SRC, and using a CC_OP_SAR of the
same width. */
tcg_gen_mov_tl(cpu_cc_src, cpu_tmp4);
set_cc_op(s, ((s->cc_op - CC_OP_MULB) & 3) + CC_OP_SARB);
break;
default:
/* Otherwise, generate EFLAGS and replace the C bit. */
gen_compute_eflags(s);
tcg_gen_deposit_tl(cpu_cc_src, cpu_cc_src, cpu_tmp4,
ctz32(CC_C), 1);
break;
}
break;
case 0x1bc: /* bsf / tzcnt */
case 0x1bd: /* bsr / lzcnt */
ot = dflag;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
gen_extu(ot, cpu_T0);
/* Note that lzcnt and tzcnt are in different extensions. */
if ((prefixes & PREFIX_REPZ)
&& (b & 1
? s->cpuid_ext3_features & CPUID_EXT3_ABM
: s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_BMI1)) {
int size = 8 << ot;
/* For lzcnt/tzcnt, C bit is defined related to the input. */
tcg_gen_mov_tl(cpu_cc_src, cpu_T0);
if (b & 1) {
/* For lzcnt, reduce the target_ulong result by the
number of zeros that we expect to find at the top. */
tcg_gen_clzi_tl(cpu_T0, cpu_T0, TARGET_LONG_BITS);
tcg_gen_subi_tl(cpu_T0, cpu_T0, TARGET_LONG_BITS - size);
} else {
/* For tzcnt, a zero input must return the operand size. */
tcg_gen_ctzi_tl(cpu_T0, cpu_T0, size);
}
/* For lzcnt/tzcnt, Z bit is defined related to the result. */
gen_op_update1_cc();
set_cc_op(s, CC_OP_BMILGB + ot);
} else {
/* For bsr/bsf, only the Z bit is defined and it is related
to the input and not the result. */
tcg_gen_mov_tl(cpu_cc_dst, cpu_T0);
set_cc_op(s, CC_OP_LOGICB + ot);
/* ??? The manual says that the output is undefined when the
input is zero, but real hardware leaves it unchanged, and
real programs appear to depend on that. Accomplish this
by passing the output as the value to return upon zero. */
if (b & 1) {
/* For bsr, return the bit index of the first 1 bit,
not the count of leading zeros. */
tcg_gen_xori_tl(cpu_T1, cpu_regs[reg], TARGET_LONG_BITS - 1);
tcg_gen_clz_tl(cpu_T0, cpu_T0, cpu_T1);
tcg_gen_xori_tl(cpu_T0, cpu_T0, TARGET_LONG_BITS - 1);
} else {
tcg_gen_ctz_tl(cpu_T0, cpu_T0, cpu_regs[reg]);
}
}
gen_op_mov_reg_v(ot, reg, cpu_T0);
break;
/************************/
/* bcd */
case 0x27: /* daa */
if (CODE64(s))
goto illegal_op;
gen_update_cc_op(s);
gen_helper_daa(cpu_env);
set_cc_op(s, CC_OP_EFLAGS);
break;
case 0x2f: /* das */
if (CODE64(s))
goto illegal_op;
gen_update_cc_op(s);
gen_helper_das(cpu_env);
set_cc_op(s, CC_OP_EFLAGS);
break;
case 0x37: /* aaa */
if (CODE64(s))
goto illegal_op;
gen_update_cc_op(s);
gen_helper_aaa(cpu_env);
set_cc_op(s, CC_OP_EFLAGS);
break;
case 0x3f: /* aas */
if (CODE64(s))
goto illegal_op;
gen_update_cc_op(s);
gen_helper_aas(cpu_env);
set_cc_op(s, CC_OP_EFLAGS);
break;
case 0xd4: /* aam */
if (CODE64(s))
goto illegal_op;
val = cpu_ldub_code(env, s->pc++);
if (val == 0) {
gen_exception(s, EXCP00_DIVZ, pc_start - s->cs_base);
} else {
gen_helper_aam(cpu_env, tcg_const_i32(val));
set_cc_op(s, CC_OP_LOGICB);
}
break;
case 0xd5: /* aad */
if (CODE64(s))
goto illegal_op;
val = cpu_ldub_code(env, s->pc++);
gen_helper_aad(cpu_env, tcg_const_i32(val));
set_cc_op(s, CC_OP_LOGICB);
break;
/************************/
/* misc */
case 0x90: /* nop */
/* XXX: correct lock test for all insn */
if (prefixes & PREFIX_LOCK) {
goto illegal_op;
}
/* If REX_B is set, then this is xchg eax, r8d, not a nop. */
if (REX_B(s)) {
goto do_xchg_reg_eax;
}
if (prefixes & PREFIX_REPZ) {
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_pause(cpu_env, tcg_const_i32(s->pc - pc_start));
s->is_jmp = DISAS_TB_JUMP;
}
break;
case 0x9b: /* fwait */
if ((s->flags & (HF_MP_MASK | HF_TS_MASK)) ==
(HF_MP_MASK | HF_TS_MASK)) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
} else {
gen_helper_fwait(cpu_env);
}
break;
case 0xcc: /* int3 */
gen_interrupt(s, EXCP03_INT3, pc_start - s->cs_base, s->pc - s->cs_base);
break;
case 0xcd: /* int N */
val = cpu_ldub_code(env, s->pc++);
if (s->vm86 && s->iopl != 3) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_interrupt(s, val, pc_start - s->cs_base, s->pc - s->cs_base);
}
break;
case 0xce: /* into */
if (CODE64(s))
goto illegal_op;
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_into(cpu_env, tcg_const_i32(s->pc - pc_start));
break;
#ifdef WANT_ICEBP
case 0xf1: /* icebp (undocumented, exits to external debugger) */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_ICEBP);
#if 1
gen_debug(s, pc_start - s->cs_base);
#else
/* start debug */
tb_flush(CPU(x86_env_get_cpu(env)));
qemu_set_log(CPU_LOG_INT | CPU_LOG_TB_IN_ASM);
#endif
break;
#endif
case 0xfa: /* cli */
if (!s->vm86) {
if (s->cpl <= s->iopl) {
gen_helper_cli(cpu_env);
} else {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
}
} else {
if (s->iopl == 3) {
gen_helper_cli(cpu_env);
} else {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
}
}
break;
case 0xfb: /* sti */
if (s->vm86 ? s->iopl == 3 : s->cpl <= s->iopl) {
gen_helper_sti(cpu_env);
/* interruptions are enabled only the first insn after sti */
gen_jmp_im(s->pc - s->cs_base);
gen_eob_inhibit_irq(s, true);
} else {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
}
break;
case 0x62: /* bound */
if (CODE64(s))
goto illegal_op;
ot = dflag;
modrm = cpu_ldub_code(env, s->pc++);
reg = (modrm >> 3) & 7;
mod = (modrm >> 6) & 3;
if (mod == 3)
goto illegal_op;
gen_op_mov_v_reg(ot, cpu_T0, reg);
gen_lea_modrm(env, s, modrm);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
if (ot == MO_16) {
gen_helper_boundw(cpu_env, cpu_A0, cpu_tmp2_i32);
} else {
gen_helper_boundl(cpu_env, cpu_A0, cpu_tmp2_i32);
}
break;
case 0x1c8 ... 0x1cf: /* bswap reg */
reg = (b & 7) | REX_B(s);
#ifdef TARGET_X86_64
if (dflag == MO_64) {
gen_op_mov_v_reg(MO_64, cpu_T0, reg);
tcg_gen_bswap64_i64(cpu_T0, cpu_T0);
gen_op_mov_reg_v(MO_64, reg, cpu_T0);
} else
#endif
{
gen_op_mov_v_reg(MO_32, cpu_T0, reg);
tcg_gen_ext32u_tl(cpu_T0, cpu_T0);
tcg_gen_bswap32_tl(cpu_T0, cpu_T0);
gen_op_mov_reg_v(MO_32, reg, cpu_T0);
}
break;
case 0xd6: /* salc */
if (CODE64(s))
goto illegal_op;
gen_compute_eflags_c(s, cpu_T0);
tcg_gen_neg_tl(cpu_T0, cpu_T0);
gen_op_mov_reg_v(MO_8, R_EAX, cpu_T0);
break;
case 0xe0: /* loopnz */
case 0xe1: /* loopz */
case 0xe2: /* loop */
case 0xe3: /* jecxz */
{
TCGLabel *l1, *l2, *l3;
tval = (int8_t)insn_get(env, s, MO_8);
next_eip = s->pc - s->cs_base;
tval += next_eip;
if (dflag == MO_16) {
tval &= 0xffff;
}
l1 = gen_new_label();
l2 = gen_new_label();
l3 = gen_new_label();
b &= 3;
switch(b) {
case 0: /* loopnz */
case 1: /* loopz */
gen_op_add_reg_im(s->aflag, R_ECX, -1);
gen_op_jz_ecx(s->aflag, l3);
gen_jcc1(s, (JCC_Z << 1) | (b ^ 1), l1);
break;
case 2: /* loop */
gen_op_add_reg_im(s->aflag, R_ECX, -1);
gen_op_jnz_ecx(s->aflag, l1);
break;
default:
case 3: /* jcxz */
gen_op_jz_ecx(s->aflag, l1);
break;
}
gen_set_label(l3);
gen_jmp_im(next_eip);
tcg_gen_br(l2);
gen_set_label(l1);
gen_jmp_im(tval);
gen_set_label(l2);
gen_eob(s);
}
break;
case 0x130: /* wrmsr */
case 0x132: /* rdmsr */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
if (b & 2) {
gen_helper_rdmsr(cpu_env);
} else {
gen_helper_wrmsr(cpu_env);
}
}
break;
case 0x131: /* rdtsc */
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_start();
}
gen_helper_rdtsc(cpu_env);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
case 0x133: /* rdpmc */
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_rdpmc(cpu_env);
break;
case 0x134: /* sysenter */
/* For Intel SYSENTER is valid on 64-bit */
if (CODE64(s) && env->cpuid_vendor1 != CPUID_VENDOR_INTEL_1)
goto illegal_op;
if (!s->pe) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_helper_sysenter(cpu_env);
gen_eob(s);
}
break;
case 0x135: /* sysexit */
/* For Intel SYSEXIT is valid on 64-bit */
if (CODE64(s) && env->cpuid_vendor1 != CPUID_VENDOR_INTEL_1)
goto illegal_op;
if (!s->pe) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_helper_sysexit(cpu_env, tcg_const_i32(dflag - 1));
gen_eob(s);
}
break;
#ifdef TARGET_X86_64
case 0x105: /* syscall */
/* XXX: is it usable in real mode ? */
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_syscall(cpu_env, tcg_const_i32(s->pc - pc_start));
/* TF handling for the syscall insn is different. The TF bit is checked
after the syscall insn completes. This allows #DB to not be
generated after one has entered CPL0 if TF is set in FMASK. */
gen_eob_worker(s, false, true);
break;
case 0x107: /* sysret */
if (!s->pe) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_helper_sysret(cpu_env, tcg_const_i32(dflag - 1));
/* condition codes are modified only in long mode */
if (s->lma) {
set_cc_op(s, CC_OP_EFLAGS);
}
/* TF handling for the sysret insn is different. The TF bit is
checked after the sysret insn completes. This allows #DB to be
generated "as if" the syscall insn in userspace has just
completed. */
gen_eob_worker(s, false, true);
}
break;
#endif
case 0x1a2: /* cpuid */
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_cpuid(cpu_env);
break;
case 0xf4: /* hlt */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_hlt(cpu_env, tcg_const_i32(s->pc - pc_start));
s->is_jmp = DISAS_TB_JUMP;
}
break;
case 0x100:
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
op = (modrm >> 3) & 7;
switch(op) {
case 0: /* sldt */
if (!s->pe || s->vm86)
goto illegal_op;
gen_svm_check_intercept(s, pc_start, SVM_EXIT_LDTR_READ);
tcg_gen_ld32u_tl(cpu_T0, cpu_env,
offsetof(CPUX86State, ldt.selector));
ot = mod == 3 ? dflag : MO_16;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 1);
break;
case 2: /* lldt */
if (!s->pe || s->vm86)
goto illegal_op;
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_LDTR_WRITE);
gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_lldt(cpu_env, cpu_tmp2_i32);
}
break;
case 1: /* str */
if (!s->pe || s->vm86)
goto illegal_op;
gen_svm_check_intercept(s, pc_start, SVM_EXIT_TR_READ);
tcg_gen_ld32u_tl(cpu_T0, cpu_env,
offsetof(CPUX86State, tr.selector));
ot = mod == 3 ? dflag : MO_16;
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 1);
break;
case 3: /* ltr */
if (!s->pe || s->vm86)
goto illegal_op;
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_TR_WRITE);
gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T0);
gen_helper_ltr(cpu_env, cpu_tmp2_i32);
}
break;
case 4: /* verr */
case 5: /* verw */
if (!s->pe || s->vm86)
goto illegal_op;
gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0);
gen_update_cc_op(s);
if (op == 4) {
gen_helper_verr(cpu_env, cpu_T0);
} else {
gen_helper_verw(cpu_env, cpu_T0);
}
set_cc_op(s, CC_OP_EFLAGS);
break;
default:
goto unknown_op;
}
break;
case 0x101:
modrm = cpu_ldub_code(env, s->pc++);
switch (modrm) {
CASE_MODRM_MEM_OP(0): /* sgdt */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_GDTR_READ);
gen_lea_modrm(env, s, modrm);
tcg_gen_ld32u_tl(cpu_T0,
cpu_env, offsetof(CPUX86State, gdt.limit));
gen_op_st_v(s, MO_16, cpu_T0, cpu_A0);
gen_add_A0_im(s, 2);
tcg_gen_ld_tl(cpu_T0, cpu_env, offsetof(CPUX86State, gdt.base));
if (dflag == MO_16) {
tcg_gen_andi_tl(cpu_T0, cpu_T0, 0xffffff);
}
gen_op_st_v(s, CODE64(s) + MO_32, cpu_T0, cpu_A0);
break;
case 0xc8: /* monitor */
if (!(s->cpuid_ext_features & CPUID_EXT_MONITOR) || s->cpl != 0) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
tcg_gen_mov_tl(cpu_A0, cpu_regs[R_EAX]);
gen_extu(s->aflag, cpu_A0);
gen_add_A0_ds_seg(s);
gen_helper_monitor(cpu_env, cpu_A0);
break;
case 0xc9: /* mwait */
if (!(s->cpuid_ext_features & CPUID_EXT_MONITOR) || s->cpl != 0) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_mwait(cpu_env, tcg_const_i32(s->pc - pc_start));
gen_eob(s);
break;
case 0xca: /* clac */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_SMAP)
|| s->cpl != 0) {
goto illegal_op;
}
gen_helper_clac(cpu_env);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
break;
case 0xcb: /* stac */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_SMAP)
|| s->cpl != 0) {
goto illegal_op;
}
gen_helper_stac(cpu_env);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
break;
CASE_MODRM_MEM_OP(1): /* sidt */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_IDTR_READ);
gen_lea_modrm(env, s, modrm);
tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State, idt.limit));
gen_op_st_v(s, MO_16, cpu_T0, cpu_A0);
gen_add_A0_im(s, 2);
tcg_gen_ld_tl(cpu_T0, cpu_env, offsetof(CPUX86State, idt.base));
if (dflag == MO_16) {
tcg_gen_andi_tl(cpu_T0, cpu_T0, 0xffffff);
}
gen_op_st_v(s, CODE64(s) + MO_32, cpu_T0, cpu_A0);
break;
case 0xd0: /* xgetbv */
if ((s->cpuid_ext_features & CPUID_EXT_XSAVE) == 0
|| (s->prefix & (PREFIX_LOCK | PREFIX_DATA
| PREFIX_REPZ | PREFIX_REPNZ))) {
goto illegal_op;
}
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_ECX]);
gen_helper_xgetbv(cpu_tmp1_i64, cpu_env, cpu_tmp2_i32);
tcg_gen_extr_i64_tl(cpu_regs[R_EAX], cpu_regs[R_EDX], cpu_tmp1_i64);
break;
case 0xd1: /* xsetbv */
if ((s->cpuid_ext_features & CPUID_EXT_XSAVE) == 0
|| (s->prefix & (PREFIX_LOCK | PREFIX_DATA
| PREFIX_REPZ | PREFIX_REPNZ))) {
goto illegal_op;
}
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
tcg_gen_concat_tl_i64(cpu_tmp1_i64, cpu_regs[R_EAX],
cpu_regs[R_EDX]);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_ECX]);
gen_helper_xsetbv(cpu_env, cpu_tmp2_i32, cpu_tmp1_i64);
/* End TB because translation flags may change. */
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
break;
case 0xd8: /* VMRUN */
if (!(s->flags & HF_SVME_MASK) || !s->pe) {
goto illegal_op;
}
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_vmrun(cpu_env, tcg_const_i32(s->aflag - 1),
tcg_const_i32(s->pc - pc_start));
tcg_gen_exit_tb(0);
s->is_jmp = DISAS_TB_JUMP;
break;
case 0xd9: /* VMMCALL */
if (!(s->flags & HF_SVME_MASK)) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_vmmcall(cpu_env);
break;
case 0xda: /* VMLOAD */
if (!(s->flags & HF_SVME_MASK) || !s->pe) {
goto illegal_op;
}
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_vmload(cpu_env, tcg_const_i32(s->aflag - 1));
break;
case 0xdb: /* VMSAVE */
if (!(s->flags & HF_SVME_MASK) || !s->pe) {
goto illegal_op;
}
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_vmsave(cpu_env, tcg_const_i32(s->aflag - 1));
break;
case 0xdc: /* STGI */
if ((!(s->flags & HF_SVME_MASK)
&& !(s->cpuid_ext3_features & CPUID_EXT3_SKINIT))
|| !s->pe) {
goto illegal_op;
}
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_stgi(cpu_env);
break;
case 0xdd: /* CLGI */
if (!(s->flags & HF_SVME_MASK) || !s->pe) {
goto illegal_op;
}
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_clgi(cpu_env);
break;
case 0xde: /* SKINIT */
if ((!(s->flags & HF_SVME_MASK)
&& !(s->cpuid_ext3_features & CPUID_EXT3_SKINIT))
|| !s->pe) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_skinit(cpu_env);
break;
case 0xdf: /* INVLPGA */
if (!(s->flags & HF_SVME_MASK) || !s->pe) {
goto illegal_op;
}
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_helper_invlpga(cpu_env, tcg_const_i32(s->aflag - 1));
break;
CASE_MODRM_MEM_OP(2): /* lgdt */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_svm_check_intercept(s, pc_start, SVM_EXIT_GDTR_WRITE);
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, MO_16, cpu_T1, cpu_A0);
gen_add_A0_im(s, 2);
gen_op_ld_v(s, CODE64(s) + MO_32, cpu_T0, cpu_A0);
if (dflag == MO_16) {
tcg_gen_andi_tl(cpu_T0, cpu_T0, 0xffffff);
}
tcg_gen_st_tl(cpu_T0, cpu_env, offsetof(CPUX86State, gdt.base));
tcg_gen_st32_tl(cpu_T1, cpu_env, offsetof(CPUX86State, gdt.limit));
break;
CASE_MODRM_MEM_OP(3): /* lidt */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_svm_check_intercept(s, pc_start, SVM_EXIT_IDTR_WRITE);
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, MO_16, cpu_T1, cpu_A0);
gen_add_A0_im(s, 2);
gen_op_ld_v(s, CODE64(s) + MO_32, cpu_T0, cpu_A0);
if (dflag == MO_16) {
tcg_gen_andi_tl(cpu_T0, cpu_T0, 0xffffff);
}
tcg_gen_st_tl(cpu_T0, cpu_env, offsetof(CPUX86State, idt.base));
tcg_gen_st32_tl(cpu_T1, cpu_env, offsetof(CPUX86State, idt.limit));
break;
CASE_MODRM_OP(4): /* smsw */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_READ_CR0);
tcg_gen_ld_tl(cpu_T0, cpu_env, offsetof(CPUX86State, cr[0]));
if (CODE64(s)) {
mod = (modrm >> 6) & 3;
ot = (mod != 3 ? MO_16 : s->dflag);
} else {
ot = MO_16;
}
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 1);
break;
case 0xee: /* rdpkru */
if (prefixes & PREFIX_LOCK) {
goto illegal_op;
}
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_ECX]);
gen_helper_rdpkru(cpu_tmp1_i64, cpu_env, cpu_tmp2_i32);
tcg_gen_extr_i64_tl(cpu_regs[R_EAX], cpu_regs[R_EDX], cpu_tmp1_i64);
break;
case 0xef: /* wrpkru */
if (prefixes & PREFIX_LOCK) {
goto illegal_op;
}
tcg_gen_concat_tl_i64(cpu_tmp1_i64, cpu_regs[R_EAX],
cpu_regs[R_EDX]);
tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_regs[R_ECX]);
gen_helper_wrpkru(cpu_env, cpu_tmp2_i32, cpu_tmp1_i64);
break;
CASE_MODRM_OP(6): /* lmsw */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_svm_check_intercept(s, pc_start, SVM_EXIT_WRITE_CR0);
gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0);
gen_helper_lmsw(cpu_env, cpu_T0);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
break;
CASE_MODRM_MEM_OP(7): /* invlpg */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
break;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
gen_lea_modrm(env, s, modrm);
gen_helper_invlpg(cpu_env, cpu_A0);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
break;
case 0xf8: /* swapgs */
#ifdef TARGET_X86_64
if (CODE64(s)) {
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
tcg_gen_mov_tl(cpu_T0, cpu_seg_base[R_GS]);
tcg_gen_ld_tl(cpu_seg_base[R_GS], cpu_env,
offsetof(CPUX86State, kernelgsbase));
tcg_gen_st_tl(cpu_T0, cpu_env,
offsetof(CPUX86State, kernelgsbase));
}
break;
}
#endif
goto illegal_op;
case 0xf9: /* rdtscp */
if (!(s->cpuid_ext2_features & CPUID_EXT2_RDTSCP)) {
goto illegal_op;
}
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_start();
}
gen_helper_rdtscp(cpu_env);
if (s->tb->cflags & CF_USE_ICOUNT) {
gen_io_end();
gen_jmp(s, s->pc - s->cs_base);
}
break;
default:
goto unknown_op;
}
break;
case 0x108: /* invd */
case 0x109: /* wbinvd */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_svm_check_intercept(s, pc_start, (b & 2) ? SVM_EXIT_INVD : SVM_EXIT_WBINVD);
/* nothing to do */
}
break;
case 0x63: /* arpl or movslS (x86_64) */
#ifdef TARGET_X86_64
if (CODE64(s)) {
int d_ot;
/* d_ot is the size of destination */
d_ot = dflag;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
mod = (modrm >> 6) & 3;
rm = (modrm & 7) | REX_B(s);
if (mod == 3) {
gen_op_mov_v_reg(MO_32, cpu_T0, rm);
/* sign extend */
if (d_ot == MO_64) {
tcg_gen_ext32s_tl(cpu_T0, cpu_T0);
}
gen_op_mov_reg_v(d_ot, reg, cpu_T0);
} else {
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, MO_32 | MO_SIGN, cpu_T0, cpu_A0);
gen_op_mov_reg_v(d_ot, reg, cpu_T0);
}
} else
#endif
{
TCGLabel *label1;
TCGv t0, t1, t2, a0;
if (!s->pe || s->vm86)
goto illegal_op;
t0 = tcg_temp_local_new();
t1 = tcg_temp_local_new();
t2 = tcg_temp_local_new();
ot = MO_16;
modrm = cpu_ldub_code(env, s->pc++);
reg = (modrm >> 3) & 7;
mod = (modrm >> 6) & 3;
rm = modrm & 7;
if (mod != 3) {
gen_lea_modrm(env, s, modrm);
gen_op_ld_v(s, ot, t0, cpu_A0);
a0 = tcg_temp_local_new();
tcg_gen_mov_tl(a0, cpu_A0);
} else {
gen_op_mov_v_reg(ot, t0, rm);
TCGV_UNUSED(a0);
}
gen_op_mov_v_reg(ot, t1, reg);
tcg_gen_andi_tl(cpu_tmp0, t0, 3);
tcg_gen_andi_tl(t1, t1, 3);
tcg_gen_movi_tl(t2, 0);
label1 = gen_new_label();
tcg_gen_brcond_tl(TCG_COND_GE, cpu_tmp0, t1, label1);
tcg_gen_andi_tl(t0, t0, ~3);
tcg_gen_or_tl(t0, t0, t1);
tcg_gen_movi_tl(t2, CC_Z);
gen_set_label(label1);
if (mod != 3) {
gen_op_st_v(s, ot, t0, a0);
tcg_temp_free(a0);
} else {
gen_op_mov_reg_v(ot, rm, t0);
}
gen_compute_eflags(s);
tcg_gen_andi_tl(cpu_cc_src, cpu_cc_src, ~CC_Z);
tcg_gen_or_tl(cpu_cc_src, cpu_cc_src, t2);
tcg_temp_free(t0);
tcg_temp_free(t1);
tcg_temp_free(t2);
}
break;
case 0x102: /* lar */
case 0x103: /* lsl */
{
TCGLabel *label1;
TCGv t0;
if (!s->pe || s->vm86)
goto illegal_op;
ot = dflag != MO_16 ? MO_32 : MO_16;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
gen_ldst_modrm(env, s, modrm, MO_16, OR_TMP0, 0);
t0 = tcg_temp_local_new();
gen_update_cc_op(s);
if (b == 0x102) {
gen_helper_lar(t0, cpu_env, cpu_T0);
} else {
gen_helper_lsl(t0, cpu_env, cpu_T0);
}
tcg_gen_andi_tl(cpu_tmp0, cpu_cc_src, CC_Z);
label1 = gen_new_label();
tcg_gen_brcondi_tl(TCG_COND_EQ, cpu_tmp0, 0, label1);
gen_op_mov_reg_v(ot, reg, t0);
gen_set_label(label1);
set_cc_op(s, CC_OP_EFLAGS);
tcg_temp_free(t0);
}
break;
case 0x118:
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
op = (modrm >> 3) & 7;
switch(op) {
case 0: /* prefetchnta */
case 1: /* prefetchnt0 */
case 2: /* prefetchnt0 */
case 3: /* prefetchnt0 */
if (mod == 3)
goto illegal_op;
gen_nop_modrm(env, s, modrm);
/* nothing more to do */
break;
default: /* nop (multi byte) */
gen_nop_modrm(env, s, modrm);
break;
}
break;
case 0x11a:
modrm = cpu_ldub_code(env, s->pc++);
if (s->flags & HF_MPX_EN_MASK) {
mod = (modrm >> 6) & 3;
reg = ((modrm >> 3) & 7) | rex_r;
if (prefixes & PREFIX_REPZ) {
/* bndcl */
if (reg >= 4
|| (prefixes & PREFIX_LOCK)
|| s->aflag == MO_16) {
goto illegal_op;
}
gen_bndck(env, s, modrm, TCG_COND_LTU, cpu_bndl[reg]);
} else if (prefixes & PREFIX_REPNZ) {
/* bndcu */
if (reg >= 4
|| (prefixes & PREFIX_LOCK)
|| s->aflag == MO_16) {
goto illegal_op;
}
TCGv_i64 notu = tcg_temp_new_i64();
tcg_gen_not_i64(notu, cpu_bndu[reg]);
gen_bndck(env, s, modrm, TCG_COND_GTU, notu);
tcg_temp_free_i64(notu);
} else if (prefixes & PREFIX_DATA) {
/* bndmov -- from reg/mem */
if (reg >= 4 || s->aflag == MO_16) {
goto illegal_op;
}
if (mod == 3) {
int reg2 = (modrm & 7) | REX_B(s);
if (reg2 >= 4 || (prefixes & PREFIX_LOCK)) {
goto illegal_op;
}
if (s->flags & HF_MPX_IU_MASK) {
tcg_gen_mov_i64(cpu_bndl[reg], cpu_bndl[reg2]);
tcg_gen_mov_i64(cpu_bndu[reg], cpu_bndu[reg2]);
}
} else {
gen_lea_modrm(env, s, modrm);
if (CODE64(s)) {
tcg_gen_qemu_ld_i64(cpu_bndl[reg], cpu_A0,
s->mem_index, MO_LEQ);
tcg_gen_addi_tl(cpu_A0, cpu_A0, 8);
tcg_gen_qemu_ld_i64(cpu_bndu[reg], cpu_A0,
s->mem_index, MO_LEQ);
} else {
tcg_gen_qemu_ld_i64(cpu_bndl[reg], cpu_A0,
s->mem_index, MO_LEUL);
tcg_gen_addi_tl(cpu_A0, cpu_A0, 4);
tcg_gen_qemu_ld_i64(cpu_bndu[reg], cpu_A0,
s->mem_index, MO_LEUL);
}
/* bnd registers are now in-use */
gen_set_hflag(s, HF_MPX_IU_MASK);
}
} else if (mod != 3) {
/* bndldx */
AddressParts a = gen_lea_modrm_0(env, s, modrm);
if (reg >= 4
|| (prefixes & PREFIX_LOCK)
|| s->aflag == MO_16
|| a.base < -1) {
goto illegal_op;
}
if (a.base >= 0) {
tcg_gen_addi_tl(cpu_A0, cpu_regs[a.base], a.disp);
} else {
tcg_gen_movi_tl(cpu_A0, 0);
}
gen_lea_v_seg(s, s->aflag, cpu_A0, a.def_seg, s->override);
if (a.index >= 0) {
tcg_gen_mov_tl(cpu_T0, cpu_regs[a.index]);
} else {
tcg_gen_movi_tl(cpu_T0, 0);
}
if (CODE64(s)) {
gen_helper_bndldx64(cpu_bndl[reg], cpu_env, cpu_A0, cpu_T0);
tcg_gen_ld_i64(cpu_bndu[reg], cpu_env,
offsetof(CPUX86State, mmx_t0.MMX_Q(0)));
} else {
gen_helper_bndldx32(cpu_bndu[reg], cpu_env, cpu_A0, cpu_T0);
tcg_gen_ext32u_i64(cpu_bndl[reg], cpu_bndu[reg]);
tcg_gen_shri_i64(cpu_bndu[reg], cpu_bndu[reg], 32);
}
gen_set_hflag(s, HF_MPX_IU_MASK);
}
}
gen_nop_modrm(env, s, modrm);
break;
case 0x11b:
modrm = cpu_ldub_code(env, s->pc++);
if (s->flags & HF_MPX_EN_MASK) {
mod = (modrm >> 6) & 3;
reg = ((modrm >> 3) & 7) | rex_r;
if (mod != 3 && (prefixes & PREFIX_REPZ)) {
/* bndmk */
if (reg >= 4
|| (prefixes & PREFIX_LOCK)
|| s->aflag == MO_16) {
goto illegal_op;
}
AddressParts a = gen_lea_modrm_0(env, s, modrm);
if (a.base >= 0) {
tcg_gen_extu_tl_i64(cpu_bndl[reg], cpu_regs[a.base]);
if (!CODE64(s)) {
tcg_gen_ext32u_i64(cpu_bndl[reg], cpu_bndl[reg]);
}
} else if (a.base == -1) {
/* no base register has lower bound of 0 */
tcg_gen_movi_i64(cpu_bndl[reg], 0);
} else {
/* rip-relative generates #ud */
goto illegal_op;
}
tcg_gen_not_tl(cpu_A0, gen_lea_modrm_1(a));
if (!CODE64(s)) {
tcg_gen_ext32u_tl(cpu_A0, cpu_A0);
}
tcg_gen_extu_tl_i64(cpu_bndu[reg], cpu_A0);
/* bnd registers are now in-use */
gen_set_hflag(s, HF_MPX_IU_MASK);
break;
} else if (prefixes & PREFIX_REPNZ) {
/* bndcn */
if (reg >= 4
|| (prefixes & PREFIX_LOCK)
|| s->aflag == MO_16) {
goto illegal_op;
}
gen_bndck(env, s, modrm, TCG_COND_GTU, cpu_bndu[reg]);
} else if (prefixes & PREFIX_DATA) {
/* bndmov -- to reg/mem */
if (reg >= 4 || s->aflag == MO_16) {
goto illegal_op;
}
if (mod == 3) {
int reg2 = (modrm & 7) | REX_B(s);
if (reg2 >= 4 || (prefixes & PREFIX_LOCK)) {
goto illegal_op;
}
if (s->flags & HF_MPX_IU_MASK) {
tcg_gen_mov_i64(cpu_bndl[reg2], cpu_bndl[reg]);
tcg_gen_mov_i64(cpu_bndu[reg2], cpu_bndu[reg]);
}
} else {
gen_lea_modrm(env, s, modrm);
if (CODE64(s)) {
tcg_gen_qemu_st_i64(cpu_bndl[reg], cpu_A0,
s->mem_index, MO_LEQ);
tcg_gen_addi_tl(cpu_A0, cpu_A0, 8);
tcg_gen_qemu_st_i64(cpu_bndu[reg], cpu_A0,
s->mem_index, MO_LEQ);
} else {
tcg_gen_qemu_st_i64(cpu_bndl[reg], cpu_A0,
s->mem_index, MO_LEUL);
tcg_gen_addi_tl(cpu_A0, cpu_A0, 4);
tcg_gen_qemu_st_i64(cpu_bndu[reg], cpu_A0,
s->mem_index, MO_LEUL);
}
}
} else if (mod != 3) {
/* bndstx */
AddressParts a = gen_lea_modrm_0(env, s, modrm);
if (reg >= 4
|| (prefixes & PREFIX_LOCK)
|| s->aflag == MO_16
|| a.base < -1) {
goto illegal_op;
}
if (a.base >= 0) {
tcg_gen_addi_tl(cpu_A0, cpu_regs[a.base], a.disp);
} else {
tcg_gen_movi_tl(cpu_A0, 0);
}
gen_lea_v_seg(s, s->aflag, cpu_A0, a.def_seg, s->override);
if (a.index >= 0) {
tcg_gen_mov_tl(cpu_T0, cpu_regs[a.index]);
} else {
tcg_gen_movi_tl(cpu_T0, 0);
}
if (CODE64(s)) {
gen_helper_bndstx64(cpu_env, cpu_A0, cpu_T0,
cpu_bndl[reg], cpu_bndu[reg]);
} else {
gen_helper_bndstx32(cpu_env, cpu_A0, cpu_T0,
cpu_bndl[reg], cpu_bndu[reg]);
}
}
}
gen_nop_modrm(env, s, modrm);
break;
case 0x119: case 0x11c ... 0x11f: /* nop (multi byte) */
modrm = cpu_ldub_code(env, s->pc++);
gen_nop_modrm(env, s, modrm);
break;
case 0x120: /* mov reg, crN */
case 0x122: /* mov crN, reg */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
modrm = cpu_ldub_code(env, s->pc++);
/* Ignore the mod bits (assume (modrm&0xc0)==0xc0).
* AMD documentation (24594.pdf) and testing of
* intel 386 and 486 processors all show that the mod bits
* are assumed to be 1's, regardless of actual values.
*/
rm = (modrm & 7) | REX_B(s);
reg = ((modrm >> 3) & 7) | rex_r;
if (CODE64(s))
ot = MO_64;
else
ot = MO_32;
if ((prefixes & PREFIX_LOCK) && (reg == 0) &&
(s->cpuid_ext3_features & CPUID_EXT3_CR8LEG)) {
reg = 8;
}
switch(reg) {
case 0:
case 2:
case 3:
case 4:
case 8:
gen_update_cc_op(s);
gen_jmp_im(pc_start - s->cs_base);
if (b & 2) {
gen_op_mov_v_reg(ot, cpu_T0, rm);
gen_helper_write_crN(cpu_env, tcg_const_i32(reg),
cpu_T0);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
} else {
gen_helper_read_crN(cpu_T0, cpu_env, tcg_const_i32(reg));
gen_op_mov_reg_v(ot, rm, cpu_T0);
}
break;
default:
goto unknown_op;
}
}
break;
case 0x121: /* mov reg, drN */
case 0x123: /* mov drN, reg */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
modrm = cpu_ldub_code(env, s->pc++);
/* Ignore the mod bits (assume (modrm&0xc0)==0xc0).
* AMD documentation (24594.pdf) and testing of
* intel 386 and 486 processors all show that the mod bits
* are assumed to be 1's, regardless of actual values.
*/
rm = (modrm & 7) | REX_B(s);
reg = ((modrm >> 3) & 7) | rex_r;
if (CODE64(s))
ot = MO_64;
else
ot = MO_32;
if (reg >= 8) {
goto illegal_op;
}
if (b & 2) {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_WRITE_DR0 + reg);
gen_op_mov_v_reg(ot, cpu_T0, rm);
tcg_gen_movi_i32(cpu_tmp2_i32, reg);
gen_helper_set_dr(cpu_env, cpu_tmp2_i32, cpu_T0);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
} else {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_READ_DR0 + reg);
tcg_gen_movi_i32(cpu_tmp2_i32, reg);
gen_helper_get_dr(cpu_T0, cpu_env, cpu_tmp2_i32);
gen_op_mov_reg_v(ot, rm, cpu_T0);
}
}
break;
case 0x106: /* clts */
if (s->cpl != 0) {
gen_exception(s, EXCP0D_GPF, pc_start - s->cs_base);
} else {
gen_svm_check_intercept(s, pc_start, SVM_EXIT_WRITE_CR0);
gen_helper_clts(cpu_env);
/* abort block because static cpu state changed */
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
}
break;
/* MMX/3DNow!/SSE/SSE2/SSE3/SSSE3/SSE4 support */
case 0x1c3: /* MOVNTI reg, mem */
if (!(s->cpuid_features & CPUID_SSE2))
goto illegal_op;
ot = mo_64_32(dflag);
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
if (mod == 3)
goto illegal_op;
reg = ((modrm >> 3) & 7) | rex_r;
/* generate a generic store */
gen_ldst_modrm(env, s, modrm, ot, reg, 1);
break;
case 0x1ae:
modrm = cpu_ldub_code(env, s->pc++);
switch (modrm) {
CASE_MODRM_MEM_OP(0): /* fxsave */
if (!(s->cpuid_features & CPUID_FXSR)
|| (prefixes & PREFIX_LOCK)) {
goto illegal_op;
}
if ((s->flags & HF_EM_MASK) || (s->flags & HF_TS_MASK)) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
break;
}
gen_lea_modrm(env, s, modrm);
gen_helper_fxsave(cpu_env, cpu_A0);
break;
CASE_MODRM_MEM_OP(1): /* fxrstor */
if (!(s->cpuid_features & CPUID_FXSR)
|| (prefixes & PREFIX_LOCK)) {
goto illegal_op;
}
if ((s->flags & HF_EM_MASK) || (s->flags & HF_TS_MASK)) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
break;
}
gen_lea_modrm(env, s, modrm);
gen_helper_fxrstor(cpu_env, cpu_A0);
break;
CASE_MODRM_MEM_OP(2): /* ldmxcsr */
if ((s->flags & HF_EM_MASK) || !(s->flags & HF_OSFXSR_MASK)) {
goto illegal_op;
}
if (s->flags & HF_TS_MASK) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
break;
}
gen_lea_modrm(env, s, modrm);
tcg_gen_qemu_ld_i32(cpu_tmp2_i32, cpu_A0, s->mem_index, MO_LEUL);
gen_helper_ldmxcsr(cpu_env, cpu_tmp2_i32);
break;
CASE_MODRM_MEM_OP(3): /* stmxcsr */
if ((s->flags & HF_EM_MASK) || !(s->flags & HF_OSFXSR_MASK)) {
goto illegal_op;
}
if (s->flags & HF_TS_MASK) {
gen_exception(s, EXCP07_PREX, pc_start - s->cs_base);
break;
}
gen_lea_modrm(env, s, modrm);
tcg_gen_ld32u_tl(cpu_T0, cpu_env, offsetof(CPUX86State, mxcsr));
gen_op_st_v(s, MO_32, cpu_T0, cpu_A0);
break;
CASE_MODRM_MEM_OP(4): /* xsave */
if ((s->cpuid_ext_features & CPUID_EXT_XSAVE) == 0
|| (prefixes & (PREFIX_LOCK | PREFIX_DATA
| PREFIX_REPZ | PREFIX_REPNZ))) {
goto illegal_op;
}
gen_lea_modrm(env, s, modrm);
tcg_gen_concat_tl_i64(cpu_tmp1_i64, cpu_regs[R_EAX],
cpu_regs[R_EDX]);
gen_helper_xsave(cpu_env, cpu_A0, cpu_tmp1_i64);
break;
CASE_MODRM_MEM_OP(5): /* xrstor */
if ((s->cpuid_ext_features & CPUID_EXT_XSAVE) == 0
|| (prefixes & (PREFIX_LOCK | PREFIX_DATA
| PREFIX_REPZ | PREFIX_REPNZ))) {
goto illegal_op;
}
gen_lea_modrm(env, s, modrm);
tcg_gen_concat_tl_i64(cpu_tmp1_i64, cpu_regs[R_EAX],
cpu_regs[R_EDX]);
gen_helper_xrstor(cpu_env, cpu_A0, cpu_tmp1_i64);
/* XRSTOR is how MPX is enabled, which changes how
we translate. Thus we need to end the TB. */
gen_update_cc_op(s);
gen_jmp_im(s->pc - s->cs_base);
gen_eob(s);
break;
CASE_MODRM_MEM_OP(6): /* xsaveopt / clwb */
if (prefixes & PREFIX_LOCK) {
goto illegal_op;
}
if (prefixes & PREFIX_DATA) {
/* clwb */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_CLWB)) {
goto illegal_op;
}
gen_nop_modrm(env, s, modrm);
} else {
/* xsaveopt */
if ((s->cpuid_ext_features & CPUID_EXT_XSAVE) == 0
|| (s->cpuid_xsave_features & CPUID_XSAVE_XSAVEOPT) == 0
|| (prefixes & (PREFIX_REPZ | PREFIX_REPNZ))) {
goto illegal_op;
}
gen_lea_modrm(env, s, modrm);
tcg_gen_concat_tl_i64(cpu_tmp1_i64, cpu_regs[R_EAX],
cpu_regs[R_EDX]);
gen_helper_xsaveopt(cpu_env, cpu_A0, cpu_tmp1_i64);
}
break;
CASE_MODRM_MEM_OP(7): /* clflush / clflushopt */
if (prefixes & PREFIX_LOCK) {
goto illegal_op;
}
if (prefixes & PREFIX_DATA) {
/* clflushopt */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_CLFLUSHOPT)) {
goto illegal_op;
}
} else {
/* clflush */
if ((s->prefix & (PREFIX_REPZ | PREFIX_REPNZ))
|| !(s->cpuid_features & CPUID_CLFLUSH)) {
goto illegal_op;
}
}
gen_nop_modrm(env, s, modrm);
break;
case 0xc0 ... 0xc7: /* rdfsbase (f3 0f ae /0) */
case 0xc8 ... 0xc8: /* rdgsbase (f3 0f ae /1) */
case 0xd0 ... 0xd7: /* wrfsbase (f3 0f ae /2) */
case 0xd8 ... 0xd8: /* wrgsbase (f3 0f ae /3) */
if (CODE64(s)
&& (prefixes & PREFIX_REPZ)
&& !(prefixes & PREFIX_LOCK)
&& (s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_FSGSBASE)) {
TCGv base, treg, src, dst;
/* Preserve hflags bits by testing CR4 at runtime. */
tcg_gen_movi_i32(cpu_tmp2_i32, CR4_FSGSBASE_MASK);
gen_helper_cr4_testbit(cpu_env, cpu_tmp2_i32);
base = cpu_seg_base[modrm & 8 ? R_GS : R_FS];
treg = cpu_regs[(modrm & 7) | REX_B(s)];
if (modrm & 0x10) {
/* wr*base */
dst = base, src = treg;
} else {
/* rd*base */
dst = treg, src = base;
}
if (s->dflag == MO_32) {
tcg_gen_ext32u_tl(dst, src);
} else {
tcg_gen_mov_tl(dst, src);
}
break;
}
goto unknown_op;
case 0xf8: /* sfence / pcommit */
if (prefixes & PREFIX_DATA) {
/* pcommit */
if (!(s->cpuid_7_0_ebx_features & CPUID_7_0_EBX_PCOMMIT)
|| (prefixes & PREFIX_LOCK)) {
goto illegal_op;
}
break;
}
/* fallthru */
case 0xf9 ... 0xff: /* sfence */
if (!(s->cpuid_features & CPUID_SSE)
|| (prefixes & PREFIX_LOCK)) {
goto illegal_op;
}
tcg_gen_mb(TCG_MO_ST_ST | TCG_BAR_SC);
break;
case 0xe8 ... 0xef: /* lfence */
if (!(s->cpuid_features & CPUID_SSE)
|| (prefixes & PREFIX_LOCK)) {
goto illegal_op;
}
tcg_gen_mb(TCG_MO_LD_LD | TCG_BAR_SC);
break;
case 0xf0 ... 0xf7: /* mfence */
if (!(s->cpuid_features & CPUID_SSE2)
|| (prefixes & PREFIX_LOCK)) {
goto illegal_op;
}
tcg_gen_mb(TCG_MO_ALL | TCG_BAR_SC);
break;
default:
goto unknown_op;
}
break;
case 0x10d: /* 3DNow! prefetch(w) */
modrm = cpu_ldub_code(env, s->pc++);
mod = (modrm >> 6) & 3;
if (mod == 3)
goto illegal_op;
gen_nop_modrm(env, s, modrm);
break;
case 0x1aa: /* rsm */
gen_svm_check_intercept(s, pc_start, SVM_EXIT_RSM);
if (!(s->flags & HF_SMM_MASK))
goto illegal_op;
gen_update_cc_op(s);
gen_jmp_im(s->pc - s->cs_base);
gen_helper_rsm(cpu_env);
gen_eob(s);
break;
case 0x1b8: /* SSE4.2 popcnt */
if ((prefixes & (PREFIX_REPZ | PREFIX_LOCK | PREFIX_REPNZ)) !=
PREFIX_REPZ)
goto illegal_op;
if (!(s->cpuid_ext_features & CPUID_EXT_POPCNT))
goto illegal_op;
modrm = cpu_ldub_code(env, s->pc++);
reg = ((modrm >> 3) & 7) | rex_r;
if (s->prefix & PREFIX_DATA) {
ot = MO_16;
} else {
ot = mo_64_32(dflag);
}
gen_ldst_modrm(env, s, modrm, ot, OR_TMP0, 0);
gen_extu(ot, cpu_T0);
tcg_gen_mov_tl(cpu_cc_src, cpu_T0);
tcg_gen_ctpop_tl(cpu_T0, cpu_T0);
gen_op_mov_reg_v(ot, reg, cpu_T0);
set_cc_op(s, CC_OP_POPCNT);
break;
case 0x10e ... 0x10f:
/* 3DNow! instructions, ignore prefixes */
s->prefix &= ~(PREFIX_REPZ | PREFIX_REPNZ | PREFIX_DATA);
case 0x110 ... 0x117:
case 0x128 ... 0x12f:
case 0x138 ... 0x13a:
case 0x150 ... 0x179:
case 0x17c ... 0x17f:
case 0x1c2:
case 0x1c4 ... 0x1c6:
case 0x1d0 ... 0x1fe:
gen_sse(env, s, b, pc_start, rex_r);
break;
default:
goto unknown_op;
}
return s->pc;
illegal_op:
gen_illegal_opcode(s);
return s->pc;
unknown_op:
gen_unknown_opcode(env, s);
return s->pc;
}
void tcg_x86_init(void)
{
static const char reg_names[CPU_NB_REGS][4] = {
#ifdef TARGET_X86_64
[R_EAX] = "rax",
[R_EBX] = "rbx",
[R_ECX] = "rcx",
[R_EDX] = "rdx",
[R_ESI] = "rsi",
[R_EDI] = "rdi",
[R_EBP] = "rbp",
[R_ESP] = "rsp",
[8] = "r8",
[9] = "r9",
[10] = "r10",
[11] = "r11",
[12] = "r12",
[13] = "r13",
[14] = "r14",
[15] = "r15",
#else
[R_EAX] = "eax",
[R_EBX] = "ebx",
[R_ECX] = "ecx",
[R_EDX] = "edx",
[R_ESI] = "esi",
[R_EDI] = "edi",
[R_EBP] = "ebp",
[R_ESP] = "esp",
#endif
};
static const char seg_base_names[6][8] = {
[R_CS] = "cs_base",
[R_DS] = "ds_base",
[R_ES] = "es_base",
[R_FS] = "fs_base",
[R_GS] = "gs_base",
[R_SS] = "ss_base",
};
static const char bnd_regl_names[4][8] = {
"bnd0_lb", "bnd1_lb", "bnd2_lb", "bnd3_lb"
};
static const char bnd_regu_names[4][8] = {
"bnd0_ub", "bnd1_ub", "bnd2_ub", "bnd3_ub"
};
int i;
static bool initialized;
if (initialized) {
return;
}
initialized = true;
cpu_env = tcg_global_reg_new_ptr(TCG_AREG0, "env");
tcg_ctx.tcg_env = cpu_env;
cpu_cc_op = tcg_global_mem_new_i32(cpu_env,
offsetof(CPUX86State, cc_op), "cc_op");
cpu_cc_dst = tcg_global_mem_new(cpu_env, offsetof(CPUX86State, cc_dst),
"cc_dst");
cpu_cc_src = tcg_global_mem_new(cpu_env, offsetof(CPUX86State, cc_src),
"cc_src");
cpu_cc_src2 = tcg_global_mem_new(cpu_env, offsetof(CPUX86State, cc_src2),
"cc_src2");
for (i = 0; i < CPU_NB_REGS; ++i) {
cpu_regs[i] = tcg_global_mem_new(cpu_env,
offsetof(CPUX86State, regs[i]),
reg_names[i]);
}
for (i = 0; i < 6; ++i) {
cpu_seg_base[i]
= tcg_global_mem_new(cpu_env,
offsetof(CPUX86State, segs[i].base),
seg_base_names[i]);
}
for (i = 0; i < 4; ++i) {
cpu_bndl[i]
= tcg_global_mem_new_i64(cpu_env,
offsetof(CPUX86State, bnd_regs[i].lb),
bnd_regl_names[i]);
cpu_bndu[i]
= tcg_global_mem_new_i64(cpu_env,
offsetof(CPUX86State, bnd_regs[i].ub),
bnd_regu_names[i]);
}
}
/* generate intermediate code for basic block 'tb'. */
void gen_intermediate_code(CPUX86State *env, TranslationBlock *tb)
{
X86CPU *cpu = x86_env_get_cpu(env);
CPUState *cs = CPU(cpu);
DisasContext dc1, *dc = &dc1;
target_ulong pc_ptr;
uint32_t flags;
target_ulong pc_start;
target_ulong cs_base;
int num_insns;
int max_insns;
/* generate intermediate code */
pc_start = tb->pc;
cs_base = tb->cs_base;
flags = tb->flags;
dc->pe = (flags >> HF_PE_SHIFT) & 1;
dc->code32 = (flags >> HF_CS32_SHIFT) & 1;
dc->ss32 = (flags >> HF_SS32_SHIFT) & 1;
dc->addseg = (flags >> HF_ADDSEG_SHIFT) & 1;
dc->f_st = 0;
dc->vm86 = (flags >> VM_SHIFT) & 1;
dc->cpl = (flags >> HF_CPL_SHIFT) & 3;
dc->iopl = (flags >> IOPL_SHIFT) & 3;
dc->tf = (flags >> TF_SHIFT) & 1;
dc->singlestep_enabled = cs->singlestep_enabled;
dc->cc_op = CC_OP_DYNAMIC;
dc->cc_op_dirty = false;
dc->cs_base = cs_base;
dc->tb = tb;
dc->popl_esp_hack = 0;
/* select memory access functions */
dc->mem_index = 0;
#ifdef CONFIG_SOFTMMU
dc->mem_index = cpu_mmu_index(env, false);
#endif
dc->cpuid_features = env->features[FEAT_1_EDX];
dc->cpuid_ext_features = env->features[FEAT_1_ECX];
dc->cpuid_ext2_features = env->features[FEAT_8000_0001_EDX];
dc->cpuid_ext3_features = env->features[FEAT_8000_0001_ECX];
dc->cpuid_7_0_ebx_features = env->features[FEAT_7_0_EBX];
dc->cpuid_xsave_features = env->features[FEAT_XSAVE];
#ifdef TARGET_X86_64
dc->lma = (flags >> HF_LMA_SHIFT) & 1;
dc->code64 = (flags >> HF_CS64_SHIFT) & 1;
#endif
dc->flags = flags;
dc->jmp_opt = !(dc->tf || cs->singlestep_enabled ||
(flags & HF_INHIBIT_IRQ_MASK));
/* Do not optimize repz jumps at all in icount mode, because
rep movsS instructions are execured with different paths
in !repz_opt and repz_opt modes. The first one was used
always except single step mode. And this setting
disables jumps optimization and control paths become
equivalent in run and single step modes.
Now there will be no jump optimization for repz in
record/replay modes and there will always be an
additional step for ecx=0 when icount is enabled.
*/
dc->repz_opt = !dc->jmp_opt && !(tb->cflags & CF_USE_ICOUNT);
#if 0
/* check addseg logic */
if (!dc->addseg && (dc->vm86 || !dc->pe || !dc->code32))
printf("ERROR addseg\n");
#endif
cpu_T0 = tcg_temp_new();
cpu_T1 = tcg_temp_new();
cpu_A0 = tcg_temp_new();
cpu_tmp0 = tcg_temp_new();
cpu_tmp1_i64 = tcg_temp_new_i64();
cpu_tmp2_i32 = tcg_temp_new_i32();
cpu_tmp3_i32 = tcg_temp_new_i32();
cpu_tmp4 = tcg_temp_new();
cpu_ptr0 = tcg_temp_new_ptr();
cpu_ptr1 = tcg_temp_new_ptr();
cpu_cc_srcT = tcg_temp_local_new();
dc->is_jmp = DISAS_NEXT;
pc_ptr = pc_start;
num_insns = 0;
max_insns = tb->cflags & CF_COUNT_MASK;
if (max_insns == 0) {
max_insns = CF_COUNT_MASK;
}
if (max_insns > TCG_MAX_INSNS) {
max_insns = TCG_MAX_INSNS;
}
gen_tb_start(tb);
for(;;) {
tcg_gen_insn_start(pc_ptr, dc->cc_op);
num_insns++;
/* If RF is set, suppress an internally generated breakpoint. */
if (unlikely(cpu_breakpoint_test(cs, pc_ptr,
tb->flags & HF_RF_MASK
? BP_GDB : BP_ANY))) {
gen_debug(dc, pc_ptr - dc->cs_base);
/* The address covered by the breakpoint must be included in
[tb->pc, tb->pc + tb->size) in order to for it to be
properly cleared -- thus we increment the PC here so that
the logic setting tb->size below does the right thing. */
pc_ptr += 1;
goto done_generating;
}
if (num_insns == max_insns && (tb->cflags & CF_LAST_IO)) {
gen_io_start();
}
pc_ptr = disas_insn(env, dc, pc_ptr);
/* stop translation if indicated */
if (dc->is_jmp)
break;
/* if single step mode, we generate only one instruction and
generate an exception */
/* if irq were inhibited with HF_INHIBIT_IRQ_MASK, we clear
the flag and abort the translation to give the irqs a
change to be happen */
if (dc->tf || dc->singlestep_enabled ||
(flags & HF_INHIBIT_IRQ_MASK)) {
gen_jmp_im(pc_ptr - dc->cs_base);
gen_eob(dc);
break;
}
/* Do not cross the boundary of the pages in icount mode,
it can cause an exception. Do it only when boundary is
crossed by the first instruction in the block.
If current instruction already crossed the bound - it's ok,
because an exception hasn't stopped this code.
*/
if ((tb->cflags & CF_USE_ICOUNT)
&& ((pc_ptr & TARGET_PAGE_MASK)
!= ((pc_ptr + TARGET_MAX_INSN_SIZE - 1) & TARGET_PAGE_MASK)
|| (pc_ptr & ~TARGET_PAGE_MASK) == 0)) {
gen_jmp_im(pc_ptr - dc->cs_base);
gen_eob(dc);
break;
}
/* if too long translation, stop generation too */
if (tcg_op_buf_full() ||
(pc_ptr - pc_start) >= (TARGET_PAGE_SIZE - 32) ||
num_insns >= max_insns) {
gen_jmp_im(pc_ptr - dc->cs_base);
gen_eob(dc);
break;
}
if (singlestep) {
gen_jmp_im(pc_ptr - dc->cs_base);
gen_eob(dc);
break;
}
}
if (tb->cflags & CF_LAST_IO)
gen_io_end();
done_generating:
gen_tb_end(tb, num_insns);
#ifdef DEBUG_DISAS
if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)
&& qemu_log_in_addr_range(pc_start)) {
int disas_flags;
qemu_log_lock();
qemu_log("----------------\n");
qemu_log("IN: %s\n", lookup_symbol(pc_start));
#ifdef TARGET_X86_64
if (dc->code64)
disas_flags = 2;
else
#endif
disas_flags = !dc->code32;
log_target_disas(cs, pc_start, pc_ptr - pc_start, disas_flags);
qemu_log("\n");
qemu_log_unlock();
}
#endif
tb->size = pc_ptr - pc_start;
tb->icount = num_insns;
}
void restore_state_to_opc(CPUX86State *env, TranslationBlock *tb,
target_ulong *data)
{
int cc_op = data[1];
env->eip = data[0] - tb->cs_base;
if (cc_op != CC_OP_DYNAMIC) {
env->cc_op = cc_op;
}
}
| ./CrossVul/dataset_final_sorted/CWE-94/c/bad_3326_0 |
crossvul-cpp_data_bad_1213_0 | /* Copyright (C) 2007-2016 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
* \author Gurvinder Singh <gurvindersinghdahiya@gmail.com>
*
* TCP stream tracking and reassembly engine.
*
* \todo - 4WHS: what if after the 2nd SYN we turn out to be normal 3WHS anyway?
*/
#include "suricata-common.h"
#include "suricata.h"
#include "decode.h"
#include "debug.h"
#include "detect.h"
#include "flow.h"
#include "flow-util.h"
#include "conf.h"
#include "conf-yaml-loader.h"
#include "threads.h"
#include "threadvars.h"
#include "tm-threads.h"
#include "util-pool.h"
#include "util-pool-thread.h"
#include "util-checksum.h"
#include "util-unittest.h"
#include "util-print.h"
#include "util-debug.h"
#include "util-device.h"
#include "stream-tcp-private.h"
#include "stream-tcp-reassemble.h"
#include "stream-tcp.h"
#include "stream-tcp-inline.h"
#include "stream-tcp-sack.h"
#include "stream-tcp-util.h"
#include "stream.h"
#include "pkt-var.h"
#include "host.h"
#include "app-layer.h"
#include "app-layer-parser.h"
#include "app-layer-protos.h"
#include "app-layer-htp-mem.h"
#include "util-host-os-info.h"
#include "util-privs.h"
#include "util-profiling.h"
#include "util-misc.h"
#include "util-validate.h"
#include "util-runmodes.h"
#include "util-random.h"
#include "source-pcap-file.h"
//#define DEBUG
#define STREAMTCP_DEFAULT_PREALLOC 2048
#define STREAMTCP_DEFAULT_MEMCAP (32 * 1024 * 1024) /* 32mb */
#define STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP (64 * 1024 * 1024) /* 64mb */
#define STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED 5
#define STREAMTCP_NEW_TIMEOUT 60
#define STREAMTCP_EST_TIMEOUT 3600
#define STREAMTCP_CLOSED_TIMEOUT 120
#define STREAMTCP_EMERG_NEW_TIMEOUT 10
#define STREAMTCP_EMERG_EST_TIMEOUT 300
#define STREAMTCP_EMERG_CLOSED_TIMEOUT 20
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *, TcpSession *, Packet *, PacketQueue *);
void StreamTcpReturnStreamSegments (TcpStream *);
void StreamTcpInitConfig(char);
int StreamTcpGetFlowState(void *);
void StreamTcpSetOSPolicy(TcpStream*, Packet*);
static int StreamTcpValidateTimestamp(TcpSession * , Packet *);
static int StreamTcpHandleTimestamp(TcpSession * , Packet *);
static int StreamTcpValidateRst(TcpSession * , Packet *);
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *, Packet *);
static int StreamTcpStateDispatch(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq,
uint8_t state);
extern int g_detect_disabled;
static PoolThread *ssn_pool = NULL;
static SCMutex ssn_pool_mutex = SCMUTEX_INITIALIZER; /**< init only, protect initializing and growing pool */
#ifdef DEBUG
static uint64_t ssn_pool_cnt = 0; /** counts ssns, protected by ssn_pool_mutex */
#endif
uint64_t StreamTcpReassembleMemuseGlobalCounter(void);
SC_ATOMIC_DECLARE(uint64_t, st_memuse);
void StreamTcpInitMemuse(void)
{
SC_ATOMIC_INIT(st_memuse);
}
void StreamTcpIncrMemuse(uint64_t size)
{
(void) SC_ATOMIC_ADD(st_memuse, size);
SCLogDebug("STREAM %"PRIu64", incr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
void StreamTcpDecrMemuse(uint64_t size)
{
#ifdef DEBUG_VALIDATION
uint64_t presize = SC_ATOMIC_GET(st_memuse);
if (RunmodeIsUnittests()) {
BUG_ON(presize > UINT_MAX);
}
#endif
(void) SC_ATOMIC_SUB(st_memuse, size);
#ifdef DEBUG_VALIDATION
if (RunmodeIsUnittests()) {
uint64_t postsize = SC_ATOMIC_GET(st_memuse);
BUG_ON(postsize > presize);
}
#endif
SCLogDebug("STREAM %"PRIu64", decr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
uint64_t StreamTcpMemuseCounter(void)
{
uint64_t memusecopy = SC_ATOMIC_GET(st_memuse);
return memusecopy;
}
/**
* \brief Check if alloc'ing "size" would mean we're over memcap
*
* \retval 1 if in bounds
* \retval 0 if not in bounds
*/
int StreamTcpCheckMemcap(uint64_t size)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
if (memcapcopy == 0 || size + SC_ATOMIC_GET(st_memuse) <= memcapcopy)
return 1;
return 0;
}
/**
* \brief Update memcap value
*
* \param size new memcap value
*/
int StreamTcpSetMemcap(uint64_t size)
{
if (size == 0 || (uint64_t)SC_ATOMIC_GET(st_memuse) < size) {
SC_ATOMIC_SET(stream_config.memcap, size);
return 1;
}
return 0;
}
/**
* \brief Return memcap value
*
* \param memcap memcap value
*/
uint64_t StreamTcpGetMemcap(void)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
return memcapcopy;
}
void StreamTcpStreamCleanup(TcpStream *stream)
{
if (stream != NULL) {
StreamTcpSackFreeList(stream);
StreamTcpReturnStreamSegments(stream);
StreamingBufferClear(&stream->sb);
}
}
/**
* \brief Session cleanup function. Does not free the ssn.
* \param ssn tcp session
*/
void StreamTcpSessionCleanup(TcpSession *ssn)
{
SCEnter();
TcpStateQueue *q, *q_next;
if (ssn == NULL)
return;
StreamTcpStreamCleanup(&ssn->client);
StreamTcpStreamCleanup(&ssn->server);
q = ssn->queue;
while (q != NULL) {
q_next = q->next;
SCFree(q);
q = q_next;
StreamTcpDecrMemuse((uint64_t)sizeof(TcpStateQueue));
}
ssn->queue = NULL;
ssn->queue_len = 0;
SCReturn;
}
/**
* \brief Function to return the stream back to the pool. It returns the
* segments in the stream to the segment pool.
*
* This function is called when the flow is destroyed, so it should free
* *everything* related to the tcp session. So including the app layer
* data. We are guaranteed to only get here when the flow's use_cnt is 0.
*
* \param ssn Void ptr to the ssn.
*/
void StreamTcpSessionClear(void *ssnptr)
{
SCEnter();
TcpSession *ssn = (TcpSession *)ssnptr;
if (ssn == NULL)
return;
StreamTcpSessionCleanup(ssn);
/* HACK: don't loose track of thread id */
PoolThreadReserved a = ssn->res;
memset(ssn, 0, sizeof(TcpSession));
ssn->res = a;
PoolThreadReturn(ssn_pool, ssn);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
ssn_pool_cnt--;
SCMutexUnlock(&ssn_pool_mutex);
#endif
SCReturn;
}
/**
* \brief Function to return the stream segments back to the pool.
*
* We don't clear out the app layer storage here as that is under protection
* of the "use_cnt" reference counter in the flow. This function is called
* when the use_cnt is always at least 1 (this pkt has incremented the flow
* use_cnt itself), so we don't bother.
*
* \param p Packet used to identify the stream.
*/
void StreamTcpSessionPktFree (Packet *p)
{
SCEnter();
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL)
SCReturn;
StreamTcpReturnStreamSegments(&ssn->client);
StreamTcpReturnStreamSegments(&ssn->server);
SCReturn;
}
/** \brief Stream alloc function for the Pool
* \retval ptr void ptr to TcpSession structure with all vars set to 0/NULL
*/
static void *StreamTcpSessionPoolAlloc(void)
{
void *ptr = NULL;
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpSession)) == 0)
return NULL;
ptr = SCMalloc(sizeof(TcpSession));
if (unlikely(ptr == NULL))
return NULL;
return ptr;
}
static int StreamTcpSessionPoolInit(void *data, void* initdata)
{
memset(data, 0, sizeof(TcpSession));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpSession));
return 1;
}
/** \brief Pool cleanup function
* \param s Void ptr to TcpSession memory */
static void StreamTcpSessionPoolCleanup(void *s)
{
if (s != NULL) {
StreamTcpSessionCleanup(s);
/** \todo not very clean, as the memory is not freed here */
StreamTcpDecrMemuse((uint64_t)sizeof(TcpSession));
}
}
/**
* \brief See if stream engine is dropping invalid packet in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineDropInvalid(void)
{
return ((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
&& (stream_config.flags & STREAMTCP_INIT_FLAG_DROP_INVALID));
}
/* hack: stream random range code expects random values in range of 0-RAND_MAX,
* but we can get both <0 and >RAND_MAX values from RandomGet
*/
static int RandomGetWrap(void)
{
unsigned long r;
do {
r = RandomGet();
} while(r >= ULONG_MAX - (ULONG_MAX % RAND_MAX));
return r % RAND_MAX;
}
/** \brief To initialize the stream global configuration data
*
* \param quiet It tells the mode of operation, if it is TRUE nothing will
* be get printed.
*/
void StreamTcpInitConfig(char quiet)
{
intmax_t value = 0;
uint16_t rdrange = 10;
SCLogDebug("Initializing Stream");
memset(&stream_config, 0, sizeof(stream_config));
SC_ATOMIC_INIT(stream_config.memcap);
SC_ATOMIC_INIT(stream_config.reassembly_memcap);
if ((ConfGetInt("stream.max-sessions", &value)) == 1) {
SCLogWarning(SC_WARN_OPTION_OBSOLETE, "max-sessions is obsolete. "
"Number of concurrent sessions is now only limited by Flow and "
"TCP stream engine memcaps.");
}
if ((ConfGetInt("stream.prealloc-sessions", &value)) == 1) {
stream_config.prealloc_sessions = (uint32_t)value;
} else {
if (RunmodeIsUnittests()) {
stream_config.prealloc_sessions = 128;
} else {
stream_config.prealloc_sessions = STREAMTCP_DEFAULT_PREALLOC;
if (ConfGetNode("stream.prealloc-sessions") != NULL) {
WarnInvalidConfEntry("stream.prealloc_sessions",
"%"PRIu32,
stream_config.prealloc_sessions);
}
}
}
if (!quiet) {
SCLogConfig("stream \"prealloc-sessions\": %"PRIu32" (per thread)",
stream_config.prealloc_sessions);
}
const char *temp_stream_memcap_str;
if (ConfGetValue("stream.memcap", &temp_stream_memcap_str) == 1) {
uint64_t stream_memcap_copy;
if (ParseSizeStringU64(temp_stream_memcap_str, &stream_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing stream.memcap "
"from conf file - %s. Killing engine",
temp_stream_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.memcap, stream_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.memcap, STREAMTCP_DEFAULT_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream \"memcap\": %"PRIu64, SC_ATOMIC_GET(stream_config.memcap));
}
ConfGetBool("stream.midstream", &stream_config.midstream);
if (!quiet) {
SCLogConfig("stream \"midstream\" session pickups: %s", stream_config.midstream ? "enabled" : "disabled");
}
ConfGetBool("stream.async-oneside", &stream_config.async_oneside);
if (!quiet) {
SCLogConfig("stream \"async-oneside\": %s", stream_config.async_oneside ? "enabled" : "disabled");
}
int csum = 0;
if ((ConfGetBool("stream.checksum-validation", &csum)) == 1) {
if (csum == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
/* Default is that we validate the checksum of all the packets */
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
if (!quiet) {
SCLogConfig("stream \"checksum-validation\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION ?
"enabled" : "disabled");
}
const char *temp_stream_inline_str;
if (ConfGetValue("stream.inline", &temp_stream_inline_str) == 1) {
int inl = 0;
/* checking for "auto" and falling back to boolean to provide
* backward compatibility */
if (strcmp(temp_stream_inline_str, "auto") == 0) {
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
} else if (ConfGetBool("stream.inline", &inl) == 1) {
if (inl) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
} else {
/* default to 'auto' */
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
if (!quiet) {
SCLogConfig("stream.\"inline\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_INLINE
? "enabled" : "disabled");
}
int bypass = 0;
if ((ConfGetBool("stream.bypass", &bypass)) == 1) {
if (bypass == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_BYPASS;
}
}
if (!quiet) {
SCLogConfig("stream \"bypass\": %s",
(stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS)
? "enabled" : "disabled");
}
int drop_invalid = 0;
if ((ConfGetBool("stream.drop-invalid", &drop_invalid)) == 1) {
if (drop_invalid == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
if ((ConfGetInt("stream.max-synack-queued", &value)) == 1) {
if (value >= 0 && value <= 255) {
stream_config.max_synack_queued = (uint8_t)value;
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
if (!quiet) {
SCLogConfig("stream \"max-synack-queued\": %"PRIu8, stream_config.max_synack_queued);
}
const char *temp_stream_reassembly_memcap_str;
if (ConfGetValue("stream.reassembly.memcap", &temp_stream_reassembly_memcap_str) == 1) {
uint64_t stream_reassembly_memcap_copy;
if (ParseSizeStringU64(temp_stream_reassembly_memcap_str,
&stream_reassembly_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.memcap "
"from conf file - %s. Killing engine",
temp_stream_reassembly_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap, stream_reassembly_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap , STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"memcap\": %"PRIu64"",
SC_ATOMIC_GET(stream_config.reassembly_memcap));
}
const char *temp_stream_reassembly_depth_str;
if (ConfGetValue("stream.reassembly.depth", &temp_stream_reassembly_depth_str) == 1) {
if (ParseSizeStringU32(temp_stream_reassembly_depth_str,
&stream_config.reassembly_depth) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.depth "
"from conf file - %s. Killing engine",
temp_stream_reassembly_depth_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_depth = 0;
}
if (!quiet) {
SCLogConfig("stream.reassembly \"depth\": %"PRIu32"", stream_config.reassembly_depth);
}
int randomize = 0;
if ((ConfGetBool("stream.reassembly.randomize-chunk-size", &randomize)) == 0) {
/* randomize by default if value not set
* In ut mode we disable, to get predictible test results */
if (!(RunmodeIsUnittests()))
randomize = 1;
}
if (randomize) {
const char *temp_rdrange;
if (ConfGetValue("stream.reassembly.randomize-chunk-range",
&temp_rdrange) == 1) {
if (ParseSizeStringU16(temp_rdrange, &rdrange) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.randomize-chunk-range "
"from conf file - %s. Killing engine",
temp_rdrange);
exit(EXIT_FAILURE);
} else if (rdrange >= 100) {
SCLogError(SC_ERR_INVALID_VALUE,
"stream.reassembly.randomize-chunk-range "
"must be lower than 100");
exit(EXIT_FAILURE);
}
}
}
const char *temp_stream_reassembly_toserver_chunk_size_str;
if (ConfGetValue("stream.reassembly.toserver-chunk-size",
&temp_stream_reassembly_toserver_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toserver_chunk_size_str,
&stream_config.reassembly_toserver_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toserver-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toserver_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toserver_chunk_size =
STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toserver_chunk_size +=
(int) (stream_config.reassembly_toserver_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
const char *temp_stream_reassembly_toclient_chunk_size_str;
if (ConfGetValue("stream.reassembly.toclient-chunk-size",
&temp_stream_reassembly_toclient_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toclient_chunk_size_str,
&stream_config.reassembly_toclient_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toclient-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toclient_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toclient_chunk_size =
STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toclient_chunk_size +=
(int) (stream_config.reassembly_toclient_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"toserver-chunk-size\": %"PRIu16,
stream_config.reassembly_toserver_chunk_size);
SCLogConfig("stream.reassembly \"toclient-chunk-size\": %"PRIu16,
stream_config.reassembly_toclient_chunk_size);
}
int enable_raw = 1;
if (ConfGetBool("stream.reassembly.raw", &enable_raw) == 1) {
if (!enable_raw) {
stream_config.stream_init_flags = STREAMTCP_STREAM_FLAG_DISABLE_RAW;
}
} else {
enable_raw = 1;
}
if (!quiet)
SCLogConfig("stream.reassembly.raw: %s", enable_raw ? "enabled" : "disabled");
/* init the memcap/use tracking */
StreamTcpInitMemuse();
StatsRegisterGlobalCounter("tcp.memuse", StreamTcpMemuseCounter);
StreamTcpReassembleInit(quiet);
/* set the default free function and flow state function
* values. */
FlowSetProtoFreeFunc(IPPROTO_TCP, StreamTcpSessionClear);
#ifdef UNITTESTS
if (RunmodeIsUnittests()) {
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
}
SCMutexUnlock(&ssn_pool_mutex);
}
#endif
}
void StreamTcpFreeConfig(char quiet)
{
SC_ATOMIC_DESTROY(stream_config.memcap);
SC_ATOMIC_DESTROY(stream_config.reassembly_memcap);
StreamTcpReassembleFree(quiet);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool != NULL) {
PoolThreadFree(ssn_pool);
ssn_pool = NULL;
}
SCMutexUnlock(&ssn_pool_mutex);
SCMutexDestroy(&ssn_pool_mutex);
SCLogDebug("ssn_pool_cnt %"PRIu64"", ssn_pool_cnt);
}
/** \internal
* \brief The function is used to to fetch a TCP session from the
* ssn_pool, when a TCP SYN is received.
*
* \param p packet starting the new TCP session.
* \param id thread pool id
*
* \retval ssn new TCP session.
*/
static TcpSession *StreamTcpNewSession (Packet *p, int id)
{
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
p->flow->protoctx = PoolThreadGetById(ssn_pool, id);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
if (p->flow->protoctx != NULL)
ssn_pool_cnt++;
SCMutexUnlock(&ssn_pool_mutex);
#endif
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
SCLogDebug("ssn_pool is empty");
return NULL;
}
ssn->state = TCP_NONE;
ssn->reassembly_depth = stream_config.reassembly_depth;
ssn->tcp_packet_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.flags = stream_config.stream_init_flags;
ssn->client.flags = stream_config.stream_init_flags;
StreamingBuffer x = STREAMING_BUFFER_INITIALIZER(&stream_config.sbcnf);
ssn->client.sb = x;
ssn->server.sb = x;
if (PKT_IS_TOSERVER(p)) {
ssn->client.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.tcp_flags = 0;
} else if (PKT_IS_TOCLIENT(p)) {
ssn->server.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->client.tcp_flags = 0;
}
}
return ssn;
}
static void StreamTcpPacketSetState(Packet *p, TcpSession *ssn,
uint8_t state)
{
if (state == ssn->state || PKT_IS_PSEUDOPKT(p))
return;
ssn->pstate = ssn->state;
ssn->state = state;
/* update the flow state */
switch(ssn->state) {
case TCP_ESTABLISHED:
case TCP_FIN_WAIT1:
case TCP_FIN_WAIT2:
case TCP_CLOSING:
case TCP_CLOSE_WAIT:
FlowUpdateState(p->flow, FLOW_STATE_ESTABLISHED);
break;
case TCP_LAST_ACK:
case TCP_TIME_WAIT:
case TCP_CLOSED:
FlowUpdateState(p->flow, FLOW_STATE_CLOSED);
break;
}
}
/**
* \brief Function to set the OS policy for the given stream based on the
* destination of the received packet.
*
* \param stream TcpStream of which os_policy needs to set
* \param p Packet which is used to set the os policy
*/
void StreamTcpSetOSPolicy(TcpStream *stream, Packet *p)
{
int ret = 0;
if (PKT_IS_IPV4(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv4HostOSFlavour((uint8_t *)GET_IPV4_DST_ADDR_PTR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
} else if (PKT_IS_IPV6(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv6HostOSFlavour((uint8_t *)GET_IPV6_DST_ADDR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
}
if (stream->os_policy == OS_POLICY_BSD_RIGHT)
stream->os_policy = OS_POLICY_BSD;
else if (stream->os_policy == OS_POLICY_OLD_SOLARIS)
stream->os_policy = OS_POLICY_SOLARIS;
SCLogDebug("Policy is %"PRIu8"", stream->os_policy);
}
/**
* \brief macro to update last_ack only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param ack ACK value to test and set
*/
#define StreamTcpUpdateLastAck(ssn, stream, ack) { \
if (SEQ_GT((ack), (stream)->last_ack)) \
{ \
SCLogDebug("ssn %p: last_ack set to %"PRIu32", moved %u forward", (ssn), (ack), (ack) - (stream)->last_ack); \
if ((SEQ_LEQ((stream)->last_ack, (stream)->next_seq) && SEQ_GT((ack),(stream)->next_seq))) { \
SCLogDebug("last_ack just passed next_seq: %u (was %u) > %u", (ack), (stream)->last_ack, (stream)->next_seq); \
} else { \
SCLogDebug("next_seq (%u) <> last_ack now %d", (stream)->next_seq, (int)(stream)->next_seq - (ack)); \
}\
(stream)->last_ack = (ack); \
StreamTcpSackPruneList((stream)); \
} else { \
SCLogDebug("ssn %p: no update: ack %u, last_ack %"PRIu32", next_seq %u (state %u)", \
(ssn), (ack), (stream)->last_ack, (stream)->next_seq, (ssn)->state); \
}\
}
#define StreamTcpAsyncLastAckUpdate(ssn, stream) { \
if ((ssn)->flags & STREAMTCP_FLAG_ASYNC) { \
if (SEQ_GT((stream)->next_seq, (stream)->last_ack)) { \
uint32_t ack_diff = (stream)->next_seq - (stream)->last_ack; \
(stream)->last_ack += ack_diff; \
SCLogDebug("ssn %p: ASYNC last_ack set to %"PRIu32", moved %u forward", \
(ssn), (stream)->next_seq, ack_diff); \
} \
} \
}
#define StreamTcpUpdateNextSeq(ssn, stream, seq) { \
(stream)->next_seq = seq; \
SCLogDebug("ssn %p: next_seq %" PRIu32, (ssn), (stream)->next_seq); \
StreamTcpAsyncLastAckUpdate((ssn), (stream)); \
}
/**
* \brief macro to update next_win only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param win window value to test and set
*/
#define StreamTcpUpdateNextWin(ssn, stream, win) { \
uint32_t sacked_size__ = StreamTcpSackedSize((stream)); \
if (SEQ_GT(((win) + sacked_size__), (stream)->next_win)) { \
(stream)->next_win = ((win) + sacked_size__); \
SCLogDebug("ssn %p: next_win set to %"PRIu32, (ssn), (stream)->next_win); \
} \
}
static int StreamTcpPacketIsRetransmission(TcpStream *stream, Packet *p)
{
if (p->payload_len == 0)
SCReturnInt(0);
/* retransmission of already partially ack'd data */
if (SEQ_LT(TCP_GET_SEQ(p), stream->last_ack) && SEQ_GT((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack))
{
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of already ack'd data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of in flight data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->next_seq)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(2);
}
SCLogDebug("seq %u payload_len %u => %u, last_ack %u, next_seq %u", TCP_GET_SEQ(p),
p->payload_len, (TCP_GET_SEQ(p) + p->payload_len), stream->last_ack, stream->next_seq);
SCReturnInt(0);
}
/**
* \internal
* \brief Function to handle the TCP_CLOSED or NONE state. The function handles
* packets while the session state is None which means a newly
* initialized structure, or a fully closed session.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateNone(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (p->tcph->th_flags & TH_RST) {
StreamTcpSetEvent(p, STREAM_RST_BUT_NO_SESSION);
SCLogDebug("RST packet received, no session setup");
return -1;
} else if (p->tcph->th_flags & TH_FIN) {
StreamTcpSetEvent(p, STREAM_FIN_BUT_NO_SESSION);
SCLogDebug("FIN packet received, no session setup");
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if (stream_config.midstream == FALSE &&
stream_config.async_oneside == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
StatsIncr(tv, stt->counter_tcp_midstream_pickups);
}
/* reverse packet and flow */
SCLogDebug("reversing flow and packet");
PacketSwap(p);
FlowSwap(p->flow);
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_SYN_RECV", ssn);
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM;
/* Flag used to change the direct in the later stage in the session */
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_SYNACK;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* sequence number & window */
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: server window %u", ssn, ssn->server.window);
ssn->client.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->client.last_ack = TCP_GET_ACK(p);
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
/** If the client has a wscale option the server had it too,
* so set the wscale for the server to max. Otherwise none
* will have the wscale opt just like it should. */
if (TCP_HAS_WSCALE(p)) {
ssn->client.wscale = TCP_GET_WSCALE(p);
ssn->server.wscale = TCP_WSCALE_MAX;
SCLogDebug("ssn %p: wscale enabled. client %u server %u",
ssn, ssn->client.wscale, ssn->server.wscale);
}
SCLogDebug("ssn %p: ssn->client.isn %"PRIu32", ssn->client.next_seq"
" %"PRIu32", ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
SCLogDebug("ssn %p: ssn->server.isn %"PRIu32", ssn->server.next_seq"
" %"PRIu32", ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
ssn->client.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SYN/ACK with SACK permitted, assuming "
"SACK permitted for both sides", ssn);
}
return 0;
} else if (p->tcph->th_flags & TH_SYN) {
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_SENT);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_SENT", ssn);
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
/* Set the stream timestamp value, if packet has timestamp option
* enabled. */
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->client.last_ts);
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
SCLogDebug("ssn %p: SACK permitted on SYN packet", ssn);
}
if (TCP_HAS_TFO(p)) {
ssn->flags |= STREAMTCP_FLAG_TCP_FAST_OPEN;
if (p->payload_len) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
SCLogDebug("ssn: %p (TFO) [len: %d] isn %u base_seq %u next_seq %u payload len %u",
ssn, p->tcpvars.tfo.len, ssn->client.isn, ssn->client.base_seq, ssn->client.next_seq, p->payload_len);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
}
}
SCLogDebug("ssn %p: ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", ssn->client.last_ack "
"%"PRIu32"", ssn, ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
} else if (p->tcph->th_flags & TH_ACK) {
if (stream_config.midstream == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
StatsIncr(tv, stt->counter_tcp_midstream_pickups);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_ESTABLISHED", ssn);
ssn->flags = STREAMTCP_FLAG_MIDSTREAM;
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/** window scaling for midstream pickups, we can't do much other
* than assume that it's set to the max value: 14 */
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->server.wscale = TCP_WSCALE_MAX;
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->client.isn %u, ssn->client.next_seq %u",
ssn, ssn->client.isn, ssn->client.next_seq);
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: ssn->client.next_win %"PRIu32", "
"ssn->server.next_win %"PRIu32"", ssn,
ssn->client.next_win, ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.last_ack %"PRIu32", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->client.last_ack, ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
ssn->server.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: assuming SACK permitted for both sides", ssn);
} else {
SCLogDebug("default case");
}
return 0;
}
/** \internal
* \brief Setup TcpStateQueue based on SYN/ACK packet
*/
static inline void StreamTcp3whsSynAckToStateQueue(Packet *p, TcpStateQueue *q)
{
q->flags = 0;
q->wscale = 0;
q->ts = 0;
q->win = TCP_GET_WINDOW(p);
q->seq = TCP_GET_SEQ(p);
q->ack = TCP_GET_ACK(p);
q->pkt_ts = p->ts.tv_sec;
if (TCP_GET_SACKOK(p) == 1)
q->flags |= STREAMTCP_QUEUE_FLAG_SACK;
if (TCP_HAS_WSCALE(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_WS;
q->wscale = TCP_GET_WSCALE(p);
}
if (TCP_HAS_TS(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_TS;
q->ts = TCP_GET_TSVAL(p);
}
}
/** \internal
* \brief Find the Queued SYN/ACK that is the same as this SYN/ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckBySynAck(TcpSession *ssn, Packet *p)
{
TcpStateQueue *q = ssn->queue;
TcpStateQueue search;
StreamTcp3whsSynAckToStateQueue(p, &search);
while (q != NULL) {
if (search.flags == q->flags &&
search.wscale == q->wscale &&
search.win == q->win &&
search.seq == q->seq &&
search.ack == q->ack &&
search.ts == q->ts) {
return q;
}
q = q->next;
}
return q;
}
static int StreamTcp3whsQueueSynAck(TcpSession *ssn, Packet *p)
{
/* first see if this is already in our list */
if (StreamTcp3whsFindSynAckBySynAck(ssn, p) != NULL)
return 0;
if (ssn->queue_len == stream_config.max_synack_queued) {
SCLogDebug("ssn %p: =~ SYN/ACK queue limit reached", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_FLOOD);
return -1;
}
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpStateQueue)) == 0) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: stream memcap reached", ssn);
return -1;
}
TcpStateQueue *q = SCMalloc(sizeof(*q));
if (unlikely(q == NULL)) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: alloc failed", ssn);
return -1;
}
memset(q, 0x00, sizeof(*q));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpStateQueue));
StreamTcp3whsSynAckToStateQueue(p, q);
/* put in list */
q->next = ssn->queue;
ssn->queue = q;
ssn->queue_len++;
return 0;
}
/** \internal
* \brief Find the Queued SYN/ACK that goes with this ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckByAck(TcpSession *ssn, Packet *p)
{
uint32_t ack = TCP_GET_SEQ(p);
uint32_t seq = TCP_GET_ACK(p) - 1;
TcpStateQueue *q = ssn->queue;
while (q != NULL) {
if (seq == q->seq &&
ack == q->ack) {
return q;
}
q = q->next;
}
return NULL;
}
/** \internal
* \brief Update SSN after receiving a valid SYN/ACK
*
* Normally we update the SSN from the SYN/ACK packet. But in case
* of queued SYN/ACKs, we can use one of those.
*
* \param ssn TCP session
* \param p Packet
* \param q queued state if used, NULL otherwise
*
* To make sure all SYN/ACK based state updates are in one place,
* this function can updated based on Packet or TcpStateQueue, where
* the latter takes precedence.
*/
static void StreamTcp3whsSynAckUpdate(TcpSession *ssn, Packet *p, TcpStateQueue *q)
{
TcpStateQueue update;
if (likely(q == NULL)) {
StreamTcp3whsSynAckToStateQueue(p, &update);
q = &update;
}
if (ssn->state != TCP_SYN_RECV) {
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_RECV", ssn);
}
/* sequence number & window */
ssn->server.isn = q->seq;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->client.window = q->win;
SCLogDebug("ssn %p: window %" PRIu32 "", ssn, ssn->server.window);
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if ((q->flags & STREAMTCP_QUEUE_FLAG_TS) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->server.last_ts = q->ts;
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = q->pkt_ts;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->client.last_ts = 0;
ssn->server.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->client.last_ack = q->ack;
ssn->server.last_ack = ssn->server.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(q->flags & STREAMTCP_QUEUE_FLAG_WS))
{
ssn->client.wscale = q->wscale;
} else {
ssn->client.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
(q->flags & STREAMTCP_QUEUE_FLAG_SACK)) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for session", ssn);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SACKOK;
}
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %" PRIu32 " "
"(ssn->client.last_ack %" PRIu32 ")", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack, ssn->client.last_ack);
/* unset the 4WHS flag as we received this SYN/ACK as part of a
* (so far) valid 3WHS */
if (ssn->flags & STREAMTCP_FLAG_4WHS)
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS unset, normal SYN/ACK"
" so considering 3WHS", ssn);
ssn->flags &=~ STREAMTCP_FLAG_4WHS;
}
/** \internal
* \brief detect timestamp anomalies when processing responses to the
* SYN packet.
* \retval true packet is ok
* \retval false packet is bad
*/
static inline bool StateSynSentValidateTimestamp(TcpSession *ssn, Packet *p)
{
/* we only care about evil server here, so skip TS packets */
if (PKT_IS_TOSERVER(p) || !(TCP_HAS_TS(p))) {
return true;
}
TcpStream *receiver_stream = &ssn->client;
uint32_t ts_echo = TCP_GET_TSECR(p);
if ((receiver_stream->flags & STREAMTCP_STREAM_FLAG_TIMESTAMP) != 0) {
if (receiver_stream->last_ts != 0 && ts_echo != 0 &&
ts_echo != receiver_stream->last_ts)
{
SCLogDebug("ssn %p: BAD TSECR echo %u recv %u", ssn,
ts_echo, receiver_stream->last_ts);
return false;
}
} else {
if (receiver_stream->last_ts == 0 && ts_echo != 0) {
SCLogDebug("ssn %p: BAD TSECR echo %u recv %u", ssn,
ts_echo, receiver_stream->last_ts);
return false;
}
}
return true;
}
/**
* \brief Function to handle the TCP_SYN_SENT state. The function handles
* SYN, SYN/ACK, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateSynSent(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
SCLogDebug("ssn %p: pkt received: %s", ssn, PKT_IS_TOCLIENT(p) ?
"toclient":"toserver");
/* check for bad responses */
if (StateSynSentValidateTimestamp(ssn, p) == false)
return -1;
/* RST */
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn) &&
SEQ_EQ(TCP_GET_WINDOW(p), 0) &&
SEQ_EQ(TCP_GET_ACK(p), (ssn->client.isn + 1)))
{
SCLogDebug("ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
SCLogDebug("ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
/* FIN */
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK received on 4WHS session", ssn);
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->server.isn + 1))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: 4WHS ACK mismatch, packet ACK %"PRIu32""
" != %" PRIu32 " from stream", ssn,
TCP_GET_ACK(p), ssn->server.isn + 1);
return -1;
}
/* Check if the SYN/ACK packet SEQ's the *FIRST* received SYN
* packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_SYN);
SCLogDebug("ssn %p: 4WHS SEQ mismatch, packet SEQ %"PRIu32""
" != %" PRIu32 " from *first* SYN pkt", ssn,
TCP_GET_SEQ(p), ssn->client.isn);
return -1;
}
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ 4WHS ssn state is now TCP_SYN_RECV", ssn);
/* sequence number & window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: 4WHS window %" PRIu32 "", ssn,
ssn->client.window);
/* Set the timestamp values used to validate the timestamp of
* received packets. */
if ((TCP_HAS_TS(p)) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: 4WHS ssn->client.last_ts %" PRIu32" "
"ssn->server.last_ts %" PRIu32"", ssn,
ssn->client.last_ts, ssn->server.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
ssn->server.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->client.last_ack = ssn->client.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(TCP_HAS_WSCALE(p)))
{
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->server.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for 4WHS session", ssn);
}
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
SCLogDebug("ssn %p: 4WHS ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: 4WHS ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %" PRIu32 " "
"(ssn->server.last_ack %" PRIu32 ")", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack, ssn->server.last_ack);
/* done here */
return 0;
}
if (PKT_IS_TOSERVER(p)) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_IN_WRONG_DIRECTION);
SCLogDebug("ssn %p: SYN/ACK received in the wrong direction", ssn);
return -1;
}
if (!(TCP_HAS_TFO(p) || (ssn->flags & STREAMTCP_FLAG_TCP_FAST_OPEN))) {
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.isn + 1))) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
return -1;
}
} else {
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.next_seq))) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: (TFO) ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.next_seq);
return -1;
}
SCLogDebug("ssn %p: (TFO) ACK match, packet ACK %" PRIu32 " == "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.next_seq);
ssn->flags |= STREAMTCP_FLAG_TCP_FAST_OPEN;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
}
StreamTcp3whsSynAckUpdate(ssn, p, /* no queue override */NULL);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent", ssn);
if (ssn->flags & STREAMTCP_FLAG_4WHS) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent of "
"4WHS SYN", ssn);
}
if (PKT_IS_TOCLIENT(p)) {
/** a SYN only packet in the opposite direction could be:
* http://www.breakingpointsystems.com/community/blog/tcp-
* portals-the-three-way-handshake-is-a-lie
*
* \todo improve resetting the session */
/* indicate that we're dealing with 4WHS here */
ssn->flags |= STREAMTCP_FLAG_4WHS;
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS flag set", ssn);
/* set the sequence numbers and window for server
* We leave the ssn->client.isn in place as we will
* check the SYN/ACK pkt with that.
*/
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
/* Set the stream timestamp value, if packet has timestamp
* option enabled. */
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->server.last_ts);
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
} else {
ssn->flags &= ~STREAMTCP_FLAG_CLIENT_SACKOK;
}
SCLogDebug("ssn %p: 4WHS ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
}
/** \todo check if it's correct or set event */
} else if (p->tcph->th_flags & TH_ACK) {
/* Handle the asynchronous stream, when we receive a SYN packet
and now istead of receving a SYN/ACK we receive a ACK from the
same host, which sent the SYN, this suggests the ASNYC streams.*/
if (stream_config.async_oneside == FALSE)
return 0;
/* we are in AYNC (one side) mode now. */
/* one side async means we won't see a SYN/ACK, so we can
* only check the SYN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))) {
StreamTcpSetEvent(p, STREAM_3WHS_ASYNC_WRONG_SEQ);
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream",ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
return -1;
}
ssn->flags |= STREAMTCP_FLAG_ASYNC;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
ssn->client.window = TCP_GET_WINDOW(p);
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
/* Set the server side parameters */
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = ssn->server.next_seq;
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: synsent => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.next_seq %" PRIu32 ""
,ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->client.next_seq);
/* if SYN had wscale, assume it to be supported. Otherwise
* we know it not to be supported. */
if (ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) {
ssn->client.wscale = TCP_WSCALE_MAX;
}
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if (TCP_HAS_TS(p) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
} else {
ssn->client.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
if (ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_SYN_RECV state. The function handles
* SYN, SYN/ACK, ACK, FIN, RST packets and correspondingly changes
* the connection state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateSynRecv(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
uint8_t reset = TRUE;
/* After receiveing the RST in SYN_RECV state and if detection
evasion flags has been set, then the following operating
systems will not closed the connection. As they consider the
packet as stray packet and not belonging to the current
session, for more information check
http://www.packetstan.com/2010/06/recently-ive-been-on-campaign-to-make.html */
if (ssn->flags & STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT) {
if (PKT_IS_TOSERVER(p)) {
if ((ssn->server.os_policy == OS_POLICY_LINUX) ||
(ssn->server.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->server.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
} else {
if ((ssn->client.os_policy == OS_POLICY_LINUX) ||
(ssn->client.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->client.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
}
}
if (reset == TRUE) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
}
} else if (p->tcph->th_flags & TH_FIN) {
/* FIN is handled in the same way as in TCP_ESTABLISHED case */;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state SYN_RECV. resent", ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_TOSERVER_ON_SYN_RECV);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN/ACK packet, server resend with different ISN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.isn);
if (StreamTcp3whsQueueSynAck(ssn, p) == -1)
return -1;
SCLogDebug("ssn %p: queued different SYN/ACK", ssn);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_RECV... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_TOCLIENT_ON_SYN_RECV);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_RESEND_DIFF_SEQ_ON_SYN_RECV);
return -1;
}
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->queue_len) {
SCLogDebug("ssn %p: checking ACK against queued SYN/ACKs", ssn);
TcpStateQueue *q = StreamTcp3whsFindSynAckByAck(ssn, p);
if (q != NULL) {
SCLogDebug("ssn %p: here we update state against queued SYN/ACK", ssn);
StreamTcp3whsSynAckUpdate(ssn, p, /* using queue to update state */q);
} else {
SCLogDebug("ssn %p: none found, now checking ACK against original SYN/ACK (state)", ssn);
}
}
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323)*/
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!(StreamTcpValidateTimestamp(ssn, p))) {
return -1;
}
}
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: ACK received on 4WHS session",ssn);
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))) {
SCLogDebug("ssn %p: 4WHS wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: 4WHS invalid ack nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_INVALID_ACK);
return -1;
}
SCLogDebug("4WHS normal pkt");
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.next_win, ssn->client.last_ack);
return 0;
}
bool ack_indicates_missed_3whs_ack_packet = false;
/* Check if the ACK received is in right direction. But when we have
* picked up a mid stream session after missing the initial SYN pkt,
* in this case the ACK packet can arrive from either client (normal
* case) or from server itself (asynchronous streams). Therefore
* the check has been avoided in this case */
if (PKT_IS_TOCLIENT(p)) {
/* special case, handle 4WHS, so SYN/ACK in the opposite
* direction */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK) {
SCLogDebug("ssn %p: ACK received on midstream SYN/ACK "
"pickup session",ssn);
/* fall through */
} else if (ssn->flags & STREAMTCP_FLAG_TCP_FAST_OPEN) {
SCLogDebug("ssn %p: ACK received on TFO session",ssn);
/* fall through */
} else {
/* if we missed traffic between the S/SA and the current
* 'wrong direction' ACK, we could end up here. In IPS
* reject it. But in IDS mode we continue.
*
* IPS rejects as it should see all packets, so pktloss
* should lead to retransmissions. As this can also be
* pattern for MOTS/MITM injection attacks, we need to be
* careful.
*/
if (StreamTcpInlineMode()) {
if (p->payload_len > 0 &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) &&
SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
/* packet loss is possible but unlikely here */
SCLogDebug("ssn %p: possible data injection", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_DATA_INJECT);
return -1;
}
SCLogDebug("ssn %p: ACK received in the wrong direction",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_IN_WRONG_DIR);
return -1;
}
ack_indicates_missed_3whs_ack_packet = true;
}
}
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ""
", ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
/* Check both seq and ack number before accepting the packet and
changing to ESTABLISHED state */
if ((SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq)) {
SCLogDebug("normal pkt");
/* process the packet normal, No Async streams :) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
if (!(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)) {
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* If asynchronous stream handling is allowed then set the session,
if packet's seq number is equal the expected seq no.*/
} else if (stream_config.async_oneside == TRUE &&
(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)))
{
/*set the ASYNC flag used to indicate the session as async stream
and helps in relaxing the windows checks.*/
ssn->flags |= STREAMTCP_FLAG_ASYNC;
ssn->server.next_seq += p->payload_len;
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_ACK(p);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->server.window = TCP_GET_WINDOW(p);
ssn->client.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
SCLogDebug("ssn %p: synrecv => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->server.next_seq %" PRIu32 "\n"
, ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->server.next_seq);
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
/* Upon receiving the packet with correct seq number and wrong
ACK number, it causes the other end to send RST. But some target
system (Linux & solaris) does not RST the connection, so it is
likely to avoid the detection */
} else if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)){
ssn->flags |= STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT;
SCLogDebug("ssn %p: wrong ack nr on packet, possible evasion!!",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_RIGHT_SEQ_WRONG_ACK_EVASION);
return -1;
/* if we get a packet with a proper ack, but a seq that is beyond
* next_seq but in-window, we probably missed some packets */
} else if (SEQ_GT(TCP_GET_SEQ(p), ssn->client.next_seq) &&
SEQ_LEQ(TCP_GET_SEQ(p),ssn->client.next_win) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq))
{
SCLogDebug("ssn %p: ACK for missing data", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ACK for missing data: ssn->client.next_seq %u", ssn, ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p);
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* toclient packet: after having missed the 3whs's final ACK */
} else if ((ack_indicates_missed_3whs_ack_packet ||
(ssn->flags & STREAMTCP_FLAG_TCP_FAST_OPEN)) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) &&
SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
{
if (ack_indicates_missed_3whs_ack_packet) {
SCLogDebug("ssn %p: packet fits perfectly after a missed 3whs-ACK", ssn);
} else {
SCLogDebug("ssn %p: (TFO) expected packet fits perfectly after SYN/ACK", ssn);
}
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_WRONG_SEQ_WRONG_ACK);
return -1;
}
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.next_win, ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the client to server. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly.
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToServer(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
"ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &(ssn->server), p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->client.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->client.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: server => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
"%" PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* update the last_ack to current seq number as the session is
* async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ."
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
} else if (SEQ_EQ(ssn->client.last_ack, (ssn->client.isn + 1)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :(*/
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->client.last_ack, ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->client.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->client.last_ack, ssn->client.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: server => SEQ before last_ack, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
SCLogDebug("ssn %p: rejecting because pkt before last_ack", ssn);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->client.next_seq && ssn->client.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->client.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (started before next_seq, ended after)",
ssn, ssn->client.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->client.next_seq, ssn->client.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->client.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->client.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->client.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->client.last_ack);
}
/* in window check */
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
SCLogDebug("ssn %p: ssn->server.window %"PRIu32"", ssn,
ssn->server.window);
/* Check if the ACK value is sane and inside the window limit */
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
SCLogDebug("ack %u last_ack %u next_seq %u", TCP_GET_ACK(p), ssn->server.last_ack, ssn->server.next_seq);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
/* handle data (if any) */
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: toserver => SEQ out of window, packet SEQ "
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
(TCP_GET_SEQ(p) + p->payload_len) - ssn->client.next_win);
SCLogDebug("ssn %p: window %u sacked %u", ssn, ssn->client.window,
StreamTcpSackedSize(&ssn->client));
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the server to client. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToClient(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ","
" ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* To get the server window value from the servers packet, when connection
is picked up as midstream */
if ((ssn->flags & STREAMTCP_FLAG_MIDSTREAM) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED))
{
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->flags &= ~STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
SCLogDebug("ssn %p: adjusted midstream ssn->server.next_win to "
"%" PRIu32 "", ssn, ssn->server.next_win);
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->server.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->server.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: client => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
" %"PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
ssn->server.last_ack = TCP_GET_SEQ(p);
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->server.last_ack, ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->server.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32". next_seq %"PRIu32,
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->server.next_seq && ssn->server.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->server.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32
" (started before next_seq, ended after)",
ssn, ssn->server.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->server.next_seq, ssn->server.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->server.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->server.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->server.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->server.last_ack);
}
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
SCLogDebug("ssn %p: ssn->client.window %"PRIu32"", ssn,
ssn->client.window);
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->client, p);
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: client => SEQ out of window, packet SEQ"
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->server.last_ack %" PRIu32 ", ssn->server.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \internal
*
* \brief Find the highest sequence number needed to consider all segments as ACK'd
*
* Used to treat all segments as ACK'd upon receiving a valid RST.
*
* \param stream stream to inspect the segments from
* \param seq sequence number to check against
*
* \retval ack highest ack we need to set
*/
static inline uint32_t StreamTcpResetGetMaxAck(TcpStream *stream, uint32_t seq)
{
uint32_t ack = seq;
if (STREAM_HAS_SEEN_DATA(stream)) {
const uint32_t tail_seq = STREAM_SEQ_RIGHT_EDGE(stream);
if (SEQ_GT(tail_seq, ack)) {
ack = tail_seq;
}
}
SCReturnUInt(ack);
}
/**
* \brief Function to handle the TCP_ESTABLISHED state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state. The function handles the data inside packets and call
* StreamTcpReassembleHandleSegment(tv, ) to handle the reassembling.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateEstablished(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_ACK(p);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len + 1;
ssn->client.next_seq = TCP_GET_ACK(p);
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
SCLogDebug("ssn (%p: FIN received SEQ"
" %" PRIu32 ", last ACK %" PRIu32 ", next win %"PRIu32","
" win %" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack, ssn->server.next_win,
ssn->server.window);
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent",
ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in ESTABLISHED state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_TOSERVER);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFF_SEQ);
return -1;
}
if (ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED) {
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND);
return -1;
}
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent. "
"Likely due server not receiving final ACK in 3whs", ssn);
return 0;
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state ESTABLISHED... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in EST state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_TOCLIENT);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND_DIFF_SEQ);
return -1;
}
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
/* Urgent pointer size can be more than the payload size, as it tells
* the future coming data from the sender will be handled urgently
* until data of size equal to urgent offset has been processed
* (RFC 2147) */
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
/* Process the received packet to server */
HandleEstablishedPacketToServer(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->client.next_seq, ssn->server.last_ack
,ssn->client.next_win, ssn->client.window);
} else { /* implied to client */
if (!(ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED)) {
ssn->flags |= STREAMTCP_FLAG_3WHS_CONFIRMED;
SCLogDebug("3whs is now confirmed by server");
}
/* Process the received packet to client */
HandleEstablishedPacketToClient(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack,
ssn->server.next_win, ssn->server.window);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the FIN packets for states TCP_SYN_RECV and
* TCP_ESTABLISHED and changes to another TCP state as required.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *stt,
TcpSession *ssn, Packet *p, PacketQueue *pq)
{
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
" ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_CLOSE_WAIT);
SCLogDebug("ssn %p: state changed to TCP_CLOSE_WAIT", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->client.next_seq %" PRIu32 "", ssn,
ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->client.next_seq, ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ", "
"ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream (last_ack %u win %u = %u)", ssn, TCP_GET_SEQ(p),
ssn->server.next_seq, ssn->server.last_ack, ssn->server.window, (ssn->server.last_ack + ssn->server.window));
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT1);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT1", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->server.next_seq, ssn->client.last_ack);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT1 state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpPacketStateFinWait1(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if ((p->tcph->th_flags & (TH_FIN|TH_ACK)) == (TH_FIN|TH_ACK)) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait1", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
if (TCP_GET_SEQ(p) == ssn->client.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
if (TCP_GET_SEQ(p) == ssn->server.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn (%p): default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT2 state. The function handles
* ACK, RST, FIN packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateFinWait2(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait2", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSING state. Upon arrival of ACK
* the connection goes to TCP_TIME_WAIT state. The state has been
* reached as both end application has been closed.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateClosing(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on Closing", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->client.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->server.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("StreamTcpPacketStateClosing (%p): =+ next SEQ "
"%" PRIu32 ", last ACK %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSE_WAIT state. Upon arrival of FIN
* packet from server the connection goes to TCP_LAST_ACK state.
* The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateCloseWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
SCEnter();
if (ssn == NULL) {
SCReturnInt(-1);
}
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
}
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
/* don't update to LAST_ACK here as we want a toclient FIN for that */
if (!retransmission)
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_LAST_ACK);
SCLogDebug("ssn %p: state changed to TCP_LAST_ACK", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on CloseWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
SCReturnInt(-1);
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->client.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->server.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
SCReturnInt(0);
}
/**
* \brief Function to handle the TCP_LAST_ACK state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool. The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateLastAck(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
SCLogDebug("ssn (%p): FIN pkt on LastAck", ssn);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on LastAck", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_LASTACK_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: not updating state as packet is before next_seq", ssn);
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq + 1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_LASTACK_ACK_WRONG_SEQ);
return -1;
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_TIME_WAIT state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateTimeWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on TimeWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq+1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->server.next_seq && TCP_GET_SEQ(p) != ssn->server.next_seq+1) {
if (p->payload_len > 0 && TCP_GET_SEQ(p) == ssn->server.last_ack) {
SCLogDebug("ssn %p: -> retransmission", ssn);
SCReturnInt(0);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
static int StreamTcpPacketStateClosed(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
SCLogDebug("RST on closed state");
return 0;
}
TcpStream *stream = NULL, *ostream = NULL;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
SCLogDebug("stream %s ostream %s",
stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV?"true":"false",
ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV ? "true":"false");
/* if we've seen a RST on our direction, but not on the other
* see if we perhaps need to continue processing anyway. */
if ((stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) == 0) {
if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->pstate) < 0)
return -1;
}
}
return 0;
}
static void StreamTcpPacketCheckPostRst(TcpSession *ssn, Packet *p)
{
if (p->flags & PKT_PSEUDO_STREAM_END) {
return;
}
/* more RSTs are not unusual */
if ((p->tcph->th_flags & (TH_RST)) != 0) {
return;
}
TcpStream *ostream = NULL;
if (PKT_IS_TOSERVER(p)) {
ostream = &ssn->server;
} else {
ostream = &ssn->client;
}
if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {
SCLogDebug("regular packet %"PRIu64" from same sender as "
"the previous RST. Looks like it injected!", p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpSetEvent(p, STREAM_SUSPECTED_RST_INJECT);
return;
}
return;
}
/**
* \retval 1 packet is a keep alive pkt
* \retval 0 packet is not a keep alive pkt
*/
static int StreamTcpPacketIsKeepAlive(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/*
rfc 1122:
An implementation SHOULD send a keep-alive segment with no
data; however, it MAY be configurable to send a keep-alive
segment containing one garbage octet, for compatibility with
erroneous TCP implementations.
*/
if (p->payload_len > 1)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0) {
return 0;
}
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
if (ack == ostream->last_ack && seq == (stream->next_seq - 1)) {
SCLogDebug("packet is TCP keep-alive: %"PRIu64, p->pcap_cnt);
stream->flags |= STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, (stream->next_seq - 1), ack, ostream->last_ack);
return 0;
}
/**
* \retval 1 packet is a keep alive ACK pkt
* \retval 0 packet is not a keep alive ACK pkt
*/
static int StreamTcpPacketIsKeepAliveACK(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/* should get a normal ACK to a Keep Alive */
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win != ostream->window)
return 0;
if ((ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) && ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP keep-aliveACK: %"PRIu64, p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u) FLAG_KEEPALIVE: %s", seq, stream->next_seq, ack, ostream->last_ack,
ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE ? "set" : "not set");
return 0;
}
static void StreamTcpClearKeepAliveFlag(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL;
if (p->flags & PKT_PSEUDO_STREAM_END)
return;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
} else {
stream = &ssn->server;
}
if (stream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) {
stream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
SCLogDebug("FLAG_KEEPALIVE cleared");
}
}
/**
* \retval 1 packet is a window update pkt
* \retval 0 packet is not a window update pkt
*/
static int StreamTcpPacketIsWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED)
return 0;
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win == ostream->window)
return 0;
if (ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP window update: %"PRIu64, p->pcap_cnt);
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/**
* Try to detect whether a packet is a valid FIN 4whs final ack.
*
*/
static int StreamTcpPacketIsFinShutdownAck(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (!(ssn->state == TCP_TIME_WAIT || ssn->state == TCP_CLOSE_WAIT || ssn->state == TCP_LAST_ACK))
return 0;
if (p->tcph->th_flags != TH_ACK)
return 0;
if (p->payload_len != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
SCLogDebug("%"PRIu64", seq %u ack %u stream->next_seq %u ostream->next_seq %u",
p->pcap_cnt, seq, ack, stream->next_seq, ostream->next_seq);
if (SEQ_EQ(stream->next_seq + 1, seq) && SEQ_EQ(ack, ostream->next_seq + 1)) {
return 1;
}
return 0;
}
/**
* Try to detect packets doing bad window updates
*
* See bug 1238.
*
* Find packets that are unexpected, and shrink the window to the point
* where the packets we do expect are rejected for being out of window.
*
* The logic we use here is:
* - packet seq > next_seq
* - packet ack > next_seq (packet acks unseen data)
* - packet shrinks window more than it's own data size
* - packet shrinks window more than the diff between it's ack and the
* last_ack value
*
* Packets coming in after packet loss can look quite a bit like this.
*/
static int StreamTcpPacketIsBadWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED || ssn->state == TCP_CLOSED)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win < ostream->window) {
uint32_t diff = ostream->window - pkt_win;
if (diff > p->payload_len &&
SEQ_GT(ack, ostream->next_seq) &&
SEQ_GT(seq, stream->next_seq))
{
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u, diff %u, dsize %u",
p->pcap_cnt, pkt_win, ostream->window, diff, p->payload_len);
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u",
p->pcap_cnt, pkt_win, ostream->window);
SCLogDebug("%"PRIu64", seq %u ack %u ostream->next_seq %u ostream->last_ack %u, ostream->next_win %u, diff %u (%u)",
p->pcap_cnt, seq, ack, ostream->next_seq, ostream->last_ack, ostream->next_win,
ostream->next_seq - ostream->last_ack, stream->next_seq - stream->last_ack);
/* get the expected window shrinking from looking at ack vs last_ack.
* Observed a lot of just a little overrunning that value. So added some
* margin that is still ok. To make sure this isn't a loophole to still
* close the window, this is limited to windows above 1024. Both values
* are rather arbitrary. */
uint32_t adiff = ack - ostream->last_ack;
if (((pkt_win > 1024) && (diff > (adiff + 32))) ||
((pkt_win <= 1024) && (diff > adiff)))
{
SCLogDebug("pkt ACK %u is %u bytes beyond last_ack %u, shrinks window by %u "
"(allowing 32 bytes extra): pkt WIN %u", ack, adiff, ostream->last_ack, diff, pkt_win);
SCLogDebug("%u - %u = %u (state %u)", diff, adiff, diff - adiff, ssn->state);
StreamTcpSetEvent(p, STREAM_PKT_BAD_WINDOW_UPDATE);
return 1;
}
}
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/** \internal
* \brief call packet handling function for 'state'
* \param state current TCP state
*/
static inline int StreamTcpStateDispatch(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq,
const uint8_t state)
{
SCLogDebug("ssn: %p", ssn);
switch (state) {
case TCP_SYN_SENT:
if (StreamTcpPacketStateSynSent(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_SYN_RECV:
if (StreamTcpPacketStateSynRecv(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_ESTABLISHED:
if (StreamTcpPacketStateEstablished(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_FIN_WAIT1:
SCLogDebug("packet received on TCP_FIN_WAIT1 state");
if (StreamTcpPacketStateFinWait1(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_FIN_WAIT2:
SCLogDebug("packet received on TCP_FIN_WAIT2 state");
if (StreamTcpPacketStateFinWait2(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSING:
SCLogDebug("packet received on TCP_CLOSING state");
if (StreamTcpPacketStateClosing(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSE_WAIT:
SCLogDebug("packet received on TCP_CLOSE_WAIT state");
if (StreamTcpPacketStateCloseWait(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_LAST_ACK:
SCLogDebug("packet received on TCP_LAST_ACK state");
if (StreamTcpPacketStateLastAck(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_TIME_WAIT:
SCLogDebug("packet received on TCP_TIME_WAIT state");
if (StreamTcpPacketStateTimeWait(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSED:
/* TCP session memory is not returned to pool until timeout. */
SCLogDebug("packet received on closed state");
if (StreamTcpPacketStateClosed(tv, p, stt, ssn, pq)) {
return -1;
}
break;
default:
SCLogDebug("packet received on default state");
break;
}
return 0;
}
static inline void HandleThreadId(ThreadVars *tv, Packet *p, StreamTcpThread *stt)
{
const int idx = (!(PKT_IS_TOSERVER(p)));
/* assign the thread id to the flow */
if (unlikely(p->flow->thread_id[idx] == 0)) {
p->flow->thread_id[idx] = (FlowThreadId)tv->id;
} else if (unlikely((FlowThreadId)tv->id != p->flow->thread_id[idx])) {
SCLogDebug("wrong thread: flow has %u, we are %d", p->flow->thread_id[idx], tv->id);
if (p->pkt_src == PKT_SRC_WIRE) {
StatsIncr(tv, stt->counter_tcp_wrong_thread);
if ((p->flow->flags & FLOW_WRONG_THREAD) == 0) {
p->flow->flags |= FLOW_WRONG_THREAD;
StreamTcpSetEvent(p, STREAM_WRONG_THREAD);
}
}
}
}
/* flow is and stays locked */
int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt,
PacketQueue *pq)
{
SCEnter();
DEBUG_ASSERT_FLOW_LOCKED(p->flow);
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
HandleThreadId(tv, p, stt);
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
/* track TCP flags */
if (ssn != NULL) {
ssn->tcp_packet_flags |= p->tcph->th_flags;
if (PKT_IS_TOSERVER(p))
ssn->client.tcp_flags |= p->tcph->th_flags;
else if (PKT_IS_TOCLIENT(p))
ssn->server.tcp_flags |= p->tcph->th_flags;
/* check if we need to unset the ASYNC flag */
if (ssn->flags & STREAMTCP_FLAG_ASYNC &&
ssn->client.tcp_flags != 0 &&
ssn->server.tcp_flags != 0)
{
SCLogDebug("ssn %p: removing ASYNC flag as we have packets on both sides", ssn);
ssn->flags &= ~STREAMTCP_FLAG_ASYNC;
}
}
/* update counters */
if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
StatsIncr(tv, stt->counter_tcp_synack);
} else if (p->tcph->th_flags & (TH_SYN)) {
StatsIncr(tv, stt->counter_tcp_syn);
}
if (p->tcph->th_flags & (TH_RST)) {
StatsIncr(tv, stt->counter_tcp_rst);
}
/* broken TCP http://ask.wireshark.org/questions/3183/acknowledgment-number-broken-tcp-the-acknowledge-field-is-nonzero-while-the-ack-flag-is-not-set */
if (!(p->tcph->th_flags & TH_ACK) && TCP_GET_ACK(p) != 0) {
StreamTcpSetEvent(p, STREAM_PKT_BROKEN_ACK);
}
/* If we are on IPS mode, and got a drop action triggered from
* the IP only module, or from a reassembled msg and/or from an
* applayer detection, then drop the rest of the packets of the
* same stream and avoid inspecting it any further */
if (StreamTcpCheckFlowDrops(p) == 1) {
SCLogDebug("This flow/stream triggered a drop rule");
FlowSetNoPacketInspectionFlag(p->flow);
DecodeSetNoPacketInspectionFlag(p);
StreamTcpDisableAppLayer(p->flow);
PACKET_DROP(p);
/* return the segments to the pool */
StreamTcpSessionPktFree(p);
SCReturnInt(0);
}
if (ssn == NULL || ssn->state == TCP_NONE) {
if (StreamTcpPacketStateNone(tv, p, stt, ssn, &stt->pseudo_queue) == -1) {
goto error;
}
if (ssn != NULL)
SCLogDebug("ssn->alproto %"PRIu16"", p->flow->alproto);
} else {
/* special case for PKT_PSEUDO_STREAM_END packets:
* bypass the state handling and various packet checks,
* we care about reassembly here. */
if (p->flags & PKT_PSEUDO_STREAM_END) {
if (PKT_IS_TOCLIENT(p)) {
ssn->client.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
ssn->server.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
}
/* straight to 'skip' as we already handled reassembly */
goto skip;
}
if (p->flow->flags & FLOW_WRONG_THREAD ||
ssn->client.flags & STREAMTCP_STREAM_FLAG_GAP ||
ssn->server.flags & STREAMTCP_STREAM_FLAG_GAP)
{
/* Stream and/or session in known bad condition. Block events
* from being set. */
p->flags |= PKT_STREAM_NO_EVENTS;
}
if (StreamTcpPacketIsKeepAlive(ssn, p) == 1) {
goto skip;
}
if (StreamTcpPacketIsKeepAliveACK(ssn, p) == 1) {
StreamTcpClearKeepAliveFlag(ssn, p);
goto skip;
}
StreamTcpClearKeepAliveFlag(ssn, p);
/* if packet is not a valid window update, check if it is perhaps
* a bad window update that we should ignore (and alert on) */
if (StreamTcpPacketIsFinShutdownAck(ssn, p) == 0)
if (StreamTcpPacketIsWindowUpdate(ssn, p) == 0)
if (StreamTcpPacketIsBadWindowUpdate(ssn,p))
goto skip;
/* handle the per 'state' logic */
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->state) < 0)
goto error;
skip:
StreamTcpPacketCheckPostRst(ssn, p);
if (ssn->state >= TCP_ESTABLISHED) {
p->flags |= PKT_STREAM_EST;
}
}
/* deal with a pseudo packet that is created upon receiving a RST
* segment. To be sure we process both sides of the connection, we
* inject a fake packet into the system, forcing reassembly of the
* opposing direction.
* There should be only one, but to be sure we do a while loop. */
if (ssn != NULL) {
while (stt->pseudo_queue.len > 0) {
SCLogDebug("processing pseudo packet / stream end");
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
/* process the opposing direction of the original packet */
if (PKT_IS_TOSERVER(np)) {
SCLogDebug("pseudo packet is to server");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, np, NULL);
} else {
SCLogDebug("pseudo packet is to client");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, np, NULL);
}
/* enqueue this packet so we inspect it in detect etc */
PacketEnqueue(pq, np);
}
SCLogDebug("processing pseudo packet / stream end done");
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
/* check for conditions that may make us not want to log this packet */
/* streams that hit depth */
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ||
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
}
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ||
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
/* encrypted packets */
if ((PKT_IS_TOSERVER(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) ||
(PKT_IS_TOCLIENT(p) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
if (ssn->flags & STREAMTCP_FLAG_BYPASS) {
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
/* if stream is dead and we have no detect engine at all, bypass. */
} else if (g_detect_disabled &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
StreamTcpBypassEnabled())
{
SCLogDebug("bypass as stream is dead and we have no rules");
PacketBypassCallback(p);
}
}
SCReturnInt(0);
error:
/* make sure we don't leave packets in our pseudo queue */
while (stt->pseudo_queue.len > 0) {
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
PacketEnqueue(pq, np);
}
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
if (StreamTcpInlineDropInvalid()) {
/* disable payload inspection as we're dropping this packet
* anyway. Doesn't disable all detection, so we can still
* match on the stream event that was set. */
DecodeSetNoPayloadInspectionFlag(p);
PACKET_DROP(p);
}
SCReturnInt(-1);
}
/**
* \brief Function to validate the checksum of the received packet. If the
* checksum is invalid, packet will be dropped, as the end system will
* also drop the packet.
*
* \param p Packet of which checksum has to be validated
* \retval 1 if the checksum is valid, otherwise 0
*/
static inline int StreamTcpValidateChecksum(Packet *p)
{
int ret = 1;
if (p->flags & PKT_IGNORE_CHECKSUM)
return ret;
if (p->level4_comp_csum == -1) {
if (PKT_IS_IPV4(p)) {
p->level4_comp_csum = TCPChecksum(p->ip4h->s_ip_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
} else if (PKT_IS_IPV6(p)) {
p->level4_comp_csum = TCPV6Checksum(p->ip6h->s_ip6_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
}
}
if (p->level4_comp_csum != 0) {
ret = 0;
if (p->livedev) {
(void) SC_ATOMIC_ADD(p->livedev->invalid_checksums, 1);
} else if (p->pcap_cnt) {
PcapIncreaseInvalidChecksum();
}
}
return ret;
}
/** \internal
* \brief check if a packet is a valid stream started
* \retval bool true/false */
static int TcpSessionPacketIsStreamStarter(const Packet *p)
{
if (p->tcph->th_flags == TH_SYN) {
SCLogDebug("packet %"PRIu64" is a stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
SCLogDebug("packet %"PRIu64" is a midstream stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
}
return 0;
}
/** \internal
* \brief Check if Flow and TCP SSN allow this flow/tuple to be reused
* \retval bool true yes reuse, false no keep tracking old ssn */
static int TcpSessionReuseDoneEnoughSyn(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOSERVER) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->client.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \internal
* \brief check if ssn is done enough for reuse by syn/ack
* \note should only be called if midstream is enabled
*/
static int TcpSessionReuseDoneEnoughSynAck(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOCLIENT) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->server.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \brief Check if SSN is done enough for reuse
*
* Reuse means a new TCP session reuses the tuple (flow in suri)
*
* \retval bool true if ssn can be reused, false if not */
static int TcpSessionReuseDoneEnough(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (p->tcph->th_flags == TH_SYN) {
return TcpSessionReuseDoneEnoughSyn(p, f, ssn);
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
return TcpSessionReuseDoneEnoughSynAck(p, f, ssn);
}
}
return 0;
}
int TcpSessionPacketSsnReuse(const Packet *p, const Flow *f, const void *tcp_ssn)
{
if (p->proto == IPPROTO_TCP && p->tcph != NULL) {
if (TcpSessionPacketIsStreamStarter(p) == 1) {
if (TcpSessionReuseDoneEnough(p, f, tcp_ssn) == 1) {
return 1;
}
}
}
return 0;
}
TmEcode StreamTcp (ThreadVars *tv, Packet *p, void *data, PacketQueue *pq, PacketQueue *postpq)
{
StreamTcpThread *stt = (StreamTcpThread *)data;
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
if (!(PKT_IS_TCP(p))) {
return TM_ECODE_OK;
}
if (p->flow == NULL) {
StatsIncr(tv, stt->counter_tcp_no_flow);
return TM_ECODE_OK;
}
/* only TCP packets with a flow from here */
if (!(p->flags & PKT_PSEUDO_STREAM_END)) {
if (stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION) {
if (StreamTcpValidateChecksum(p) == 0) {
StatsIncr(tv, stt->counter_tcp_invalid_checksum);
return TM_ECODE_OK;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM; //TODO check that this is set at creation
}
AppLayerProfilingReset(stt->ra_ctx->app_tctx);
(void)StreamTcpPacket(tv, p, stt, pq);
return TM_ECODE_OK;
}
TmEcode StreamTcpThreadInit(ThreadVars *tv, void *initdata, void **data)
{
SCEnter();
StreamTcpThread *stt = SCMalloc(sizeof(StreamTcpThread));
if (unlikely(stt == NULL))
SCReturnInt(TM_ECODE_FAILED);
memset(stt, 0, sizeof(StreamTcpThread));
stt->ssn_pool_id = -1;
*data = (void *)stt;
stt->counter_tcp_sessions = StatsRegisterCounter("tcp.sessions", tv);
stt->counter_tcp_ssn_memcap = StatsRegisterCounter("tcp.ssn_memcap_drop", tv);
stt->counter_tcp_pseudo = StatsRegisterCounter("tcp.pseudo", tv);
stt->counter_tcp_pseudo_failed = StatsRegisterCounter("tcp.pseudo_failed", tv);
stt->counter_tcp_invalid_checksum = StatsRegisterCounter("tcp.invalid_checksum", tv);
stt->counter_tcp_no_flow = StatsRegisterCounter("tcp.no_flow", tv);
stt->counter_tcp_syn = StatsRegisterCounter("tcp.syn", tv);
stt->counter_tcp_synack = StatsRegisterCounter("tcp.synack", tv);
stt->counter_tcp_rst = StatsRegisterCounter("tcp.rst", tv);
stt->counter_tcp_midstream_pickups = StatsRegisterCounter("tcp.midstream_pickups", tv);
stt->counter_tcp_wrong_thread = StatsRegisterCounter("tcp.pkt_on_wrong_thread", tv);
/* init reassembly ctx */
stt->ra_ctx = StreamTcpReassembleInitThreadCtx(tv);
if (stt->ra_ctx == NULL)
SCReturnInt(TM_ECODE_FAILED);
stt->ra_ctx->counter_tcp_segment_memcap = StatsRegisterCounter("tcp.segment_memcap_drop", tv);
stt->ra_ctx->counter_tcp_stream_depth = StatsRegisterCounter("tcp.stream_depth_reached", tv);
stt->ra_ctx->counter_tcp_reass_gap = StatsRegisterCounter("tcp.reassembly_gap", tv);
stt->ra_ctx->counter_tcp_reass_overlap = StatsRegisterCounter("tcp.overlap", tv);
stt->ra_ctx->counter_tcp_reass_overlap_diff_data = StatsRegisterCounter("tcp.overlap_diff_data", tv);
stt->ra_ctx->counter_tcp_reass_data_normal_fail = StatsRegisterCounter("tcp.insert_data_normal_fail", tv);
stt->ra_ctx->counter_tcp_reass_data_overlap_fail = StatsRegisterCounter("tcp.insert_data_overlap_fail", tv);
stt->ra_ctx->counter_tcp_reass_list_fail = StatsRegisterCounter("tcp.insert_list_fail", tv);
SCLogDebug("StreamTcp thread specific ctx online at %p, reassembly ctx %p",
stt, stt->ra_ctx);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
stt->ssn_pool_id = 0;
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
} else {
/* grow ssn_pool until we have a element for our thread id */
stt->ssn_pool_id = PoolThreadExpand(ssn_pool);
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
}
SCMutexUnlock(&ssn_pool_mutex);
if (stt->ssn_pool_id < 0 || ssn_pool == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "failed to setup/expand stream session pool. Expand stream.memcap?");
SCReturnInt(TM_ECODE_FAILED);
}
SCReturnInt(TM_ECODE_OK);
}
TmEcode StreamTcpThreadDeinit(ThreadVars *tv, void *data)
{
SCEnter();
StreamTcpThread *stt = (StreamTcpThread *)data;
if (stt == NULL) {
return TM_ECODE_OK;
}
/* XXX */
/* free reassembly ctx */
StreamTcpReassembleFreeThreadCtx(stt->ra_ctx);
/* clear memory */
memset(stt, 0, sizeof(StreamTcpThread));
SCFree(stt);
SCReturnInt(TM_ECODE_OK);
}
/**
* \brief Function to check the validity of the RST packets based on the
* target OS of the given packet.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 0 unacceptable RST
* \retval 1 acceptable RST
*
* WebSense sends RST packets that are:
* - RST flag, win 0, ack 0, seq = nextseq
*
*/
static int StreamTcpValidateRst(TcpSession *ssn, Packet *p)
{
uint8_t os_policy;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p)) {
SCReturnInt(0);
}
}
/* Set up the os_policy to be used in validating the RST packets based on
target system */
if (PKT_IS_TOSERVER(p)) {
if (ssn->server.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->server, p);
os_policy = ssn->server.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
} else {
if (ssn->client.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->client, p);
os_policy = ssn->client.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
}
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
if (PKT_IS_TOSERVER(p)) {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
} else {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
}
SCLogDebug("ssn %p: ASYNC reject RST", ssn);
return 0;
}
switch (os_policy) {
case OS_POLICY_HPUX11:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not Valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_LINUX:
case OS_POLICY_SOLARIS:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len),
ssn->client.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->client.next_seq + ssn->client.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ((TCP_GET_SEQ(p) + p->payload_len),
ssn->server.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->server.next_seq + ssn->server.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
default:
case OS_POLICY_BSD:
case OS_POLICY_FIRST:
case OS_POLICY_HPUX10:
case OS_POLICY_IRIX:
case OS_POLICY_MACOS:
case OS_POLICY_LAST:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
if(PKT_IS_TOSERVER(p)) {
if(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 " Stream %u",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 0;
}
}
break;
}
return 0;
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream.
*
* It's passive except for:
* 1. it sets the os policy on the stream if necessary
* 2. it sets an event in the packet if necessary
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpValidateTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
uint32_t last_pkt_ts = sender_stream->last_pkt_ts;
uint32_t last_ts = sender_stream->last_ts;
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/* HPUX11 igoners the timestamp of out of order packets */
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - last_ts) + 1);
} else {
result = (int32_t) (ts - last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (last_pkt_ts + PAWS_24DAYS))))
{
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream and update the session.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpHandleTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
sender_stream->flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
sender_stream->last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
default:
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/*HPUX11 igoners the timestamp of out of order packets*/
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, sender_stream->last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - sender_stream->last_ts) + 1);
} else {
result = (int32_t) (ts - sender_stream->last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (sender_stream->last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
sender_stream->last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid sender_stream->last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", sender_stream->last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
sender_stream->last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid sender_stream->last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
sender_stream->last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 1) {
/* Update the timestamp and last seen packet time for this
* stream */
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
} else if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (sender_stream->last_pkt_ts + PAWS_24DAYS))))
{
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
} else {
/* Solaris stops using timestamps if a packet is received
without a timestamp and timestamps were used on that stream. */
if (receiver_stream->os_policy == OS_POLICY_SOLARIS)
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to test the received ACK values against the stream window
* and previous ack value. ACK values should be higher than previous
* ACK value and less than the next_win value.
*
* \param ssn TcpSession for state access
* \param stream TcpStream of which last_ack needs to be tested
* \param p Packet which is used to test the last_ack
*
* \retval 0 ACK is valid, last_ack is updated if ACK was higher
* \retval -1 ACK is invalid
*/
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
uint32_t ack = TCP_GET_ACK(p);
/* fast track */
if (SEQ_GT(ack, stream->last_ack) && SEQ_LEQ(ack, stream->next_win))
{
SCLogDebug("ACK in bounds");
SCReturnInt(0);
}
/* fast track */
else if (SEQ_EQ(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" == stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
SCReturnInt(0);
}
/* exception handling */
if (SEQ_LT(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" < stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
/* This is an attempt to get a 'left edge' value that we can check against.
* It doesn't work when the window is 0, need to think of a better way. */
if (stream->window != 0 && SEQ_LT(ack, (stream->last_ack - stream->window))) {
SCLogDebug("ACK %"PRIu32" is before last_ack %"PRIu32" - window "
"%"PRIu32" = %"PRIu32, ack, stream->last_ack,
stream->window, stream->last_ack - stream->window);
goto invalid;
}
SCReturnInt(0);
}
if (ssn->state > TCP_SYN_SENT && SEQ_GT(ack, stream->next_win)) {
SCLogDebug("ACK %"PRIu32" is after next_win %"PRIu32, ack, stream->next_win);
goto invalid;
/* a toclient RST as a reponse to SYN, next_win is 0, ack will be isn+1, just like
* the syn ack */
} else if (ssn->state == TCP_SYN_SENT && PKT_IS_TOCLIENT(p) &&
p->tcph->th_flags & TH_RST &&
SEQ_EQ(ack, stream->isn + 1)) {
SCReturnInt(0);
}
SCLogDebug("default path leading to invalid: ACK %"PRIu32", last_ack %"PRIu32
" next_win %"PRIu32, ack, stream->last_ack, stream->next_win);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_ACK);
SCReturnInt(-1);
}
/** \brief disable reassembly
* Disable app layer and set raw inspect to no longer accept new data.
* Stream engine will then fully disable raw after last inspection.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionNoReassemblyFlag (TcpSession *ssn, char direction)
{
ssn->flags |= STREAMTCP_FLAG_APP_LAYER_DISABLED;
if (direction) {
ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
}
}
/** \brief Set the No reassembly flag for the given direction in given TCP
* session.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetDisableRawReassemblyFlag (TcpSession *ssn, char direction)
{
direction ? (ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) :
(ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED);
}
/** \brief enable bypass
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionBypassFlag (TcpSession *ssn)
{
ssn->flags |= STREAMTCP_FLAG_BYPASS;
}
#define PSEUDO_PKT_SET_IPV4HDR(nipv4h,ipv4h) do { \
IPV4_SET_RAW_VER(nipv4h, IPV4_GET_RAW_VER(ipv4h)); \
IPV4_SET_RAW_HLEN(nipv4h, IPV4_GET_RAW_HLEN(ipv4h)); \
IPV4_SET_RAW_IPLEN(nipv4h, IPV4_GET_RAW_IPLEN(ipv4h)); \
IPV4_SET_RAW_IPTOS(nipv4h, IPV4_GET_RAW_IPTOS(ipv4h)); \
IPV4_SET_RAW_IPPROTO(nipv4h, IPV4_GET_RAW_IPPROTO(ipv4h)); \
(nipv4h)->s_ip_src = IPV4_GET_RAW_IPDST(ipv4h); \
(nipv4h)->s_ip_dst = IPV4_GET_RAW_IPSRC(ipv4h); \
} while (0)
#define PSEUDO_PKT_SET_IPV6HDR(nipv6h,ipv6h) do { \
(nipv6h)->s_ip6_src[0] = (ipv6h)->s_ip6_dst[0]; \
(nipv6h)->s_ip6_src[1] = (ipv6h)->s_ip6_dst[1]; \
(nipv6h)->s_ip6_src[2] = (ipv6h)->s_ip6_dst[2]; \
(nipv6h)->s_ip6_src[3] = (ipv6h)->s_ip6_dst[3]; \
(nipv6h)->s_ip6_dst[0] = (ipv6h)->s_ip6_src[0]; \
(nipv6h)->s_ip6_dst[1] = (ipv6h)->s_ip6_src[1]; \
(nipv6h)->s_ip6_dst[2] = (ipv6h)->s_ip6_src[2]; \
(nipv6h)->s_ip6_dst[3] = (ipv6h)->s_ip6_src[3]; \
IPV6_SET_RAW_NH(nipv6h, IPV6_GET_RAW_NH(ipv6h)); \
} while (0)
#define PSEUDO_PKT_SET_TCPHDR(ntcph,tcph) do { \
COPY_PORT((tcph)->th_dport, (ntcph)->th_sport); \
COPY_PORT((tcph)->th_sport, (ntcph)->th_dport); \
(ntcph)->th_seq = (tcph)->th_ack; \
(ntcph)->th_ack = (tcph)->th_seq; \
} while (0)
/**
* \brief Function to fetch a packet from the packet allocation queue for
* creation of the pseudo packet from the reassembled stream.
*
* @param parent Pointer to the parent of the pseudo packet
* @param pkt pointer to the raw packet of the parent
* @param len length of the packet
* @return upon success returns the pointer to the new pseudo packet
* otherwise NULL
*/
Packet *StreamTcpPseudoSetup(Packet *parent, uint8_t *pkt, uint32_t len)
{
SCEnter();
if (len == 0) {
SCReturnPtr(NULL, "Packet");
}
Packet *p = PacketGetFromQueueOrAlloc();
if (p == NULL) {
SCReturnPtr(NULL, "Packet");
}
/* set the root ptr to the lowest layer */
if (parent->root != NULL)
p->root = parent->root;
else
p->root = parent;
/* copy packet and set lenght, proto */
p->proto = parent->proto;
p->datalink = parent->datalink;
PacketCopyData(p, pkt, len);
p->recursion_level = parent->recursion_level + 1;
p->ts.tv_sec = parent->ts.tv_sec;
p->ts.tv_usec = parent->ts.tv_usec;
FlowReference(&p->flow, parent->flow);
/* set tunnel flags */
/* tell new packet it's part of a tunnel */
SET_TUNNEL_PKT(p);
/* tell parent packet it's part of a tunnel */
SET_TUNNEL_PKT(parent);
/* increment tunnel packet refcnt in the root packet */
TUNNEL_INCR_PKT_TPR(p);
return p;
}
/** \brief Create a pseudo packet injected into the engine to signal the
* opposing direction of this stream trigger detection/logging.
*
* \param parent real packet
* \param pq packet queue to store the new pseudo packet in
* \param dir 0 ts 1 tc
*/
static void StreamTcpPseudoPacketCreateDetectLogFlush(ThreadVars *tv,
StreamTcpThread *stt, Packet *parent,
TcpSession *ssn, PacketQueue *pq, int dir)
{
SCEnter();
Flow *f = parent->flow;
if (parent->flags & PKT_PSEUDO_DETECTLOG_FLUSH) {
SCReturn;
}
Packet *np = PacketPoolGetPacket();
if (np == NULL) {
SCReturn;
}
PKT_SET_SRC(np, PKT_SRC_STREAM_TCP_DETECTLOG_FLUSH);
np->tenant_id = f->tenant_id;
np->datalink = DLT_RAW;
np->proto = IPPROTO_TCP;
FlowReference(&np->flow, f);
np->flags |= PKT_STREAM_EST;
np->flags |= PKT_HAS_FLOW;
np->flags |= PKT_IGNORE_CHECKSUM;
np->flags |= PKT_PSEUDO_DETECTLOG_FLUSH;
np->vlan_id[0] = f->vlan_id[0];
np->vlan_id[1] = f->vlan_id[1];
np->vlan_idx = f->vlan_idx;
np->livedev = (struct LiveDevice_ *)f->livedev;
if (f->flags & FLOW_NOPACKET_INSPECTION) {
DecodeSetNoPacketInspectionFlag(np);
}
if (f->flags & FLOW_NOPAYLOAD_INSPECTION) {
DecodeSetNoPayloadInspectionFlag(np);
}
if (dir == 0) {
SCLogDebug("pseudo is to_server");
np->flowflags |= FLOW_PKT_TOSERVER;
} else {
SCLogDebug("pseudo is to_client");
np->flowflags |= FLOW_PKT_TOCLIENT;
}
np->flowflags |= FLOW_PKT_ESTABLISHED;
np->payload = NULL;
np->payload_len = 0;
if (FLOW_IS_IPV4(f)) {
if (dir == 0) {
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->src, &np->src);
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->dst, &np->dst);
np->sp = f->sp;
np->dp = f->dp;
} else {
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->src, &np->dst);
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->dst, &np->src);
np->sp = f->dp;
np->dp = f->sp;
}
/* Check if we have enough room in direct data. We need ipv4 hdr + tcp hdr.
* Force an allocation if it is not the case.
*/
if (GET_PKT_DIRECT_MAX_SIZE(np) < 40) {
if (PacketCallocExtPkt(np, 40) == -1) {
goto error;
}
}
/* set the ip header */
np->ip4h = (IPV4Hdr *)GET_PKT_DATA(np);
/* version 4 and length 20 bytes for the tcp header */
np->ip4h->ip_verhl = 0x45;
np->ip4h->ip_tos = 0;
np->ip4h->ip_len = htons(40);
np->ip4h->ip_id = 0;
np->ip4h->ip_off = 0;
np->ip4h->ip_ttl = 64;
np->ip4h->ip_proto = IPPROTO_TCP;
if (dir == 0) {
np->ip4h->s_ip_src.s_addr = f->src.addr_data32[0];
np->ip4h->s_ip_dst.s_addr = f->dst.addr_data32[0];
} else {
np->ip4h->s_ip_src.s_addr = f->dst.addr_data32[0];
np->ip4h->s_ip_dst.s_addr = f->src.addr_data32[0];
}
/* set the tcp header */
np->tcph = (TCPHdr *)((uint8_t *)GET_PKT_DATA(np) + 20);
SET_PKT_LEN(np, 40); /* ipv4 hdr + tcp hdr */
} else if (FLOW_IS_IPV6(f)) {
if (dir == 0) {
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->src, &np->src);
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->dst, &np->dst);
np->sp = f->sp;
np->dp = f->dp;
} else {
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->src, &np->dst);
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->dst, &np->src);
np->sp = f->dp;
np->dp = f->sp;
}
/* Check if we have enough room in direct data. We need ipv6 hdr + tcp hdr.
* Force an allocation if it is not the case.
*/
if (GET_PKT_DIRECT_MAX_SIZE(np) < 60) {
if (PacketCallocExtPkt(np, 60) == -1) {
goto error;
}
}
/* set the ip header */
np->ip6h = (IPV6Hdr *)GET_PKT_DATA(np);
/* version 6 */
np->ip6h->s_ip6_vfc = 0x60;
np->ip6h->s_ip6_flow = 0;
np->ip6h->s_ip6_nxt = IPPROTO_TCP;
np->ip6h->s_ip6_plen = htons(20);
np->ip6h->s_ip6_hlim = 64;
if (dir == 0) {
np->ip6h->s_ip6_src[0] = f->src.addr_data32[0];
np->ip6h->s_ip6_src[1] = f->src.addr_data32[1];
np->ip6h->s_ip6_src[2] = f->src.addr_data32[2];
np->ip6h->s_ip6_src[3] = f->src.addr_data32[3];
np->ip6h->s_ip6_dst[0] = f->dst.addr_data32[0];
np->ip6h->s_ip6_dst[1] = f->dst.addr_data32[1];
np->ip6h->s_ip6_dst[2] = f->dst.addr_data32[2];
np->ip6h->s_ip6_dst[3] = f->dst.addr_data32[3];
} else {
np->ip6h->s_ip6_src[0] = f->dst.addr_data32[0];
np->ip6h->s_ip6_src[1] = f->dst.addr_data32[1];
np->ip6h->s_ip6_src[2] = f->dst.addr_data32[2];
np->ip6h->s_ip6_src[3] = f->dst.addr_data32[3];
np->ip6h->s_ip6_dst[0] = f->src.addr_data32[0];
np->ip6h->s_ip6_dst[1] = f->src.addr_data32[1];
np->ip6h->s_ip6_dst[2] = f->src.addr_data32[2];
np->ip6h->s_ip6_dst[3] = f->src.addr_data32[3];
}
/* set the tcp header */
np->tcph = (TCPHdr *)((uint8_t *)GET_PKT_DATA(np) + 40);
SET_PKT_LEN(np, 60); /* ipv6 hdr + tcp hdr */
}
np->tcph->th_offx2 = 0x50;
np->tcph->th_flags |= TH_ACK;
np->tcph->th_win = 10;
np->tcph->th_urp = 0;
/* to server */
if (dir == 0) {
np->tcph->th_sport = htons(f->sp);
np->tcph->th_dport = htons(f->dp);
np->tcph->th_seq = htonl(ssn->client.next_seq);
np->tcph->th_ack = htonl(ssn->server.last_ack);
/* to client */
} else {
np->tcph->th_sport = htons(f->dp);
np->tcph->th_dport = htons(f->sp);
np->tcph->th_seq = htonl(ssn->server.next_seq);
np->tcph->th_ack = htonl(ssn->client.last_ack);
}
/* use parent time stamp */
memcpy(&np->ts, &parent->ts, sizeof(struct timeval));
SCLogDebug("np %p", np);
PacketEnqueue(pq, np);
StatsIncr(tv, stt->counter_tcp_pseudo);
SCReturn;
error:
FlowDeReference(&np->flow);
SCReturn;
}
/** \brief create packets in both directions to flush out logging
* and detection before switching protocols.
* In IDS mode, create first in packet dir, 2nd in opposing
* In IPS mode, do the reverse.
* Flag TCP engine that data needs to be inspected regardless
* of how far we are wrt inspect limits.
*/
void StreamTcpDetectLogFlush(ThreadVars *tv, StreamTcpThread *stt, Flow *f, Packet *p, PacketQueue *pq)
{
TcpSession *ssn = f->protoctx;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
bool ts = PKT_IS_TOSERVER(p) ? true : false;
ts ^= StreamTcpInlineMode();
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^0);
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^1);
}
/**
* \brief Run callback function on each TCP segment
*
* \note when stream engine is running in inline mode all segments are used,
* in IDS/non-inline mode only ack'd segments are iterated.
*
* \note Must be called under flow lock.
*
* \return -1 in case of error, the number of segment in case of success
*
*/
int StreamTcpSegmentForEach(const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data)
{
TcpSession *ssn = NULL;
TcpStream *stream = NULL;
int ret = 0;
int cnt = 0;
if (p->flow == NULL)
return 0;
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
return 0;
}
if (flag & FLOW_PKT_TOSERVER) {
stream = &(ssn->server);
} else {
stream = &(ssn->client);
}
/* for IDS, return ack'd segments. For IPS all. */
TcpSegment *seg;
RB_FOREACH(seg, TCPSEG, &stream->seg_tree) {
if (!((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
|| SEQ_LT(seg->seq, stream->last_ack)))
break;
const uint8_t *seg_data;
uint32_t seg_datalen;
StreamingBufferSegmentGetData(&stream->sb, &seg->sbseg, &seg_data, &seg_datalen);
ret = CallbackFunc(p, data, seg_data, seg_datalen);
if (ret != 1) {
SCLogDebug("Callback function has failed");
return -1;
}
cnt++;
}
return cnt;
}
int StreamTcpBypassEnabled(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS);
}
/**
* \brief See if stream engine is operating in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineMode(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_INLINE) ? 1 : 0;
}
void TcpSessionSetReassemblyDepth(TcpSession *ssn, uint32_t size)
{
if (size > ssn->reassembly_depth || size == 0) {
ssn->reassembly_depth = size;
}
return;
}
#ifdef UNITTESTS
#define SET_ISN(stream, setseq) \
(stream)->isn = (setseq); \
(stream)->base_seq = (setseq) + 1
/**
* \test Test the allocation of TCP session for a given packet from the
* ssn_pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest01 (void)
{
StreamTcpThread stt;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
TcpSession *ssn = StreamTcpNewSession(p, 0);
if (ssn == NULL) {
printf("Session can not be allocated: ");
goto end;
}
f.protoctx = ssn;
if (f.alparser != NULL) {
printf("AppLayer field not set to NULL: ");
goto end;
}
if (ssn->state != 0) {
printf("TCP state field not set to 0: ");
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the deallocation of TCP session for a given packet and return
* the memory back to ssn_pool and corresponding segments to segment
* pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest02 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
StreamTcpSessionClear(p->flow->protoctx);
//StreamTcpUTClearSession(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN packet of the session. The session is setup only if midstream
* sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest03 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 20 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN/ACK packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest04 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(9);
p->tcph->th_ack = htonl(19);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 10 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 20)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* 3WHS packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest05 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(13);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, 4); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(16);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, 4); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 16 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we have seen only the
* FIN, RST packets packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest06 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
TcpSession ssn;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&ssn, 0, sizeof (TcpSession));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_flags = TH_FIN;
p->tcph = &tcph;
/* StreamTcpPacket returns -1 on unsolicited FIN */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed: ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't: ");
goto end;
}
p->tcph->th_flags = TH_RST;
/* StreamTcpPacket returns -1 on unsolicited RST */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed (2): ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't (2): ");
goto end;
}
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the working on PAWS. The packet will be dropped by stream, as
* its timestamp is old, although the segment is in the window.
*/
static int StreamTcpTest07 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
PacketQueue pq;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 2;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) != -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working on PAWS. The packet will be accpeted by engine as
* the timestamp is valid and it is in window.
*/
static int StreamTcpTest08 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(20);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 12;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 12);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working of No stream reassembly flag. The stream will not
* reassemble the segment if the flag is set.
*/
static int StreamTcpTest09 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(12);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(p->flow->protoctx == NULL);
StreamTcpSetSessionNoReassemblyFlag(((TcpSession *)(p->flow->protoctx)), 0);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
TcpSession *ssn = p->flow->protoctx;
FAIL_IF_NULL(ssn);
TcpSegment *seg = RB_MIN(TCPSEG, &ssn->client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCPSEG_RB_NEXT(seg) != NULL);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we see all the packets in that stream from start.
*/
static int StreamTcpTest10 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN packet of that stream.
*/
static int StreamTcpTest11 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(1);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(2);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->server.last_ack != 2 &&
((TcpSession *)(p->flow->protoctx))->client.next_seq != 1);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest12 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
* Later, we start to receive the packet from other end stream too.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest13 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(9);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 9 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 14) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.1\n"
"\n"
" linux: 192.168.0.2\n"
"\n";
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string1 =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.0/24," "192.168.1.1\n"
"\n"
" linux: 192.168.1.0/24," "192.168.0.1\n"
"\n";
/**
* \brief Function to parse the dummy conf string and get the value of IP
* address for the corresponding OS policy type.
*
* \param conf_val_name Name of the OS policy type
* \retval returns IP address as string on success and NULL on failure
*/
static const char *StreamTcpParseOSPolicy (char *conf_var_name)
{
SCEnter();
char conf_var_type_name[15] = "host-os-policy";
char *conf_var_full_name = NULL;
const char *conf_var_value = NULL;
if (conf_var_name == NULL)
goto end;
/* the + 2 is for the '.' and the string termination character '\0' */
conf_var_full_name = (char *)SCMalloc(strlen(conf_var_type_name) +
strlen(conf_var_name) + 2);
if (conf_var_full_name == NULL)
goto end;
if (snprintf(conf_var_full_name,
strlen(conf_var_type_name) + strlen(conf_var_name) + 2, "%s.%s",
conf_var_type_name, conf_var_name) < 0) {
SCLogError(SC_ERR_INVALID_VALUE, "Error in making the conf full name");
goto end;
}
if (ConfGet(conf_var_full_name, &conf_var_value) != 1) {
SCLogError(SC_ERR_UNKNOWN_VALUE, "Error in getting conf value for conf name %s",
conf_var_full_name);
goto end;
}
SCLogDebug("Value obtained from the yaml conf file, for the var "
"\"%s\" is \"%s\"", conf_var_name, conf_var_value);
end:
if (conf_var_full_name != NULL)
SCFree(conf_var_full_name);
SCReturnCharPtr(conf_var_value);
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest14 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string, strlen(dummy_conf_string));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.0.2");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest01 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(21);
p->tcph->th_ack = htonl(10);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK, but the SYN/ACK does
* not have the right SEQ
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest02 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("SYN/ACK pkt not rejected but it should have: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK: however the SYN/ACK and ACK
* are part of a normal 3WHS
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest03 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(31);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest15 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.20");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.20");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest16 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_WINDOWS)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_WINDOWS);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1". To check the setting of
* Default os policy
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest17 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("10.1.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_DEFAULT)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_DEFAULT);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest18 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS)
goto end;
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest19 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8": ",
(uint8_t)OS_POLICY_WINDOWS, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest20 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest21 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest22 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("123.231.2.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_DEFAULT) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_DEFAULT, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest23(void)
{
StreamTcpThread stt;
TcpSession ssn;
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(p == NULL);
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
SET_ISN(&ssn.client, 3184324452UL);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419609UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 6;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
TcpSegment *seg = RB_MAX(TCPSEG, &ssn.client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCP_SEG_LEN(seg) != 2);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest24(void)
{
StreamTcpThread stt;
TcpSession ssn;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF (p == NULL);
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
//ssn.client.ra_app_base_seq = ssn.client.ra_raw_base_seq = ssn.client.last_ack = 3184324453UL;
SET_ISN(&ssn.client, 3184324453UL);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 4;
FAIL_IF (StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419633UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419657UL);
p->payload_len = 4;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
TcpSegment *seg = RB_MAX(TCPSEG, &ssn.client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCP_SEG_LEN(seg) != 4);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest25(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest26(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest27(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the memcap incrementing/decrementing and memcap check */
static int StreamTcpTest28(void)
{
StreamTcpThread stt;
StreamTcpUTInit(&stt.ra_ctx);
uint32_t memuse = SC_ATOMIC_GET(st_memuse);
StreamTcpIncrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != (memuse+500));
StreamTcpDecrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != memuse);
FAIL_IF(StreamTcpCheckMemcap(500) != 1);
FAIL_IF(StreamTcpCheckMemcap((memuse + SC_ATOMIC_GET(stream_config.memcap))) != 0);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != 0);
PASS;
}
#if 0
/**
* \test Test the resetting of the sesison with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest29(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t packet[1460] = "";
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = packet;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
tcpvars.hlen = 20;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 119197101;
ssn.server.window = 5184;
ssn.server.next_win = 5184;
ssn.server.last_ack = 119197101;
ssn.server.ra_base_seq = 119197101;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 4;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(119197102);
p.tcph->th_ack = htonl(15);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(15);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the ssn.state should be TCP_ESTABLISHED(%"PRIu8"), not %"PRIu8""
"\n", TCP_ESTABLISHED, ssn.state);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the overlapping of the packet with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest30(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t payload[9] = "AAAAAAAAA";
uint8_t payload1[9] = "GET /EVIL";
uint8_t expected_content[9] = { 0x47, 0x45, 0x54, 0x20, 0x2f, 0x45, 0x56,
0x49, 0x4c };
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = payload;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload = payload1;
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(20);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (StreamTcpCheckStreamContents(expected_content, 9, &ssn.client) != 1) {
printf("the contents are not as expected(GET /EVIL), contents are: ");
PrintRawDataFp(stdout, ssn.client.seg_list->payload, 9);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the multiple SYN packet handling with bad checksum and timestamp
* value. Engine should drop the bad checksum packet and establish
* TCP session correctly.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest31(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
TCPOpt tcpopt;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
memset(&tcpopt, 0, sizeof (TCPOpt));
int result = 1;
StreamTcpInitConfig(TRUE);
FLOW_INITIALIZE(&f);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_LINUX;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
p.tcpvars.ts = &tcpopt;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 100;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 10;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
ssn.flags |= STREAMTCP_FLAG_TIMESTAMP;
tcph.th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(11);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079941);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr1;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the should have been changed to TCP_ESTABLISHED!!\n ");
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the initialization of tcp streams with ECN & CWR flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest32(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK | TH_ECN;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_flags = TH_ACK;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the same
* ports have been used to start the new session after resetting the
* previous session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest33 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_CLOSED) {
printf("Tcp session should have been closed\n");
goto end;
}
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_seq = htonl(1);
p.tcph->th_ack = htonl(2);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been ESTABLISHED\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the PUSH flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest34 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_PUSH;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the URG flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest35 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_URG;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the processing of PSH and URG flag in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest36(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_URG;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->client.next_seq != 4) {
printf("the ssn->client.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)p.flow->protoctx)->client.next_seq);
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
#endif
/**
* \test Test the processing of out of order FIN packets in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest37(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p->tcph->th_ack = htonl(2);
p->tcph->th_seq = htonl(4);
p->tcph->th_flags = TH_ACK|TH_FIN;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_CLOSE_WAIT) {
printf("the TCP state should be TCP_CLOSE_WAIT\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_ACK;
p->payload_len = 0;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
TcpStream *stream = &(((TcpSession *)p->flow->protoctx)->client);
FAIL_IF(STREAM_RAW_PROGRESS(stream) != 0); // no detect no progress update
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest38 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[128];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(29847);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 1 as the previous sent ACK value is out of
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 1) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 127, 128); /*AAA*/
p->payload = payload;
p->payload_len = 127;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 128) {
printf("the server.next_seq should be 128, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(256); // in window, but beyond next_seq
p->tcph->th_seq = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256, as the previous sent ACK value
is inside window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(128);
p->tcph->th_seq = htonl(8);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 256, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack and update the next_seq after loosing the .
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest39 (void)
{
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 4) {
printf("the server.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 4 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 4) {
printf("the server.last_ack should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_seq = htonl(4);
p->tcph->th_ack = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* next_seq value should be 2987 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 7) {
printf("the server.next_seq should be 7, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick first */
static int StreamTcpTest42 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(501);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 500) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 500);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick second */
static int StreamTcpTest43 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick neither */
static int StreamTcpTest44 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(3001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_SYN_RECV) {
SCLogDebug("state not TCP_SYN_RECV");
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, over the limit */
static int StreamTcpTest45 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
stream_config.max_synack_queued = 2;
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(2000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(3000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
#endif /* UNITTESTS */
void StreamTcpRegisterTests (void)
{
#ifdef UNITTESTS
UtRegisterTest("StreamTcpTest01 -- TCP session allocation",
StreamTcpTest01);
UtRegisterTest("StreamTcpTest02 -- TCP session deallocation",
StreamTcpTest02);
UtRegisterTest("StreamTcpTest03 -- SYN missed MidStream session",
StreamTcpTest03);
UtRegisterTest("StreamTcpTest04 -- SYN/ACK missed MidStream session",
StreamTcpTest04);
UtRegisterTest("StreamTcpTest05 -- 3WHS missed MidStream session",
StreamTcpTest05);
UtRegisterTest("StreamTcpTest06 -- FIN, RST message MidStream session",
StreamTcpTest06);
UtRegisterTest("StreamTcpTest07 -- PAWS invalid timestamp",
StreamTcpTest07);
UtRegisterTest("StreamTcpTest08 -- PAWS valid timestamp", StreamTcpTest08);
UtRegisterTest("StreamTcpTest09 -- No Client Reassembly", StreamTcpTest09);
UtRegisterTest("StreamTcpTest10 -- No missed packet Async stream",
StreamTcpTest10);
UtRegisterTest("StreamTcpTest11 -- SYN missed Async stream",
StreamTcpTest11);
UtRegisterTest("StreamTcpTest12 -- SYN/ACK missed Async stream",
StreamTcpTest12);
UtRegisterTest("StreamTcpTest13 -- opposite stream packets for Async " "stream",
StreamTcpTest13);
UtRegisterTest("StreamTcp4WHSTest01", StreamTcp4WHSTest01);
UtRegisterTest("StreamTcp4WHSTest02", StreamTcp4WHSTest02);
UtRegisterTest("StreamTcp4WHSTest03", StreamTcp4WHSTest03);
UtRegisterTest("StreamTcpTest14 -- setup OS policy", StreamTcpTest14);
UtRegisterTest("StreamTcpTest15 -- setup OS policy", StreamTcpTest15);
UtRegisterTest("StreamTcpTest16 -- setup OS policy", StreamTcpTest16);
UtRegisterTest("StreamTcpTest17 -- setup OS policy", StreamTcpTest17);
UtRegisterTest("StreamTcpTest18 -- setup OS policy", StreamTcpTest18);
UtRegisterTest("StreamTcpTest19 -- setup OS policy", StreamTcpTest19);
UtRegisterTest("StreamTcpTest20 -- setup OS policy", StreamTcpTest20);
UtRegisterTest("StreamTcpTest21 -- setup OS policy", StreamTcpTest21);
UtRegisterTest("StreamTcpTest22 -- setup OS policy", StreamTcpTest22);
UtRegisterTest("StreamTcpTest23 -- stream memory leaks", StreamTcpTest23);
UtRegisterTest("StreamTcpTest24 -- stream memory leaks", StreamTcpTest24);
UtRegisterTest("StreamTcpTest25 -- test ecn/cwr sessions",
StreamTcpTest25);
UtRegisterTest("StreamTcpTest26 -- test ecn/cwr sessions",
StreamTcpTest26);
UtRegisterTest("StreamTcpTest27 -- test ecn/cwr sessions",
StreamTcpTest27);
UtRegisterTest("StreamTcpTest28 -- Memcap Test", StreamTcpTest28);
#if 0 /* VJ 2010/09/01 disabled since they blow up on Fedora and Fedora is
* right about blowing up. The checksum functions are not used properly
* in the tests. */
UtRegisterTest("StreamTcpTest29 -- Badchecksum Reset Test", StreamTcpTest29, 1);
UtRegisterTest("StreamTcpTest30 -- Badchecksum Overlap Test", StreamTcpTest30, 1);
UtRegisterTest("StreamTcpTest31 -- MultipleSyns Test", StreamTcpTest31, 1);
UtRegisterTest("StreamTcpTest32 -- Bogus CWR Test", StreamTcpTest32, 1);
UtRegisterTest("StreamTcpTest33 -- RST-SYN Again Test", StreamTcpTest33, 1);
UtRegisterTest("StreamTcpTest34 -- SYN-PUSH Test", StreamTcpTest34, 1);
UtRegisterTest("StreamTcpTest35 -- SYN-URG Test", StreamTcpTest35, 1);
UtRegisterTest("StreamTcpTest36 -- PUSH-URG Test", StreamTcpTest36, 1);
#endif
UtRegisterTest("StreamTcpTest37 -- Out of order FIN Test",
StreamTcpTest37);
UtRegisterTest("StreamTcpTest38 -- validate ACK", StreamTcpTest38);
UtRegisterTest("StreamTcpTest39 -- update next_seq", StreamTcpTest39);
UtRegisterTest("StreamTcpTest42 -- SYN/ACK queue", StreamTcpTest42);
UtRegisterTest("StreamTcpTest43 -- SYN/ACK queue", StreamTcpTest43);
UtRegisterTest("StreamTcpTest44 -- SYN/ACK queue", StreamTcpTest44);
UtRegisterTest("StreamTcpTest45 -- SYN/ACK queue", StreamTcpTest45);
/* set up the reassembly tests as well */
StreamTcpReassembleRegisterTests();
StreamTcpSackRegisterTests ();
#endif /* UNITTESTS */
}
| ./CrossVul/dataset_final_sorted/CWE-94/c/bad_1213_0 |
crossvul-cpp_data_good_1213_0 | /* Copyright (C) 2007-2016 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
* \author Gurvinder Singh <gurvindersinghdahiya@gmail.com>
*
* TCP stream tracking and reassembly engine.
*
* \todo - 4WHS: what if after the 2nd SYN we turn out to be normal 3WHS anyway?
*/
#include "suricata-common.h"
#include "suricata.h"
#include "decode.h"
#include "debug.h"
#include "detect.h"
#include "flow.h"
#include "flow-util.h"
#include "conf.h"
#include "conf-yaml-loader.h"
#include "threads.h"
#include "threadvars.h"
#include "tm-threads.h"
#include "util-pool.h"
#include "util-pool-thread.h"
#include "util-checksum.h"
#include "util-unittest.h"
#include "util-print.h"
#include "util-debug.h"
#include "util-device.h"
#include "stream-tcp-private.h"
#include "stream-tcp-reassemble.h"
#include "stream-tcp.h"
#include "stream-tcp-inline.h"
#include "stream-tcp-sack.h"
#include "stream-tcp-util.h"
#include "stream.h"
#include "pkt-var.h"
#include "host.h"
#include "app-layer.h"
#include "app-layer-parser.h"
#include "app-layer-protos.h"
#include "app-layer-htp-mem.h"
#include "util-host-os-info.h"
#include "util-privs.h"
#include "util-profiling.h"
#include "util-misc.h"
#include "util-validate.h"
#include "util-runmodes.h"
#include "util-random.h"
#include "source-pcap-file.h"
//#define DEBUG
#define STREAMTCP_DEFAULT_PREALLOC 2048
#define STREAMTCP_DEFAULT_MEMCAP (32 * 1024 * 1024) /* 32mb */
#define STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP (64 * 1024 * 1024) /* 64mb */
#define STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED 5
#define STREAMTCP_NEW_TIMEOUT 60
#define STREAMTCP_EST_TIMEOUT 3600
#define STREAMTCP_CLOSED_TIMEOUT 120
#define STREAMTCP_EMERG_NEW_TIMEOUT 10
#define STREAMTCP_EMERG_EST_TIMEOUT 300
#define STREAMTCP_EMERG_CLOSED_TIMEOUT 20
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *, TcpSession *, Packet *, PacketQueue *);
void StreamTcpReturnStreamSegments (TcpStream *);
void StreamTcpInitConfig(char);
int StreamTcpGetFlowState(void *);
void StreamTcpSetOSPolicy(TcpStream*, Packet*);
static int StreamTcpValidateTimestamp(TcpSession * , Packet *);
static int StreamTcpHandleTimestamp(TcpSession * , Packet *);
static int StreamTcpValidateRst(TcpSession * , Packet *);
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *, Packet *);
static int StreamTcpStateDispatch(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq,
uint8_t state);
extern int g_detect_disabled;
static PoolThread *ssn_pool = NULL;
static SCMutex ssn_pool_mutex = SCMUTEX_INITIALIZER; /**< init only, protect initializing and growing pool */
#ifdef DEBUG
static uint64_t ssn_pool_cnt = 0; /** counts ssns, protected by ssn_pool_mutex */
#endif
uint64_t StreamTcpReassembleMemuseGlobalCounter(void);
SC_ATOMIC_DECLARE(uint64_t, st_memuse);
void StreamTcpInitMemuse(void)
{
SC_ATOMIC_INIT(st_memuse);
}
void StreamTcpIncrMemuse(uint64_t size)
{
(void) SC_ATOMIC_ADD(st_memuse, size);
SCLogDebug("STREAM %"PRIu64", incr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
void StreamTcpDecrMemuse(uint64_t size)
{
#ifdef DEBUG_VALIDATION
uint64_t presize = SC_ATOMIC_GET(st_memuse);
if (RunmodeIsUnittests()) {
BUG_ON(presize > UINT_MAX);
}
#endif
(void) SC_ATOMIC_SUB(st_memuse, size);
#ifdef DEBUG_VALIDATION
if (RunmodeIsUnittests()) {
uint64_t postsize = SC_ATOMIC_GET(st_memuse);
BUG_ON(postsize > presize);
}
#endif
SCLogDebug("STREAM %"PRIu64", decr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
uint64_t StreamTcpMemuseCounter(void)
{
uint64_t memusecopy = SC_ATOMIC_GET(st_memuse);
return memusecopy;
}
/**
* \brief Check if alloc'ing "size" would mean we're over memcap
*
* \retval 1 if in bounds
* \retval 0 if not in bounds
*/
int StreamTcpCheckMemcap(uint64_t size)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
if (memcapcopy == 0 || size + SC_ATOMIC_GET(st_memuse) <= memcapcopy)
return 1;
return 0;
}
/**
* \brief Update memcap value
*
* \param size new memcap value
*/
int StreamTcpSetMemcap(uint64_t size)
{
if (size == 0 || (uint64_t)SC_ATOMIC_GET(st_memuse) < size) {
SC_ATOMIC_SET(stream_config.memcap, size);
return 1;
}
return 0;
}
/**
* \brief Return memcap value
*
* \param memcap memcap value
*/
uint64_t StreamTcpGetMemcap(void)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
return memcapcopy;
}
void StreamTcpStreamCleanup(TcpStream *stream)
{
if (stream != NULL) {
StreamTcpSackFreeList(stream);
StreamTcpReturnStreamSegments(stream);
StreamingBufferClear(&stream->sb);
}
}
/**
* \brief Session cleanup function. Does not free the ssn.
* \param ssn tcp session
*/
void StreamTcpSessionCleanup(TcpSession *ssn)
{
SCEnter();
TcpStateQueue *q, *q_next;
if (ssn == NULL)
return;
StreamTcpStreamCleanup(&ssn->client);
StreamTcpStreamCleanup(&ssn->server);
q = ssn->queue;
while (q != NULL) {
q_next = q->next;
SCFree(q);
q = q_next;
StreamTcpDecrMemuse((uint64_t)sizeof(TcpStateQueue));
}
ssn->queue = NULL;
ssn->queue_len = 0;
SCReturn;
}
/**
* \brief Function to return the stream back to the pool. It returns the
* segments in the stream to the segment pool.
*
* This function is called when the flow is destroyed, so it should free
* *everything* related to the tcp session. So including the app layer
* data. We are guaranteed to only get here when the flow's use_cnt is 0.
*
* \param ssn Void ptr to the ssn.
*/
void StreamTcpSessionClear(void *ssnptr)
{
SCEnter();
TcpSession *ssn = (TcpSession *)ssnptr;
if (ssn == NULL)
return;
StreamTcpSessionCleanup(ssn);
/* HACK: don't loose track of thread id */
PoolThreadReserved a = ssn->res;
memset(ssn, 0, sizeof(TcpSession));
ssn->res = a;
PoolThreadReturn(ssn_pool, ssn);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
ssn_pool_cnt--;
SCMutexUnlock(&ssn_pool_mutex);
#endif
SCReturn;
}
/**
* \brief Function to return the stream segments back to the pool.
*
* We don't clear out the app layer storage here as that is under protection
* of the "use_cnt" reference counter in the flow. This function is called
* when the use_cnt is always at least 1 (this pkt has incremented the flow
* use_cnt itself), so we don't bother.
*
* \param p Packet used to identify the stream.
*/
void StreamTcpSessionPktFree (Packet *p)
{
SCEnter();
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL)
SCReturn;
StreamTcpReturnStreamSegments(&ssn->client);
StreamTcpReturnStreamSegments(&ssn->server);
SCReturn;
}
/** \brief Stream alloc function for the Pool
* \retval ptr void ptr to TcpSession structure with all vars set to 0/NULL
*/
static void *StreamTcpSessionPoolAlloc(void)
{
void *ptr = NULL;
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpSession)) == 0)
return NULL;
ptr = SCMalloc(sizeof(TcpSession));
if (unlikely(ptr == NULL))
return NULL;
return ptr;
}
static int StreamTcpSessionPoolInit(void *data, void* initdata)
{
memset(data, 0, sizeof(TcpSession));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpSession));
return 1;
}
/** \brief Pool cleanup function
* \param s Void ptr to TcpSession memory */
static void StreamTcpSessionPoolCleanup(void *s)
{
if (s != NULL) {
StreamTcpSessionCleanup(s);
/** \todo not very clean, as the memory is not freed here */
StreamTcpDecrMemuse((uint64_t)sizeof(TcpSession));
}
}
/**
* \brief See if stream engine is dropping invalid packet in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineDropInvalid(void)
{
return ((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
&& (stream_config.flags & STREAMTCP_INIT_FLAG_DROP_INVALID));
}
/* hack: stream random range code expects random values in range of 0-RAND_MAX,
* but we can get both <0 and >RAND_MAX values from RandomGet
*/
static int RandomGetWrap(void)
{
unsigned long r;
do {
r = RandomGet();
} while(r >= ULONG_MAX - (ULONG_MAX % RAND_MAX));
return r % RAND_MAX;
}
/** \brief To initialize the stream global configuration data
*
* \param quiet It tells the mode of operation, if it is TRUE nothing will
* be get printed.
*/
void StreamTcpInitConfig(char quiet)
{
intmax_t value = 0;
uint16_t rdrange = 10;
SCLogDebug("Initializing Stream");
memset(&stream_config, 0, sizeof(stream_config));
SC_ATOMIC_INIT(stream_config.memcap);
SC_ATOMIC_INIT(stream_config.reassembly_memcap);
if ((ConfGetInt("stream.max-sessions", &value)) == 1) {
SCLogWarning(SC_WARN_OPTION_OBSOLETE, "max-sessions is obsolete. "
"Number of concurrent sessions is now only limited by Flow and "
"TCP stream engine memcaps.");
}
if ((ConfGetInt("stream.prealloc-sessions", &value)) == 1) {
stream_config.prealloc_sessions = (uint32_t)value;
} else {
if (RunmodeIsUnittests()) {
stream_config.prealloc_sessions = 128;
} else {
stream_config.prealloc_sessions = STREAMTCP_DEFAULT_PREALLOC;
if (ConfGetNode("stream.prealloc-sessions") != NULL) {
WarnInvalidConfEntry("stream.prealloc_sessions",
"%"PRIu32,
stream_config.prealloc_sessions);
}
}
}
if (!quiet) {
SCLogConfig("stream \"prealloc-sessions\": %"PRIu32" (per thread)",
stream_config.prealloc_sessions);
}
const char *temp_stream_memcap_str;
if (ConfGetValue("stream.memcap", &temp_stream_memcap_str) == 1) {
uint64_t stream_memcap_copy;
if (ParseSizeStringU64(temp_stream_memcap_str, &stream_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing stream.memcap "
"from conf file - %s. Killing engine",
temp_stream_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.memcap, stream_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.memcap, STREAMTCP_DEFAULT_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream \"memcap\": %"PRIu64, SC_ATOMIC_GET(stream_config.memcap));
}
ConfGetBool("stream.midstream", &stream_config.midstream);
if (!quiet) {
SCLogConfig("stream \"midstream\" session pickups: %s", stream_config.midstream ? "enabled" : "disabled");
}
ConfGetBool("stream.async-oneside", &stream_config.async_oneside);
if (!quiet) {
SCLogConfig("stream \"async-oneside\": %s", stream_config.async_oneside ? "enabled" : "disabled");
}
int csum = 0;
if ((ConfGetBool("stream.checksum-validation", &csum)) == 1) {
if (csum == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
/* Default is that we validate the checksum of all the packets */
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
if (!quiet) {
SCLogConfig("stream \"checksum-validation\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION ?
"enabled" : "disabled");
}
const char *temp_stream_inline_str;
if (ConfGetValue("stream.inline", &temp_stream_inline_str) == 1) {
int inl = 0;
/* checking for "auto" and falling back to boolean to provide
* backward compatibility */
if (strcmp(temp_stream_inline_str, "auto") == 0) {
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
} else if (ConfGetBool("stream.inline", &inl) == 1) {
if (inl) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
} else {
/* default to 'auto' */
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
if (!quiet) {
SCLogConfig("stream.\"inline\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_INLINE
? "enabled" : "disabled");
}
int bypass = 0;
if ((ConfGetBool("stream.bypass", &bypass)) == 1) {
if (bypass == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_BYPASS;
}
}
if (!quiet) {
SCLogConfig("stream \"bypass\": %s",
(stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS)
? "enabled" : "disabled");
}
int drop_invalid = 0;
if ((ConfGetBool("stream.drop-invalid", &drop_invalid)) == 1) {
if (drop_invalid == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
if ((ConfGetInt("stream.max-synack-queued", &value)) == 1) {
if (value >= 0 && value <= 255) {
stream_config.max_synack_queued = (uint8_t)value;
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
if (!quiet) {
SCLogConfig("stream \"max-synack-queued\": %"PRIu8, stream_config.max_synack_queued);
}
const char *temp_stream_reassembly_memcap_str;
if (ConfGetValue("stream.reassembly.memcap", &temp_stream_reassembly_memcap_str) == 1) {
uint64_t stream_reassembly_memcap_copy;
if (ParseSizeStringU64(temp_stream_reassembly_memcap_str,
&stream_reassembly_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.memcap "
"from conf file - %s. Killing engine",
temp_stream_reassembly_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap, stream_reassembly_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap , STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"memcap\": %"PRIu64"",
SC_ATOMIC_GET(stream_config.reassembly_memcap));
}
const char *temp_stream_reassembly_depth_str;
if (ConfGetValue("stream.reassembly.depth", &temp_stream_reassembly_depth_str) == 1) {
if (ParseSizeStringU32(temp_stream_reassembly_depth_str,
&stream_config.reassembly_depth) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.depth "
"from conf file - %s. Killing engine",
temp_stream_reassembly_depth_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_depth = 0;
}
if (!quiet) {
SCLogConfig("stream.reassembly \"depth\": %"PRIu32"", stream_config.reassembly_depth);
}
int randomize = 0;
if ((ConfGetBool("stream.reassembly.randomize-chunk-size", &randomize)) == 0) {
/* randomize by default if value not set
* In ut mode we disable, to get predictible test results */
if (!(RunmodeIsUnittests()))
randomize = 1;
}
if (randomize) {
const char *temp_rdrange;
if (ConfGetValue("stream.reassembly.randomize-chunk-range",
&temp_rdrange) == 1) {
if (ParseSizeStringU16(temp_rdrange, &rdrange) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.randomize-chunk-range "
"from conf file - %s. Killing engine",
temp_rdrange);
exit(EXIT_FAILURE);
} else if (rdrange >= 100) {
SCLogError(SC_ERR_INVALID_VALUE,
"stream.reassembly.randomize-chunk-range "
"must be lower than 100");
exit(EXIT_FAILURE);
}
}
}
const char *temp_stream_reassembly_toserver_chunk_size_str;
if (ConfGetValue("stream.reassembly.toserver-chunk-size",
&temp_stream_reassembly_toserver_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toserver_chunk_size_str,
&stream_config.reassembly_toserver_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toserver-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toserver_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toserver_chunk_size =
STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toserver_chunk_size +=
(int) (stream_config.reassembly_toserver_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
const char *temp_stream_reassembly_toclient_chunk_size_str;
if (ConfGetValue("stream.reassembly.toclient-chunk-size",
&temp_stream_reassembly_toclient_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toclient_chunk_size_str,
&stream_config.reassembly_toclient_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toclient-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toclient_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toclient_chunk_size =
STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toclient_chunk_size +=
(int) (stream_config.reassembly_toclient_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"toserver-chunk-size\": %"PRIu16,
stream_config.reassembly_toserver_chunk_size);
SCLogConfig("stream.reassembly \"toclient-chunk-size\": %"PRIu16,
stream_config.reassembly_toclient_chunk_size);
}
int enable_raw = 1;
if (ConfGetBool("stream.reassembly.raw", &enable_raw) == 1) {
if (!enable_raw) {
stream_config.stream_init_flags = STREAMTCP_STREAM_FLAG_DISABLE_RAW;
}
} else {
enable_raw = 1;
}
if (!quiet)
SCLogConfig("stream.reassembly.raw: %s", enable_raw ? "enabled" : "disabled");
/* init the memcap/use tracking */
StreamTcpInitMemuse();
StatsRegisterGlobalCounter("tcp.memuse", StreamTcpMemuseCounter);
StreamTcpReassembleInit(quiet);
/* set the default free function and flow state function
* values. */
FlowSetProtoFreeFunc(IPPROTO_TCP, StreamTcpSessionClear);
#ifdef UNITTESTS
if (RunmodeIsUnittests()) {
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
}
SCMutexUnlock(&ssn_pool_mutex);
}
#endif
}
void StreamTcpFreeConfig(char quiet)
{
SC_ATOMIC_DESTROY(stream_config.memcap);
SC_ATOMIC_DESTROY(stream_config.reassembly_memcap);
StreamTcpReassembleFree(quiet);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool != NULL) {
PoolThreadFree(ssn_pool);
ssn_pool = NULL;
}
SCMutexUnlock(&ssn_pool_mutex);
SCMutexDestroy(&ssn_pool_mutex);
SCLogDebug("ssn_pool_cnt %"PRIu64"", ssn_pool_cnt);
}
/** \internal
* \brief The function is used to to fetch a TCP session from the
* ssn_pool, when a TCP SYN is received.
*
* \param p packet starting the new TCP session.
* \param id thread pool id
*
* \retval ssn new TCP session.
*/
static TcpSession *StreamTcpNewSession (Packet *p, int id)
{
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
p->flow->protoctx = PoolThreadGetById(ssn_pool, id);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
if (p->flow->protoctx != NULL)
ssn_pool_cnt++;
SCMutexUnlock(&ssn_pool_mutex);
#endif
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
SCLogDebug("ssn_pool is empty");
return NULL;
}
ssn->state = TCP_NONE;
ssn->reassembly_depth = stream_config.reassembly_depth;
ssn->tcp_packet_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.flags = stream_config.stream_init_flags;
ssn->client.flags = stream_config.stream_init_flags;
StreamingBuffer x = STREAMING_BUFFER_INITIALIZER(&stream_config.sbcnf);
ssn->client.sb = x;
ssn->server.sb = x;
if (PKT_IS_TOSERVER(p)) {
ssn->client.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.tcp_flags = 0;
} else if (PKT_IS_TOCLIENT(p)) {
ssn->server.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->client.tcp_flags = 0;
}
}
return ssn;
}
static void StreamTcpPacketSetState(Packet *p, TcpSession *ssn,
uint8_t state)
{
if (state == ssn->state || PKT_IS_PSEUDOPKT(p))
return;
ssn->pstate = ssn->state;
ssn->state = state;
/* update the flow state */
switch(ssn->state) {
case TCP_ESTABLISHED:
case TCP_FIN_WAIT1:
case TCP_FIN_WAIT2:
case TCP_CLOSING:
case TCP_CLOSE_WAIT:
FlowUpdateState(p->flow, FLOW_STATE_ESTABLISHED);
break;
case TCP_LAST_ACK:
case TCP_TIME_WAIT:
case TCP_CLOSED:
FlowUpdateState(p->flow, FLOW_STATE_CLOSED);
break;
}
}
/**
* \brief Function to set the OS policy for the given stream based on the
* destination of the received packet.
*
* \param stream TcpStream of which os_policy needs to set
* \param p Packet which is used to set the os policy
*/
void StreamTcpSetOSPolicy(TcpStream *stream, Packet *p)
{
int ret = 0;
if (PKT_IS_IPV4(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv4HostOSFlavour((uint8_t *)GET_IPV4_DST_ADDR_PTR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
} else if (PKT_IS_IPV6(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv6HostOSFlavour((uint8_t *)GET_IPV6_DST_ADDR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
}
if (stream->os_policy == OS_POLICY_BSD_RIGHT)
stream->os_policy = OS_POLICY_BSD;
else if (stream->os_policy == OS_POLICY_OLD_SOLARIS)
stream->os_policy = OS_POLICY_SOLARIS;
SCLogDebug("Policy is %"PRIu8"", stream->os_policy);
}
/**
* \brief macro to update last_ack only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param ack ACK value to test and set
*/
#define StreamTcpUpdateLastAck(ssn, stream, ack) { \
if (SEQ_GT((ack), (stream)->last_ack)) \
{ \
SCLogDebug("ssn %p: last_ack set to %"PRIu32", moved %u forward", (ssn), (ack), (ack) - (stream)->last_ack); \
if ((SEQ_LEQ((stream)->last_ack, (stream)->next_seq) && SEQ_GT((ack),(stream)->next_seq))) { \
SCLogDebug("last_ack just passed next_seq: %u (was %u) > %u", (ack), (stream)->last_ack, (stream)->next_seq); \
} else { \
SCLogDebug("next_seq (%u) <> last_ack now %d", (stream)->next_seq, (int)(stream)->next_seq - (ack)); \
}\
(stream)->last_ack = (ack); \
StreamTcpSackPruneList((stream)); \
} else { \
SCLogDebug("ssn %p: no update: ack %u, last_ack %"PRIu32", next_seq %u (state %u)", \
(ssn), (ack), (stream)->last_ack, (stream)->next_seq, (ssn)->state); \
}\
}
#define StreamTcpAsyncLastAckUpdate(ssn, stream) { \
if ((ssn)->flags & STREAMTCP_FLAG_ASYNC) { \
if (SEQ_GT((stream)->next_seq, (stream)->last_ack)) { \
uint32_t ack_diff = (stream)->next_seq - (stream)->last_ack; \
(stream)->last_ack += ack_diff; \
SCLogDebug("ssn %p: ASYNC last_ack set to %"PRIu32", moved %u forward", \
(ssn), (stream)->next_seq, ack_diff); \
} \
} \
}
#define StreamTcpUpdateNextSeq(ssn, stream, seq) { \
(stream)->next_seq = seq; \
SCLogDebug("ssn %p: next_seq %" PRIu32, (ssn), (stream)->next_seq); \
StreamTcpAsyncLastAckUpdate((ssn), (stream)); \
}
/**
* \brief macro to update next_win only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param win window value to test and set
*/
#define StreamTcpUpdateNextWin(ssn, stream, win) { \
uint32_t sacked_size__ = StreamTcpSackedSize((stream)); \
if (SEQ_GT(((win) + sacked_size__), (stream)->next_win)) { \
(stream)->next_win = ((win) + sacked_size__); \
SCLogDebug("ssn %p: next_win set to %"PRIu32, (ssn), (stream)->next_win); \
} \
}
static int StreamTcpPacketIsRetransmission(TcpStream *stream, Packet *p)
{
if (p->payload_len == 0)
SCReturnInt(0);
/* retransmission of already partially ack'd data */
if (SEQ_LT(TCP_GET_SEQ(p), stream->last_ack) && SEQ_GT((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack))
{
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of already ack'd data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of in flight data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->next_seq)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(2);
}
SCLogDebug("seq %u payload_len %u => %u, last_ack %u, next_seq %u", TCP_GET_SEQ(p),
p->payload_len, (TCP_GET_SEQ(p) + p->payload_len), stream->last_ack, stream->next_seq);
SCReturnInt(0);
}
/**
* \internal
* \brief Function to handle the TCP_CLOSED or NONE state. The function handles
* packets while the session state is None which means a newly
* initialized structure, or a fully closed session.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateNone(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (p->tcph->th_flags & TH_RST) {
StreamTcpSetEvent(p, STREAM_RST_BUT_NO_SESSION);
SCLogDebug("RST packet received, no session setup");
return -1;
} else if (p->tcph->th_flags & TH_FIN) {
StreamTcpSetEvent(p, STREAM_FIN_BUT_NO_SESSION);
SCLogDebug("FIN packet received, no session setup");
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if (stream_config.midstream == FALSE &&
stream_config.async_oneside == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
StatsIncr(tv, stt->counter_tcp_midstream_pickups);
}
/* reverse packet and flow */
SCLogDebug("reversing flow and packet");
PacketSwap(p);
FlowSwap(p->flow);
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_SYN_RECV", ssn);
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM;
/* Flag used to change the direct in the later stage in the session */
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_SYNACK;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* sequence number & window */
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: server window %u", ssn, ssn->server.window);
ssn->client.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->client.last_ack = TCP_GET_ACK(p);
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
/** If the client has a wscale option the server had it too,
* so set the wscale for the server to max. Otherwise none
* will have the wscale opt just like it should. */
if (TCP_HAS_WSCALE(p)) {
ssn->client.wscale = TCP_GET_WSCALE(p);
ssn->server.wscale = TCP_WSCALE_MAX;
SCLogDebug("ssn %p: wscale enabled. client %u server %u",
ssn, ssn->client.wscale, ssn->server.wscale);
}
SCLogDebug("ssn %p: ssn->client.isn %"PRIu32", ssn->client.next_seq"
" %"PRIu32", ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
SCLogDebug("ssn %p: ssn->server.isn %"PRIu32", ssn->server.next_seq"
" %"PRIu32", ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
ssn->client.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SYN/ACK with SACK permitted, assuming "
"SACK permitted for both sides", ssn);
}
return 0;
} else if (p->tcph->th_flags & TH_SYN) {
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_SENT);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_SENT", ssn);
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
/* Set the stream timestamp value, if packet has timestamp option
* enabled. */
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->client.last_ts);
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
SCLogDebug("ssn %p: SACK permitted on SYN packet", ssn);
}
if (TCP_HAS_TFO(p)) {
ssn->flags |= STREAMTCP_FLAG_TCP_FAST_OPEN;
if (p->payload_len) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
SCLogDebug("ssn: %p (TFO) [len: %d] isn %u base_seq %u next_seq %u payload len %u",
ssn, p->tcpvars.tfo.len, ssn->client.isn, ssn->client.base_seq, ssn->client.next_seq, p->payload_len);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
}
}
SCLogDebug("ssn %p: ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", ssn->client.last_ack "
"%"PRIu32"", ssn, ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
} else if (p->tcph->th_flags & TH_ACK) {
if (stream_config.midstream == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
StatsIncr(tv, stt->counter_tcp_midstream_pickups);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_ESTABLISHED", ssn);
ssn->flags = STREAMTCP_FLAG_MIDSTREAM;
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/** window scaling for midstream pickups, we can't do much other
* than assume that it's set to the max value: 14 */
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->server.wscale = TCP_WSCALE_MAX;
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->client.isn %u, ssn->client.next_seq %u",
ssn, ssn->client.isn, ssn->client.next_seq);
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: ssn->client.next_win %"PRIu32", "
"ssn->server.next_win %"PRIu32"", ssn,
ssn->client.next_win, ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.last_ack %"PRIu32", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->client.last_ack, ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
ssn->server.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: assuming SACK permitted for both sides", ssn);
} else {
SCLogDebug("default case");
}
return 0;
}
/** \internal
* \brief Setup TcpStateQueue based on SYN/ACK packet
*/
static inline void StreamTcp3whsSynAckToStateQueue(Packet *p, TcpStateQueue *q)
{
q->flags = 0;
q->wscale = 0;
q->ts = 0;
q->win = TCP_GET_WINDOW(p);
q->seq = TCP_GET_SEQ(p);
q->ack = TCP_GET_ACK(p);
q->pkt_ts = p->ts.tv_sec;
if (TCP_GET_SACKOK(p) == 1)
q->flags |= STREAMTCP_QUEUE_FLAG_SACK;
if (TCP_HAS_WSCALE(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_WS;
q->wscale = TCP_GET_WSCALE(p);
}
if (TCP_HAS_TS(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_TS;
q->ts = TCP_GET_TSVAL(p);
}
}
/** \internal
* \brief Find the Queued SYN/ACK that is the same as this SYN/ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckBySynAck(TcpSession *ssn, Packet *p)
{
TcpStateQueue *q = ssn->queue;
TcpStateQueue search;
StreamTcp3whsSynAckToStateQueue(p, &search);
while (q != NULL) {
if (search.flags == q->flags &&
search.wscale == q->wscale &&
search.win == q->win &&
search.seq == q->seq &&
search.ack == q->ack &&
search.ts == q->ts) {
return q;
}
q = q->next;
}
return q;
}
static int StreamTcp3whsQueueSynAck(TcpSession *ssn, Packet *p)
{
/* first see if this is already in our list */
if (StreamTcp3whsFindSynAckBySynAck(ssn, p) != NULL)
return 0;
if (ssn->queue_len == stream_config.max_synack_queued) {
SCLogDebug("ssn %p: =~ SYN/ACK queue limit reached", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_FLOOD);
return -1;
}
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpStateQueue)) == 0) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: stream memcap reached", ssn);
return -1;
}
TcpStateQueue *q = SCMalloc(sizeof(*q));
if (unlikely(q == NULL)) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: alloc failed", ssn);
return -1;
}
memset(q, 0x00, sizeof(*q));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpStateQueue));
StreamTcp3whsSynAckToStateQueue(p, q);
/* put in list */
q->next = ssn->queue;
ssn->queue = q;
ssn->queue_len++;
return 0;
}
/** \internal
* \brief Find the Queued SYN/ACK that goes with this ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckByAck(TcpSession *ssn, Packet *p)
{
uint32_t ack = TCP_GET_SEQ(p);
uint32_t seq = TCP_GET_ACK(p) - 1;
TcpStateQueue *q = ssn->queue;
while (q != NULL) {
if (seq == q->seq &&
ack == q->ack) {
return q;
}
q = q->next;
}
return NULL;
}
/** \internal
* \brief Update SSN after receiving a valid SYN/ACK
*
* Normally we update the SSN from the SYN/ACK packet. But in case
* of queued SYN/ACKs, we can use one of those.
*
* \param ssn TCP session
* \param p Packet
* \param q queued state if used, NULL otherwise
*
* To make sure all SYN/ACK based state updates are in one place,
* this function can updated based on Packet or TcpStateQueue, where
* the latter takes precedence.
*/
static void StreamTcp3whsSynAckUpdate(TcpSession *ssn, Packet *p, TcpStateQueue *q)
{
TcpStateQueue update;
if (likely(q == NULL)) {
StreamTcp3whsSynAckToStateQueue(p, &update);
q = &update;
}
if (ssn->state != TCP_SYN_RECV) {
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_RECV", ssn);
}
/* sequence number & window */
ssn->server.isn = q->seq;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->client.window = q->win;
SCLogDebug("ssn %p: window %" PRIu32 "", ssn, ssn->server.window);
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if ((q->flags & STREAMTCP_QUEUE_FLAG_TS) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->server.last_ts = q->ts;
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = q->pkt_ts;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->client.last_ts = 0;
ssn->server.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->client.last_ack = q->ack;
ssn->server.last_ack = ssn->server.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(q->flags & STREAMTCP_QUEUE_FLAG_WS))
{
ssn->client.wscale = q->wscale;
} else {
ssn->client.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
(q->flags & STREAMTCP_QUEUE_FLAG_SACK)) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for session", ssn);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SACKOK;
}
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %" PRIu32 " "
"(ssn->client.last_ack %" PRIu32 ")", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack, ssn->client.last_ack);
/* unset the 4WHS flag as we received this SYN/ACK as part of a
* (so far) valid 3WHS */
if (ssn->flags & STREAMTCP_FLAG_4WHS)
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS unset, normal SYN/ACK"
" so considering 3WHS", ssn);
ssn->flags &=~ STREAMTCP_FLAG_4WHS;
}
/** \internal
* \brief detect timestamp anomalies when processing responses to the
* SYN packet.
* \retval true packet is ok
* \retval false packet is bad
*/
static inline bool StateSynSentValidateTimestamp(TcpSession *ssn, Packet *p)
{
/* we only care about evil server here, so skip TS packets */
if (PKT_IS_TOSERVER(p) || !(TCP_HAS_TS(p))) {
return true;
}
TcpStream *receiver_stream = &ssn->client;
uint32_t ts_echo = TCP_GET_TSECR(p);
if ((receiver_stream->flags & STREAMTCP_STREAM_FLAG_TIMESTAMP) != 0) {
if (receiver_stream->last_ts != 0 && ts_echo != 0 &&
ts_echo != receiver_stream->last_ts)
{
SCLogDebug("ssn %p: BAD TSECR echo %u recv %u", ssn,
ts_echo, receiver_stream->last_ts);
return false;
}
} else {
if (receiver_stream->last_ts == 0 && ts_echo != 0) {
SCLogDebug("ssn %p: BAD TSECR echo %u recv %u", ssn,
ts_echo, receiver_stream->last_ts);
return false;
}
}
return true;
}
/**
* \brief Function to handle the TCP_SYN_SENT state. The function handles
* SYN, SYN/ACK, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateSynSent(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
SCLogDebug("ssn %p: pkt received: %s", ssn, PKT_IS_TOCLIENT(p) ?
"toclient":"toserver");
/* check for bad responses */
if (StateSynSentValidateTimestamp(ssn, p) == false)
return -1;
/* RST */
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn) &&
SEQ_EQ(TCP_GET_WINDOW(p), 0) &&
SEQ_EQ(TCP_GET_ACK(p), (ssn->client.isn + 1)))
{
SCLogDebug("ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
SCLogDebug("ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
/* FIN */
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK received on 4WHS session", ssn);
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->server.isn + 1))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: 4WHS ACK mismatch, packet ACK %"PRIu32""
" != %" PRIu32 " from stream", ssn,
TCP_GET_ACK(p), ssn->server.isn + 1);
return -1;
}
/* Check if the SYN/ACK packet SEQ's the *FIRST* received SYN
* packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_SYN);
SCLogDebug("ssn %p: 4WHS SEQ mismatch, packet SEQ %"PRIu32""
" != %" PRIu32 " from *first* SYN pkt", ssn,
TCP_GET_SEQ(p), ssn->client.isn);
return -1;
}
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ 4WHS ssn state is now TCP_SYN_RECV", ssn);
/* sequence number & window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: 4WHS window %" PRIu32 "", ssn,
ssn->client.window);
/* Set the timestamp values used to validate the timestamp of
* received packets. */
if ((TCP_HAS_TS(p)) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: 4WHS ssn->client.last_ts %" PRIu32" "
"ssn->server.last_ts %" PRIu32"", ssn,
ssn->client.last_ts, ssn->server.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
ssn->server.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->client.last_ack = ssn->client.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(TCP_HAS_WSCALE(p)))
{
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->server.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for 4WHS session", ssn);
}
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
SCLogDebug("ssn %p: 4WHS ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: 4WHS ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %" PRIu32 " "
"(ssn->server.last_ack %" PRIu32 ")", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack, ssn->server.last_ack);
/* done here */
return 0;
}
if (PKT_IS_TOSERVER(p)) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_IN_WRONG_DIRECTION);
SCLogDebug("ssn %p: SYN/ACK received in the wrong direction", ssn);
return -1;
}
if (!(TCP_HAS_TFO(p) || (ssn->flags & STREAMTCP_FLAG_TCP_FAST_OPEN))) {
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.isn + 1))) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
return -1;
}
} else {
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.next_seq))) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: (TFO) ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.next_seq);
return -1;
}
SCLogDebug("ssn %p: (TFO) ACK match, packet ACK %" PRIu32 " == "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.next_seq);
ssn->flags |= STREAMTCP_FLAG_TCP_FAST_OPEN;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
}
StreamTcp3whsSynAckUpdate(ssn, p, /* no queue override */NULL);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent", ssn);
if (ssn->flags & STREAMTCP_FLAG_4WHS) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent of "
"4WHS SYN", ssn);
}
if (PKT_IS_TOCLIENT(p)) {
/** a SYN only packet in the opposite direction could be:
* http://www.breakingpointsystems.com/community/blog/tcp-
* portals-the-three-way-handshake-is-a-lie
*
* \todo improve resetting the session */
/* indicate that we're dealing with 4WHS here */
ssn->flags |= STREAMTCP_FLAG_4WHS;
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS flag set", ssn);
/* set the sequence numbers and window for server
* We leave the ssn->client.isn in place as we will
* check the SYN/ACK pkt with that.
*/
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
/* Set the stream timestamp value, if packet has timestamp
* option enabled. */
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->server.last_ts);
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
} else {
ssn->flags &= ~STREAMTCP_FLAG_CLIENT_SACKOK;
}
SCLogDebug("ssn %p: 4WHS ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
}
/** \todo check if it's correct or set event */
} else if (p->tcph->th_flags & TH_ACK) {
/* Handle the asynchronous stream, when we receive a SYN packet
and now istead of receving a SYN/ACK we receive a ACK from the
same host, which sent the SYN, this suggests the ASNYC streams.*/
if (stream_config.async_oneside == FALSE)
return 0;
/* we are in AYNC (one side) mode now. */
/* one side async means we won't see a SYN/ACK, so we can
* only check the SYN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))) {
StreamTcpSetEvent(p, STREAM_3WHS_ASYNC_WRONG_SEQ);
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream",ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
return -1;
}
ssn->flags |= STREAMTCP_FLAG_ASYNC;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
ssn->client.window = TCP_GET_WINDOW(p);
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
/* Set the server side parameters */
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = ssn->server.next_seq;
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: synsent => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.next_seq %" PRIu32 ""
,ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->client.next_seq);
/* if SYN had wscale, assume it to be supported. Otherwise
* we know it not to be supported. */
if (ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) {
ssn->client.wscale = TCP_WSCALE_MAX;
}
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if (TCP_HAS_TS(p) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
} else {
ssn->client.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
if (ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_SYN_RECV state. The function handles
* SYN, SYN/ACK, ACK, FIN, RST packets and correspondingly changes
* the connection state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateSynRecv(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
uint8_t reset = TRUE;
/* After receiveing the RST in SYN_RECV state and if detection
evasion flags has been set, then the following operating
systems will not closed the connection. As they consider the
packet as stray packet and not belonging to the current
session, for more information check
http://www.packetstan.com/2010/06/recently-ive-been-on-campaign-to-make.html */
if (ssn->flags & STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT) {
if (PKT_IS_TOSERVER(p)) {
if ((ssn->server.os_policy == OS_POLICY_LINUX) ||
(ssn->server.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->server.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
} else {
if ((ssn->client.os_policy == OS_POLICY_LINUX) ||
(ssn->client.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->client.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
}
}
if (reset == TRUE) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
}
} else if (p->tcph->th_flags & TH_FIN) {
/* FIN is handled in the same way as in TCP_ESTABLISHED case */;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state SYN_RECV. resent", ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_TOSERVER_ON_SYN_RECV);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN/ACK packet, server resend with different ISN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.isn);
if (StreamTcp3whsQueueSynAck(ssn, p) == -1)
return -1;
SCLogDebug("ssn %p: queued different SYN/ACK", ssn);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_RECV... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_TOCLIENT_ON_SYN_RECV);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_RESEND_DIFF_SEQ_ON_SYN_RECV);
return -1;
}
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->queue_len) {
SCLogDebug("ssn %p: checking ACK against queued SYN/ACKs", ssn);
TcpStateQueue *q = StreamTcp3whsFindSynAckByAck(ssn, p);
if (q != NULL) {
SCLogDebug("ssn %p: here we update state against queued SYN/ACK", ssn);
StreamTcp3whsSynAckUpdate(ssn, p, /* using queue to update state */q);
} else {
SCLogDebug("ssn %p: none found, now checking ACK against original SYN/ACK (state)", ssn);
}
}
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323)*/
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!(StreamTcpValidateTimestamp(ssn, p))) {
return -1;
}
}
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: ACK received on 4WHS session",ssn);
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))) {
SCLogDebug("ssn %p: 4WHS wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: 4WHS invalid ack nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_INVALID_ACK);
return -1;
}
SCLogDebug("4WHS normal pkt");
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.next_win, ssn->client.last_ack);
return 0;
}
bool ack_indicates_missed_3whs_ack_packet = false;
/* Check if the ACK received is in right direction. But when we have
* picked up a mid stream session after missing the initial SYN pkt,
* in this case the ACK packet can arrive from either client (normal
* case) or from server itself (asynchronous streams). Therefore
* the check has been avoided in this case */
if (PKT_IS_TOCLIENT(p)) {
/* special case, handle 4WHS, so SYN/ACK in the opposite
* direction */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK) {
SCLogDebug("ssn %p: ACK received on midstream SYN/ACK "
"pickup session",ssn);
/* fall through */
} else if (ssn->flags & STREAMTCP_FLAG_TCP_FAST_OPEN) {
SCLogDebug("ssn %p: ACK received on TFO session",ssn);
/* fall through */
} else {
/* if we missed traffic between the S/SA and the current
* 'wrong direction' ACK, we could end up here. In IPS
* reject it. But in IDS mode we continue.
*
* IPS rejects as it should see all packets, so pktloss
* should lead to retransmissions. As this can also be
* pattern for MOTS/MITM injection attacks, we need to be
* careful.
*/
if (StreamTcpInlineMode()) {
if (p->payload_len > 0 &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) &&
SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
/* packet loss is possible but unlikely here */
SCLogDebug("ssn %p: possible data injection", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_DATA_INJECT);
return -1;
}
SCLogDebug("ssn %p: ACK received in the wrong direction",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_IN_WRONG_DIR);
return -1;
}
ack_indicates_missed_3whs_ack_packet = true;
}
}
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ""
", ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
/* Check both seq and ack number before accepting the packet and
changing to ESTABLISHED state */
if ((SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq)) {
SCLogDebug("normal pkt");
/* process the packet normal, No Async streams :) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
if (!(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)) {
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* If asynchronous stream handling is allowed then set the session,
if packet's seq number is equal the expected seq no.*/
} else if (stream_config.async_oneside == TRUE &&
(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)))
{
/*set the ASYNC flag used to indicate the session as async stream
and helps in relaxing the windows checks.*/
ssn->flags |= STREAMTCP_FLAG_ASYNC;
ssn->server.next_seq += p->payload_len;
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_ACK(p);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->server.window = TCP_GET_WINDOW(p);
ssn->client.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
SCLogDebug("ssn %p: synrecv => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->server.next_seq %" PRIu32 "\n"
, ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->server.next_seq);
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
/* Upon receiving the packet with correct seq number and wrong
ACK number, it causes the other end to send RST. But some target
system (Linux & solaris) does not RST the connection, so it is
likely to avoid the detection */
} else if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)){
ssn->flags |= STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT;
SCLogDebug("ssn %p: wrong ack nr on packet, possible evasion!!",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_RIGHT_SEQ_WRONG_ACK_EVASION);
return -1;
/* if we get a packet with a proper ack, but a seq that is beyond
* next_seq but in-window, we probably missed some packets */
} else if (SEQ_GT(TCP_GET_SEQ(p), ssn->client.next_seq) &&
SEQ_LEQ(TCP_GET_SEQ(p),ssn->client.next_win) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq))
{
SCLogDebug("ssn %p: ACK for missing data", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ACK for missing data: ssn->client.next_seq %u", ssn, ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p);
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* toclient packet: after having missed the 3whs's final ACK */
} else if ((ack_indicates_missed_3whs_ack_packet ||
(ssn->flags & STREAMTCP_FLAG_TCP_FAST_OPEN)) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) &&
SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
{
if (ack_indicates_missed_3whs_ack_packet) {
SCLogDebug("ssn %p: packet fits perfectly after a missed 3whs-ACK", ssn);
} else {
SCLogDebug("ssn %p: (TFO) expected packet fits perfectly after SYN/ACK", ssn);
}
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_WRONG_SEQ_WRONG_ACK);
return -1;
}
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.next_win, ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the client to server. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly.
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToServer(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
"ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &(ssn->server), p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->client.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->client.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: server => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
"%" PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* update the last_ack to current seq number as the session is
* async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ."
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
} else if (SEQ_EQ(ssn->client.last_ack, (ssn->client.isn + 1)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :(*/
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->client.last_ack, ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->client.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->client.last_ack, ssn->client.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: server => SEQ before last_ack, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
SCLogDebug("ssn %p: rejecting because pkt before last_ack", ssn);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->client.next_seq && ssn->client.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->client.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (started before next_seq, ended after)",
ssn, ssn->client.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->client.next_seq, ssn->client.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->client.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->client.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->client.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->client.last_ack);
}
/* in window check */
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
SCLogDebug("ssn %p: ssn->server.window %"PRIu32"", ssn,
ssn->server.window);
/* Check if the ACK value is sane and inside the window limit */
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
SCLogDebug("ack %u last_ack %u next_seq %u", TCP_GET_ACK(p), ssn->server.last_ack, ssn->server.next_seq);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
/* handle data (if any) */
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: toserver => SEQ out of window, packet SEQ "
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
(TCP_GET_SEQ(p) + p->payload_len) - ssn->client.next_win);
SCLogDebug("ssn %p: window %u sacked %u", ssn, ssn->client.window,
StreamTcpSackedSize(&ssn->client));
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the server to client. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToClient(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ","
" ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* To get the server window value from the servers packet, when connection
is picked up as midstream */
if ((ssn->flags & STREAMTCP_FLAG_MIDSTREAM) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED))
{
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->flags &= ~STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
SCLogDebug("ssn %p: adjusted midstream ssn->server.next_win to "
"%" PRIu32 "", ssn, ssn->server.next_win);
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->server.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->server.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: client => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
" %"PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
ssn->server.last_ack = TCP_GET_SEQ(p);
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->server.last_ack, ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->server.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32". next_seq %"PRIu32,
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->server.next_seq && ssn->server.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->server.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32
" (started before next_seq, ended after)",
ssn, ssn->server.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->server.next_seq, ssn->server.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->server.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->server.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->server.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->server.last_ack);
}
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
SCLogDebug("ssn %p: ssn->client.window %"PRIu32"", ssn,
ssn->client.window);
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->client, p);
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: client => SEQ out of window, packet SEQ"
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->server.last_ack %" PRIu32 ", ssn->server.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \internal
*
* \brief Find the highest sequence number needed to consider all segments as ACK'd
*
* Used to treat all segments as ACK'd upon receiving a valid RST.
*
* \param stream stream to inspect the segments from
* \param seq sequence number to check against
*
* \retval ack highest ack we need to set
*/
static inline uint32_t StreamTcpResetGetMaxAck(TcpStream *stream, uint32_t seq)
{
uint32_t ack = seq;
if (STREAM_HAS_SEEN_DATA(stream)) {
const uint32_t tail_seq = STREAM_SEQ_RIGHT_EDGE(stream);
if (SEQ_GT(tail_seq, ack)) {
ack = tail_seq;
}
}
SCReturnUInt(ack);
}
/**
* \brief Function to handle the TCP_ESTABLISHED state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state. The function handles the data inside packets and call
* StreamTcpReassembleHandleSegment(tv, ) to handle the reassembling.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateEstablished(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_ACK(p);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len + 1;
ssn->client.next_seq = TCP_GET_ACK(p);
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
SCLogDebug("ssn (%p: FIN received SEQ"
" %" PRIu32 ", last ACK %" PRIu32 ", next win %"PRIu32","
" win %" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack, ssn->server.next_win,
ssn->server.window);
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent",
ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in ESTABLISHED state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_TOSERVER);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFF_SEQ);
return -1;
}
if (ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED) {
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND);
return -1;
}
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent. "
"Likely due server not receiving final ACK in 3whs", ssn);
return 0;
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state ESTABLISHED... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in EST state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_TOCLIENT);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND_DIFF_SEQ);
return -1;
}
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
/* Urgent pointer size can be more than the payload size, as it tells
* the future coming data from the sender will be handled urgently
* until data of size equal to urgent offset has been processed
* (RFC 2147) */
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
/* Process the received packet to server */
HandleEstablishedPacketToServer(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->client.next_seq, ssn->server.last_ack
,ssn->client.next_win, ssn->client.window);
} else { /* implied to client */
if (!(ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED)) {
ssn->flags |= STREAMTCP_FLAG_3WHS_CONFIRMED;
SCLogDebug("3whs is now confirmed by server");
}
/* Process the received packet to client */
HandleEstablishedPacketToClient(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack,
ssn->server.next_win, ssn->server.window);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the FIN packets for states TCP_SYN_RECV and
* TCP_ESTABLISHED and changes to another TCP state as required.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *stt,
TcpSession *ssn, Packet *p, PacketQueue *pq)
{
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
" ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_CLOSE_WAIT);
SCLogDebug("ssn %p: state changed to TCP_CLOSE_WAIT", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->client.next_seq %" PRIu32 "", ssn,
ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->client.next_seq, ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ", "
"ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream (last_ack %u win %u = %u)", ssn, TCP_GET_SEQ(p),
ssn->server.next_seq, ssn->server.last_ack, ssn->server.window, (ssn->server.last_ack + ssn->server.window));
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT1);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT1", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->server.next_seq, ssn->client.last_ack);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT1 state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpPacketStateFinWait1(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if ((p->tcph->th_flags & (TH_FIN|TH_ACK)) == (TH_FIN|TH_ACK)) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait1", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
if (TCP_GET_SEQ(p) == ssn->client.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
if (TCP_GET_SEQ(p) == ssn->server.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn (%p): default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT2 state. The function handles
* ACK, RST, FIN packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateFinWait2(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait2", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSING state. Upon arrival of ACK
* the connection goes to TCP_TIME_WAIT state. The state has been
* reached as both end application has been closed.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateClosing(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on Closing", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->client.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->server.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("StreamTcpPacketStateClosing (%p): =+ next SEQ "
"%" PRIu32 ", last ACK %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSE_WAIT state. Upon arrival of FIN
* packet from server the connection goes to TCP_LAST_ACK state.
* The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateCloseWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
SCEnter();
if (ssn == NULL) {
SCReturnInt(-1);
}
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
}
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
/* don't update to LAST_ACK here as we want a toclient FIN for that */
if (!retransmission)
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_LAST_ACK);
SCLogDebug("ssn %p: state changed to TCP_LAST_ACK", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on CloseWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
SCReturnInt(-1);
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->client.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->server.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
SCReturnInt(0);
}
/**
* \brief Function to handle the TCP_LAST_ACK state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool. The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateLastAck(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
SCLogDebug("ssn (%p): FIN pkt on LastAck", ssn);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on LastAck", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_LASTACK_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: not updating state as packet is before next_seq", ssn);
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq + 1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_LASTACK_ACK_WRONG_SEQ);
return -1;
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_TIME_WAIT state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateTimeWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on TimeWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq+1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->server.next_seq && TCP_GET_SEQ(p) != ssn->server.next_seq+1) {
if (p->payload_len > 0 && TCP_GET_SEQ(p) == ssn->server.last_ack) {
SCLogDebug("ssn %p: -> retransmission", ssn);
SCReturnInt(0);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
static int StreamTcpPacketStateClosed(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
SCLogDebug("RST on closed state");
return 0;
}
TcpStream *stream = NULL, *ostream = NULL;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
SCLogDebug("stream %s ostream %s",
stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV?"true":"false",
ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV ? "true":"false");
/* if we've seen a RST on our direction, but not on the other
* see if we perhaps need to continue processing anyway. */
if ((stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) == 0) {
if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->pstate) < 0)
return -1;
}
}
return 0;
}
static void StreamTcpPacketCheckPostRst(TcpSession *ssn, Packet *p)
{
if (p->flags & PKT_PSEUDO_STREAM_END) {
return;
}
/* more RSTs are not unusual */
if ((p->tcph->th_flags & (TH_RST)) != 0) {
return;
}
TcpStream *ostream = NULL;
if (PKT_IS_TOSERVER(p)) {
ostream = &ssn->server;
} else {
ostream = &ssn->client;
}
if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {
SCLogDebug("regular packet %"PRIu64" from same sender as "
"the previous RST. Looks like it injected!", p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpSetEvent(p, STREAM_SUSPECTED_RST_INJECT);
return;
}
return;
}
/**
* \retval 1 packet is a keep alive pkt
* \retval 0 packet is not a keep alive pkt
*/
static int StreamTcpPacketIsKeepAlive(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/*
rfc 1122:
An implementation SHOULD send a keep-alive segment with no
data; however, it MAY be configurable to send a keep-alive
segment containing one garbage octet, for compatibility with
erroneous TCP implementations.
*/
if (p->payload_len > 1)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0) {
return 0;
}
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
if (ack == ostream->last_ack && seq == (stream->next_seq - 1)) {
SCLogDebug("packet is TCP keep-alive: %"PRIu64, p->pcap_cnt);
stream->flags |= STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, (stream->next_seq - 1), ack, ostream->last_ack);
return 0;
}
/**
* \retval 1 packet is a keep alive ACK pkt
* \retval 0 packet is not a keep alive ACK pkt
*/
static int StreamTcpPacketIsKeepAliveACK(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/* should get a normal ACK to a Keep Alive */
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win != ostream->window)
return 0;
if ((ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) && ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP keep-aliveACK: %"PRIu64, p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u) FLAG_KEEPALIVE: %s", seq, stream->next_seq, ack, ostream->last_ack,
ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE ? "set" : "not set");
return 0;
}
static void StreamTcpClearKeepAliveFlag(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL;
if (p->flags & PKT_PSEUDO_STREAM_END)
return;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
} else {
stream = &ssn->server;
}
if (stream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) {
stream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
SCLogDebug("FLAG_KEEPALIVE cleared");
}
}
/**
* \retval 1 packet is a window update pkt
* \retval 0 packet is not a window update pkt
*/
static int StreamTcpPacketIsWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED)
return 0;
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win == ostream->window)
return 0;
if (ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP window update: %"PRIu64, p->pcap_cnt);
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/**
* Try to detect whether a packet is a valid FIN 4whs final ack.
*
*/
static int StreamTcpPacketIsFinShutdownAck(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (!(ssn->state == TCP_TIME_WAIT || ssn->state == TCP_CLOSE_WAIT || ssn->state == TCP_LAST_ACK))
return 0;
if (p->tcph->th_flags != TH_ACK)
return 0;
if (p->payload_len != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
SCLogDebug("%"PRIu64", seq %u ack %u stream->next_seq %u ostream->next_seq %u",
p->pcap_cnt, seq, ack, stream->next_seq, ostream->next_seq);
if (SEQ_EQ(stream->next_seq + 1, seq) && SEQ_EQ(ack, ostream->next_seq + 1)) {
return 1;
}
return 0;
}
/**
* Try to detect packets doing bad window updates
*
* See bug 1238.
*
* Find packets that are unexpected, and shrink the window to the point
* where the packets we do expect are rejected for being out of window.
*
* The logic we use here is:
* - packet seq > next_seq
* - packet ack > next_seq (packet acks unseen data)
* - packet shrinks window more than it's own data size
* - packet shrinks window more than the diff between it's ack and the
* last_ack value
*
* Packets coming in after packet loss can look quite a bit like this.
*/
static int StreamTcpPacketIsBadWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED || ssn->state == TCP_CLOSED)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win < ostream->window) {
uint32_t diff = ostream->window - pkt_win;
if (diff > p->payload_len &&
SEQ_GT(ack, ostream->next_seq) &&
SEQ_GT(seq, stream->next_seq))
{
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u, diff %u, dsize %u",
p->pcap_cnt, pkt_win, ostream->window, diff, p->payload_len);
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u",
p->pcap_cnt, pkt_win, ostream->window);
SCLogDebug("%"PRIu64", seq %u ack %u ostream->next_seq %u ostream->last_ack %u, ostream->next_win %u, diff %u (%u)",
p->pcap_cnt, seq, ack, ostream->next_seq, ostream->last_ack, ostream->next_win,
ostream->next_seq - ostream->last_ack, stream->next_seq - stream->last_ack);
/* get the expected window shrinking from looking at ack vs last_ack.
* Observed a lot of just a little overrunning that value. So added some
* margin that is still ok. To make sure this isn't a loophole to still
* close the window, this is limited to windows above 1024. Both values
* are rather arbitrary. */
uint32_t adiff = ack - ostream->last_ack;
if (((pkt_win > 1024) && (diff > (adiff + 32))) ||
((pkt_win <= 1024) && (diff > adiff)))
{
SCLogDebug("pkt ACK %u is %u bytes beyond last_ack %u, shrinks window by %u "
"(allowing 32 bytes extra): pkt WIN %u", ack, adiff, ostream->last_ack, diff, pkt_win);
SCLogDebug("%u - %u = %u (state %u)", diff, adiff, diff - adiff, ssn->state);
StreamTcpSetEvent(p, STREAM_PKT_BAD_WINDOW_UPDATE);
return 1;
}
}
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/** \internal
* \brief call packet handling function for 'state'
* \param state current TCP state
*/
static inline int StreamTcpStateDispatch(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq,
const uint8_t state)
{
SCLogDebug("ssn: %p", ssn);
switch (state) {
case TCP_SYN_SENT:
if (StreamTcpPacketStateSynSent(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_SYN_RECV:
if (StreamTcpPacketStateSynRecv(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_ESTABLISHED:
if (StreamTcpPacketStateEstablished(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_FIN_WAIT1:
SCLogDebug("packet received on TCP_FIN_WAIT1 state");
if (StreamTcpPacketStateFinWait1(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_FIN_WAIT2:
SCLogDebug("packet received on TCP_FIN_WAIT2 state");
if (StreamTcpPacketStateFinWait2(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSING:
SCLogDebug("packet received on TCP_CLOSING state");
if (StreamTcpPacketStateClosing(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSE_WAIT:
SCLogDebug("packet received on TCP_CLOSE_WAIT state");
if (StreamTcpPacketStateCloseWait(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_LAST_ACK:
SCLogDebug("packet received on TCP_LAST_ACK state");
if (StreamTcpPacketStateLastAck(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_TIME_WAIT:
SCLogDebug("packet received on TCP_TIME_WAIT state");
if (StreamTcpPacketStateTimeWait(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSED:
/* TCP session memory is not returned to pool until timeout. */
SCLogDebug("packet received on closed state");
if (StreamTcpPacketStateClosed(tv, p, stt, ssn, pq)) {
return -1;
}
break;
default:
SCLogDebug("packet received on default state");
break;
}
return 0;
}
static inline void HandleThreadId(ThreadVars *tv, Packet *p, StreamTcpThread *stt)
{
const int idx = (!(PKT_IS_TOSERVER(p)));
/* assign the thread id to the flow */
if (unlikely(p->flow->thread_id[idx] == 0)) {
p->flow->thread_id[idx] = (FlowThreadId)tv->id;
} else if (unlikely((FlowThreadId)tv->id != p->flow->thread_id[idx])) {
SCLogDebug("wrong thread: flow has %u, we are %d", p->flow->thread_id[idx], tv->id);
if (p->pkt_src == PKT_SRC_WIRE) {
StatsIncr(tv, stt->counter_tcp_wrong_thread);
if ((p->flow->flags & FLOW_WRONG_THREAD) == 0) {
p->flow->flags |= FLOW_WRONG_THREAD;
StreamTcpSetEvent(p, STREAM_WRONG_THREAD);
}
}
}
}
/* flow is and stays locked */
int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt,
PacketQueue *pq)
{
SCEnter();
DEBUG_ASSERT_FLOW_LOCKED(p->flow);
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
HandleThreadId(tv, p, stt);
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
/* track TCP flags */
if (ssn != NULL) {
ssn->tcp_packet_flags |= p->tcph->th_flags;
if (PKT_IS_TOSERVER(p))
ssn->client.tcp_flags |= p->tcph->th_flags;
else if (PKT_IS_TOCLIENT(p))
ssn->server.tcp_flags |= p->tcph->th_flags;
/* check if we need to unset the ASYNC flag */
if (ssn->flags & STREAMTCP_FLAG_ASYNC &&
ssn->client.tcp_flags != 0 &&
ssn->server.tcp_flags != 0)
{
SCLogDebug("ssn %p: removing ASYNC flag as we have packets on both sides", ssn);
ssn->flags &= ~STREAMTCP_FLAG_ASYNC;
}
}
/* update counters */
if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
StatsIncr(tv, stt->counter_tcp_synack);
} else if (p->tcph->th_flags & (TH_SYN)) {
StatsIncr(tv, stt->counter_tcp_syn);
}
if (p->tcph->th_flags & (TH_RST)) {
StatsIncr(tv, stt->counter_tcp_rst);
}
/* broken TCP http://ask.wireshark.org/questions/3183/acknowledgment-number-broken-tcp-the-acknowledge-field-is-nonzero-while-the-ack-flag-is-not-set */
if (!(p->tcph->th_flags & TH_ACK) && TCP_GET_ACK(p) != 0) {
StreamTcpSetEvent(p, STREAM_PKT_BROKEN_ACK);
goto error;
}
/* If we are on IPS mode, and got a drop action triggered from
* the IP only module, or from a reassembled msg and/or from an
* applayer detection, then drop the rest of the packets of the
* same stream and avoid inspecting it any further */
if (StreamTcpCheckFlowDrops(p) == 1) {
SCLogDebug("This flow/stream triggered a drop rule");
FlowSetNoPacketInspectionFlag(p->flow);
DecodeSetNoPacketInspectionFlag(p);
StreamTcpDisableAppLayer(p->flow);
PACKET_DROP(p);
/* return the segments to the pool */
StreamTcpSessionPktFree(p);
SCReturnInt(0);
}
if (ssn == NULL || ssn->state == TCP_NONE) {
if (StreamTcpPacketStateNone(tv, p, stt, ssn, &stt->pseudo_queue) == -1) {
goto error;
}
if (ssn != NULL)
SCLogDebug("ssn->alproto %"PRIu16"", p->flow->alproto);
} else {
/* special case for PKT_PSEUDO_STREAM_END packets:
* bypass the state handling and various packet checks,
* we care about reassembly here. */
if (p->flags & PKT_PSEUDO_STREAM_END) {
if (PKT_IS_TOCLIENT(p)) {
ssn->client.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
ssn->server.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
}
/* straight to 'skip' as we already handled reassembly */
goto skip;
}
if (p->flow->flags & FLOW_WRONG_THREAD ||
ssn->client.flags & STREAMTCP_STREAM_FLAG_GAP ||
ssn->server.flags & STREAMTCP_STREAM_FLAG_GAP)
{
/* Stream and/or session in known bad condition. Block events
* from being set. */
p->flags |= PKT_STREAM_NO_EVENTS;
}
if (StreamTcpPacketIsKeepAlive(ssn, p) == 1) {
goto skip;
}
if (StreamTcpPacketIsKeepAliveACK(ssn, p) == 1) {
StreamTcpClearKeepAliveFlag(ssn, p);
goto skip;
}
StreamTcpClearKeepAliveFlag(ssn, p);
/* if packet is not a valid window update, check if it is perhaps
* a bad window update that we should ignore (and alert on) */
if (StreamTcpPacketIsFinShutdownAck(ssn, p) == 0)
if (StreamTcpPacketIsWindowUpdate(ssn, p) == 0)
if (StreamTcpPacketIsBadWindowUpdate(ssn,p))
goto skip;
/* handle the per 'state' logic */
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->state) < 0)
goto error;
skip:
StreamTcpPacketCheckPostRst(ssn, p);
if (ssn->state >= TCP_ESTABLISHED) {
p->flags |= PKT_STREAM_EST;
}
}
/* deal with a pseudo packet that is created upon receiving a RST
* segment. To be sure we process both sides of the connection, we
* inject a fake packet into the system, forcing reassembly of the
* opposing direction.
* There should be only one, but to be sure we do a while loop. */
if (ssn != NULL) {
while (stt->pseudo_queue.len > 0) {
SCLogDebug("processing pseudo packet / stream end");
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
/* process the opposing direction of the original packet */
if (PKT_IS_TOSERVER(np)) {
SCLogDebug("pseudo packet is to server");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, np, NULL);
} else {
SCLogDebug("pseudo packet is to client");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, np, NULL);
}
/* enqueue this packet so we inspect it in detect etc */
PacketEnqueue(pq, np);
}
SCLogDebug("processing pseudo packet / stream end done");
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
/* check for conditions that may make us not want to log this packet */
/* streams that hit depth */
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ||
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
}
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ||
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
/* encrypted packets */
if ((PKT_IS_TOSERVER(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) ||
(PKT_IS_TOCLIENT(p) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
if (ssn->flags & STREAMTCP_FLAG_BYPASS) {
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
/* if stream is dead and we have no detect engine at all, bypass. */
} else if (g_detect_disabled &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
StreamTcpBypassEnabled())
{
SCLogDebug("bypass as stream is dead and we have no rules");
PacketBypassCallback(p);
}
}
SCReturnInt(0);
error:
/* make sure we don't leave packets in our pseudo queue */
while (stt->pseudo_queue.len > 0) {
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
PacketEnqueue(pq, np);
}
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
if (StreamTcpInlineDropInvalid()) {
/* disable payload inspection as we're dropping this packet
* anyway. Doesn't disable all detection, so we can still
* match on the stream event that was set. */
DecodeSetNoPayloadInspectionFlag(p);
PACKET_DROP(p);
}
SCReturnInt(-1);
}
/**
* \brief Function to validate the checksum of the received packet. If the
* checksum is invalid, packet will be dropped, as the end system will
* also drop the packet.
*
* \param p Packet of which checksum has to be validated
* \retval 1 if the checksum is valid, otherwise 0
*/
static inline int StreamTcpValidateChecksum(Packet *p)
{
int ret = 1;
if (p->flags & PKT_IGNORE_CHECKSUM)
return ret;
if (p->level4_comp_csum == -1) {
if (PKT_IS_IPV4(p)) {
p->level4_comp_csum = TCPChecksum(p->ip4h->s_ip_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
} else if (PKT_IS_IPV6(p)) {
p->level4_comp_csum = TCPV6Checksum(p->ip6h->s_ip6_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
}
}
if (p->level4_comp_csum != 0) {
ret = 0;
if (p->livedev) {
(void) SC_ATOMIC_ADD(p->livedev->invalid_checksums, 1);
} else if (p->pcap_cnt) {
PcapIncreaseInvalidChecksum();
}
}
return ret;
}
/** \internal
* \brief check if a packet is a valid stream started
* \retval bool true/false */
static int TcpSessionPacketIsStreamStarter(const Packet *p)
{
if (p->tcph->th_flags == TH_SYN) {
SCLogDebug("packet %"PRIu64" is a stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
SCLogDebug("packet %"PRIu64" is a midstream stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
}
return 0;
}
/** \internal
* \brief Check if Flow and TCP SSN allow this flow/tuple to be reused
* \retval bool true yes reuse, false no keep tracking old ssn */
static int TcpSessionReuseDoneEnoughSyn(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOSERVER) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->client.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \internal
* \brief check if ssn is done enough for reuse by syn/ack
* \note should only be called if midstream is enabled
*/
static int TcpSessionReuseDoneEnoughSynAck(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOCLIENT) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->server.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \brief Check if SSN is done enough for reuse
*
* Reuse means a new TCP session reuses the tuple (flow in suri)
*
* \retval bool true if ssn can be reused, false if not */
static int TcpSessionReuseDoneEnough(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (p->tcph->th_flags == TH_SYN) {
return TcpSessionReuseDoneEnoughSyn(p, f, ssn);
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
return TcpSessionReuseDoneEnoughSynAck(p, f, ssn);
}
}
return 0;
}
int TcpSessionPacketSsnReuse(const Packet *p, const Flow *f, const void *tcp_ssn)
{
if (p->proto == IPPROTO_TCP && p->tcph != NULL) {
if (TcpSessionPacketIsStreamStarter(p) == 1) {
if (TcpSessionReuseDoneEnough(p, f, tcp_ssn) == 1) {
return 1;
}
}
}
return 0;
}
TmEcode StreamTcp (ThreadVars *tv, Packet *p, void *data, PacketQueue *pq, PacketQueue *postpq)
{
StreamTcpThread *stt = (StreamTcpThread *)data;
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
if (!(PKT_IS_TCP(p))) {
return TM_ECODE_OK;
}
if (p->flow == NULL) {
StatsIncr(tv, stt->counter_tcp_no_flow);
return TM_ECODE_OK;
}
/* only TCP packets with a flow from here */
if (!(p->flags & PKT_PSEUDO_STREAM_END)) {
if (stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION) {
if (StreamTcpValidateChecksum(p) == 0) {
StatsIncr(tv, stt->counter_tcp_invalid_checksum);
return TM_ECODE_OK;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM; //TODO check that this is set at creation
}
AppLayerProfilingReset(stt->ra_ctx->app_tctx);
(void)StreamTcpPacket(tv, p, stt, pq);
return TM_ECODE_OK;
}
TmEcode StreamTcpThreadInit(ThreadVars *tv, void *initdata, void **data)
{
SCEnter();
StreamTcpThread *stt = SCMalloc(sizeof(StreamTcpThread));
if (unlikely(stt == NULL))
SCReturnInt(TM_ECODE_FAILED);
memset(stt, 0, sizeof(StreamTcpThread));
stt->ssn_pool_id = -1;
*data = (void *)stt;
stt->counter_tcp_sessions = StatsRegisterCounter("tcp.sessions", tv);
stt->counter_tcp_ssn_memcap = StatsRegisterCounter("tcp.ssn_memcap_drop", tv);
stt->counter_tcp_pseudo = StatsRegisterCounter("tcp.pseudo", tv);
stt->counter_tcp_pseudo_failed = StatsRegisterCounter("tcp.pseudo_failed", tv);
stt->counter_tcp_invalid_checksum = StatsRegisterCounter("tcp.invalid_checksum", tv);
stt->counter_tcp_no_flow = StatsRegisterCounter("tcp.no_flow", tv);
stt->counter_tcp_syn = StatsRegisterCounter("tcp.syn", tv);
stt->counter_tcp_synack = StatsRegisterCounter("tcp.synack", tv);
stt->counter_tcp_rst = StatsRegisterCounter("tcp.rst", tv);
stt->counter_tcp_midstream_pickups = StatsRegisterCounter("tcp.midstream_pickups", tv);
stt->counter_tcp_wrong_thread = StatsRegisterCounter("tcp.pkt_on_wrong_thread", tv);
/* init reassembly ctx */
stt->ra_ctx = StreamTcpReassembleInitThreadCtx(tv);
if (stt->ra_ctx == NULL)
SCReturnInt(TM_ECODE_FAILED);
stt->ra_ctx->counter_tcp_segment_memcap = StatsRegisterCounter("tcp.segment_memcap_drop", tv);
stt->ra_ctx->counter_tcp_stream_depth = StatsRegisterCounter("tcp.stream_depth_reached", tv);
stt->ra_ctx->counter_tcp_reass_gap = StatsRegisterCounter("tcp.reassembly_gap", tv);
stt->ra_ctx->counter_tcp_reass_overlap = StatsRegisterCounter("tcp.overlap", tv);
stt->ra_ctx->counter_tcp_reass_overlap_diff_data = StatsRegisterCounter("tcp.overlap_diff_data", tv);
stt->ra_ctx->counter_tcp_reass_data_normal_fail = StatsRegisterCounter("tcp.insert_data_normal_fail", tv);
stt->ra_ctx->counter_tcp_reass_data_overlap_fail = StatsRegisterCounter("tcp.insert_data_overlap_fail", tv);
stt->ra_ctx->counter_tcp_reass_list_fail = StatsRegisterCounter("tcp.insert_list_fail", tv);
SCLogDebug("StreamTcp thread specific ctx online at %p, reassembly ctx %p",
stt, stt->ra_ctx);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
stt->ssn_pool_id = 0;
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
} else {
/* grow ssn_pool until we have a element for our thread id */
stt->ssn_pool_id = PoolThreadExpand(ssn_pool);
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
}
SCMutexUnlock(&ssn_pool_mutex);
if (stt->ssn_pool_id < 0 || ssn_pool == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "failed to setup/expand stream session pool. Expand stream.memcap?");
SCReturnInt(TM_ECODE_FAILED);
}
SCReturnInt(TM_ECODE_OK);
}
TmEcode StreamTcpThreadDeinit(ThreadVars *tv, void *data)
{
SCEnter();
StreamTcpThread *stt = (StreamTcpThread *)data;
if (stt == NULL) {
return TM_ECODE_OK;
}
/* XXX */
/* free reassembly ctx */
StreamTcpReassembleFreeThreadCtx(stt->ra_ctx);
/* clear memory */
memset(stt, 0, sizeof(StreamTcpThread));
SCFree(stt);
SCReturnInt(TM_ECODE_OK);
}
/**
* \brief Function to check the validity of the RST packets based on the
* target OS of the given packet.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 0 unacceptable RST
* \retval 1 acceptable RST
*
* WebSense sends RST packets that are:
* - RST flag, win 0, ack 0, seq = nextseq
*
*/
static int StreamTcpValidateRst(TcpSession *ssn, Packet *p)
{
uint8_t os_policy;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p)) {
SCReturnInt(0);
}
}
/* Set up the os_policy to be used in validating the RST packets based on
target system */
if (PKT_IS_TOSERVER(p)) {
if (ssn->server.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->server, p);
os_policy = ssn->server.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
} else {
if (ssn->client.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->client, p);
os_policy = ssn->client.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
}
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
if (PKT_IS_TOSERVER(p)) {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
} else {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
}
SCLogDebug("ssn %p: ASYNC reject RST", ssn);
return 0;
}
switch (os_policy) {
case OS_POLICY_HPUX11:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not Valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_LINUX:
case OS_POLICY_SOLARIS:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len),
ssn->client.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->client.next_seq + ssn->client.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ((TCP_GET_SEQ(p) + p->payload_len),
ssn->server.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->server.next_seq + ssn->server.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
default:
case OS_POLICY_BSD:
case OS_POLICY_FIRST:
case OS_POLICY_HPUX10:
case OS_POLICY_IRIX:
case OS_POLICY_MACOS:
case OS_POLICY_LAST:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
if(PKT_IS_TOSERVER(p)) {
if(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 " Stream %u",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 0;
}
}
break;
}
return 0;
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream.
*
* It's passive except for:
* 1. it sets the os policy on the stream if necessary
* 2. it sets an event in the packet if necessary
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpValidateTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
uint32_t last_pkt_ts = sender_stream->last_pkt_ts;
uint32_t last_ts = sender_stream->last_ts;
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/* HPUX11 igoners the timestamp of out of order packets */
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - last_ts) + 1);
} else {
result = (int32_t) (ts - last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (last_pkt_ts + PAWS_24DAYS))))
{
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream and update the session.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpHandleTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
sender_stream->flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
sender_stream->last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
default:
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/*HPUX11 igoners the timestamp of out of order packets*/
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, sender_stream->last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - sender_stream->last_ts) + 1);
} else {
result = (int32_t) (ts - sender_stream->last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (sender_stream->last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
sender_stream->last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid sender_stream->last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", sender_stream->last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
sender_stream->last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid sender_stream->last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
sender_stream->last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 1) {
/* Update the timestamp and last seen packet time for this
* stream */
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
} else if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (sender_stream->last_pkt_ts + PAWS_24DAYS))))
{
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
} else {
/* Solaris stops using timestamps if a packet is received
without a timestamp and timestamps were used on that stream. */
if (receiver_stream->os_policy == OS_POLICY_SOLARIS)
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to test the received ACK values against the stream window
* and previous ack value. ACK values should be higher than previous
* ACK value and less than the next_win value.
*
* \param ssn TcpSession for state access
* \param stream TcpStream of which last_ack needs to be tested
* \param p Packet which is used to test the last_ack
*
* \retval 0 ACK is valid, last_ack is updated if ACK was higher
* \retval -1 ACK is invalid
*/
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
uint32_t ack = TCP_GET_ACK(p);
/* fast track */
if (SEQ_GT(ack, stream->last_ack) && SEQ_LEQ(ack, stream->next_win))
{
SCLogDebug("ACK in bounds");
SCReturnInt(0);
}
/* fast track */
else if (SEQ_EQ(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" == stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
SCReturnInt(0);
}
/* exception handling */
if (SEQ_LT(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" < stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
/* This is an attempt to get a 'left edge' value that we can check against.
* It doesn't work when the window is 0, need to think of a better way. */
if (stream->window != 0 && SEQ_LT(ack, (stream->last_ack - stream->window))) {
SCLogDebug("ACK %"PRIu32" is before last_ack %"PRIu32" - window "
"%"PRIu32" = %"PRIu32, ack, stream->last_ack,
stream->window, stream->last_ack - stream->window);
goto invalid;
}
SCReturnInt(0);
}
if (ssn->state > TCP_SYN_SENT && SEQ_GT(ack, stream->next_win)) {
SCLogDebug("ACK %"PRIu32" is after next_win %"PRIu32, ack, stream->next_win);
goto invalid;
/* a toclient RST as a reponse to SYN, next_win is 0, ack will be isn+1, just like
* the syn ack */
} else if (ssn->state == TCP_SYN_SENT && PKT_IS_TOCLIENT(p) &&
p->tcph->th_flags & TH_RST &&
SEQ_EQ(ack, stream->isn + 1)) {
SCReturnInt(0);
}
SCLogDebug("default path leading to invalid: ACK %"PRIu32", last_ack %"PRIu32
" next_win %"PRIu32, ack, stream->last_ack, stream->next_win);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_ACK);
SCReturnInt(-1);
}
/** \brief disable reassembly
* Disable app layer and set raw inspect to no longer accept new data.
* Stream engine will then fully disable raw after last inspection.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionNoReassemblyFlag (TcpSession *ssn, char direction)
{
ssn->flags |= STREAMTCP_FLAG_APP_LAYER_DISABLED;
if (direction) {
ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
}
}
/** \brief Set the No reassembly flag for the given direction in given TCP
* session.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetDisableRawReassemblyFlag (TcpSession *ssn, char direction)
{
direction ? (ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) :
(ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED);
}
/** \brief enable bypass
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionBypassFlag (TcpSession *ssn)
{
ssn->flags |= STREAMTCP_FLAG_BYPASS;
}
#define PSEUDO_PKT_SET_IPV4HDR(nipv4h,ipv4h) do { \
IPV4_SET_RAW_VER(nipv4h, IPV4_GET_RAW_VER(ipv4h)); \
IPV4_SET_RAW_HLEN(nipv4h, IPV4_GET_RAW_HLEN(ipv4h)); \
IPV4_SET_RAW_IPLEN(nipv4h, IPV4_GET_RAW_IPLEN(ipv4h)); \
IPV4_SET_RAW_IPTOS(nipv4h, IPV4_GET_RAW_IPTOS(ipv4h)); \
IPV4_SET_RAW_IPPROTO(nipv4h, IPV4_GET_RAW_IPPROTO(ipv4h)); \
(nipv4h)->s_ip_src = IPV4_GET_RAW_IPDST(ipv4h); \
(nipv4h)->s_ip_dst = IPV4_GET_RAW_IPSRC(ipv4h); \
} while (0)
#define PSEUDO_PKT_SET_IPV6HDR(nipv6h,ipv6h) do { \
(nipv6h)->s_ip6_src[0] = (ipv6h)->s_ip6_dst[0]; \
(nipv6h)->s_ip6_src[1] = (ipv6h)->s_ip6_dst[1]; \
(nipv6h)->s_ip6_src[2] = (ipv6h)->s_ip6_dst[2]; \
(nipv6h)->s_ip6_src[3] = (ipv6h)->s_ip6_dst[3]; \
(nipv6h)->s_ip6_dst[0] = (ipv6h)->s_ip6_src[0]; \
(nipv6h)->s_ip6_dst[1] = (ipv6h)->s_ip6_src[1]; \
(nipv6h)->s_ip6_dst[2] = (ipv6h)->s_ip6_src[2]; \
(nipv6h)->s_ip6_dst[3] = (ipv6h)->s_ip6_src[3]; \
IPV6_SET_RAW_NH(nipv6h, IPV6_GET_RAW_NH(ipv6h)); \
} while (0)
#define PSEUDO_PKT_SET_TCPHDR(ntcph,tcph) do { \
COPY_PORT((tcph)->th_dport, (ntcph)->th_sport); \
COPY_PORT((tcph)->th_sport, (ntcph)->th_dport); \
(ntcph)->th_seq = (tcph)->th_ack; \
(ntcph)->th_ack = (tcph)->th_seq; \
} while (0)
/**
* \brief Function to fetch a packet from the packet allocation queue for
* creation of the pseudo packet from the reassembled stream.
*
* @param parent Pointer to the parent of the pseudo packet
* @param pkt pointer to the raw packet of the parent
* @param len length of the packet
* @return upon success returns the pointer to the new pseudo packet
* otherwise NULL
*/
Packet *StreamTcpPseudoSetup(Packet *parent, uint8_t *pkt, uint32_t len)
{
SCEnter();
if (len == 0) {
SCReturnPtr(NULL, "Packet");
}
Packet *p = PacketGetFromQueueOrAlloc();
if (p == NULL) {
SCReturnPtr(NULL, "Packet");
}
/* set the root ptr to the lowest layer */
if (parent->root != NULL)
p->root = parent->root;
else
p->root = parent;
/* copy packet and set lenght, proto */
p->proto = parent->proto;
p->datalink = parent->datalink;
PacketCopyData(p, pkt, len);
p->recursion_level = parent->recursion_level + 1;
p->ts.tv_sec = parent->ts.tv_sec;
p->ts.tv_usec = parent->ts.tv_usec;
FlowReference(&p->flow, parent->flow);
/* set tunnel flags */
/* tell new packet it's part of a tunnel */
SET_TUNNEL_PKT(p);
/* tell parent packet it's part of a tunnel */
SET_TUNNEL_PKT(parent);
/* increment tunnel packet refcnt in the root packet */
TUNNEL_INCR_PKT_TPR(p);
return p;
}
/** \brief Create a pseudo packet injected into the engine to signal the
* opposing direction of this stream trigger detection/logging.
*
* \param parent real packet
* \param pq packet queue to store the new pseudo packet in
* \param dir 0 ts 1 tc
*/
static void StreamTcpPseudoPacketCreateDetectLogFlush(ThreadVars *tv,
StreamTcpThread *stt, Packet *parent,
TcpSession *ssn, PacketQueue *pq, int dir)
{
SCEnter();
Flow *f = parent->flow;
if (parent->flags & PKT_PSEUDO_DETECTLOG_FLUSH) {
SCReturn;
}
Packet *np = PacketPoolGetPacket();
if (np == NULL) {
SCReturn;
}
PKT_SET_SRC(np, PKT_SRC_STREAM_TCP_DETECTLOG_FLUSH);
np->tenant_id = f->tenant_id;
np->datalink = DLT_RAW;
np->proto = IPPROTO_TCP;
FlowReference(&np->flow, f);
np->flags |= PKT_STREAM_EST;
np->flags |= PKT_HAS_FLOW;
np->flags |= PKT_IGNORE_CHECKSUM;
np->flags |= PKT_PSEUDO_DETECTLOG_FLUSH;
np->vlan_id[0] = f->vlan_id[0];
np->vlan_id[1] = f->vlan_id[1];
np->vlan_idx = f->vlan_idx;
np->livedev = (struct LiveDevice_ *)f->livedev;
if (f->flags & FLOW_NOPACKET_INSPECTION) {
DecodeSetNoPacketInspectionFlag(np);
}
if (f->flags & FLOW_NOPAYLOAD_INSPECTION) {
DecodeSetNoPayloadInspectionFlag(np);
}
if (dir == 0) {
SCLogDebug("pseudo is to_server");
np->flowflags |= FLOW_PKT_TOSERVER;
} else {
SCLogDebug("pseudo is to_client");
np->flowflags |= FLOW_PKT_TOCLIENT;
}
np->flowflags |= FLOW_PKT_ESTABLISHED;
np->payload = NULL;
np->payload_len = 0;
if (FLOW_IS_IPV4(f)) {
if (dir == 0) {
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->src, &np->src);
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->dst, &np->dst);
np->sp = f->sp;
np->dp = f->dp;
} else {
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->src, &np->dst);
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->dst, &np->src);
np->sp = f->dp;
np->dp = f->sp;
}
/* Check if we have enough room in direct data. We need ipv4 hdr + tcp hdr.
* Force an allocation if it is not the case.
*/
if (GET_PKT_DIRECT_MAX_SIZE(np) < 40) {
if (PacketCallocExtPkt(np, 40) == -1) {
goto error;
}
}
/* set the ip header */
np->ip4h = (IPV4Hdr *)GET_PKT_DATA(np);
/* version 4 and length 20 bytes for the tcp header */
np->ip4h->ip_verhl = 0x45;
np->ip4h->ip_tos = 0;
np->ip4h->ip_len = htons(40);
np->ip4h->ip_id = 0;
np->ip4h->ip_off = 0;
np->ip4h->ip_ttl = 64;
np->ip4h->ip_proto = IPPROTO_TCP;
if (dir == 0) {
np->ip4h->s_ip_src.s_addr = f->src.addr_data32[0];
np->ip4h->s_ip_dst.s_addr = f->dst.addr_data32[0];
} else {
np->ip4h->s_ip_src.s_addr = f->dst.addr_data32[0];
np->ip4h->s_ip_dst.s_addr = f->src.addr_data32[0];
}
/* set the tcp header */
np->tcph = (TCPHdr *)((uint8_t *)GET_PKT_DATA(np) + 20);
SET_PKT_LEN(np, 40); /* ipv4 hdr + tcp hdr */
} else if (FLOW_IS_IPV6(f)) {
if (dir == 0) {
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->src, &np->src);
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->dst, &np->dst);
np->sp = f->sp;
np->dp = f->dp;
} else {
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->src, &np->dst);
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->dst, &np->src);
np->sp = f->dp;
np->dp = f->sp;
}
/* Check if we have enough room in direct data. We need ipv6 hdr + tcp hdr.
* Force an allocation if it is not the case.
*/
if (GET_PKT_DIRECT_MAX_SIZE(np) < 60) {
if (PacketCallocExtPkt(np, 60) == -1) {
goto error;
}
}
/* set the ip header */
np->ip6h = (IPV6Hdr *)GET_PKT_DATA(np);
/* version 6 */
np->ip6h->s_ip6_vfc = 0x60;
np->ip6h->s_ip6_flow = 0;
np->ip6h->s_ip6_nxt = IPPROTO_TCP;
np->ip6h->s_ip6_plen = htons(20);
np->ip6h->s_ip6_hlim = 64;
if (dir == 0) {
np->ip6h->s_ip6_src[0] = f->src.addr_data32[0];
np->ip6h->s_ip6_src[1] = f->src.addr_data32[1];
np->ip6h->s_ip6_src[2] = f->src.addr_data32[2];
np->ip6h->s_ip6_src[3] = f->src.addr_data32[3];
np->ip6h->s_ip6_dst[0] = f->dst.addr_data32[0];
np->ip6h->s_ip6_dst[1] = f->dst.addr_data32[1];
np->ip6h->s_ip6_dst[2] = f->dst.addr_data32[2];
np->ip6h->s_ip6_dst[3] = f->dst.addr_data32[3];
} else {
np->ip6h->s_ip6_src[0] = f->dst.addr_data32[0];
np->ip6h->s_ip6_src[1] = f->dst.addr_data32[1];
np->ip6h->s_ip6_src[2] = f->dst.addr_data32[2];
np->ip6h->s_ip6_src[3] = f->dst.addr_data32[3];
np->ip6h->s_ip6_dst[0] = f->src.addr_data32[0];
np->ip6h->s_ip6_dst[1] = f->src.addr_data32[1];
np->ip6h->s_ip6_dst[2] = f->src.addr_data32[2];
np->ip6h->s_ip6_dst[3] = f->src.addr_data32[3];
}
/* set the tcp header */
np->tcph = (TCPHdr *)((uint8_t *)GET_PKT_DATA(np) + 40);
SET_PKT_LEN(np, 60); /* ipv6 hdr + tcp hdr */
}
np->tcph->th_offx2 = 0x50;
np->tcph->th_flags |= TH_ACK;
np->tcph->th_win = 10;
np->tcph->th_urp = 0;
/* to server */
if (dir == 0) {
np->tcph->th_sport = htons(f->sp);
np->tcph->th_dport = htons(f->dp);
np->tcph->th_seq = htonl(ssn->client.next_seq);
np->tcph->th_ack = htonl(ssn->server.last_ack);
/* to client */
} else {
np->tcph->th_sport = htons(f->dp);
np->tcph->th_dport = htons(f->sp);
np->tcph->th_seq = htonl(ssn->server.next_seq);
np->tcph->th_ack = htonl(ssn->client.last_ack);
}
/* use parent time stamp */
memcpy(&np->ts, &parent->ts, sizeof(struct timeval));
SCLogDebug("np %p", np);
PacketEnqueue(pq, np);
StatsIncr(tv, stt->counter_tcp_pseudo);
SCReturn;
error:
FlowDeReference(&np->flow);
SCReturn;
}
/** \brief create packets in both directions to flush out logging
* and detection before switching protocols.
* In IDS mode, create first in packet dir, 2nd in opposing
* In IPS mode, do the reverse.
* Flag TCP engine that data needs to be inspected regardless
* of how far we are wrt inspect limits.
*/
void StreamTcpDetectLogFlush(ThreadVars *tv, StreamTcpThread *stt, Flow *f, Packet *p, PacketQueue *pq)
{
TcpSession *ssn = f->protoctx;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
bool ts = PKT_IS_TOSERVER(p) ? true : false;
ts ^= StreamTcpInlineMode();
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^0);
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^1);
}
/**
* \brief Run callback function on each TCP segment
*
* \note when stream engine is running in inline mode all segments are used,
* in IDS/non-inline mode only ack'd segments are iterated.
*
* \note Must be called under flow lock.
*
* \return -1 in case of error, the number of segment in case of success
*
*/
int StreamTcpSegmentForEach(const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data)
{
TcpSession *ssn = NULL;
TcpStream *stream = NULL;
int ret = 0;
int cnt = 0;
if (p->flow == NULL)
return 0;
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
return 0;
}
if (flag & FLOW_PKT_TOSERVER) {
stream = &(ssn->server);
} else {
stream = &(ssn->client);
}
/* for IDS, return ack'd segments. For IPS all. */
TcpSegment *seg;
RB_FOREACH(seg, TCPSEG, &stream->seg_tree) {
if (!((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
|| SEQ_LT(seg->seq, stream->last_ack)))
break;
const uint8_t *seg_data;
uint32_t seg_datalen;
StreamingBufferSegmentGetData(&stream->sb, &seg->sbseg, &seg_data, &seg_datalen);
ret = CallbackFunc(p, data, seg_data, seg_datalen);
if (ret != 1) {
SCLogDebug("Callback function has failed");
return -1;
}
cnt++;
}
return cnt;
}
int StreamTcpBypassEnabled(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS);
}
/**
* \brief See if stream engine is operating in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineMode(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_INLINE) ? 1 : 0;
}
void TcpSessionSetReassemblyDepth(TcpSession *ssn, uint32_t size)
{
if (size > ssn->reassembly_depth || size == 0) {
ssn->reassembly_depth = size;
}
return;
}
#ifdef UNITTESTS
#define SET_ISN(stream, setseq) \
(stream)->isn = (setseq); \
(stream)->base_seq = (setseq) + 1
/**
* \test Test the allocation of TCP session for a given packet from the
* ssn_pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest01 (void)
{
StreamTcpThread stt;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
TcpSession *ssn = StreamTcpNewSession(p, 0);
if (ssn == NULL) {
printf("Session can not be allocated: ");
goto end;
}
f.protoctx = ssn;
if (f.alparser != NULL) {
printf("AppLayer field not set to NULL: ");
goto end;
}
if (ssn->state != 0) {
printf("TCP state field not set to 0: ");
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the deallocation of TCP session for a given packet and return
* the memory back to ssn_pool and corresponding segments to segment
* pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest02 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
StreamTcpSessionClear(p->flow->protoctx);
//StreamTcpUTClearSession(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN packet of the session. The session is setup only if midstream
* sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest03 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 20 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN/ACK packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest04 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(9);
p->tcph->th_ack = htonl(19);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 10 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 20)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* 3WHS packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest05 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(13);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, 4); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(16);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, 4); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 16 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we have seen only the
* FIN, RST packets packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest06 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
TcpSession ssn;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&ssn, 0, sizeof (TcpSession));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_flags = TH_FIN;
p->tcph = &tcph;
/* StreamTcpPacket returns -1 on unsolicited FIN */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed: ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't: ");
goto end;
}
p->tcph->th_flags = TH_RST;
/* StreamTcpPacket returns -1 on unsolicited RST */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed (2): ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't (2): ");
goto end;
}
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the working on PAWS. The packet will be dropped by stream, as
* its timestamp is old, although the segment is in the window.
*/
static int StreamTcpTest07 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
PacketQueue pq;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 2;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) != -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working on PAWS. The packet will be accpeted by engine as
* the timestamp is valid and it is in window.
*/
static int StreamTcpTest08 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(20);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 12;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 12);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working of No stream reassembly flag. The stream will not
* reassemble the segment if the flag is set.
*/
static int StreamTcpTest09 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(12);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(p->flow->protoctx == NULL);
StreamTcpSetSessionNoReassemblyFlag(((TcpSession *)(p->flow->protoctx)), 0);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
TcpSession *ssn = p->flow->protoctx;
FAIL_IF_NULL(ssn);
TcpSegment *seg = RB_MIN(TCPSEG, &ssn->client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCPSEG_RB_NEXT(seg) != NULL);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we see all the packets in that stream from start.
*/
static int StreamTcpTest10 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN packet of that stream.
*/
static int StreamTcpTest11 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(1);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(2);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->server.last_ack != 2 &&
((TcpSession *)(p->flow->protoctx))->client.next_seq != 1);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest12 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
* Later, we start to receive the packet from other end stream too.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest13 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(9);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 9 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 14) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.1\n"
"\n"
" linux: 192.168.0.2\n"
"\n";
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string1 =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.0/24," "192.168.1.1\n"
"\n"
" linux: 192.168.1.0/24," "192.168.0.1\n"
"\n";
/**
* \brief Function to parse the dummy conf string and get the value of IP
* address for the corresponding OS policy type.
*
* \param conf_val_name Name of the OS policy type
* \retval returns IP address as string on success and NULL on failure
*/
static const char *StreamTcpParseOSPolicy (char *conf_var_name)
{
SCEnter();
char conf_var_type_name[15] = "host-os-policy";
char *conf_var_full_name = NULL;
const char *conf_var_value = NULL;
if (conf_var_name == NULL)
goto end;
/* the + 2 is for the '.' and the string termination character '\0' */
conf_var_full_name = (char *)SCMalloc(strlen(conf_var_type_name) +
strlen(conf_var_name) + 2);
if (conf_var_full_name == NULL)
goto end;
if (snprintf(conf_var_full_name,
strlen(conf_var_type_name) + strlen(conf_var_name) + 2, "%s.%s",
conf_var_type_name, conf_var_name) < 0) {
SCLogError(SC_ERR_INVALID_VALUE, "Error in making the conf full name");
goto end;
}
if (ConfGet(conf_var_full_name, &conf_var_value) != 1) {
SCLogError(SC_ERR_UNKNOWN_VALUE, "Error in getting conf value for conf name %s",
conf_var_full_name);
goto end;
}
SCLogDebug("Value obtained from the yaml conf file, for the var "
"\"%s\" is \"%s\"", conf_var_name, conf_var_value);
end:
if (conf_var_full_name != NULL)
SCFree(conf_var_full_name);
SCReturnCharPtr(conf_var_value);
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest14 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string, strlen(dummy_conf_string));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.0.2");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest01 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(21);
p->tcph->th_ack = htonl(10);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK, but the SYN/ACK does
* not have the right SEQ
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest02 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("SYN/ACK pkt not rejected but it should have: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK: however the SYN/ACK and ACK
* are part of a normal 3WHS
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest03 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(31);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest15 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.20");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.20");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest16 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_WINDOWS)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_WINDOWS);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1". To check the setting of
* Default os policy
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest17 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("10.1.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_DEFAULT)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_DEFAULT);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest18 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS)
goto end;
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest19 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8": ",
(uint8_t)OS_POLICY_WINDOWS, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest20 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest21 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest22 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("123.231.2.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_DEFAULT) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_DEFAULT, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest23(void)
{
StreamTcpThread stt;
TcpSession ssn;
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(p == NULL);
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
SET_ISN(&ssn.client, 3184324452UL);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419609UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 6;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
TcpSegment *seg = RB_MAX(TCPSEG, &ssn.client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCP_SEG_LEN(seg) != 2);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest24(void)
{
StreamTcpThread stt;
TcpSession ssn;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF (p == NULL);
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
memset(&tv, 0, sizeof (ThreadVars));
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
//ssn.client.ra_app_base_seq = ssn.client.ra_raw_base_seq = ssn.client.last_ack = 3184324453UL;
SET_ISN(&ssn.client, 3184324453UL);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 4;
FAIL_IF (StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419633UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419657UL);
p->payload_len = 4;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
TcpSegment *seg = RB_MAX(TCPSEG, &ssn.client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCP_SEG_LEN(seg) != 4);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest25(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest26(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest27(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the memcap incrementing/decrementing and memcap check */
static int StreamTcpTest28(void)
{
StreamTcpThread stt;
StreamTcpUTInit(&stt.ra_ctx);
uint32_t memuse = SC_ATOMIC_GET(st_memuse);
StreamTcpIncrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != (memuse+500));
StreamTcpDecrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != memuse);
FAIL_IF(StreamTcpCheckMemcap(500) != 1);
FAIL_IF(StreamTcpCheckMemcap((memuse + SC_ATOMIC_GET(stream_config.memcap))) != 0);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != 0);
PASS;
}
#if 0
/**
* \test Test the resetting of the sesison with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest29(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t packet[1460] = "";
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = packet;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
tcpvars.hlen = 20;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 119197101;
ssn.server.window = 5184;
ssn.server.next_win = 5184;
ssn.server.last_ack = 119197101;
ssn.server.ra_base_seq = 119197101;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 4;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(119197102);
p.tcph->th_ack = htonl(15);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(15);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the ssn.state should be TCP_ESTABLISHED(%"PRIu8"), not %"PRIu8""
"\n", TCP_ESTABLISHED, ssn.state);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the overlapping of the packet with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest30(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t payload[9] = "AAAAAAAAA";
uint8_t payload1[9] = "GET /EVIL";
uint8_t expected_content[9] = { 0x47, 0x45, 0x54, 0x20, 0x2f, 0x45, 0x56,
0x49, 0x4c };
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = payload;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload = payload1;
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(20);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (StreamTcpCheckStreamContents(expected_content, 9, &ssn.client) != 1) {
printf("the contents are not as expected(GET /EVIL), contents are: ");
PrintRawDataFp(stdout, ssn.client.seg_list->payload, 9);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the multiple SYN packet handling with bad checksum and timestamp
* value. Engine should drop the bad checksum packet and establish
* TCP session correctly.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest31(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
TCPOpt tcpopt;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
memset(&tcpopt, 0, sizeof (TCPOpt));
int result = 1;
StreamTcpInitConfig(TRUE);
FLOW_INITIALIZE(&f);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_LINUX;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
p.tcpvars.ts = &tcpopt;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 100;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 10;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
ssn.flags |= STREAMTCP_FLAG_TIMESTAMP;
tcph.th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(11);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079941);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr1;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the should have been changed to TCP_ESTABLISHED!!\n ");
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the initialization of tcp streams with ECN & CWR flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest32(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK | TH_ECN;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_flags = TH_ACK;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the same
* ports have been used to start the new session after resetting the
* previous session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest33 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_CLOSED) {
printf("Tcp session should have been closed\n");
goto end;
}
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_seq = htonl(1);
p.tcph->th_ack = htonl(2);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been ESTABLISHED\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the PUSH flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest34 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_PUSH;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the URG flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest35 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_URG;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the processing of PSH and URG flag in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest36(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_URG;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->client.next_seq != 4) {
printf("the ssn->client.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)p.flow->protoctx)->client.next_seq);
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
#endif
/**
* \test Test the processing of out of order FIN packets in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest37(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p->tcph->th_ack = htonl(2);
p->tcph->th_seq = htonl(4);
p->tcph->th_flags = TH_ACK|TH_FIN;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_CLOSE_WAIT) {
printf("the TCP state should be TCP_CLOSE_WAIT\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_ACK;
p->payload_len = 0;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
TcpStream *stream = &(((TcpSession *)p->flow->protoctx)->client);
FAIL_IF(STREAM_RAW_PROGRESS(stream) != 0); // no detect no progress update
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest38 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[128];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(29847);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 1 as the previous sent ACK value is out of
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 1) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 127, 128); /*AAA*/
p->payload = payload;
p->payload_len = 127;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 128) {
printf("the server.next_seq should be 128, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(256); // in window, but beyond next_seq
p->tcph->th_seq = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256, as the previous sent ACK value
is inside window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(128);
p->tcph->th_seq = htonl(8);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 256, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack and update the next_seq after loosing the .
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest39 (void)
{
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 4) {
printf("the server.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 4 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 4) {
printf("the server.last_ack should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_seq = htonl(4);
p->tcph->th_ack = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* next_seq value should be 2987 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 7) {
printf("the server.next_seq should be 7, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick first */
static int StreamTcpTest42 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(501);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 500) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 500);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick second */
static int StreamTcpTest43 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick neither */
static int StreamTcpTest44 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(3001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_SYN_RECV) {
SCLogDebug("state not TCP_SYN_RECV");
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, over the limit */
static int StreamTcpTest45 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
stream_config.max_synack_queued = 2;
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(2000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(3000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
#endif /* UNITTESTS */
void StreamTcpRegisterTests (void)
{
#ifdef UNITTESTS
UtRegisterTest("StreamTcpTest01 -- TCP session allocation",
StreamTcpTest01);
UtRegisterTest("StreamTcpTest02 -- TCP session deallocation",
StreamTcpTest02);
UtRegisterTest("StreamTcpTest03 -- SYN missed MidStream session",
StreamTcpTest03);
UtRegisterTest("StreamTcpTest04 -- SYN/ACK missed MidStream session",
StreamTcpTest04);
UtRegisterTest("StreamTcpTest05 -- 3WHS missed MidStream session",
StreamTcpTest05);
UtRegisterTest("StreamTcpTest06 -- FIN, RST message MidStream session",
StreamTcpTest06);
UtRegisterTest("StreamTcpTest07 -- PAWS invalid timestamp",
StreamTcpTest07);
UtRegisterTest("StreamTcpTest08 -- PAWS valid timestamp", StreamTcpTest08);
UtRegisterTest("StreamTcpTest09 -- No Client Reassembly", StreamTcpTest09);
UtRegisterTest("StreamTcpTest10 -- No missed packet Async stream",
StreamTcpTest10);
UtRegisterTest("StreamTcpTest11 -- SYN missed Async stream",
StreamTcpTest11);
UtRegisterTest("StreamTcpTest12 -- SYN/ACK missed Async stream",
StreamTcpTest12);
UtRegisterTest("StreamTcpTest13 -- opposite stream packets for Async " "stream",
StreamTcpTest13);
UtRegisterTest("StreamTcp4WHSTest01", StreamTcp4WHSTest01);
UtRegisterTest("StreamTcp4WHSTest02", StreamTcp4WHSTest02);
UtRegisterTest("StreamTcp4WHSTest03", StreamTcp4WHSTest03);
UtRegisterTest("StreamTcpTest14 -- setup OS policy", StreamTcpTest14);
UtRegisterTest("StreamTcpTest15 -- setup OS policy", StreamTcpTest15);
UtRegisterTest("StreamTcpTest16 -- setup OS policy", StreamTcpTest16);
UtRegisterTest("StreamTcpTest17 -- setup OS policy", StreamTcpTest17);
UtRegisterTest("StreamTcpTest18 -- setup OS policy", StreamTcpTest18);
UtRegisterTest("StreamTcpTest19 -- setup OS policy", StreamTcpTest19);
UtRegisterTest("StreamTcpTest20 -- setup OS policy", StreamTcpTest20);
UtRegisterTest("StreamTcpTest21 -- setup OS policy", StreamTcpTest21);
UtRegisterTest("StreamTcpTest22 -- setup OS policy", StreamTcpTest22);
UtRegisterTest("StreamTcpTest23 -- stream memory leaks", StreamTcpTest23);
UtRegisterTest("StreamTcpTest24 -- stream memory leaks", StreamTcpTest24);
UtRegisterTest("StreamTcpTest25 -- test ecn/cwr sessions",
StreamTcpTest25);
UtRegisterTest("StreamTcpTest26 -- test ecn/cwr sessions",
StreamTcpTest26);
UtRegisterTest("StreamTcpTest27 -- test ecn/cwr sessions",
StreamTcpTest27);
UtRegisterTest("StreamTcpTest28 -- Memcap Test", StreamTcpTest28);
#if 0 /* VJ 2010/09/01 disabled since they blow up on Fedora and Fedora is
* right about blowing up. The checksum functions are not used properly
* in the tests. */
UtRegisterTest("StreamTcpTest29 -- Badchecksum Reset Test", StreamTcpTest29, 1);
UtRegisterTest("StreamTcpTest30 -- Badchecksum Overlap Test", StreamTcpTest30, 1);
UtRegisterTest("StreamTcpTest31 -- MultipleSyns Test", StreamTcpTest31, 1);
UtRegisterTest("StreamTcpTest32 -- Bogus CWR Test", StreamTcpTest32, 1);
UtRegisterTest("StreamTcpTest33 -- RST-SYN Again Test", StreamTcpTest33, 1);
UtRegisterTest("StreamTcpTest34 -- SYN-PUSH Test", StreamTcpTest34, 1);
UtRegisterTest("StreamTcpTest35 -- SYN-URG Test", StreamTcpTest35, 1);
UtRegisterTest("StreamTcpTest36 -- PUSH-URG Test", StreamTcpTest36, 1);
#endif
UtRegisterTest("StreamTcpTest37 -- Out of order FIN Test",
StreamTcpTest37);
UtRegisterTest("StreamTcpTest38 -- validate ACK", StreamTcpTest38);
UtRegisterTest("StreamTcpTest39 -- update next_seq", StreamTcpTest39);
UtRegisterTest("StreamTcpTest42 -- SYN/ACK queue", StreamTcpTest42);
UtRegisterTest("StreamTcpTest43 -- SYN/ACK queue", StreamTcpTest43);
UtRegisterTest("StreamTcpTest44 -- SYN/ACK queue", StreamTcpTest44);
UtRegisterTest("StreamTcpTest45 -- SYN/ACK queue", StreamTcpTest45);
/* set up the reassembly tests as well */
StreamTcpReassembleRegisterTests();
StreamTcpSackRegisterTests ();
#endif /* UNITTESTS */
}
| ./CrossVul/dataset_final_sorted/CWE-94/c/good_1213_0 |
crossvul-cpp_data_bad_1212_0 | /* Copyright (C) 2007-2016 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
* \author Gurvinder Singh <gurvindersinghdahiya@gmail.com>
*
* TCP stream tracking and reassembly engine.
*
* \todo - 4WHS: what if after the 2nd SYN we turn out to be normal 3WHS anyway?
*/
#include "suricata-common.h"
#include "suricata.h"
#include "decode.h"
#include "debug.h"
#include "detect.h"
#include "flow.h"
#include "flow-util.h"
#include "conf.h"
#include "conf-yaml-loader.h"
#include "threads.h"
#include "threadvars.h"
#include "tm-threads.h"
#include "util-pool.h"
#include "util-pool-thread.h"
#include "util-checksum.h"
#include "util-unittest.h"
#include "util-print.h"
#include "util-debug.h"
#include "util-device.h"
#include "stream-tcp-private.h"
#include "stream-tcp-reassemble.h"
#include "stream-tcp.h"
#include "stream-tcp-inline.h"
#include "stream-tcp-sack.h"
#include "stream-tcp-util.h"
#include "stream.h"
#include "pkt-var.h"
#include "host.h"
#include "app-layer.h"
#include "app-layer-parser.h"
#include "app-layer-protos.h"
#include "app-layer-htp-mem.h"
#include "util-host-os-info.h"
#include "util-privs.h"
#include "util-profiling.h"
#include "util-misc.h"
#include "util-validate.h"
#include "util-runmodes.h"
#include "util-random.h"
#include "source-pcap-file.h"
//#define DEBUG
#define STREAMTCP_DEFAULT_PREALLOC 2048
#define STREAMTCP_DEFAULT_MEMCAP (32 * 1024 * 1024) /* 32mb */
#define STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP (64 * 1024 * 1024) /* 64mb */
#define STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED 5
#define STREAMTCP_NEW_TIMEOUT 60
#define STREAMTCP_EST_TIMEOUT 3600
#define STREAMTCP_CLOSED_TIMEOUT 120
#define STREAMTCP_EMERG_NEW_TIMEOUT 10
#define STREAMTCP_EMERG_EST_TIMEOUT 300
#define STREAMTCP_EMERG_CLOSED_TIMEOUT 20
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *, TcpSession *, Packet *, PacketQueue *);
void StreamTcpReturnStreamSegments (TcpStream *);
void StreamTcpInitConfig(char);
int StreamTcpGetFlowState(void *);
void StreamTcpSetOSPolicy(TcpStream*, Packet*);
static int StreamTcpValidateTimestamp(TcpSession * , Packet *);
static int StreamTcpHandleTimestamp(TcpSession * , Packet *);
static int StreamTcpValidateRst(TcpSession * , Packet *);
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *, Packet *);
static int StreamTcpStateDispatch(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq,
uint8_t state);
extern int g_detect_disabled;
static PoolThread *ssn_pool = NULL;
static SCMutex ssn_pool_mutex = SCMUTEX_INITIALIZER; /**< init only, protect initializing and growing pool */
#ifdef DEBUG
static uint64_t ssn_pool_cnt = 0; /** counts ssns, protected by ssn_pool_mutex */
#endif
uint64_t StreamTcpReassembleMemuseGlobalCounter(void);
SC_ATOMIC_DECLARE(uint64_t, st_memuse);
void StreamTcpInitMemuse(void)
{
SC_ATOMIC_INIT(st_memuse);
}
void StreamTcpIncrMemuse(uint64_t size)
{
(void) SC_ATOMIC_ADD(st_memuse, size);
SCLogDebug("STREAM %"PRIu64", incr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
void StreamTcpDecrMemuse(uint64_t size)
{
#ifdef DEBUG_VALIDATION
uint64_t presize = SC_ATOMIC_GET(st_memuse);
if (RunmodeIsUnittests()) {
BUG_ON(presize > UINT_MAX);
}
#endif
(void) SC_ATOMIC_SUB(st_memuse, size);
#ifdef DEBUG_VALIDATION
if (RunmodeIsUnittests()) {
uint64_t postsize = SC_ATOMIC_GET(st_memuse);
BUG_ON(postsize > presize);
}
#endif
SCLogDebug("STREAM %"PRIu64", decr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
uint64_t StreamTcpMemuseCounter(void)
{
uint64_t memusecopy = SC_ATOMIC_GET(st_memuse);
return memusecopy;
}
/**
* \brief Check if alloc'ing "size" would mean we're over memcap
*
* \retval 1 if in bounds
* \retval 0 if not in bounds
*/
int StreamTcpCheckMemcap(uint64_t size)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
if (memcapcopy == 0 || size + SC_ATOMIC_GET(st_memuse) <= memcapcopy)
return 1;
return 0;
}
/**
* \brief Update memcap value
*
* \param size new memcap value
*/
int StreamTcpSetMemcap(uint64_t size)
{
if (size == 0 || (uint64_t)SC_ATOMIC_GET(st_memuse) < size) {
SC_ATOMIC_SET(stream_config.memcap, size);
return 1;
}
return 0;
}
/**
* \brief Return memcap value
*
* \param memcap memcap value
*/
uint64_t StreamTcpGetMemcap(void)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
return memcapcopy;
}
void StreamTcpStreamCleanup(TcpStream *stream)
{
if (stream != NULL) {
StreamTcpSackFreeList(stream);
StreamTcpReturnStreamSegments(stream);
StreamingBufferClear(&stream->sb);
}
}
/**
* \brief Session cleanup function. Does not free the ssn.
* \param ssn tcp session
*/
void StreamTcpSessionCleanup(TcpSession *ssn)
{
SCEnter();
TcpStateQueue *q, *q_next;
if (ssn == NULL)
return;
StreamTcpStreamCleanup(&ssn->client);
StreamTcpStreamCleanup(&ssn->server);
q = ssn->queue;
while (q != NULL) {
q_next = q->next;
SCFree(q);
q = q_next;
StreamTcpDecrMemuse((uint64_t)sizeof(TcpStateQueue));
}
ssn->queue = NULL;
ssn->queue_len = 0;
SCReturn;
}
/**
* \brief Function to return the stream back to the pool. It returns the
* segments in the stream to the segment pool.
*
* This function is called when the flow is destroyed, so it should free
* *everything* related to the tcp session. So including the app layer
* data. We are guaranteed to only get here when the flow's use_cnt is 0.
*
* \param ssn Void ptr to the ssn.
*/
void StreamTcpSessionClear(void *ssnptr)
{
SCEnter();
TcpSession *ssn = (TcpSession *)ssnptr;
if (ssn == NULL)
return;
StreamTcpSessionCleanup(ssn);
/* HACK: don't loose track of thread id */
PoolThreadReserved a = ssn->res;
memset(ssn, 0, sizeof(TcpSession));
ssn->res = a;
PoolThreadReturn(ssn_pool, ssn);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
ssn_pool_cnt--;
SCMutexUnlock(&ssn_pool_mutex);
#endif
SCReturn;
}
/**
* \brief Function to return the stream segments back to the pool.
*
* We don't clear out the app layer storage here as that is under protection
* of the "use_cnt" reference counter in the flow. This function is called
* when the use_cnt is always at least 1 (this pkt has incremented the flow
* use_cnt itself), so we don't bother.
*
* \param p Packet used to identify the stream.
*/
void StreamTcpSessionPktFree (Packet *p)
{
SCEnter();
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL)
SCReturn;
StreamTcpReturnStreamSegments(&ssn->client);
StreamTcpReturnStreamSegments(&ssn->server);
SCReturn;
}
/** \brief Stream alloc function for the Pool
* \retval ptr void ptr to TcpSession structure with all vars set to 0/NULL
*/
static void *StreamTcpSessionPoolAlloc(void)
{
void *ptr = NULL;
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpSession)) == 0)
return NULL;
ptr = SCMalloc(sizeof(TcpSession));
if (unlikely(ptr == NULL))
return NULL;
return ptr;
}
static int StreamTcpSessionPoolInit(void *data, void* initdata)
{
memset(data, 0, sizeof(TcpSession));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpSession));
return 1;
}
/** \brief Pool cleanup function
* \param s Void ptr to TcpSession memory */
static void StreamTcpSessionPoolCleanup(void *s)
{
if (s != NULL) {
StreamTcpSessionCleanup(s);
/** \todo not very clean, as the memory is not freed here */
StreamTcpDecrMemuse((uint64_t)sizeof(TcpSession));
}
}
/**
* \brief See if stream engine is dropping invalid packet in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineDropInvalid(void)
{
return ((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
&& (stream_config.flags & STREAMTCP_INIT_FLAG_DROP_INVALID));
}
/* hack: stream random range code expects random values in range of 0-RAND_MAX,
* but we can get both <0 and >RAND_MAX values from RandomGet
*/
static int RandomGetWrap(void)
{
unsigned long r;
do {
r = RandomGet();
} while(r >= ULONG_MAX - (ULONG_MAX % RAND_MAX));
return r % RAND_MAX;
}
/** \brief To initialize the stream global configuration data
*
* \param quiet It tells the mode of operation, if it is TRUE nothing will
* be get printed.
*/
void StreamTcpInitConfig(char quiet)
{
intmax_t value = 0;
uint16_t rdrange = 10;
SCLogDebug("Initializing Stream");
memset(&stream_config, 0, sizeof(stream_config));
SC_ATOMIC_INIT(stream_config.memcap);
SC_ATOMIC_INIT(stream_config.reassembly_memcap);
if ((ConfGetInt("stream.max-sessions", &value)) == 1) {
SCLogWarning(SC_WARN_OPTION_OBSOLETE, "max-sessions is obsolete. "
"Number of concurrent sessions is now only limited by Flow and "
"TCP stream engine memcaps.");
}
if ((ConfGetInt("stream.prealloc-sessions", &value)) == 1) {
stream_config.prealloc_sessions = (uint32_t)value;
} else {
if (RunmodeIsUnittests()) {
stream_config.prealloc_sessions = 128;
} else {
stream_config.prealloc_sessions = STREAMTCP_DEFAULT_PREALLOC;
if (ConfGetNode("stream.prealloc-sessions") != NULL) {
WarnInvalidConfEntry("stream.prealloc_sessions",
"%"PRIu32,
stream_config.prealloc_sessions);
}
}
}
if (!quiet) {
SCLogConfig("stream \"prealloc-sessions\": %"PRIu32" (per thread)",
stream_config.prealloc_sessions);
}
const char *temp_stream_memcap_str;
if (ConfGetValue("stream.memcap", &temp_stream_memcap_str) == 1) {
uint64_t stream_memcap_copy;
if (ParseSizeStringU64(temp_stream_memcap_str, &stream_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing stream.memcap "
"from conf file - %s. Killing engine",
temp_stream_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.memcap, stream_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.memcap, STREAMTCP_DEFAULT_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream \"memcap\": %"PRIu64, SC_ATOMIC_GET(stream_config.memcap));
}
ConfGetBool("stream.midstream", &stream_config.midstream);
if (!quiet) {
SCLogConfig("stream \"midstream\" session pickups: %s", stream_config.midstream ? "enabled" : "disabled");
}
ConfGetBool("stream.async-oneside", &stream_config.async_oneside);
if (!quiet) {
SCLogConfig("stream \"async-oneside\": %s", stream_config.async_oneside ? "enabled" : "disabled");
}
int csum = 0;
if ((ConfGetBool("stream.checksum-validation", &csum)) == 1) {
if (csum == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
/* Default is that we validate the checksum of all the packets */
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
if (!quiet) {
SCLogConfig("stream \"checksum-validation\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION ?
"enabled" : "disabled");
}
const char *temp_stream_inline_str;
if (ConfGetValue("stream.inline", &temp_stream_inline_str) == 1) {
int inl = 0;
/* checking for "auto" and falling back to boolean to provide
* backward compatibility */
if (strcmp(temp_stream_inline_str, "auto") == 0) {
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
} else if (ConfGetBool("stream.inline", &inl) == 1) {
if (inl) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
} else {
/* default to 'auto' */
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
if (!quiet) {
SCLogConfig("stream.\"inline\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_INLINE
? "enabled" : "disabled");
}
int bypass = 0;
if ((ConfGetBool("stream.bypass", &bypass)) == 1) {
if (bypass == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_BYPASS;
}
}
if (!quiet) {
SCLogConfig("stream \"bypass\": %s",
(stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS)
? "enabled" : "disabled");
}
int drop_invalid = 0;
if ((ConfGetBool("stream.drop-invalid", &drop_invalid)) == 1) {
if (drop_invalid == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
if ((ConfGetInt("stream.max-synack-queued", &value)) == 1) {
if (value >= 0 && value <= 255) {
stream_config.max_synack_queued = (uint8_t)value;
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
if (!quiet) {
SCLogConfig("stream \"max-synack-queued\": %"PRIu8, stream_config.max_synack_queued);
}
const char *temp_stream_reassembly_memcap_str;
if (ConfGetValue("stream.reassembly.memcap", &temp_stream_reassembly_memcap_str) == 1) {
uint64_t stream_reassembly_memcap_copy;
if (ParseSizeStringU64(temp_stream_reassembly_memcap_str,
&stream_reassembly_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.memcap "
"from conf file - %s. Killing engine",
temp_stream_reassembly_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap, stream_reassembly_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap , STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"memcap\": %"PRIu64"",
SC_ATOMIC_GET(stream_config.reassembly_memcap));
}
const char *temp_stream_reassembly_depth_str;
if (ConfGetValue("stream.reassembly.depth", &temp_stream_reassembly_depth_str) == 1) {
if (ParseSizeStringU32(temp_stream_reassembly_depth_str,
&stream_config.reassembly_depth) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.depth "
"from conf file - %s. Killing engine",
temp_stream_reassembly_depth_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_depth = 0;
}
if (!quiet) {
SCLogConfig("stream.reassembly \"depth\": %"PRIu32"", stream_config.reassembly_depth);
}
int randomize = 0;
if ((ConfGetBool("stream.reassembly.randomize-chunk-size", &randomize)) == 0) {
/* randomize by default if value not set
* In ut mode we disable, to get predictible test results */
if (!(RunmodeIsUnittests()))
randomize = 1;
}
if (randomize) {
const char *temp_rdrange;
if (ConfGetValue("stream.reassembly.randomize-chunk-range",
&temp_rdrange) == 1) {
if (ParseSizeStringU16(temp_rdrange, &rdrange) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.randomize-chunk-range "
"from conf file - %s. Killing engine",
temp_rdrange);
exit(EXIT_FAILURE);
} else if (rdrange >= 100) {
SCLogError(SC_ERR_INVALID_VALUE,
"stream.reassembly.randomize-chunk-range "
"must be lower than 100");
exit(EXIT_FAILURE);
}
}
}
const char *temp_stream_reassembly_toserver_chunk_size_str;
if (ConfGetValue("stream.reassembly.toserver-chunk-size",
&temp_stream_reassembly_toserver_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toserver_chunk_size_str,
&stream_config.reassembly_toserver_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toserver-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toserver_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toserver_chunk_size =
STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toserver_chunk_size +=
(int) (stream_config.reassembly_toserver_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
const char *temp_stream_reassembly_toclient_chunk_size_str;
if (ConfGetValue("stream.reassembly.toclient-chunk-size",
&temp_stream_reassembly_toclient_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toclient_chunk_size_str,
&stream_config.reassembly_toclient_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toclient-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toclient_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toclient_chunk_size =
STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toclient_chunk_size +=
(int) (stream_config.reassembly_toclient_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"toserver-chunk-size\": %"PRIu16,
stream_config.reassembly_toserver_chunk_size);
SCLogConfig("stream.reassembly \"toclient-chunk-size\": %"PRIu16,
stream_config.reassembly_toclient_chunk_size);
}
int enable_raw = 1;
if (ConfGetBool("stream.reassembly.raw", &enable_raw) == 1) {
if (!enable_raw) {
stream_config.stream_init_flags = STREAMTCP_STREAM_FLAG_DISABLE_RAW;
}
} else {
enable_raw = 1;
}
if (!quiet)
SCLogConfig("stream.reassembly.raw: %s", enable_raw ? "enabled" : "disabled");
/* init the memcap/use tracking */
StreamTcpInitMemuse();
StatsRegisterGlobalCounter("tcp.memuse", StreamTcpMemuseCounter);
StreamTcpReassembleInit(quiet);
/* set the default free function and flow state function
* values. */
FlowSetProtoFreeFunc(IPPROTO_TCP, StreamTcpSessionClear);
#ifdef UNITTESTS
if (RunmodeIsUnittests()) {
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
}
SCMutexUnlock(&ssn_pool_mutex);
}
#endif
}
void StreamTcpFreeConfig(char quiet)
{
SC_ATOMIC_DESTROY(stream_config.memcap);
SC_ATOMIC_DESTROY(stream_config.reassembly_memcap);
StreamTcpReassembleFree(quiet);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool != NULL) {
PoolThreadFree(ssn_pool);
ssn_pool = NULL;
}
SCMutexUnlock(&ssn_pool_mutex);
SCMutexDestroy(&ssn_pool_mutex);
SCLogDebug("ssn_pool_cnt %"PRIu64"", ssn_pool_cnt);
}
/** \internal
* \brief The function is used to to fetch a TCP session from the
* ssn_pool, when a TCP SYN is received.
*
* \param p packet starting the new TCP session.
* \param id thread pool id
*
* \retval ssn new TCP session.
*/
static TcpSession *StreamTcpNewSession (Packet *p, int id)
{
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
p->flow->protoctx = PoolThreadGetById(ssn_pool, id);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
if (p->flow->protoctx != NULL)
ssn_pool_cnt++;
SCMutexUnlock(&ssn_pool_mutex);
#endif
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
SCLogDebug("ssn_pool is empty");
return NULL;
}
ssn->state = TCP_NONE;
ssn->reassembly_depth = stream_config.reassembly_depth;
ssn->tcp_packet_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.flags = stream_config.stream_init_flags;
ssn->client.flags = stream_config.stream_init_flags;
StreamingBuffer x = STREAMING_BUFFER_INITIALIZER(&stream_config.sbcnf);
ssn->client.sb = x;
ssn->server.sb = x;
if (PKT_IS_TOSERVER(p)) {
ssn->client.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.tcp_flags = 0;
} else if (PKT_IS_TOCLIENT(p)) {
ssn->server.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->client.tcp_flags = 0;
}
}
return ssn;
}
static void StreamTcpPacketSetState(Packet *p, TcpSession *ssn,
uint8_t state)
{
if (state == ssn->state || PKT_IS_PSEUDOPKT(p))
return;
ssn->pstate = ssn->state;
ssn->state = state;
/* update the flow state */
switch(ssn->state) {
case TCP_ESTABLISHED:
case TCP_FIN_WAIT1:
case TCP_FIN_WAIT2:
case TCP_CLOSING:
case TCP_CLOSE_WAIT:
FlowUpdateState(p->flow, FLOW_STATE_ESTABLISHED);
break;
case TCP_LAST_ACK:
case TCP_TIME_WAIT:
case TCP_CLOSED:
FlowUpdateState(p->flow, FLOW_STATE_CLOSED);
break;
}
}
/**
* \brief Function to set the OS policy for the given stream based on the
* destination of the received packet.
*
* \param stream TcpStream of which os_policy needs to set
* \param p Packet which is used to set the os policy
*/
void StreamTcpSetOSPolicy(TcpStream *stream, Packet *p)
{
int ret = 0;
if (PKT_IS_IPV4(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv4HostOSFlavour((uint8_t *)GET_IPV4_DST_ADDR_PTR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
} else if (PKT_IS_IPV6(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv6HostOSFlavour((uint8_t *)GET_IPV6_DST_ADDR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
}
if (stream->os_policy == OS_POLICY_BSD_RIGHT)
stream->os_policy = OS_POLICY_BSD;
else if (stream->os_policy == OS_POLICY_OLD_SOLARIS)
stream->os_policy = OS_POLICY_SOLARIS;
SCLogDebug("Policy is %"PRIu8"", stream->os_policy);
}
/**
* \brief macro to update last_ack only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param ack ACK value to test and set
*/
#define StreamTcpUpdateLastAck(ssn, stream, ack) { \
if (SEQ_GT((ack), (stream)->last_ack)) \
{ \
SCLogDebug("ssn %p: last_ack set to %"PRIu32", moved %u forward", (ssn), (ack), (ack) - (stream)->last_ack); \
if ((SEQ_LEQ((stream)->last_ack, (stream)->next_seq) && SEQ_GT((ack),(stream)->next_seq))) { \
SCLogDebug("last_ack just passed next_seq: %u (was %u) > %u", (ack), (stream)->last_ack, (stream)->next_seq); \
} else { \
SCLogDebug("next_seq (%u) <> last_ack now %d", (stream)->next_seq, (int)(stream)->next_seq - (ack)); \
}\
(stream)->last_ack = (ack); \
StreamTcpSackPruneList((stream)); \
} else { \
SCLogDebug("ssn %p: no update: ack %u, last_ack %"PRIu32", next_seq %u (state %u)", \
(ssn), (ack), (stream)->last_ack, (stream)->next_seq, (ssn)->state); \
}\
}
#define StreamTcpAsyncLastAckUpdate(ssn, stream) { \
if ((ssn)->flags & STREAMTCP_FLAG_ASYNC) { \
if (SEQ_GT((stream)->next_seq, (stream)->last_ack)) { \
uint32_t ack_diff = (stream)->next_seq - (stream)->last_ack; \
(stream)->last_ack += ack_diff; \
SCLogDebug("ssn %p: ASYNC last_ack set to %"PRIu32", moved %u forward", \
(ssn), (stream)->next_seq, ack_diff); \
} \
} \
}
#define StreamTcpUpdateNextSeq(ssn, stream, seq) { \
(stream)->next_seq = seq; \
SCLogDebug("ssn %p: next_seq %" PRIu32, (ssn), (stream)->next_seq); \
StreamTcpAsyncLastAckUpdate((ssn), (stream)); \
}
/**
* \brief macro to update next_win only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param win window value to test and set
*/
#define StreamTcpUpdateNextWin(ssn, stream, win) { \
uint32_t sacked_size__ = StreamTcpSackedSize((stream)); \
if (SEQ_GT(((win) + sacked_size__), (stream)->next_win)) { \
(stream)->next_win = ((win) + sacked_size__); \
SCLogDebug("ssn %p: next_win set to %"PRIu32, (ssn), (stream)->next_win); \
} \
}
static int StreamTcpPacketIsRetransmission(TcpStream *stream, Packet *p)
{
if (p->payload_len == 0)
SCReturnInt(0);
/* retransmission of already partially ack'd data */
if (SEQ_LT(TCP_GET_SEQ(p), stream->last_ack) && SEQ_GT((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack))
{
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of already ack'd data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of in flight data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->next_seq)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(2);
}
SCLogDebug("seq %u payload_len %u => %u, last_ack %u, next_seq %u", TCP_GET_SEQ(p),
p->payload_len, (TCP_GET_SEQ(p) + p->payload_len), stream->last_ack, stream->next_seq);
SCReturnInt(0);
}
/**
* \internal
* \brief Function to handle the TCP_CLOSED or NONE state. The function handles
* packets while the session state is None which means a newly
* initialized structure, or a fully closed session.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateNone(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (p->tcph->th_flags & TH_RST) {
StreamTcpSetEvent(p, STREAM_RST_BUT_NO_SESSION);
SCLogDebug("RST packet received, no session setup");
return -1;
} else if (p->tcph->th_flags & TH_FIN) {
StreamTcpSetEvent(p, STREAM_FIN_BUT_NO_SESSION);
SCLogDebug("FIN packet received, no session setup");
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if (stream_config.midstream == FALSE &&
stream_config.async_oneside == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
StatsIncr(tv, stt->counter_tcp_midstream_pickups);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_SYN_RECV", ssn);
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM;
/* Flag used to change the direct in the later stage in the session */
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_SYNACK;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* sequence number & window */
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: server window %u", ssn, ssn->server.window);
ssn->client.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->client.last_ack = TCP_GET_ACK(p);
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
/** If the client has a wscale option the server had it too,
* so set the wscale for the server to max. Otherwise none
* will have the wscale opt just like it should. */
if (TCP_HAS_WSCALE(p)) {
ssn->client.wscale = TCP_GET_WSCALE(p);
ssn->server.wscale = TCP_WSCALE_MAX;
SCLogDebug("ssn %p: wscale enabled. client %u server %u",
ssn, ssn->client.wscale, ssn->server.wscale);
}
SCLogDebug("ssn %p: ssn->client.isn %"PRIu32", ssn->client.next_seq"
" %"PRIu32", ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
SCLogDebug("ssn %p: ssn->server.isn %"PRIu32", ssn->server.next_seq"
" %"PRIu32", ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
ssn->client.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SYN/ACK with SACK permitted, assuming "
"SACK permitted for both sides", ssn);
}
/* packet thinks it is in the wrong direction, flip it */
StreamTcpPacketSwitchDir(ssn, p);
} else if (p->tcph->th_flags & TH_SYN) {
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_SENT);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_SENT", ssn);
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
/* Set the stream timestamp value, if packet has timestamp option
* enabled. */
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->client.last_ts);
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
SCLogDebug("ssn %p: SACK permited on SYN packet", ssn);
}
SCLogDebug("ssn %p: ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", ssn->client.last_ack "
"%"PRIu32"", ssn, ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
} else if (p->tcph->th_flags & TH_ACK) {
if (stream_config.midstream == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
StatsIncr(tv, stt->counter_tcp_midstream_pickups);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_ESTABLISHED", ssn);
ssn->flags = STREAMTCP_FLAG_MIDSTREAM;
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/** window scaling for midstream pickups, we can't do much other
* than assume that it's set to the max value: 14 */
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->server.wscale = TCP_WSCALE_MAX;
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->client.isn %u, ssn->client.next_seq %u",
ssn, ssn->client.isn, ssn->client.next_seq);
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: ssn->client.next_win %"PRIu32", "
"ssn->server.next_win %"PRIu32"", ssn,
ssn->client.next_win, ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.last_ack %"PRIu32", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->client.last_ack, ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
ssn->server.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: assuming SACK permitted for both sides", ssn);
} else {
SCLogDebug("default case");
}
return 0;
}
/** \internal
* \brief Setup TcpStateQueue based on SYN/ACK packet
*/
static inline void StreamTcp3whsSynAckToStateQueue(Packet *p, TcpStateQueue *q)
{
q->flags = 0;
q->wscale = 0;
q->ts = 0;
q->win = TCP_GET_WINDOW(p);
q->seq = TCP_GET_SEQ(p);
q->ack = TCP_GET_ACK(p);
q->pkt_ts = p->ts.tv_sec;
if (TCP_GET_SACKOK(p) == 1)
q->flags |= STREAMTCP_QUEUE_FLAG_SACK;
if (TCP_HAS_WSCALE(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_WS;
q->wscale = TCP_GET_WSCALE(p);
}
if (TCP_HAS_TS(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_TS;
q->ts = TCP_GET_TSVAL(p);
}
}
/** \internal
* \brief Find the Queued SYN/ACK that is the same as this SYN/ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckBySynAck(TcpSession *ssn, Packet *p)
{
TcpStateQueue *q = ssn->queue;
TcpStateQueue search;
StreamTcp3whsSynAckToStateQueue(p, &search);
while (q != NULL) {
if (search.flags == q->flags &&
search.wscale == q->wscale &&
search.win == q->win &&
search.seq == q->seq &&
search.ack == q->ack &&
search.ts == q->ts) {
return q;
}
q = q->next;
}
return q;
}
static int StreamTcp3whsQueueSynAck(TcpSession *ssn, Packet *p)
{
/* first see if this is already in our list */
if (StreamTcp3whsFindSynAckBySynAck(ssn, p) != NULL)
return 0;
if (ssn->queue_len == stream_config.max_synack_queued) {
SCLogDebug("ssn %p: =~ SYN/ACK queue limit reached", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_FLOOD);
return -1;
}
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpStateQueue)) == 0) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: stream memcap reached", ssn);
return -1;
}
TcpStateQueue *q = SCMalloc(sizeof(*q));
if (unlikely(q == NULL)) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: alloc failed", ssn);
return -1;
}
memset(q, 0x00, sizeof(*q));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpStateQueue));
StreamTcp3whsSynAckToStateQueue(p, q);
/* put in list */
q->next = ssn->queue;
ssn->queue = q;
ssn->queue_len++;
return 0;
}
/** \internal
* \brief Find the Queued SYN/ACK that goes with this ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckByAck(TcpSession *ssn, Packet *p)
{
uint32_t ack = TCP_GET_SEQ(p);
uint32_t seq = TCP_GET_ACK(p) - 1;
TcpStateQueue *q = ssn->queue;
while (q != NULL) {
if (seq == q->seq &&
ack == q->ack) {
return q;
}
q = q->next;
}
return NULL;
}
/** \internal
* \brief Update SSN after receiving a valid SYN/ACK
*
* Normally we update the SSN from the SYN/ACK packet. But in case
* of queued SYN/ACKs, we can use one of those.
*
* \param ssn TCP session
* \param p Packet
* \param q queued state if used, NULL otherwise
*
* To make sure all SYN/ACK based state updates are in one place,
* this function can updated based on Packet or TcpStateQueue, where
* the latter takes precedence.
*/
static void StreamTcp3whsSynAckUpdate(TcpSession *ssn, Packet *p, TcpStateQueue *q)
{
TcpStateQueue update;
if (likely(q == NULL)) {
StreamTcp3whsSynAckToStateQueue(p, &update);
q = &update;
}
if (ssn->state != TCP_SYN_RECV) {
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_RECV", ssn);
}
/* sequence number & window */
ssn->server.isn = q->seq;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->client.window = q->win;
SCLogDebug("ssn %p: window %" PRIu32 "", ssn, ssn->server.window);
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if ((q->flags & STREAMTCP_QUEUE_FLAG_TS) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->server.last_ts = q->ts;
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = q->pkt_ts;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->client.last_ts = 0;
ssn->server.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->client.last_ack = q->ack;
ssn->server.last_ack = ssn->server.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(q->flags & STREAMTCP_QUEUE_FLAG_WS))
{
ssn->client.wscale = q->wscale;
} else {
ssn->client.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
(q->flags & STREAMTCP_QUEUE_FLAG_SACK)) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for session", ssn);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SACKOK;
}
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %" PRIu32 " "
"(ssn->client.last_ack %" PRIu32 ")", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack, ssn->client.last_ack);
/* unset the 4WHS flag as we received this SYN/ACK as part of a
* (so far) valid 3WHS */
if (ssn->flags & STREAMTCP_FLAG_4WHS)
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS unset, normal SYN/ACK"
" so considering 3WHS", ssn);
ssn->flags &=~ STREAMTCP_FLAG_4WHS;
}
/** \internal
* \brief detect timestamp anomalies when processing responses to the
* SYN packet.
* \retval true packet is ok
* \retval false packet is bad
*/
static inline bool StateSynSentValidateTimestamp(TcpSession *ssn, Packet *p)
{
/* we only care about evil server here, so skip TS packets */
if (PKT_IS_TOSERVER(p) || !(TCP_HAS_TS(p))) {
return true;
}
TcpStream *receiver_stream = &ssn->client;
uint32_t ts_echo = TCP_GET_TSECR(p);
if ((receiver_stream->flags & STREAMTCP_STREAM_FLAG_TIMESTAMP) != 0) {
if (receiver_stream->last_ts != 0 && ts_echo != 0 &&
ts_echo != receiver_stream->last_ts)
{
SCLogDebug("ssn %p: BAD TSECR echo %u recv %u", ssn,
ts_echo, receiver_stream->last_ts);
return false;
}
} else {
if (receiver_stream->last_ts == 0 && ts_echo != 0) {
SCLogDebug("ssn %p: BAD TSECR echo %u recv %u", ssn,
ts_echo, receiver_stream->last_ts);
return false;
}
}
return true;
}
/**
* \brief Function to handle the TCP_SYN_SENT state. The function handles
* SYN, SYN/ACK, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateSynSent(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
SCLogDebug("ssn %p: pkt received: %s", ssn, PKT_IS_TOCLIENT(p) ?
"toclient":"toserver");
/* check for bad responses */
if (StateSynSentValidateTimestamp(ssn, p) == false)
return -1;
/* RST */
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn) &&
SEQ_EQ(TCP_GET_WINDOW(p), 0) &&
SEQ_EQ(TCP_GET_ACK(p), (ssn->client.isn + 1)))
{
SCLogDebug("ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
SCLogDebug("ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
/* FIN */
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK received on 4WHS session", ssn);
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->server.isn + 1))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: 4WHS ACK mismatch, packet ACK %"PRIu32""
" != %" PRIu32 " from stream", ssn,
TCP_GET_ACK(p), ssn->server.isn + 1);
return -1;
}
/* Check if the SYN/ACK packet SEQ's the *FIRST* received SYN
* packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_SYN);
SCLogDebug("ssn %p: 4WHS SEQ mismatch, packet SEQ %"PRIu32""
" != %" PRIu32 " from *first* SYN pkt", ssn,
TCP_GET_SEQ(p), ssn->client.isn);
return -1;
}
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ 4WHS ssn state is now TCP_SYN_RECV", ssn);
/* sequence number & window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: 4WHS window %" PRIu32 "", ssn,
ssn->client.window);
/* Set the timestamp values used to validate the timestamp of
* received packets. */
if ((TCP_HAS_TS(p)) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: 4WHS ssn->client.last_ts %" PRIu32" "
"ssn->server.last_ts %" PRIu32"", ssn,
ssn->client.last_ts, ssn->server.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
ssn->server.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->client.last_ack = ssn->client.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(TCP_HAS_WSCALE(p)))
{
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->server.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for 4WHS session", ssn);
}
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
SCLogDebug("ssn %p: 4WHS ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: 4WHS ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %" PRIu32 " "
"(ssn->server.last_ack %" PRIu32 ")", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack, ssn->server.last_ack);
/* done here */
return 0;
}
if (PKT_IS_TOSERVER(p)) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_IN_WRONG_DIRECTION);
SCLogDebug("ssn %p: SYN/ACK received in the wrong direction", ssn);
return -1;
}
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.isn + 1))) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
return -1;
}
StreamTcp3whsSynAckUpdate(ssn, p, /* no queue override */NULL);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent", ssn);
if (ssn->flags & STREAMTCP_FLAG_4WHS) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent of "
"4WHS SYN", ssn);
}
if (PKT_IS_TOCLIENT(p)) {
/** a SYN only packet in the opposite direction could be:
* http://www.breakingpointsystems.com/community/blog/tcp-
* portals-the-three-way-handshake-is-a-lie
*
* \todo improve resetting the session */
/* indicate that we're dealing with 4WHS here */
ssn->flags |= STREAMTCP_FLAG_4WHS;
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS flag set", ssn);
/* set the sequence numbers and window for server
* We leave the ssn->client.isn in place as we will
* check the SYN/ACK pkt with that.
*/
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
/* Set the stream timestamp value, if packet has timestamp
* option enabled. */
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->server.last_ts);
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
} else {
ssn->flags &= ~STREAMTCP_FLAG_CLIENT_SACKOK;
}
SCLogDebug("ssn %p: 4WHS ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
}
/** \todo check if it's correct or set event */
} else if (p->tcph->th_flags & TH_ACK) {
/* Handle the asynchronous stream, when we receive a SYN packet
and now istead of receving a SYN/ACK we receive a ACK from the
same host, which sent the SYN, this suggests the ASNYC streams.*/
if (stream_config.async_oneside == FALSE)
return 0;
/* we are in AYNC (one side) mode now. */
/* one side async means we won't see a SYN/ACK, so we can
* only check the SYN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))) {
StreamTcpSetEvent(p, STREAM_3WHS_ASYNC_WRONG_SEQ);
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream",ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
return -1;
}
ssn->flags |= STREAMTCP_FLAG_ASYNC;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
ssn->client.window = TCP_GET_WINDOW(p);
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
/* Set the server side parameters */
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = ssn->server.next_seq;
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: synsent => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.next_seq %" PRIu32 ""
,ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->client.next_seq);
/* if SYN had wscale, assume it to be supported. Otherwise
* we know it not to be supported. */
if (ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) {
ssn->client.wscale = TCP_WSCALE_MAX;
}
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if (TCP_HAS_TS(p) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
} else {
ssn->client.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
if (ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_SYN_RECV state. The function handles
* SYN, SYN/ACK, ACK, FIN, RST packets and correspondingly changes
* the connection state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateSynRecv(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
uint8_t reset = TRUE;
/* After receiveing the RST in SYN_RECV state and if detection
evasion flags has been set, then the following operating
systems will not closed the connection. As they consider the
packet as stray packet and not belonging to the current
session, for more information check
http://www.packetstan.com/2010/06/recently-ive-been-on-campaign-to-make.html */
if (ssn->flags & STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT) {
if (PKT_IS_TOSERVER(p)) {
if ((ssn->server.os_policy == OS_POLICY_LINUX) ||
(ssn->server.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->server.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
} else {
if ((ssn->client.os_policy == OS_POLICY_LINUX) ||
(ssn->client.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->client.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
}
}
if (reset == TRUE) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
}
} else if (p->tcph->th_flags & TH_FIN) {
/* FIN is handled in the same way as in TCP_ESTABLISHED case */;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state SYN_RECV. resent", ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_TOSERVER_ON_SYN_RECV);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN/ACK packet, server resend with different ISN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.isn);
if (StreamTcp3whsQueueSynAck(ssn, p) == -1)
return -1;
SCLogDebug("ssn %p: queued different SYN/ACK", ssn);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_RECV... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_TOCLIENT_ON_SYN_RECV);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_RESEND_DIFF_SEQ_ON_SYN_RECV);
return -1;
}
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->queue_len) {
SCLogDebug("ssn %p: checking ACK against queued SYN/ACKs", ssn);
TcpStateQueue *q = StreamTcp3whsFindSynAckByAck(ssn, p);
if (q != NULL) {
SCLogDebug("ssn %p: here we update state against queued SYN/ACK", ssn);
StreamTcp3whsSynAckUpdate(ssn, p, /* using queue to update state */q);
} else {
SCLogDebug("ssn %p: none found, now checking ACK against original SYN/ACK (state)", ssn);
}
}
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323)*/
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!(StreamTcpValidateTimestamp(ssn, p))) {
return -1;
}
}
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: ACK received on 4WHS session",ssn);
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))) {
SCLogDebug("ssn %p: 4WHS wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: 4WHS invalid ack nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_INVALID_ACK);
return -1;
}
SCLogDebug("4WHS normal pkt");
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.next_win, ssn->client.last_ack);
return 0;
}
bool ack_indicates_missed_3whs_ack_packet = false;
/* Check if the ACK received is in right direction. But when we have
* picked up a mid stream session after missing the initial SYN pkt,
* in this case the ACK packet can arrive from either client (normal
* case) or from server itself (asynchronous streams). Therefore
* the check has been avoided in this case */
if (PKT_IS_TOCLIENT(p)) {
/* special case, handle 4WHS, so SYN/ACK in the opposite
* direction */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK) {
SCLogDebug("ssn %p: ACK received on midstream SYN/ACK "
"pickup session",ssn);
/* fall through */
} else {
/* if we missed traffic between the S/SA and the current
* 'wrong direction' ACK, we could end up here. In IPS
* reject it. But in IDS mode we continue.
*
* IPS rejects as it should see all packets, so pktloss
* should lead to retransmissions. As this can also be
* pattern for MOTS/MITM injection attacks, we need to be
* careful.
*/
if (StreamTcpInlineMode()) {
if (p->payload_len > 0 &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) &&
SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
/* packet loss is possible but unlikely here */
SCLogDebug("ssn %p: possible data injection", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_DATA_INJECT);
return -1;
}
SCLogDebug("ssn %p: ACK received in the wrong direction",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_IN_WRONG_DIR);
return -1;
}
ack_indicates_missed_3whs_ack_packet = true;
}
}
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ""
", ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
/* Check both seq and ack number before accepting the packet and
changing to ESTABLISHED state */
if ((SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq)) {
SCLogDebug("normal pkt");
/* process the packet normal, No Async streams :) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
if (!(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)) {
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* If asynchronous stream handling is allowed then set the session,
if packet's seq number is equal the expected seq no.*/
} else if (stream_config.async_oneside == TRUE &&
(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)))
{
/*set the ASYNC flag used to indicate the session as async stream
and helps in relaxing the windows checks.*/
ssn->flags |= STREAMTCP_FLAG_ASYNC;
ssn->server.next_seq += p->payload_len;
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_ACK(p);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->server.window = TCP_GET_WINDOW(p);
ssn->client.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
SCLogDebug("ssn %p: synrecv => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->server.next_seq %" PRIu32 "\n"
, ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->server.next_seq);
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
/* Upon receiving the packet with correct seq number and wrong
ACK number, it causes the other end to send RST. But some target
system (Linux & solaris) does not RST the connection, so it is
likely to avoid the detection */
} else if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)){
ssn->flags |= STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT;
SCLogDebug("ssn %p: wrong ack nr on packet, possible evasion!!",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_RIGHT_SEQ_WRONG_ACK_EVASION);
return -1;
/* if we get a packet with a proper ack, but a seq that is beyond
* next_seq but in-window, we probably missed some packets */
} else if (SEQ_GT(TCP_GET_SEQ(p), ssn->client.next_seq) &&
SEQ_LEQ(TCP_GET_SEQ(p),ssn->client.next_win) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq))
{
SCLogDebug("ssn %p: ACK for missing data", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ACK for missing data: ssn->client.next_seq %u", ssn, ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p);
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* toclient packet: after having missed the 3whs's final ACK */
} else if (ack_indicates_missed_3whs_ack_packet &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) &&
SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
{
SCLogDebug("ssn %p: packet fits perfectly after a missed 3whs-ACK", ssn);
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_WRONG_SEQ_WRONG_ACK);
return -1;
}
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.next_win, ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the client to server. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly.
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToServer(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
"ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &(ssn->server), p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->client.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->client.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: server => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
"%" PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* update the last_ack to current seq number as the session is
* async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ."
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
} else if (SEQ_EQ(ssn->client.last_ack, (ssn->client.isn + 1)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :(*/
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->client.last_ack, ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->client.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->client.last_ack, ssn->client.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: server => SEQ before last_ack, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
SCLogDebug("ssn %p: rejecting because pkt before last_ack", ssn);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->client.next_seq && ssn->client.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->client.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (started before next_seq, ended after)",
ssn, ssn->client.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->client.next_seq, ssn->client.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->client.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->client.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->client.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->client.last_ack);
}
/* in window check */
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
SCLogDebug("ssn %p: ssn->server.window %"PRIu32"", ssn,
ssn->server.window);
/* Check if the ACK value is sane and inside the window limit */
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
SCLogDebug("ack %u last_ack %u next_seq %u", TCP_GET_ACK(p), ssn->server.last_ack, ssn->server.next_seq);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
/* handle data (if any) */
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: toserver => SEQ out of window, packet SEQ "
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
(TCP_GET_SEQ(p) + p->payload_len) - ssn->client.next_win);
SCLogDebug("ssn %p: window %u sacked %u", ssn, ssn->client.window,
StreamTcpSackedSize(&ssn->client));
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the server to client. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToClient(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ","
" ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* To get the server window value from the servers packet, when connection
is picked up as midstream */
if ((ssn->flags & STREAMTCP_FLAG_MIDSTREAM) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED))
{
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->flags &= ~STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
SCLogDebug("ssn %p: adjusted midstream ssn->server.next_win to "
"%" PRIu32 "", ssn, ssn->server.next_win);
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->server.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->server.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: client => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
" %"PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
ssn->server.last_ack = TCP_GET_SEQ(p);
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->server.last_ack, ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->server.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32". next_seq %"PRIu32,
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->server.next_seq && ssn->server.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->server.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32
" (started before next_seq, ended after)",
ssn, ssn->server.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->server.next_seq, ssn->server.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->server.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->server.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->server.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->server.last_ack);
}
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
SCLogDebug("ssn %p: ssn->client.window %"PRIu32"", ssn,
ssn->client.window);
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->client, p);
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: client => SEQ out of window, packet SEQ"
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->server.last_ack %" PRIu32 ", ssn->server.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \internal
*
* \brief Find the highest sequence number needed to consider all segments as ACK'd
*
* Used to treat all segments as ACK'd upon receiving a valid RST.
*
* \param stream stream to inspect the segments from
* \param seq sequence number to check against
*
* \retval ack highest ack we need to set
*/
static inline uint32_t StreamTcpResetGetMaxAck(TcpStream *stream, uint32_t seq)
{
uint32_t ack = seq;
if (STREAM_HAS_SEEN_DATA(stream)) {
const uint32_t tail_seq = STREAM_SEQ_RIGHT_EDGE(stream);
if (SEQ_GT(tail_seq, ack)) {
ack = tail_seq;
}
}
SCReturnUInt(ack);
}
/**
* \brief Function to handle the TCP_ESTABLISHED state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state. The function handles the data inside packets and call
* StreamTcpReassembleHandleSegment(tv, ) to handle the reassembling.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateEstablished(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_ACK(p);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len + 1;
ssn->client.next_seq = TCP_GET_ACK(p);
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
SCLogDebug("ssn (%p: FIN received SEQ"
" %" PRIu32 ", last ACK %" PRIu32 ", next win %"PRIu32","
" win %" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack, ssn->server.next_win,
ssn->server.window);
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent",
ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in ESTABLISHED state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_TOSERVER);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFF_SEQ);
return -1;
}
if (ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED) {
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND);
return -1;
}
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent. "
"Likely due server not receiving final ACK in 3whs", ssn);
return 0;
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state ESTABLISHED... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in EST state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_TOCLIENT);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND_DIFF_SEQ);
return -1;
}
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
/* Urgent pointer size can be more than the payload size, as it tells
* the future coming data from the sender will be handled urgently
* until data of size equal to urgent offset has been processed
* (RFC 2147) */
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
/* Process the received packet to server */
HandleEstablishedPacketToServer(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->client.next_seq, ssn->server.last_ack
,ssn->client.next_win, ssn->client.window);
} else { /* implied to client */
if (!(ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED)) {
ssn->flags |= STREAMTCP_FLAG_3WHS_CONFIRMED;
SCLogDebug("3whs is now confirmed by server");
}
/* Process the received packet to client */
HandleEstablishedPacketToClient(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack,
ssn->server.next_win, ssn->server.window);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the FIN packets for states TCP_SYN_RECV and
* TCP_ESTABLISHED and changes to another TCP state as required.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *stt,
TcpSession *ssn, Packet *p, PacketQueue *pq)
{
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
" ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_CLOSE_WAIT);
SCLogDebug("ssn %p: state changed to TCP_CLOSE_WAIT", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->client.next_seq %" PRIu32 "", ssn,
ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->client.next_seq, ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ", "
"ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream (last_ack %u win %u = %u)", ssn, TCP_GET_SEQ(p),
ssn->server.next_seq, ssn->server.last_ack, ssn->server.window, (ssn->server.last_ack + ssn->server.window));
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT1);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT1", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->server.next_seq, ssn->client.last_ack);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT1 state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpPacketStateFinWait1(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if ((p->tcph->th_flags & (TH_FIN|TH_ACK)) == (TH_FIN|TH_ACK)) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait1", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
if (TCP_GET_SEQ(p) == ssn->client.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
if (TCP_GET_SEQ(p) == ssn->server.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn (%p): default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT2 state. The function handles
* ACK, RST, FIN packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateFinWait2(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait2", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSING state. Upon arrival of ACK
* the connection goes to TCP_TIME_WAIT state. The state has been
* reached as both end application has been closed.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateClosing(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on Closing", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->client.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->server.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("StreamTcpPacketStateClosing (%p): =+ next SEQ "
"%" PRIu32 ", last ACK %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSE_WAIT state. Upon arrival of FIN
* packet from server the connection goes to TCP_LAST_ACK state.
* The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateCloseWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
SCEnter();
if (ssn == NULL) {
SCReturnInt(-1);
}
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
}
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
/* don't update to LAST_ACK here as we want a toclient FIN for that */
if (!retransmission)
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_LAST_ACK);
SCLogDebug("ssn %p: state changed to TCP_LAST_ACK", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on CloseWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
SCReturnInt(-1);
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->client.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->server.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
SCReturnInt(0);
}
/**
* \brief Function to handle the TCP_LAST_ACK state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool. The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateLastAck(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
SCLogDebug("ssn (%p): FIN pkt on LastAck", ssn);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on LastAck", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_LASTACK_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: not updating state as packet is before next_seq", ssn);
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq + 1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_LASTACK_ACK_WRONG_SEQ);
return -1;
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_TIME_WAIT state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateTimeWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on TimeWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq+1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->server.next_seq && TCP_GET_SEQ(p) != ssn->server.next_seq+1) {
if (p->payload_len > 0 && TCP_GET_SEQ(p) == ssn->server.last_ack) {
SCLogDebug("ssn %p: -> retransmission", ssn);
SCReturnInt(0);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
static int StreamTcpPacketStateClosed(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
SCLogDebug("RST on closed state");
return 0;
}
TcpStream *stream = NULL, *ostream = NULL;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
SCLogDebug("stream %s ostream %s",
stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV?"true":"false",
ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV ? "true":"false");
/* if we've seen a RST on our direction, but not on the other
* see if we perhaps need to continue processing anyway. */
if ((stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) == 0) {
if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->pstate) < 0)
return -1;
}
}
return 0;
}
static void StreamTcpPacketCheckPostRst(TcpSession *ssn, Packet *p)
{
if (p->flags & PKT_PSEUDO_STREAM_END) {
return;
}
/* more RSTs are not unusual */
if ((p->tcph->th_flags & (TH_RST)) != 0) {
return;
}
TcpStream *ostream = NULL;
if (PKT_IS_TOSERVER(p)) {
ostream = &ssn->server;
} else {
ostream = &ssn->client;
}
if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {
SCLogDebug("regular packet %"PRIu64" from same sender as "
"the previous RST. Looks like it injected!", p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpSetEvent(p, STREAM_SUSPECTED_RST_INJECT);
return;
}
return;
}
/**
* \retval 1 packet is a keep alive pkt
* \retval 0 packet is not a keep alive pkt
*/
static int StreamTcpPacketIsKeepAlive(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/*
rfc 1122:
An implementation SHOULD send a keep-alive segment with no
data; however, it MAY be configurable to send a keep-alive
segment containing one garbage octet, for compatibility with
erroneous TCP implementations.
*/
if (p->payload_len > 1)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0) {
return 0;
}
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
if (ack == ostream->last_ack && seq == (stream->next_seq - 1)) {
SCLogDebug("packet is TCP keep-alive: %"PRIu64, p->pcap_cnt);
stream->flags |= STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, (stream->next_seq - 1), ack, ostream->last_ack);
return 0;
}
/**
* \retval 1 packet is a keep alive ACK pkt
* \retval 0 packet is not a keep alive ACK pkt
*/
static int StreamTcpPacketIsKeepAliveACK(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/* should get a normal ACK to a Keep Alive */
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win != ostream->window)
return 0;
if ((ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) && ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP keep-aliveACK: %"PRIu64, p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u) FLAG_KEEPALIVE: %s", seq, stream->next_seq, ack, ostream->last_ack,
ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE ? "set" : "not set");
return 0;
}
static void StreamTcpClearKeepAliveFlag(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL;
if (p->flags & PKT_PSEUDO_STREAM_END)
return;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
} else {
stream = &ssn->server;
}
if (stream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) {
stream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
SCLogDebug("FLAG_KEEPALIVE cleared");
}
}
/**
* \retval 1 packet is a window update pkt
* \retval 0 packet is not a window update pkt
*/
static int StreamTcpPacketIsWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED)
return 0;
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win == ostream->window)
return 0;
if (ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP window update: %"PRIu64, p->pcap_cnt);
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/**
* Try to detect whether a packet is a valid FIN 4whs final ack.
*
*/
static int StreamTcpPacketIsFinShutdownAck(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (!(ssn->state == TCP_TIME_WAIT || ssn->state == TCP_CLOSE_WAIT || ssn->state == TCP_LAST_ACK))
return 0;
if (p->tcph->th_flags != TH_ACK)
return 0;
if (p->payload_len != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
SCLogDebug("%"PRIu64", seq %u ack %u stream->next_seq %u ostream->next_seq %u",
p->pcap_cnt, seq, ack, stream->next_seq, ostream->next_seq);
if (SEQ_EQ(stream->next_seq + 1, seq) && SEQ_EQ(ack, ostream->next_seq + 1)) {
return 1;
}
return 0;
}
/**
* Try to detect packets doing bad window updates
*
* See bug 1238.
*
* Find packets that are unexpected, and shrink the window to the point
* where the packets we do expect are rejected for being out of window.
*
* The logic we use here is:
* - packet seq > next_seq
* - packet ack > next_seq (packet acks unseen data)
* - packet shrinks window more than it's own data size
* - packet shrinks window more than the diff between it's ack and the
* last_ack value
*
* Packets coming in after packet loss can look quite a bit like this.
*/
static int StreamTcpPacketIsBadWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED || ssn->state == TCP_CLOSED)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win < ostream->window) {
uint32_t diff = ostream->window - pkt_win;
if (diff > p->payload_len &&
SEQ_GT(ack, ostream->next_seq) &&
SEQ_GT(seq, stream->next_seq))
{
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u, diff %u, dsize %u",
p->pcap_cnt, pkt_win, ostream->window, diff, p->payload_len);
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u",
p->pcap_cnt, pkt_win, ostream->window);
SCLogDebug("%"PRIu64", seq %u ack %u ostream->next_seq %u ostream->last_ack %u, ostream->next_win %u, diff %u (%u)",
p->pcap_cnt, seq, ack, ostream->next_seq, ostream->last_ack, ostream->next_win,
ostream->next_seq - ostream->last_ack, stream->next_seq - stream->last_ack);
/* get the expected window shrinking from looking at ack vs last_ack.
* Observed a lot of just a little overrunning that value. So added some
* margin that is still ok. To make sure this isn't a loophole to still
* close the window, this is limited to windows above 1024. Both values
* are rather arbitrary. */
uint32_t adiff = ack - ostream->last_ack;
if (((pkt_win > 1024) && (diff > (adiff + 32))) ||
((pkt_win <= 1024) && (diff > adiff)))
{
SCLogDebug("pkt ACK %u is %u bytes beyond last_ack %u, shrinks window by %u "
"(allowing 32 bytes extra): pkt WIN %u", ack, adiff, ostream->last_ack, diff, pkt_win);
SCLogDebug("%u - %u = %u (state %u)", diff, adiff, diff - adiff, ssn->state);
StreamTcpSetEvent(p, STREAM_PKT_BAD_WINDOW_UPDATE);
return 1;
}
}
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/** \internal
* \brief call packet handling function for 'state'
* \param state current TCP state
*/
static inline int StreamTcpStateDispatch(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq,
const uint8_t state)
{
SCLogDebug("ssn: %p", ssn);
switch (state) {
case TCP_SYN_SENT:
if (StreamTcpPacketStateSynSent(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_SYN_RECV:
if (StreamTcpPacketStateSynRecv(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_ESTABLISHED:
if (StreamTcpPacketStateEstablished(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_FIN_WAIT1:
SCLogDebug("packet received on TCP_FIN_WAIT1 state");
if (StreamTcpPacketStateFinWait1(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_FIN_WAIT2:
SCLogDebug("packet received on TCP_FIN_WAIT2 state");
if (StreamTcpPacketStateFinWait2(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSING:
SCLogDebug("packet received on TCP_CLOSING state");
if (StreamTcpPacketStateClosing(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSE_WAIT:
SCLogDebug("packet received on TCP_CLOSE_WAIT state");
if (StreamTcpPacketStateCloseWait(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_LAST_ACK:
SCLogDebug("packet received on TCP_LAST_ACK state");
if (StreamTcpPacketStateLastAck(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_TIME_WAIT:
SCLogDebug("packet received on TCP_TIME_WAIT state");
if (StreamTcpPacketStateTimeWait(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSED:
/* TCP session memory is not returned to pool until timeout. */
SCLogDebug("packet received on closed state");
if (StreamTcpPacketStateClosed(tv, p, stt, ssn, pq)) {
return -1;
}
break;
default:
SCLogDebug("packet received on default state");
break;
}
return 0;
}
/* flow is and stays locked */
int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt,
PacketQueue *pq)
{
SCEnter();
DEBUG_ASSERT_FLOW_LOCKED(p->flow);
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
/* assign the thread id to the flow */
if (unlikely(p->flow->thread_id == 0)) {
p->flow->thread_id = (FlowThreadId)tv->id;
} else if (unlikely((FlowThreadId)tv->id != p->flow->thread_id)) {
SCLogDebug("wrong thread: flow has %u, we are %d", p->flow->thread_id, tv->id);
if (p->pkt_src == PKT_SRC_WIRE) {
StatsIncr(tv, stt->counter_tcp_wrong_thread);
if ((p->flow->flags & FLOW_WRONG_THREAD) == 0) {
p->flow->flags |= FLOW_WRONG_THREAD;
StreamTcpSetEvent(p, STREAM_WRONG_THREAD);
}
}
}
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
/* track TCP flags */
if (ssn != NULL) {
ssn->tcp_packet_flags |= p->tcph->th_flags;
if (PKT_IS_TOSERVER(p))
ssn->client.tcp_flags |= p->tcph->th_flags;
else if (PKT_IS_TOCLIENT(p))
ssn->server.tcp_flags |= p->tcph->th_flags;
/* check if we need to unset the ASYNC flag */
if (ssn->flags & STREAMTCP_FLAG_ASYNC &&
ssn->client.tcp_flags != 0 &&
ssn->server.tcp_flags != 0)
{
SCLogDebug("ssn %p: removing ASYNC flag as we have packets on both sides", ssn);
ssn->flags &= ~STREAMTCP_FLAG_ASYNC;
}
}
/* update counters */
if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
StatsIncr(tv, stt->counter_tcp_synack);
} else if (p->tcph->th_flags & (TH_SYN)) {
StatsIncr(tv, stt->counter_tcp_syn);
}
if (p->tcph->th_flags & (TH_RST)) {
StatsIncr(tv, stt->counter_tcp_rst);
}
/* broken TCP http://ask.wireshark.org/questions/3183/acknowledgment-number-broken-tcp-the-acknowledge-field-is-nonzero-while-the-ack-flag-is-not-set */
if (!(p->tcph->th_flags & TH_ACK) && TCP_GET_ACK(p) != 0) {
StreamTcpSetEvent(p, STREAM_PKT_BROKEN_ACK);
}
/* If we are on IPS mode, and got a drop action triggered from
* the IP only module, or from a reassembled msg and/or from an
* applayer detection, then drop the rest of the packets of the
* same stream and avoid inspecting it any further */
if (StreamTcpCheckFlowDrops(p) == 1) {
SCLogDebug("This flow/stream triggered a drop rule");
FlowSetNoPacketInspectionFlag(p->flow);
DecodeSetNoPacketInspectionFlag(p);
StreamTcpDisableAppLayer(p->flow);
PACKET_DROP(p);
/* return the segments to the pool */
StreamTcpSessionPktFree(p);
SCReturnInt(0);
}
if (ssn == NULL || ssn->state == TCP_NONE) {
if (StreamTcpPacketStateNone(tv, p, stt, ssn, &stt->pseudo_queue) == -1) {
goto error;
}
if (ssn != NULL)
SCLogDebug("ssn->alproto %"PRIu16"", p->flow->alproto);
} else {
/* special case for PKT_PSEUDO_STREAM_END packets:
* bypass the state handling and various packet checks,
* we care about reassembly here. */
if (p->flags & PKT_PSEUDO_STREAM_END) {
if (PKT_IS_TOCLIENT(p)) {
ssn->client.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
ssn->server.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
}
/* straight to 'skip' as we already handled reassembly */
goto skip;
}
/* check if the packet is in right direction, when we missed the
SYN packet and picked up midstream session. */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)
StreamTcpPacketSwitchDir(ssn, p);
if (StreamTcpPacketIsKeepAlive(ssn, p) == 1) {
goto skip;
}
if (StreamTcpPacketIsKeepAliveACK(ssn, p) == 1) {
StreamTcpClearKeepAliveFlag(ssn, p);
goto skip;
}
StreamTcpClearKeepAliveFlag(ssn, p);
/* if packet is not a valid window update, check if it is perhaps
* a bad window update that we should ignore (and alert on) */
if (StreamTcpPacketIsFinShutdownAck(ssn, p) == 0)
if (StreamTcpPacketIsWindowUpdate(ssn, p) == 0)
if (StreamTcpPacketIsBadWindowUpdate(ssn,p))
goto skip;
/* handle the per 'state' logic */
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->state) < 0)
goto error;
skip:
StreamTcpPacketCheckPostRst(ssn, p);
if (ssn->state >= TCP_ESTABLISHED) {
p->flags |= PKT_STREAM_EST;
}
}
/* deal with a pseudo packet that is created upon receiving a RST
* segment. To be sure we process both sides of the connection, we
* inject a fake packet into the system, forcing reassembly of the
* opposing direction.
* There should be only one, but to be sure we do a while loop. */
if (ssn != NULL) {
while (stt->pseudo_queue.len > 0) {
SCLogDebug("processing pseudo packet / stream end");
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
/* process the opposing direction of the original packet */
if (PKT_IS_TOSERVER(np)) {
SCLogDebug("pseudo packet is to server");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, np, NULL);
} else {
SCLogDebug("pseudo packet is to client");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, np, NULL);
}
/* enqueue this packet so we inspect it in detect etc */
PacketEnqueue(pq, np);
}
SCLogDebug("processing pseudo packet / stream end done");
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
/* check for conditions that may make us not want to log this packet */
/* streams that hit depth */
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
}
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ||
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
/* encrypted packets */
if ((PKT_IS_TOSERVER(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) ||
(PKT_IS_TOCLIENT(p) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
if (ssn->flags & STREAMTCP_FLAG_BYPASS) {
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
/* if stream is dead and we have no detect engine at all, bypass. */
} else if (g_detect_disabled &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
StreamTcpBypassEnabled())
{
SCLogDebug("bypass as stream is dead and we have no rules");
PacketBypassCallback(p);
}
}
SCReturnInt(0);
error:
/* make sure we don't leave packets in our pseudo queue */
while (stt->pseudo_queue.len > 0) {
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
PacketEnqueue(pq, np);
}
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
if (StreamTcpInlineDropInvalid()) {
/* disable payload inspection as we're dropping this packet
* anyway. Doesn't disable all detection, so we can still
* match on the stream event that was set. */
DecodeSetNoPayloadInspectionFlag(p);
PACKET_DROP(p);
}
SCReturnInt(-1);
}
/**
* \brief Function to validate the checksum of the received packet. If the
* checksum is invalid, packet will be dropped, as the end system will
* also drop the packet.
*
* \param p Packet of which checksum has to be validated
* \retval 1 if the checksum is valid, otherwise 0
*/
static inline int StreamTcpValidateChecksum(Packet *p)
{
int ret = 1;
if (p->flags & PKT_IGNORE_CHECKSUM)
return ret;
if (p->level4_comp_csum == -1) {
if (PKT_IS_IPV4(p)) {
p->level4_comp_csum = TCPChecksum(p->ip4h->s_ip_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
} else if (PKT_IS_IPV6(p)) {
p->level4_comp_csum = TCPV6Checksum(p->ip6h->s_ip6_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
}
}
if (p->level4_comp_csum != 0) {
ret = 0;
if (p->livedev) {
(void) SC_ATOMIC_ADD(p->livedev->invalid_checksums, 1);
} else if (p->pcap_cnt) {
PcapIncreaseInvalidChecksum();
}
}
return ret;
}
/** \internal
* \brief check if a packet is a valid stream started
* \retval bool true/false */
static int TcpSessionPacketIsStreamStarter(const Packet *p)
{
if (p->tcph->th_flags == TH_SYN) {
SCLogDebug("packet %"PRIu64" is a stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
SCLogDebug("packet %"PRIu64" is a midstream stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
}
return 0;
}
/** \internal
* \brief Check if Flow and TCP SSN allow this flow/tuple to be reused
* \retval bool true yes reuse, false no keep tracking old ssn */
static int TcpSessionReuseDoneEnoughSyn(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOSERVER) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->client.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \internal
* \brief check if ssn is done enough for reuse by syn/ack
* \note should only be called if midstream is enabled
*/
static int TcpSessionReuseDoneEnoughSynAck(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOCLIENT) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->server.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \brief Check if SSN is done enough for reuse
*
* Reuse means a new TCP session reuses the tuple (flow in suri)
*
* \retval bool true if ssn can be reused, false if not */
static int TcpSessionReuseDoneEnough(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (p->tcph->th_flags == TH_SYN) {
return TcpSessionReuseDoneEnoughSyn(p, f, ssn);
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
return TcpSessionReuseDoneEnoughSynAck(p, f, ssn);
}
}
return 0;
}
int TcpSessionPacketSsnReuse(const Packet *p, const Flow *f, const void *tcp_ssn)
{
if (p->proto == IPPROTO_TCP && p->tcph != NULL) {
if (TcpSessionPacketIsStreamStarter(p) == 1) {
if (TcpSessionReuseDoneEnough(p, f, tcp_ssn) == 1) {
return 1;
}
}
}
return 0;
}
TmEcode StreamTcp (ThreadVars *tv, Packet *p, void *data, PacketQueue *pq, PacketQueue *postpq)
{
StreamTcpThread *stt = (StreamTcpThread *)data;
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
if (!(PKT_IS_TCP(p))) {
return TM_ECODE_OK;
}
if (p->flow == NULL) {
StatsIncr(tv, stt->counter_tcp_no_flow);
return TM_ECODE_OK;
}
/* only TCP packets with a flow from here */
if (!(p->flags & PKT_PSEUDO_STREAM_END)) {
if (stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION) {
if (StreamTcpValidateChecksum(p) == 0) {
StatsIncr(tv, stt->counter_tcp_invalid_checksum);
return TM_ECODE_OK;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM; //TODO check that this is set at creation
}
AppLayerProfilingReset(stt->ra_ctx->app_tctx);
(void)StreamTcpPacket(tv, p, stt, pq);
return TM_ECODE_OK;
}
TmEcode StreamTcpThreadInit(ThreadVars *tv, void *initdata, void **data)
{
SCEnter();
StreamTcpThread *stt = SCMalloc(sizeof(StreamTcpThread));
if (unlikely(stt == NULL))
SCReturnInt(TM_ECODE_FAILED);
memset(stt, 0, sizeof(StreamTcpThread));
stt->ssn_pool_id = -1;
*data = (void *)stt;
stt->counter_tcp_sessions = StatsRegisterCounter("tcp.sessions", tv);
stt->counter_tcp_ssn_memcap = StatsRegisterCounter("tcp.ssn_memcap_drop", tv);
stt->counter_tcp_pseudo = StatsRegisterCounter("tcp.pseudo", tv);
stt->counter_tcp_pseudo_failed = StatsRegisterCounter("tcp.pseudo_failed", tv);
stt->counter_tcp_invalid_checksum = StatsRegisterCounter("tcp.invalid_checksum", tv);
stt->counter_tcp_no_flow = StatsRegisterCounter("tcp.no_flow", tv);
stt->counter_tcp_syn = StatsRegisterCounter("tcp.syn", tv);
stt->counter_tcp_synack = StatsRegisterCounter("tcp.synack", tv);
stt->counter_tcp_rst = StatsRegisterCounter("tcp.rst", tv);
stt->counter_tcp_midstream_pickups = StatsRegisterCounter("tcp.midstream_pickups", tv);
stt->counter_tcp_wrong_thread = StatsRegisterCounter("tcp.pkt_on_wrong_thread", tv);
/* init reassembly ctx */
stt->ra_ctx = StreamTcpReassembleInitThreadCtx(tv);
if (stt->ra_ctx == NULL)
SCReturnInt(TM_ECODE_FAILED);
stt->ra_ctx->counter_tcp_segment_memcap = StatsRegisterCounter("tcp.segment_memcap_drop", tv);
stt->ra_ctx->counter_tcp_stream_depth = StatsRegisterCounter("tcp.stream_depth_reached", tv);
stt->ra_ctx->counter_tcp_reass_gap = StatsRegisterCounter("tcp.reassembly_gap", tv);
stt->ra_ctx->counter_tcp_reass_overlap = StatsRegisterCounter("tcp.overlap", tv);
stt->ra_ctx->counter_tcp_reass_overlap_diff_data = StatsRegisterCounter("tcp.overlap_diff_data", tv);
stt->ra_ctx->counter_tcp_reass_data_normal_fail = StatsRegisterCounter("tcp.insert_data_normal_fail", tv);
stt->ra_ctx->counter_tcp_reass_data_overlap_fail = StatsRegisterCounter("tcp.insert_data_overlap_fail", tv);
stt->ra_ctx->counter_tcp_reass_list_fail = StatsRegisterCounter("tcp.insert_list_fail", tv);
SCLogDebug("StreamTcp thread specific ctx online at %p, reassembly ctx %p",
stt, stt->ra_ctx);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
stt->ssn_pool_id = 0;
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
} else {
/* grow ssn_pool until we have a element for our thread id */
stt->ssn_pool_id = PoolThreadGrow(ssn_pool,
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
}
SCMutexUnlock(&ssn_pool_mutex);
if (stt->ssn_pool_id < 0 || ssn_pool == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "failed to setup/expand stream session pool. Expand stream.memcap?");
SCReturnInt(TM_ECODE_FAILED);
}
SCReturnInt(TM_ECODE_OK);
}
TmEcode StreamTcpThreadDeinit(ThreadVars *tv, void *data)
{
SCEnter();
StreamTcpThread *stt = (StreamTcpThread *)data;
if (stt == NULL) {
return TM_ECODE_OK;
}
/* XXX */
/* free reassembly ctx */
StreamTcpReassembleFreeThreadCtx(stt->ra_ctx);
/* clear memory */
memset(stt, 0, sizeof(StreamTcpThread));
SCFree(stt);
SCReturnInt(TM_ECODE_OK);
}
/**
* \brief Function to check the validity of the RST packets based on the
* target OS of the given packet.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 0 unacceptable RST
* \retval 1 acceptable RST
*
* WebSense sends RST packets that are:
* - RST flag, win 0, ack 0, seq = nextseq
*
*/
static int StreamTcpValidateRst(TcpSession *ssn, Packet *p)
{
uint8_t os_policy;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p)) {
SCReturnInt(0);
}
}
/* Set up the os_policy to be used in validating the RST packets based on
target system */
if (PKT_IS_TOSERVER(p)) {
if (ssn->server.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->server, p);
os_policy = ssn->server.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
} else {
if (ssn->client.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->client, p);
os_policy = ssn->client.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
}
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
if (PKT_IS_TOSERVER(p)) {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
} else {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
}
SCLogDebug("ssn %p: ASYNC reject RST", ssn);
return 0;
}
switch (os_policy) {
case OS_POLICY_HPUX11:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not Valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_LINUX:
case OS_POLICY_SOLARIS:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len),
ssn->client.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->client.next_seq + ssn->client.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ((TCP_GET_SEQ(p) + p->payload_len),
ssn->server.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->server.next_seq + ssn->server.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
default:
case OS_POLICY_BSD:
case OS_POLICY_FIRST:
case OS_POLICY_HPUX10:
case OS_POLICY_IRIX:
case OS_POLICY_MACOS:
case OS_POLICY_LAST:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
if(PKT_IS_TOSERVER(p)) {
if(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 " Stream %u",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 0;
}
}
break;
}
return 0;
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream.
*
* It's passive except for:
* 1. it sets the os policy on the stream if necessary
* 2. it sets an event in the packet if necessary
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpValidateTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
uint32_t last_pkt_ts = sender_stream->last_pkt_ts;
uint32_t last_ts = sender_stream->last_ts;
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/* HPUX11 igoners the timestamp of out of order packets */
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - last_ts) + 1);
} else {
result = (int32_t) (ts - last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (last_pkt_ts + PAWS_24DAYS))))
{
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream and update the session.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpHandleTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
sender_stream->flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
sender_stream->last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
default:
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/*HPUX11 igoners the timestamp of out of order packets*/
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, sender_stream->last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - sender_stream->last_ts) + 1);
} else {
result = (int32_t) (ts - sender_stream->last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (sender_stream->last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
sender_stream->last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid sender_stream->last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", sender_stream->last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
sender_stream->last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid sender_stream->last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
sender_stream->last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 1) {
/* Update the timestamp and last seen packet time for this
* stream */
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
} else if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (sender_stream->last_pkt_ts + PAWS_24DAYS))))
{
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
} else {
/* Solaris stops using timestamps if a packet is received
without a timestamp and timestamps were used on that stream. */
if (receiver_stream->os_policy == OS_POLICY_SOLARIS)
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to test the received ACK values against the stream window
* and previous ack value. ACK values should be higher than previous
* ACK value and less than the next_win value.
*
* \param ssn TcpSession for state access
* \param stream TcpStream of which last_ack needs to be tested
* \param p Packet which is used to test the last_ack
*
* \retval 0 ACK is valid, last_ack is updated if ACK was higher
* \retval -1 ACK is invalid
*/
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
uint32_t ack = TCP_GET_ACK(p);
/* fast track */
if (SEQ_GT(ack, stream->last_ack) && SEQ_LEQ(ack, stream->next_win))
{
SCLogDebug("ACK in bounds");
SCReturnInt(0);
}
/* fast track */
else if (SEQ_EQ(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" == stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
SCReturnInt(0);
}
/* exception handling */
if (SEQ_LT(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" < stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
/* This is an attempt to get a 'left edge' value that we can check against.
* It doesn't work when the window is 0, need to think of a better way. */
if (stream->window != 0 && SEQ_LT(ack, (stream->last_ack - stream->window))) {
SCLogDebug("ACK %"PRIu32" is before last_ack %"PRIu32" - window "
"%"PRIu32" = %"PRIu32, ack, stream->last_ack,
stream->window, stream->last_ack - stream->window);
goto invalid;
}
SCReturnInt(0);
}
if (ssn->state > TCP_SYN_SENT && SEQ_GT(ack, stream->next_win)) {
SCLogDebug("ACK %"PRIu32" is after next_win %"PRIu32, ack, stream->next_win);
goto invalid;
/* a toclient RST as a reponse to SYN, next_win is 0, ack will be isn+1, just like
* the syn ack */
} else if (ssn->state == TCP_SYN_SENT && PKT_IS_TOCLIENT(p) &&
p->tcph->th_flags & TH_RST &&
SEQ_EQ(ack, stream->isn + 1)) {
SCReturnInt(0);
}
SCLogDebug("default path leading to invalid: ACK %"PRIu32", last_ack %"PRIu32
" next_win %"PRIu32, ack, stream->last_ack, stream->next_win);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_ACK);
SCReturnInt(-1);
}
/** \brief disable reassembly
* Disable app layer and set raw inspect to no longer accept new data.
* Stream engine will then fully disable raw after last inspection.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionNoReassemblyFlag (TcpSession *ssn, char direction)
{
ssn->flags |= STREAMTCP_FLAG_APP_LAYER_DISABLED;
if (direction) {
ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
}
}
/** \brief Set the No reassembly flag for the given direction in given TCP
* session.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetDisableRawReassemblyFlag (TcpSession *ssn, char direction)
{
direction ? (ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) :
(ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED);
}
/** \brief enable bypass
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionBypassFlag (TcpSession *ssn)
{
ssn->flags |= STREAMTCP_FLAG_BYPASS;
}
#define PSEUDO_PKT_SET_IPV4HDR(nipv4h,ipv4h) do { \
IPV4_SET_RAW_VER(nipv4h, IPV4_GET_RAW_VER(ipv4h)); \
IPV4_SET_RAW_HLEN(nipv4h, IPV4_GET_RAW_HLEN(ipv4h)); \
IPV4_SET_RAW_IPLEN(nipv4h, IPV4_GET_RAW_IPLEN(ipv4h)); \
IPV4_SET_RAW_IPTOS(nipv4h, IPV4_GET_RAW_IPTOS(ipv4h)); \
IPV4_SET_RAW_IPPROTO(nipv4h, IPV4_GET_RAW_IPPROTO(ipv4h)); \
(nipv4h)->s_ip_src = IPV4_GET_RAW_IPDST(ipv4h); \
(nipv4h)->s_ip_dst = IPV4_GET_RAW_IPSRC(ipv4h); \
} while (0)
#define PSEUDO_PKT_SET_IPV6HDR(nipv6h,ipv6h) do { \
(nipv6h)->s_ip6_src[0] = (ipv6h)->s_ip6_dst[0]; \
(nipv6h)->s_ip6_src[1] = (ipv6h)->s_ip6_dst[1]; \
(nipv6h)->s_ip6_src[2] = (ipv6h)->s_ip6_dst[2]; \
(nipv6h)->s_ip6_src[3] = (ipv6h)->s_ip6_dst[3]; \
(nipv6h)->s_ip6_dst[0] = (ipv6h)->s_ip6_src[0]; \
(nipv6h)->s_ip6_dst[1] = (ipv6h)->s_ip6_src[1]; \
(nipv6h)->s_ip6_dst[2] = (ipv6h)->s_ip6_src[2]; \
(nipv6h)->s_ip6_dst[3] = (ipv6h)->s_ip6_src[3]; \
IPV6_SET_RAW_NH(nipv6h, IPV6_GET_RAW_NH(ipv6h)); \
} while (0)
#define PSEUDO_PKT_SET_TCPHDR(ntcph,tcph) do { \
COPY_PORT((tcph)->th_dport, (ntcph)->th_sport); \
COPY_PORT((tcph)->th_sport, (ntcph)->th_dport); \
(ntcph)->th_seq = (tcph)->th_ack; \
(ntcph)->th_ack = (tcph)->th_seq; \
} while (0)
/**
* \brief Function to fetch a packet from the packet allocation queue for
* creation of the pseudo packet from the reassembled stream.
*
* @param parent Pointer to the parent of the pseudo packet
* @param pkt pointer to the raw packet of the parent
* @param len length of the packet
* @return upon success returns the pointer to the new pseudo packet
* otherwise NULL
*/
Packet *StreamTcpPseudoSetup(Packet *parent, uint8_t *pkt, uint32_t len)
{
SCEnter();
if (len == 0) {
SCReturnPtr(NULL, "Packet");
}
Packet *p = PacketGetFromQueueOrAlloc();
if (p == NULL) {
SCReturnPtr(NULL, "Packet");
}
/* set the root ptr to the lowest layer */
if (parent->root != NULL)
p->root = parent->root;
else
p->root = parent;
/* copy packet and set lenght, proto */
p->proto = parent->proto;
p->datalink = parent->datalink;
PacketCopyData(p, pkt, len);
p->recursion_level = parent->recursion_level + 1;
p->ts.tv_sec = parent->ts.tv_sec;
p->ts.tv_usec = parent->ts.tv_usec;
FlowReference(&p->flow, parent->flow);
/* set tunnel flags */
/* tell new packet it's part of a tunnel */
SET_TUNNEL_PKT(p);
/* tell parent packet it's part of a tunnel */
SET_TUNNEL_PKT(parent);
/* increment tunnel packet refcnt in the root packet */
TUNNEL_INCR_PKT_TPR(p);
return p;
}
/** \brief Create a pseudo packet injected into the engine to signal the
* opposing direction of this stream trigger detection/logging.
*
* \param parent real packet
* \param pq packet queue to store the new pseudo packet in
* \param dir 0 ts 1 tc
*/
static void StreamTcpPseudoPacketCreateDetectLogFlush(ThreadVars *tv,
StreamTcpThread *stt, Packet *parent,
TcpSession *ssn, PacketQueue *pq, int dir)
{
SCEnter();
Flow *f = parent->flow;
if (parent->flags & PKT_PSEUDO_DETECTLOG_FLUSH) {
SCReturn;
}
Packet *np = PacketPoolGetPacket();
if (np == NULL) {
SCReturn;
}
PKT_SET_SRC(np, PKT_SRC_STREAM_TCP_DETECTLOG_FLUSH);
np->tenant_id = f->tenant_id;
np->datalink = DLT_RAW;
np->proto = IPPROTO_TCP;
FlowReference(&np->flow, f);
np->flags |= PKT_STREAM_EST;
np->flags |= PKT_HAS_FLOW;
np->flags |= PKT_IGNORE_CHECKSUM;
np->flags |= PKT_PSEUDO_DETECTLOG_FLUSH;
if (f->flags & FLOW_NOPACKET_INSPECTION) {
DecodeSetNoPacketInspectionFlag(np);
}
if (f->flags & FLOW_NOPAYLOAD_INSPECTION) {
DecodeSetNoPayloadInspectionFlag(np);
}
if (dir == 0) {
SCLogDebug("pseudo is to_server");
np->flowflags |= FLOW_PKT_TOSERVER;
} else {
SCLogDebug("pseudo is to_client");
np->flowflags |= FLOW_PKT_TOCLIENT;
}
np->flowflags |= FLOW_PKT_ESTABLISHED;
np->payload = NULL;
np->payload_len = 0;
if (FLOW_IS_IPV4(f)) {
if (dir == 0) {
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->src, &np->src);
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->dst, &np->dst);
np->sp = f->sp;
np->dp = f->dp;
} else {
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->src, &np->dst);
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->dst, &np->src);
np->sp = f->dp;
np->dp = f->sp;
}
/* Check if we have enough room in direct data. We need ipv4 hdr + tcp hdr.
* Force an allocation if it is not the case.
*/
if (GET_PKT_DIRECT_MAX_SIZE(np) < 40) {
if (PacketCallocExtPkt(np, 40) == -1) {
goto error;
}
}
/* set the ip header */
np->ip4h = (IPV4Hdr *)GET_PKT_DATA(np);
/* version 4 and length 20 bytes for the tcp header */
np->ip4h->ip_verhl = 0x45;
np->ip4h->ip_tos = 0;
np->ip4h->ip_len = htons(40);
np->ip4h->ip_id = 0;
np->ip4h->ip_off = 0;
np->ip4h->ip_ttl = 64;
np->ip4h->ip_proto = IPPROTO_TCP;
if (dir == 0) {
np->ip4h->s_ip_src.s_addr = f->src.addr_data32[0];
np->ip4h->s_ip_dst.s_addr = f->dst.addr_data32[0];
} else {
np->ip4h->s_ip_src.s_addr = f->dst.addr_data32[0];
np->ip4h->s_ip_dst.s_addr = f->src.addr_data32[0];
}
/* set the tcp header */
np->tcph = (TCPHdr *)((uint8_t *)GET_PKT_DATA(np) + 20);
SET_PKT_LEN(np, 40); /* ipv4 hdr + tcp hdr */
} else if (FLOW_IS_IPV6(f)) {
if (dir == 0) {
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->src, &np->src);
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->dst, &np->dst);
np->sp = f->sp;
np->dp = f->dp;
} else {
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->src, &np->dst);
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->dst, &np->src);
np->sp = f->dp;
np->dp = f->sp;
}
/* Check if we have enough room in direct data. We need ipv6 hdr + tcp hdr.
* Force an allocation if it is not the case.
*/
if (GET_PKT_DIRECT_MAX_SIZE(np) < 60) {
if (PacketCallocExtPkt(np, 60) == -1) {
goto error;
}
}
/* set the ip header */
np->ip6h = (IPV6Hdr *)GET_PKT_DATA(np);
/* version 6 */
np->ip6h->s_ip6_vfc = 0x60;
np->ip6h->s_ip6_flow = 0;
np->ip6h->s_ip6_nxt = IPPROTO_TCP;
np->ip6h->s_ip6_plen = htons(20);
np->ip6h->s_ip6_hlim = 64;
if (dir == 0) {
np->ip6h->s_ip6_src[0] = f->src.addr_data32[0];
np->ip6h->s_ip6_src[1] = f->src.addr_data32[1];
np->ip6h->s_ip6_src[2] = f->src.addr_data32[2];
np->ip6h->s_ip6_src[3] = f->src.addr_data32[3];
np->ip6h->s_ip6_dst[0] = f->dst.addr_data32[0];
np->ip6h->s_ip6_dst[1] = f->dst.addr_data32[1];
np->ip6h->s_ip6_dst[2] = f->dst.addr_data32[2];
np->ip6h->s_ip6_dst[3] = f->dst.addr_data32[3];
} else {
np->ip6h->s_ip6_src[0] = f->dst.addr_data32[0];
np->ip6h->s_ip6_src[1] = f->dst.addr_data32[1];
np->ip6h->s_ip6_src[2] = f->dst.addr_data32[2];
np->ip6h->s_ip6_src[3] = f->dst.addr_data32[3];
np->ip6h->s_ip6_dst[0] = f->src.addr_data32[0];
np->ip6h->s_ip6_dst[1] = f->src.addr_data32[1];
np->ip6h->s_ip6_dst[2] = f->src.addr_data32[2];
np->ip6h->s_ip6_dst[3] = f->src.addr_data32[3];
}
/* set the tcp header */
np->tcph = (TCPHdr *)((uint8_t *)GET_PKT_DATA(np) + 40);
SET_PKT_LEN(np, 60); /* ipv6 hdr + tcp hdr */
}
np->tcph->th_offx2 = 0x50;
np->tcph->th_flags |= TH_ACK;
np->tcph->th_win = 10;
np->tcph->th_urp = 0;
/* to server */
if (dir == 0) {
np->tcph->th_sport = htons(f->sp);
np->tcph->th_dport = htons(f->dp);
np->tcph->th_seq = htonl(ssn->client.next_seq);
np->tcph->th_ack = htonl(ssn->server.last_ack);
/* to client */
} else {
np->tcph->th_sport = htons(f->dp);
np->tcph->th_dport = htons(f->sp);
np->tcph->th_seq = htonl(ssn->server.next_seq);
np->tcph->th_ack = htonl(ssn->client.last_ack);
}
/* use parent time stamp */
memcpy(&np->ts, &parent->ts, sizeof(struct timeval));
SCLogDebug("np %p", np);
PacketEnqueue(pq, np);
StatsIncr(tv, stt->counter_tcp_pseudo);
SCReturn;
error:
FlowDeReference(&np->flow);
SCReturn;
}
/** \brief create packets in both directions to flush out logging
* and detection before switching protocols.
* In IDS mode, create first in packet dir, 2nd in opposing
* In IPS mode, do the reverse.
* Flag TCP engine that data needs to be inspected regardless
* of how far we are wrt inspect limits.
*/
void StreamTcpDetectLogFlush(ThreadVars *tv, StreamTcpThread *stt, Flow *f, Packet *p, PacketQueue *pq)
{
TcpSession *ssn = f->protoctx;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
bool ts = PKT_IS_TOSERVER(p) ? true : false;
ts ^= StreamTcpInlineMode();
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^0);
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^1);
}
/**
* \brief Run callback function on each TCP segment
*
* \note when stream engine is running in inline mode all segments are used,
* in IDS/non-inline mode only ack'd segments are iterated.
*
* \note Must be called under flow lock.
*
* \return -1 in case of error, the number of segment in case of success
*
*/
int StreamTcpSegmentForEach(const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data)
{
TcpSession *ssn = NULL;
TcpStream *stream = NULL;
int ret = 0;
int cnt = 0;
if (p->flow == NULL)
return 0;
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
return 0;
}
if (flag & FLOW_PKT_TOSERVER) {
stream = &(ssn->server);
} else {
stream = &(ssn->client);
}
/* for IDS, return ack'd segments. For IPS all. */
TcpSegment *seg;
RB_FOREACH(seg, TCPSEG, &stream->seg_tree) {
if (!((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
|| SEQ_LT(seg->seq, stream->last_ack)))
break;
const uint8_t *seg_data;
uint32_t seg_datalen;
StreamingBufferSegmentGetData(&stream->sb, &seg->sbseg, &seg_data, &seg_datalen);
ret = CallbackFunc(p, data, seg_data, seg_datalen);
if (ret != 1) {
SCLogDebug("Callback function has failed");
return -1;
}
cnt++;
}
return cnt;
}
int StreamTcpBypassEnabled(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS);
}
/**
* \brief See if stream engine is operating in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineMode(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_INLINE) ? 1 : 0;
}
void TcpSessionSetReassemblyDepth(TcpSession *ssn, uint32_t size)
{
if (size > ssn->reassembly_depth || size == 0) {
ssn->reassembly_depth = size;
}
return;
}
#ifdef UNITTESTS
#define SET_ISN(stream, setseq) \
(stream)->isn = (setseq); \
(stream)->base_seq = (setseq) + 1
/**
* \test Test the allocation of TCP session for a given packet from the
* ssn_pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest01 (void)
{
StreamTcpThread stt;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
TcpSession *ssn = StreamTcpNewSession(p, 0);
if (ssn == NULL) {
printf("Session can not be allocated: ");
goto end;
}
f.protoctx = ssn;
if (f.alparser != NULL) {
printf("AppLayer field not set to NULL: ");
goto end;
}
if (ssn->state != 0) {
printf("TCP state field not set to 0: ");
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the deallocation of TCP session for a given packet and return
* the memory back to ssn_pool and corresponding segments to segment
* pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest02 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
StreamTcpSessionClear(p->flow->protoctx);
//StreamTcpUTClearSession(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN packet of the session. The session is setup only if midstream
* sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest03 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 20 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN/ACK packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest04 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(9);
p->tcph->th_ack = htonl(19);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 10 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 20)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* 3WHS packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest05 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(13);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, 4); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(16);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, 4); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 16 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we have seen only the
* FIN, RST packets packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest06 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
TcpSession ssn;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&ssn, 0, sizeof (TcpSession));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_flags = TH_FIN;
p->tcph = &tcph;
/* StreamTcpPacket returns -1 on unsolicited FIN */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed: ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't: ");
goto end;
}
p->tcph->th_flags = TH_RST;
/* StreamTcpPacket returns -1 on unsolicited RST */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed (2): ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't (2): ");
goto end;
}
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the working on PAWS. The packet will be dropped by stream, as
* its timestamp is old, although the segment is in the window.
*/
static int StreamTcpTest07 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
PacketQueue pq;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 2;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) != -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working on PAWS. The packet will be accpeted by engine as
* the timestamp is valid and it is in window.
*/
static int StreamTcpTest08 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(20);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 12;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 12);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working of No stream reassembly flag. The stream will not
* reassemble the segment if the flag is set.
*/
static int StreamTcpTest09 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(12);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(p->flow->protoctx == NULL);
StreamTcpSetSessionNoReassemblyFlag(((TcpSession *)(p->flow->protoctx)), 0);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
TcpSession *ssn = p->flow->protoctx;
FAIL_IF_NULL(ssn);
TcpSegment *seg = RB_MIN(TCPSEG, &ssn->client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCPSEG_RB_NEXT(seg) != NULL);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we see all the packets in that stream from start.
*/
static int StreamTcpTest10 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN packet of that stream.
*/
static int StreamTcpTest11 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(1);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(2);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->server.last_ack != 2 &&
((TcpSession *)(p->flow->protoctx))->client.next_seq != 1);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest12 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
* Later, we start to receive the packet from other end stream too.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest13 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(9);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 9 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 14) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.1\n"
"\n"
" linux: 192.168.0.2\n"
"\n";
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string1 =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.0/24," "192.168.1.1\n"
"\n"
" linux: 192.168.1.0/24," "192.168.0.1\n"
"\n";
/**
* \brief Function to parse the dummy conf string and get the value of IP
* address for the corresponding OS policy type.
*
* \param conf_val_name Name of the OS policy type
* \retval returns IP address as string on success and NULL on failure
*/
static const char *StreamTcpParseOSPolicy (char *conf_var_name)
{
SCEnter();
char conf_var_type_name[15] = "host-os-policy";
char *conf_var_full_name = NULL;
const char *conf_var_value = NULL;
if (conf_var_name == NULL)
goto end;
/* the + 2 is for the '.' and the string termination character '\0' */
conf_var_full_name = (char *)SCMalloc(strlen(conf_var_type_name) +
strlen(conf_var_name) + 2);
if (conf_var_full_name == NULL)
goto end;
if (snprintf(conf_var_full_name,
strlen(conf_var_type_name) + strlen(conf_var_name) + 2, "%s.%s",
conf_var_type_name, conf_var_name) < 0) {
SCLogError(SC_ERR_INVALID_VALUE, "Error in making the conf full name");
goto end;
}
if (ConfGet(conf_var_full_name, &conf_var_value) != 1) {
SCLogError(SC_ERR_UNKNOWN_VALUE, "Error in getting conf value for conf name %s",
conf_var_full_name);
goto end;
}
SCLogDebug("Value obtained from the yaml conf file, for the var "
"\"%s\" is \"%s\"", conf_var_name, conf_var_value);
end:
if (conf_var_full_name != NULL)
SCFree(conf_var_full_name);
SCReturnCharPtr(conf_var_value);
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest14 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string, strlen(dummy_conf_string));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.0.2");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest01 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(21);
p->tcph->th_ack = htonl(10);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK, but the SYN/ACK does
* not have the right SEQ
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest02 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("SYN/ACK pkt not rejected but it should have: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK: however the SYN/ACK and ACK
* are part of a normal 3WHS
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest03 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(31);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest15 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.20");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.20");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest16 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_WINDOWS)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_WINDOWS);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1". To check the setting of
* Default os policy
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest17 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("10.1.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_DEFAULT)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_DEFAULT);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest18 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS)
goto end;
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest19 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8": ",
(uint8_t)OS_POLICY_WINDOWS, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest20 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest21 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest22 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("123.231.2.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_DEFAULT) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_DEFAULT, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest23(void)
{
StreamTcpThread stt;
TcpSession ssn;
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(p == NULL);
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
SET_ISN(&ssn.client, 3184324452UL);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419609UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 6;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
TcpSegment *seg = RB_MAX(TCPSEG, &ssn.client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCP_SEG_LEN(seg) != 2);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest24(void)
{
StreamTcpThread stt;
TcpSession ssn;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF (p == NULL);
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
//ssn.client.ra_app_base_seq = ssn.client.ra_raw_base_seq = ssn.client.last_ack = 3184324453UL;
SET_ISN(&ssn.client, 3184324453UL);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 4;
FAIL_IF (StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419633UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419657UL);
p->payload_len = 4;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
TcpSegment *seg = RB_MAX(TCPSEG, &ssn.client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCP_SEG_LEN(seg) != 4);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest25(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest26(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest27(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the memcap incrementing/decrementing and memcap check */
static int StreamTcpTest28(void)
{
StreamTcpThread stt;
StreamTcpUTInit(&stt.ra_ctx);
uint32_t memuse = SC_ATOMIC_GET(st_memuse);
StreamTcpIncrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != (memuse+500));
StreamTcpDecrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != memuse);
FAIL_IF(StreamTcpCheckMemcap(500) != 1);
FAIL_IF(StreamTcpCheckMemcap((memuse + SC_ATOMIC_GET(stream_config.memcap))) != 0);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != 0);
PASS;
}
#if 0
/**
* \test Test the resetting of the sesison with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest29(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t packet[1460] = "";
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = packet;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
tcpvars.hlen = 20;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 119197101;
ssn.server.window = 5184;
ssn.server.next_win = 5184;
ssn.server.last_ack = 119197101;
ssn.server.ra_base_seq = 119197101;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 4;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(119197102);
p.tcph->th_ack = htonl(15);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(15);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the ssn.state should be TCP_ESTABLISHED(%"PRIu8"), not %"PRIu8""
"\n", TCP_ESTABLISHED, ssn.state);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the overlapping of the packet with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest30(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t payload[9] = "AAAAAAAAA";
uint8_t payload1[9] = "GET /EVIL";
uint8_t expected_content[9] = { 0x47, 0x45, 0x54, 0x20, 0x2f, 0x45, 0x56,
0x49, 0x4c };
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = payload;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload = payload1;
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(20);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (StreamTcpCheckStreamContents(expected_content, 9, &ssn.client) != 1) {
printf("the contents are not as expected(GET /EVIL), contents are: ");
PrintRawDataFp(stdout, ssn.client.seg_list->payload, 9);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the multiple SYN packet handling with bad checksum and timestamp
* value. Engine should drop the bad checksum packet and establish
* TCP session correctly.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest31(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
TCPOpt tcpopt;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
memset(&tcpopt, 0, sizeof (TCPOpt));
int result = 1;
StreamTcpInitConfig(TRUE);
FLOW_INITIALIZE(&f);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_LINUX;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
p.tcpvars.ts = &tcpopt;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 100;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 10;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
ssn.flags |= STREAMTCP_FLAG_TIMESTAMP;
tcph.th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(11);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079941);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr1;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the should have been changed to TCP_ESTABLISHED!!\n ");
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the initialization of tcp streams with ECN & CWR flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest32(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK | TH_ECN;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_flags = TH_ACK;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the same
* ports have been used to start the new session after resetting the
* previous session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest33 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_CLOSED) {
printf("Tcp session should have been closed\n");
goto end;
}
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_seq = htonl(1);
p.tcph->th_ack = htonl(2);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been ESTABLISHED\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the PUSH flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest34 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_PUSH;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the URG flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest35 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_URG;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the processing of PSH and URG flag in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest36(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_URG;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->client.next_seq != 4) {
printf("the ssn->client.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)p.flow->protoctx)->client.next_seq);
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
#endif
/**
* \test Test the processing of out of order FIN packets in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest37(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p->tcph->th_ack = htonl(2);
p->tcph->th_seq = htonl(4);
p->tcph->th_flags = TH_ACK|TH_FIN;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_CLOSE_WAIT) {
printf("the TCP state should be TCP_CLOSE_WAIT\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_ACK;
p->payload_len = 0;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
TcpStream *stream = &(((TcpSession *)p->flow->protoctx)->client);
FAIL_IF(STREAM_RAW_PROGRESS(stream) != 0); // no detect no progress update
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest38 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[128];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(29847);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 1 as the previous sent ACK value is out of
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 1) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 127, 128); /*AAA*/
p->payload = payload;
p->payload_len = 127;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 128) {
printf("the server.next_seq should be 128, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(256); // in window, but beyond next_seq
p->tcph->th_seq = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256, as the previous sent ACK value
is inside window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(128);
p->tcph->th_seq = htonl(8);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 256, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack and update the next_seq after loosing the .
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest39 (void)
{
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 4) {
printf("the server.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 4 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 4) {
printf("the server.last_ack should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_seq = htonl(4);
p->tcph->th_ack = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* next_seq value should be 2987 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 7) {
printf("the server.next_seq should be 7, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick first */
static int StreamTcpTest42 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(501);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 500) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 500);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick second */
static int StreamTcpTest43 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick neither */
static int StreamTcpTest44 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(3001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_SYN_RECV) {
SCLogDebug("state not TCP_SYN_RECV");
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, over the limit */
static int StreamTcpTest45 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
stream_config.max_synack_queued = 2;
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(2000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(3000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
#endif /* UNITTESTS */
void StreamTcpRegisterTests (void)
{
#ifdef UNITTESTS
UtRegisterTest("StreamTcpTest01 -- TCP session allocation",
StreamTcpTest01);
UtRegisterTest("StreamTcpTest02 -- TCP session deallocation",
StreamTcpTest02);
UtRegisterTest("StreamTcpTest03 -- SYN missed MidStream session",
StreamTcpTest03);
UtRegisterTest("StreamTcpTest04 -- SYN/ACK missed MidStream session",
StreamTcpTest04);
UtRegisterTest("StreamTcpTest05 -- 3WHS missed MidStream session",
StreamTcpTest05);
UtRegisterTest("StreamTcpTest06 -- FIN, RST message MidStream session",
StreamTcpTest06);
UtRegisterTest("StreamTcpTest07 -- PAWS invalid timestamp",
StreamTcpTest07);
UtRegisterTest("StreamTcpTest08 -- PAWS valid timestamp", StreamTcpTest08);
UtRegisterTest("StreamTcpTest09 -- No Client Reassembly", StreamTcpTest09);
UtRegisterTest("StreamTcpTest10 -- No missed packet Async stream",
StreamTcpTest10);
UtRegisterTest("StreamTcpTest11 -- SYN missed Async stream",
StreamTcpTest11);
UtRegisterTest("StreamTcpTest12 -- SYN/ACK missed Async stream",
StreamTcpTest12);
UtRegisterTest("StreamTcpTest13 -- opposite stream packets for Async " "stream",
StreamTcpTest13);
UtRegisterTest("StreamTcp4WHSTest01", StreamTcp4WHSTest01);
UtRegisterTest("StreamTcp4WHSTest02", StreamTcp4WHSTest02);
UtRegisterTest("StreamTcp4WHSTest03", StreamTcp4WHSTest03);
UtRegisterTest("StreamTcpTest14 -- setup OS policy", StreamTcpTest14);
UtRegisterTest("StreamTcpTest15 -- setup OS policy", StreamTcpTest15);
UtRegisterTest("StreamTcpTest16 -- setup OS policy", StreamTcpTest16);
UtRegisterTest("StreamTcpTest17 -- setup OS policy", StreamTcpTest17);
UtRegisterTest("StreamTcpTest18 -- setup OS policy", StreamTcpTest18);
UtRegisterTest("StreamTcpTest19 -- setup OS policy", StreamTcpTest19);
UtRegisterTest("StreamTcpTest20 -- setup OS policy", StreamTcpTest20);
UtRegisterTest("StreamTcpTest21 -- setup OS policy", StreamTcpTest21);
UtRegisterTest("StreamTcpTest22 -- setup OS policy", StreamTcpTest22);
UtRegisterTest("StreamTcpTest23 -- stream memory leaks", StreamTcpTest23);
UtRegisterTest("StreamTcpTest24 -- stream memory leaks", StreamTcpTest24);
UtRegisterTest("StreamTcpTest25 -- test ecn/cwr sessions",
StreamTcpTest25);
UtRegisterTest("StreamTcpTest26 -- test ecn/cwr sessions",
StreamTcpTest26);
UtRegisterTest("StreamTcpTest27 -- test ecn/cwr sessions",
StreamTcpTest27);
UtRegisterTest("StreamTcpTest28 -- Memcap Test", StreamTcpTest28);
#if 0 /* VJ 2010/09/01 disabled since they blow up on Fedora and Fedora is
* right about blowing up. The checksum functions are not used properly
* in the tests. */
UtRegisterTest("StreamTcpTest29 -- Badchecksum Reset Test", StreamTcpTest29, 1);
UtRegisterTest("StreamTcpTest30 -- Badchecksum Overlap Test", StreamTcpTest30, 1);
UtRegisterTest("StreamTcpTest31 -- MultipleSyns Test", StreamTcpTest31, 1);
UtRegisterTest("StreamTcpTest32 -- Bogus CWR Test", StreamTcpTest32, 1);
UtRegisterTest("StreamTcpTest33 -- RST-SYN Again Test", StreamTcpTest33, 1);
UtRegisterTest("StreamTcpTest34 -- SYN-PUSH Test", StreamTcpTest34, 1);
UtRegisterTest("StreamTcpTest35 -- SYN-URG Test", StreamTcpTest35, 1);
UtRegisterTest("StreamTcpTest36 -- PUSH-URG Test", StreamTcpTest36, 1);
#endif
UtRegisterTest("StreamTcpTest37 -- Out of order FIN Test",
StreamTcpTest37);
UtRegisterTest("StreamTcpTest38 -- validate ACK", StreamTcpTest38);
UtRegisterTest("StreamTcpTest39 -- update next_seq", StreamTcpTest39);
UtRegisterTest("StreamTcpTest42 -- SYN/ACK queue", StreamTcpTest42);
UtRegisterTest("StreamTcpTest43 -- SYN/ACK queue", StreamTcpTest43);
UtRegisterTest("StreamTcpTest44 -- SYN/ACK queue", StreamTcpTest44);
UtRegisterTest("StreamTcpTest45 -- SYN/ACK queue", StreamTcpTest45);
/* set up the reassembly tests as well */
StreamTcpReassembleRegisterTests();
StreamTcpSackRegisterTests ();
#endif /* UNITTESTS */
}
| ./CrossVul/dataset_final_sorted/CWE-94/c/bad_1212_0 |
crossvul-cpp_data_good_1212_0 | /* Copyright (C) 2007-2016 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \file
*
* \author Victor Julien <victor@inliniac.net>
* \author Gurvinder Singh <gurvindersinghdahiya@gmail.com>
*
* TCP stream tracking and reassembly engine.
*
* \todo - 4WHS: what if after the 2nd SYN we turn out to be normal 3WHS anyway?
*/
#include "suricata-common.h"
#include "suricata.h"
#include "decode.h"
#include "debug.h"
#include "detect.h"
#include "flow.h"
#include "flow-util.h"
#include "conf.h"
#include "conf-yaml-loader.h"
#include "threads.h"
#include "threadvars.h"
#include "tm-threads.h"
#include "util-pool.h"
#include "util-pool-thread.h"
#include "util-checksum.h"
#include "util-unittest.h"
#include "util-print.h"
#include "util-debug.h"
#include "util-device.h"
#include "stream-tcp-private.h"
#include "stream-tcp-reassemble.h"
#include "stream-tcp.h"
#include "stream-tcp-inline.h"
#include "stream-tcp-sack.h"
#include "stream-tcp-util.h"
#include "stream.h"
#include "pkt-var.h"
#include "host.h"
#include "app-layer.h"
#include "app-layer-parser.h"
#include "app-layer-protos.h"
#include "app-layer-htp-mem.h"
#include "util-host-os-info.h"
#include "util-privs.h"
#include "util-profiling.h"
#include "util-misc.h"
#include "util-validate.h"
#include "util-runmodes.h"
#include "util-random.h"
#include "source-pcap-file.h"
//#define DEBUG
#define STREAMTCP_DEFAULT_PREALLOC 2048
#define STREAMTCP_DEFAULT_MEMCAP (32 * 1024 * 1024) /* 32mb */
#define STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP (64 * 1024 * 1024) /* 64mb */
#define STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE 2560
#define STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED 5
#define STREAMTCP_NEW_TIMEOUT 60
#define STREAMTCP_EST_TIMEOUT 3600
#define STREAMTCP_CLOSED_TIMEOUT 120
#define STREAMTCP_EMERG_NEW_TIMEOUT 10
#define STREAMTCP_EMERG_EST_TIMEOUT 300
#define STREAMTCP_EMERG_CLOSED_TIMEOUT 20
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *, TcpSession *, Packet *, PacketQueue *);
void StreamTcpReturnStreamSegments (TcpStream *);
void StreamTcpInitConfig(char);
int StreamTcpGetFlowState(void *);
void StreamTcpSetOSPolicy(TcpStream*, Packet*);
static int StreamTcpValidateTimestamp(TcpSession * , Packet *);
static int StreamTcpHandleTimestamp(TcpSession * , Packet *);
static int StreamTcpValidateRst(TcpSession * , Packet *);
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *, Packet *);
static int StreamTcpStateDispatch(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq,
uint8_t state);
extern int g_detect_disabled;
static PoolThread *ssn_pool = NULL;
static SCMutex ssn_pool_mutex = SCMUTEX_INITIALIZER; /**< init only, protect initializing and growing pool */
#ifdef DEBUG
static uint64_t ssn_pool_cnt = 0; /** counts ssns, protected by ssn_pool_mutex */
#endif
uint64_t StreamTcpReassembleMemuseGlobalCounter(void);
SC_ATOMIC_DECLARE(uint64_t, st_memuse);
void StreamTcpInitMemuse(void)
{
SC_ATOMIC_INIT(st_memuse);
}
void StreamTcpIncrMemuse(uint64_t size)
{
(void) SC_ATOMIC_ADD(st_memuse, size);
SCLogDebug("STREAM %"PRIu64", incr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
void StreamTcpDecrMemuse(uint64_t size)
{
#ifdef DEBUG_VALIDATION
uint64_t presize = SC_ATOMIC_GET(st_memuse);
if (RunmodeIsUnittests()) {
BUG_ON(presize > UINT_MAX);
}
#endif
(void) SC_ATOMIC_SUB(st_memuse, size);
#ifdef DEBUG_VALIDATION
if (RunmodeIsUnittests()) {
uint64_t postsize = SC_ATOMIC_GET(st_memuse);
BUG_ON(postsize > presize);
}
#endif
SCLogDebug("STREAM %"PRIu64", decr %"PRIu64, StreamTcpMemuseCounter(), size);
return;
}
uint64_t StreamTcpMemuseCounter(void)
{
uint64_t memusecopy = SC_ATOMIC_GET(st_memuse);
return memusecopy;
}
/**
* \brief Check if alloc'ing "size" would mean we're over memcap
*
* \retval 1 if in bounds
* \retval 0 if not in bounds
*/
int StreamTcpCheckMemcap(uint64_t size)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
if (memcapcopy == 0 || size + SC_ATOMIC_GET(st_memuse) <= memcapcopy)
return 1;
return 0;
}
/**
* \brief Update memcap value
*
* \param size new memcap value
*/
int StreamTcpSetMemcap(uint64_t size)
{
if (size == 0 || (uint64_t)SC_ATOMIC_GET(st_memuse) < size) {
SC_ATOMIC_SET(stream_config.memcap, size);
return 1;
}
return 0;
}
/**
* \brief Return memcap value
*
* \param memcap memcap value
*/
uint64_t StreamTcpGetMemcap(void)
{
uint64_t memcapcopy = SC_ATOMIC_GET(stream_config.memcap);
return memcapcopy;
}
void StreamTcpStreamCleanup(TcpStream *stream)
{
if (stream != NULL) {
StreamTcpSackFreeList(stream);
StreamTcpReturnStreamSegments(stream);
StreamingBufferClear(&stream->sb);
}
}
/**
* \brief Session cleanup function. Does not free the ssn.
* \param ssn tcp session
*/
void StreamTcpSessionCleanup(TcpSession *ssn)
{
SCEnter();
TcpStateQueue *q, *q_next;
if (ssn == NULL)
return;
StreamTcpStreamCleanup(&ssn->client);
StreamTcpStreamCleanup(&ssn->server);
q = ssn->queue;
while (q != NULL) {
q_next = q->next;
SCFree(q);
q = q_next;
StreamTcpDecrMemuse((uint64_t)sizeof(TcpStateQueue));
}
ssn->queue = NULL;
ssn->queue_len = 0;
SCReturn;
}
/**
* \brief Function to return the stream back to the pool. It returns the
* segments in the stream to the segment pool.
*
* This function is called when the flow is destroyed, so it should free
* *everything* related to the tcp session. So including the app layer
* data. We are guaranteed to only get here when the flow's use_cnt is 0.
*
* \param ssn Void ptr to the ssn.
*/
void StreamTcpSessionClear(void *ssnptr)
{
SCEnter();
TcpSession *ssn = (TcpSession *)ssnptr;
if (ssn == NULL)
return;
StreamTcpSessionCleanup(ssn);
/* HACK: don't loose track of thread id */
PoolThreadReserved a = ssn->res;
memset(ssn, 0, sizeof(TcpSession));
ssn->res = a;
PoolThreadReturn(ssn_pool, ssn);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
ssn_pool_cnt--;
SCMutexUnlock(&ssn_pool_mutex);
#endif
SCReturn;
}
/**
* \brief Function to return the stream segments back to the pool.
*
* We don't clear out the app layer storage here as that is under protection
* of the "use_cnt" reference counter in the flow. This function is called
* when the use_cnt is always at least 1 (this pkt has incremented the flow
* use_cnt itself), so we don't bother.
*
* \param p Packet used to identify the stream.
*/
void StreamTcpSessionPktFree (Packet *p)
{
SCEnter();
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL)
SCReturn;
StreamTcpReturnStreamSegments(&ssn->client);
StreamTcpReturnStreamSegments(&ssn->server);
SCReturn;
}
/** \brief Stream alloc function for the Pool
* \retval ptr void ptr to TcpSession structure with all vars set to 0/NULL
*/
static void *StreamTcpSessionPoolAlloc(void)
{
void *ptr = NULL;
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpSession)) == 0)
return NULL;
ptr = SCMalloc(sizeof(TcpSession));
if (unlikely(ptr == NULL))
return NULL;
return ptr;
}
static int StreamTcpSessionPoolInit(void *data, void* initdata)
{
memset(data, 0, sizeof(TcpSession));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpSession));
return 1;
}
/** \brief Pool cleanup function
* \param s Void ptr to TcpSession memory */
static void StreamTcpSessionPoolCleanup(void *s)
{
if (s != NULL) {
StreamTcpSessionCleanup(s);
/** \todo not very clean, as the memory is not freed here */
StreamTcpDecrMemuse((uint64_t)sizeof(TcpSession));
}
}
/**
* \brief See if stream engine is dropping invalid packet in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineDropInvalid(void)
{
return ((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
&& (stream_config.flags & STREAMTCP_INIT_FLAG_DROP_INVALID));
}
/* hack: stream random range code expects random values in range of 0-RAND_MAX,
* but we can get both <0 and >RAND_MAX values from RandomGet
*/
static int RandomGetWrap(void)
{
unsigned long r;
do {
r = RandomGet();
} while(r >= ULONG_MAX - (ULONG_MAX % RAND_MAX));
return r % RAND_MAX;
}
/** \brief To initialize the stream global configuration data
*
* \param quiet It tells the mode of operation, if it is TRUE nothing will
* be get printed.
*/
void StreamTcpInitConfig(char quiet)
{
intmax_t value = 0;
uint16_t rdrange = 10;
SCLogDebug("Initializing Stream");
memset(&stream_config, 0, sizeof(stream_config));
SC_ATOMIC_INIT(stream_config.memcap);
SC_ATOMIC_INIT(stream_config.reassembly_memcap);
if ((ConfGetInt("stream.max-sessions", &value)) == 1) {
SCLogWarning(SC_WARN_OPTION_OBSOLETE, "max-sessions is obsolete. "
"Number of concurrent sessions is now only limited by Flow and "
"TCP stream engine memcaps.");
}
if ((ConfGetInt("stream.prealloc-sessions", &value)) == 1) {
stream_config.prealloc_sessions = (uint32_t)value;
} else {
if (RunmodeIsUnittests()) {
stream_config.prealloc_sessions = 128;
} else {
stream_config.prealloc_sessions = STREAMTCP_DEFAULT_PREALLOC;
if (ConfGetNode("stream.prealloc-sessions") != NULL) {
WarnInvalidConfEntry("stream.prealloc_sessions",
"%"PRIu32,
stream_config.prealloc_sessions);
}
}
}
if (!quiet) {
SCLogConfig("stream \"prealloc-sessions\": %"PRIu32" (per thread)",
stream_config.prealloc_sessions);
}
const char *temp_stream_memcap_str;
if (ConfGetValue("stream.memcap", &temp_stream_memcap_str) == 1) {
uint64_t stream_memcap_copy;
if (ParseSizeStringU64(temp_stream_memcap_str, &stream_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing stream.memcap "
"from conf file - %s. Killing engine",
temp_stream_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.memcap, stream_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.memcap, STREAMTCP_DEFAULT_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream \"memcap\": %"PRIu64, SC_ATOMIC_GET(stream_config.memcap));
}
ConfGetBool("stream.midstream", &stream_config.midstream);
if (!quiet) {
SCLogConfig("stream \"midstream\" session pickups: %s", stream_config.midstream ? "enabled" : "disabled");
}
ConfGetBool("stream.async-oneside", &stream_config.async_oneside);
if (!quiet) {
SCLogConfig("stream \"async-oneside\": %s", stream_config.async_oneside ? "enabled" : "disabled");
}
int csum = 0;
if ((ConfGetBool("stream.checksum-validation", &csum)) == 1) {
if (csum == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
/* Default is that we validate the checksum of all the packets */
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION;
}
if (!quiet) {
SCLogConfig("stream \"checksum-validation\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION ?
"enabled" : "disabled");
}
const char *temp_stream_inline_str;
if (ConfGetValue("stream.inline", &temp_stream_inline_str) == 1) {
int inl = 0;
/* checking for "auto" and falling back to boolean to provide
* backward compatibility */
if (strcmp(temp_stream_inline_str, "auto") == 0) {
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
} else if (ConfGetBool("stream.inline", &inl) == 1) {
if (inl) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
} else {
/* default to 'auto' */
if (EngineModeIsIPS()) {
stream_config.flags |= STREAMTCP_INIT_FLAG_INLINE;
}
}
if (!quiet) {
SCLogConfig("stream.\"inline\": %s",
stream_config.flags & STREAMTCP_INIT_FLAG_INLINE
? "enabled" : "disabled");
}
int bypass = 0;
if ((ConfGetBool("stream.bypass", &bypass)) == 1) {
if (bypass == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_BYPASS;
}
}
if (!quiet) {
SCLogConfig("stream \"bypass\": %s",
(stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS)
? "enabled" : "disabled");
}
int drop_invalid = 0;
if ((ConfGetBool("stream.drop-invalid", &drop_invalid)) == 1) {
if (drop_invalid == 1) {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
} else {
stream_config.flags |= STREAMTCP_INIT_FLAG_DROP_INVALID;
}
if ((ConfGetInt("stream.max-synack-queued", &value)) == 1) {
if (value >= 0 && value <= 255) {
stream_config.max_synack_queued = (uint8_t)value;
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
} else {
stream_config.max_synack_queued = (uint8_t)STREAMTCP_DEFAULT_MAX_SYNACK_QUEUED;
}
if (!quiet) {
SCLogConfig("stream \"max-synack-queued\": %"PRIu8, stream_config.max_synack_queued);
}
const char *temp_stream_reassembly_memcap_str;
if (ConfGetValue("stream.reassembly.memcap", &temp_stream_reassembly_memcap_str) == 1) {
uint64_t stream_reassembly_memcap_copy;
if (ParseSizeStringU64(temp_stream_reassembly_memcap_str,
&stream_reassembly_memcap_copy) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.memcap "
"from conf file - %s. Killing engine",
temp_stream_reassembly_memcap_str);
exit(EXIT_FAILURE);
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap, stream_reassembly_memcap_copy);
}
} else {
SC_ATOMIC_SET(stream_config.reassembly_memcap , STREAMTCP_DEFAULT_REASSEMBLY_MEMCAP);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"memcap\": %"PRIu64"",
SC_ATOMIC_GET(stream_config.reassembly_memcap));
}
const char *temp_stream_reassembly_depth_str;
if (ConfGetValue("stream.reassembly.depth", &temp_stream_reassembly_depth_str) == 1) {
if (ParseSizeStringU32(temp_stream_reassembly_depth_str,
&stream_config.reassembly_depth) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.depth "
"from conf file - %s. Killing engine",
temp_stream_reassembly_depth_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_depth = 0;
}
if (!quiet) {
SCLogConfig("stream.reassembly \"depth\": %"PRIu32"", stream_config.reassembly_depth);
}
int randomize = 0;
if ((ConfGetBool("stream.reassembly.randomize-chunk-size", &randomize)) == 0) {
/* randomize by default if value not set
* In ut mode we disable, to get predictible test results */
if (!(RunmodeIsUnittests()))
randomize = 1;
}
if (randomize) {
const char *temp_rdrange;
if (ConfGetValue("stream.reassembly.randomize-chunk-range",
&temp_rdrange) == 1) {
if (ParseSizeStringU16(temp_rdrange, &rdrange) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.randomize-chunk-range "
"from conf file - %s. Killing engine",
temp_rdrange);
exit(EXIT_FAILURE);
} else if (rdrange >= 100) {
SCLogError(SC_ERR_INVALID_VALUE,
"stream.reassembly.randomize-chunk-range "
"must be lower than 100");
exit(EXIT_FAILURE);
}
}
}
const char *temp_stream_reassembly_toserver_chunk_size_str;
if (ConfGetValue("stream.reassembly.toserver-chunk-size",
&temp_stream_reassembly_toserver_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toserver_chunk_size_str,
&stream_config.reassembly_toserver_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toserver-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toserver_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toserver_chunk_size =
STREAMTCP_DEFAULT_TOSERVER_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toserver_chunk_size +=
(int) (stream_config.reassembly_toserver_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
const char *temp_stream_reassembly_toclient_chunk_size_str;
if (ConfGetValue("stream.reassembly.toclient-chunk-size",
&temp_stream_reassembly_toclient_chunk_size_str) == 1) {
if (ParseSizeStringU16(temp_stream_reassembly_toclient_chunk_size_str,
&stream_config.reassembly_toclient_chunk_size) < 0) {
SCLogError(SC_ERR_SIZE_PARSE, "Error parsing "
"stream.reassembly.toclient-chunk-size "
"from conf file - %s. Killing engine",
temp_stream_reassembly_toclient_chunk_size_str);
exit(EXIT_FAILURE);
}
} else {
stream_config.reassembly_toclient_chunk_size =
STREAMTCP_DEFAULT_TOCLIENT_CHUNK_SIZE;
}
if (randomize) {
long int r = RandomGetWrap();
stream_config.reassembly_toclient_chunk_size +=
(int) (stream_config.reassembly_toclient_chunk_size *
(r * 1.0 / RAND_MAX - 0.5) * rdrange / 100);
}
if (!quiet) {
SCLogConfig("stream.reassembly \"toserver-chunk-size\": %"PRIu16,
stream_config.reassembly_toserver_chunk_size);
SCLogConfig("stream.reassembly \"toclient-chunk-size\": %"PRIu16,
stream_config.reassembly_toclient_chunk_size);
}
int enable_raw = 1;
if (ConfGetBool("stream.reassembly.raw", &enable_raw) == 1) {
if (!enable_raw) {
stream_config.stream_init_flags = STREAMTCP_STREAM_FLAG_DISABLE_RAW;
}
} else {
enable_raw = 1;
}
if (!quiet)
SCLogConfig("stream.reassembly.raw: %s", enable_raw ? "enabled" : "disabled");
/* init the memcap/use tracking */
StreamTcpInitMemuse();
StatsRegisterGlobalCounter("tcp.memuse", StreamTcpMemuseCounter);
StreamTcpReassembleInit(quiet);
/* set the default free function and flow state function
* values. */
FlowSetProtoFreeFunc(IPPROTO_TCP, StreamTcpSessionClear);
#ifdef UNITTESTS
if (RunmodeIsUnittests()) {
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
}
SCMutexUnlock(&ssn_pool_mutex);
}
#endif
}
void StreamTcpFreeConfig(char quiet)
{
SC_ATOMIC_DESTROY(stream_config.memcap);
SC_ATOMIC_DESTROY(stream_config.reassembly_memcap);
StreamTcpReassembleFree(quiet);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool != NULL) {
PoolThreadFree(ssn_pool);
ssn_pool = NULL;
}
SCMutexUnlock(&ssn_pool_mutex);
SCMutexDestroy(&ssn_pool_mutex);
SCLogDebug("ssn_pool_cnt %"PRIu64"", ssn_pool_cnt);
}
/** \internal
* \brief The function is used to to fetch a TCP session from the
* ssn_pool, when a TCP SYN is received.
*
* \param p packet starting the new TCP session.
* \param id thread pool id
*
* \retval ssn new TCP session.
*/
static TcpSession *StreamTcpNewSession (Packet *p, int id)
{
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
p->flow->protoctx = PoolThreadGetById(ssn_pool, id);
#ifdef DEBUG
SCMutexLock(&ssn_pool_mutex);
if (p->flow->protoctx != NULL)
ssn_pool_cnt++;
SCMutexUnlock(&ssn_pool_mutex);
#endif
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
SCLogDebug("ssn_pool is empty");
return NULL;
}
ssn->state = TCP_NONE;
ssn->reassembly_depth = stream_config.reassembly_depth;
ssn->tcp_packet_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.flags = stream_config.stream_init_flags;
ssn->client.flags = stream_config.stream_init_flags;
StreamingBuffer x = STREAMING_BUFFER_INITIALIZER(&stream_config.sbcnf);
ssn->client.sb = x;
ssn->server.sb = x;
if (PKT_IS_TOSERVER(p)) {
ssn->client.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->server.tcp_flags = 0;
} else if (PKT_IS_TOCLIENT(p)) {
ssn->server.tcp_flags = p->tcph ? p->tcph->th_flags : 0;
ssn->client.tcp_flags = 0;
}
}
return ssn;
}
static void StreamTcpPacketSetState(Packet *p, TcpSession *ssn,
uint8_t state)
{
if (state == ssn->state || PKT_IS_PSEUDOPKT(p))
return;
ssn->pstate = ssn->state;
ssn->state = state;
/* update the flow state */
switch(ssn->state) {
case TCP_ESTABLISHED:
case TCP_FIN_WAIT1:
case TCP_FIN_WAIT2:
case TCP_CLOSING:
case TCP_CLOSE_WAIT:
FlowUpdateState(p->flow, FLOW_STATE_ESTABLISHED);
break;
case TCP_LAST_ACK:
case TCP_TIME_WAIT:
case TCP_CLOSED:
FlowUpdateState(p->flow, FLOW_STATE_CLOSED);
break;
}
}
/**
* \brief Function to set the OS policy for the given stream based on the
* destination of the received packet.
*
* \param stream TcpStream of which os_policy needs to set
* \param p Packet which is used to set the os policy
*/
void StreamTcpSetOSPolicy(TcpStream *stream, Packet *p)
{
int ret = 0;
if (PKT_IS_IPV4(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv4HostOSFlavour((uint8_t *)GET_IPV4_DST_ADDR_PTR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
} else if (PKT_IS_IPV6(p)) {
/* Get the OS policy based on destination IP address, as destination
OS will decide how to react on the anomalies of newly received
packets */
ret = SCHInfoGetIPv6HostOSFlavour((uint8_t *)GET_IPV6_DST_ADDR(p));
if (ret > 0)
stream->os_policy = ret;
else
stream->os_policy = OS_POLICY_DEFAULT;
}
if (stream->os_policy == OS_POLICY_BSD_RIGHT)
stream->os_policy = OS_POLICY_BSD;
else if (stream->os_policy == OS_POLICY_OLD_SOLARIS)
stream->os_policy = OS_POLICY_SOLARIS;
SCLogDebug("Policy is %"PRIu8"", stream->os_policy);
}
/**
* \brief macro to update last_ack only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param ack ACK value to test and set
*/
#define StreamTcpUpdateLastAck(ssn, stream, ack) { \
if (SEQ_GT((ack), (stream)->last_ack)) \
{ \
SCLogDebug("ssn %p: last_ack set to %"PRIu32", moved %u forward", (ssn), (ack), (ack) - (stream)->last_ack); \
if ((SEQ_LEQ((stream)->last_ack, (stream)->next_seq) && SEQ_GT((ack),(stream)->next_seq))) { \
SCLogDebug("last_ack just passed next_seq: %u (was %u) > %u", (ack), (stream)->last_ack, (stream)->next_seq); \
} else { \
SCLogDebug("next_seq (%u) <> last_ack now %d", (stream)->next_seq, (int)(stream)->next_seq - (ack)); \
}\
(stream)->last_ack = (ack); \
StreamTcpSackPruneList((stream)); \
} else { \
SCLogDebug("ssn %p: no update: ack %u, last_ack %"PRIu32", next_seq %u (state %u)", \
(ssn), (ack), (stream)->last_ack, (stream)->next_seq, (ssn)->state); \
}\
}
#define StreamTcpAsyncLastAckUpdate(ssn, stream) { \
if ((ssn)->flags & STREAMTCP_FLAG_ASYNC) { \
if (SEQ_GT((stream)->next_seq, (stream)->last_ack)) { \
uint32_t ack_diff = (stream)->next_seq - (stream)->last_ack; \
(stream)->last_ack += ack_diff; \
SCLogDebug("ssn %p: ASYNC last_ack set to %"PRIu32", moved %u forward", \
(ssn), (stream)->next_seq, ack_diff); \
} \
} \
}
#define StreamTcpUpdateNextSeq(ssn, stream, seq) { \
(stream)->next_seq = seq; \
SCLogDebug("ssn %p: next_seq %" PRIu32, (ssn), (stream)->next_seq); \
StreamTcpAsyncLastAckUpdate((ssn), (stream)); \
}
/**
* \brief macro to update next_win only if the new value is higher
*
* \param ssn session
* \param stream stream to update
* \param win window value to test and set
*/
#define StreamTcpUpdateNextWin(ssn, stream, win) { \
uint32_t sacked_size__ = StreamTcpSackedSize((stream)); \
if (SEQ_GT(((win) + sacked_size__), (stream)->next_win)) { \
(stream)->next_win = ((win) + sacked_size__); \
SCLogDebug("ssn %p: next_win set to %"PRIu32, (ssn), (stream)->next_win); \
} \
}
static int StreamTcpPacketIsRetransmission(TcpStream *stream, Packet *p)
{
if (p->payload_len == 0)
SCReturnInt(0);
/* retransmission of already partially ack'd data */
if (SEQ_LT(TCP_GET_SEQ(p), stream->last_ack) && SEQ_GT((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack))
{
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of already ack'd data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->last_ack)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(1);
}
/* retransmission of in flight data */
if (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), stream->next_seq)) {
StreamTcpSetEvent(p, STREAM_PKT_RETRANSMISSION);
SCReturnInt(2);
}
SCLogDebug("seq %u payload_len %u => %u, last_ack %u, next_seq %u", TCP_GET_SEQ(p),
p->payload_len, (TCP_GET_SEQ(p) + p->payload_len), stream->last_ack, stream->next_seq);
SCReturnInt(0);
}
/**
* \internal
* \brief Function to handle the TCP_CLOSED or NONE state. The function handles
* packets while the session state is None which means a newly
* initialized structure, or a fully closed session.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateNone(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (p->tcph->th_flags & TH_RST) {
StreamTcpSetEvent(p, STREAM_RST_BUT_NO_SESSION);
SCLogDebug("RST packet received, no session setup");
return -1;
} else if (p->tcph->th_flags & TH_FIN) {
StreamTcpSetEvent(p, STREAM_FIN_BUT_NO_SESSION);
SCLogDebug("FIN packet received, no session setup");
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if (stream_config.midstream == FALSE &&
stream_config.async_oneside == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
StatsIncr(tv, stt->counter_tcp_midstream_pickups);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_SYN_RECV", ssn);
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM;
/* Flag used to change the direct in the later stage in the session */
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_SYNACK;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* sequence number & window */
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: server window %u", ssn, ssn->server.window);
ssn->client.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->client.last_ack = TCP_GET_ACK(p);
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
/** If the client has a wscale option the server had it too,
* so set the wscale for the server to max. Otherwise none
* will have the wscale opt just like it should. */
if (TCP_HAS_WSCALE(p)) {
ssn->client.wscale = TCP_GET_WSCALE(p);
ssn->server.wscale = TCP_WSCALE_MAX;
SCLogDebug("ssn %p: wscale enabled. client %u server %u",
ssn, ssn->client.wscale, ssn->server.wscale);
}
SCLogDebug("ssn %p: ssn->client.isn %"PRIu32", ssn->client.next_seq"
" %"PRIu32", ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
SCLogDebug("ssn %p: ssn->server.isn %"PRIu32", ssn->server.next_seq"
" %"PRIu32", ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
ssn->client.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SYN/ACK with SACK permitted, assuming "
"SACK permitted for both sides", ssn);
}
/* packet thinks it is in the wrong direction, flip it */
StreamTcpPacketSwitchDir(ssn, p);
} else if (p->tcph->th_flags & TH_SYN) {
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_SENT);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_SENT", ssn);
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
/* Set the stream timestamp value, if packet has timestamp option
* enabled. */
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->client.last_ts);
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
SCLogDebug("ssn %p: SACK permited on SYN packet", ssn);
}
SCLogDebug("ssn %p: ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", ssn->client.last_ack "
"%"PRIu32"", ssn, ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
} else if (p->tcph->th_flags & TH_ACK) {
if (stream_config.midstream == FALSE)
return 0;
if (ssn == NULL) {
ssn = StreamTcpNewSession(p, stt->ssn_pool_id);
if (ssn == NULL) {
StatsIncr(tv, stt->counter_tcp_ssn_memcap);
return -1;
}
StatsIncr(tv, stt->counter_tcp_sessions);
StatsIncr(tv, stt->counter_tcp_midstream_pickups);
}
/* set the state */
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ midstream picked ssn state is now "
"TCP_ESTABLISHED", ssn);
ssn->flags = STREAMTCP_FLAG_MIDSTREAM;
ssn->flags |= STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
if (stream_config.async_oneside) {
SCLogDebug("ssn %p: =~ ASYNC", ssn);
ssn->flags |= STREAMTCP_FLAG_ASYNC;
}
/** window scaling for midstream pickups, we can't do much other
* than assume that it's set to the max value: 14 */
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->server.wscale = TCP_WSCALE_MAX;
/* set the sequence numbers and window */
ssn->client.isn = TCP_GET_SEQ(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->client.isn %u, ssn->client.next_seq %u",
ssn, ssn->client.isn, ssn->client.next_seq);
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: ssn->client.next_win %"PRIu32", "
"ssn->server.next_win %"PRIu32"", ssn,
ssn->client.next_win, ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.last_ack %"PRIu32", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->client.last_ack, ssn->server.last_ack);
/* Set the timestamp value for both streams, if packet has timestamp
* option enabled.*/
if (TCP_HAS_TS(p)) {
ssn->client.last_ts = TCP_GET_TSVAL(p);
ssn->server.last_ts = TCP_GET_TSECR(p);
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: assuming SACK permitted for both sides", ssn);
} else {
SCLogDebug("default case");
}
return 0;
}
/** \internal
* \brief Setup TcpStateQueue based on SYN/ACK packet
*/
static inline void StreamTcp3whsSynAckToStateQueue(Packet *p, TcpStateQueue *q)
{
q->flags = 0;
q->wscale = 0;
q->ts = 0;
q->win = TCP_GET_WINDOW(p);
q->seq = TCP_GET_SEQ(p);
q->ack = TCP_GET_ACK(p);
q->pkt_ts = p->ts.tv_sec;
if (TCP_GET_SACKOK(p) == 1)
q->flags |= STREAMTCP_QUEUE_FLAG_SACK;
if (TCP_HAS_WSCALE(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_WS;
q->wscale = TCP_GET_WSCALE(p);
}
if (TCP_HAS_TS(p)) {
q->flags |= STREAMTCP_QUEUE_FLAG_TS;
q->ts = TCP_GET_TSVAL(p);
}
}
/** \internal
* \brief Find the Queued SYN/ACK that is the same as this SYN/ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckBySynAck(TcpSession *ssn, Packet *p)
{
TcpStateQueue *q = ssn->queue;
TcpStateQueue search;
StreamTcp3whsSynAckToStateQueue(p, &search);
while (q != NULL) {
if (search.flags == q->flags &&
search.wscale == q->wscale &&
search.win == q->win &&
search.seq == q->seq &&
search.ack == q->ack &&
search.ts == q->ts) {
return q;
}
q = q->next;
}
return q;
}
static int StreamTcp3whsQueueSynAck(TcpSession *ssn, Packet *p)
{
/* first see if this is already in our list */
if (StreamTcp3whsFindSynAckBySynAck(ssn, p) != NULL)
return 0;
if (ssn->queue_len == stream_config.max_synack_queued) {
SCLogDebug("ssn %p: =~ SYN/ACK queue limit reached", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_FLOOD);
return -1;
}
if (StreamTcpCheckMemcap((uint32_t)sizeof(TcpStateQueue)) == 0) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: stream memcap reached", ssn);
return -1;
}
TcpStateQueue *q = SCMalloc(sizeof(*q));
if (unlikely(q == NULL)) {
SCLogDebug("ssn %p: =~ SYN/ACK queue failed: alloc failed", ssn);
return -1;
}
memset(q, 0x00, sizeof(*q));
StreamTcpIncrMemuse((uint64_t)sizeof(TcpStateQueue));
StreamTcp3whsSynAckToStateQueue(p, q);
/* put in list */
q->next = ssn->queue;
ssn->queue = q;
ssn->queue_len++;
return 0;
}
/** \internal
* \brief Find the Queued SYN/ACK that goes with this ACK
* \retval q or NULL */
static TcpStateQueue *StreamTcp3whsFindSynAckByAck(TcpSession *ssn, Packet *p)
{
uint32_t ack = TCP_GET_SEQ(p);
uint32_t seq = TCP_GET_ACK(p) - 1;
TcpStateQueue *q = ssn->queue;
while (q != NULL) {
if (seq == q->seq &&
ack == q->ack) {
return q;
}
q = q->next;
}
return NULL;
}
/** \internal
* \brief Update SSN after receiving a valid SYN/ACK
*
* Normally we update the SSN from the SYN/ACK packet. But in case
* of queued SYN/ACKs, we can use one of those.
*
* \param ssn TCP session
* \param p Packet
* \param q queued state if used, NULL otherwise
*
* To make sure all SYN/ACK based state updates are in one place,
* this function can updated based on Packet or TcpStateQueue, where
* the latter takes precedence.
*/
static void StreamTcp3whsSynAckUpdate(TcpSession *ssn, Packet *p, TcpStateQueue *q)
{
TcpStateQueue update;
if (likely(q == NULL)) {
StreamTcp3whsSynAckToStateQueue(p, &update);
q = &update;
}
if (ssn->state != TCP_SYN_RECV) {
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ ssn state is now TCP_SYN_RECV", ssn);
}
/* sequence number & window */
ssn->server.isn = q->seq;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->client.window = q->win;
SCLogDebug("ssn %p: window %" PRIu32 "", ssn, ssn->server.window);
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if ((q->flags & STREAMTCP_QUEUE_FLAG_TS) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->server.last_ts = q->ts;
SCLogDebug("ssn %p: ssn->server.last_ts %" PRIu32" "
"ssn->client.last_ts %" PRIu32"", ssn,
ssn->server.last_ts, ssn->client.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->server.last_pkt_ts = q->pkt_ts;
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->client.last_ts = 0;
ssn->server.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->client.last_ack = q->ack;
ssn->server.last_ack = ssn->server.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(q->flags & STREAMTCP_QUEUE_FLAG_WS))
{
ssn->client.wscale = q->wscale;
} else {
ssn->client.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
(q->flags & STREAMTCP_QUEUE_FLAG_SACK)) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for session", ssn);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SACKOK;
}
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %" PRIu32 " "
"(ssn->client.last_ack %" PRIu32 ")", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack, ssn->client.last_ack);
/* unset the 4WHS flag as we received this SYN/ACK as part of a
* (so far) valid 3WHS */
if (ssn->flags & STREAMTCP_FLAG_4WHS)
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS unset, normal SYN/ACK"
" so considering 3WHS", ssn);
ssn->flags &=~ STREAMTCP_FLAG_4WHS;
}
/** \internal
* \brief detect timestamp anomalies when processing responses to the
* SYN packet.
* \retval true packet is ok
* \retval false packet is bad
*/
static inline bool StateSynSentValidateTimestamp(TcpSession *ssn, Packet *p)
{
/* we only care about evil server here, so skip TS packets */
if (PKT_IS_TOSERVER(p) || !(TCP_HAS_TS(p))) {
return true;
}
TcpStream *receiver_stream = &ssn->client;
uint32_t ts_echo = TCP_GET_TSECR(p);
if ((receiver_stream->flags & STREAMTCP_STREAM_FLAG_TIMESTAMP) != 0) {
if (receiver_stream->last_ts != 0 && ts_echo != 0 &&
ts_echo != receiver_stream->last_ts)
{
SCLogDebug("ssn %p: BAD TSECR echo %u recv %u", ssn,
ts_echo, receiver_stream->last_ts);
return false;
}
} else {
if (receiver_stream->last_ts == 0 && ts_echo != 0) {
SCLogDebug("ssn %p: BAD TSECR echo %u recv %u", ssn,
ts_echo, receiver_stream->last_ts);
return false;
}
}
return true;
}
/**
* \brief Function to handle the TCP_SYN_SENT state. The function handles
* SYN, SYN/ACK, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateSynSent(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
SCLogDebug("ssn %p: pkt received: %s", ssn, PKT_IS_TOCLIENT(p) ?
"toclient":"toserver");
/* check for bad responses */
if (StateSynSentValidateTimestamp(ssn, p) == false)
return -1;
/* RST */
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn) &&
SEQ_EQ(TCP_GET_WINDOW(p), 0) &&
SEQ_EQ(TCP_GET_ACK(p), (ssn->client.isn + 1)))
{
SCLogDebug("ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
ssn->server.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV;
SCLogDebug("ssn->client.flags |= STREAMTCP_STREAM_FLAG_RST_RECV");
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
}
/* FIN */
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK received on 4WHS session", ssn);
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->server.isn + 1))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: 4WHS ACK mismatch, packet ACK %"PRIu32""
" != %" PRIu32 " from stream", ssn,
TCP_GET_ACK(p), ssn->server.isn + 1);
return -1;
}
/* Check if the SYN/ACK packet SEQ's the *FIRST* received SYN
* packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
StreamTcpSetEvent(p, STREAM_4WHS_SYNACK_WITH_WRONG_SYN);
SCLogDebug("ssn %p: 4WHS SEQ mismatch, packet SEQ %"PRIu32""
" != %" PRIu32 " from *first* SYN pkt", ssn,
TCP_GET_SEQ(p), ssn->client.isn);
return -1;
}
/* update state */
StreamTcpPacketSetState(p, ssn, TCP_SYN_RECV);
SCLogDebug("ssn %p: =~ 4WHS ssn state is now TCP_SYN_RECV", ssn);
/* sequence number & window */
ssn->client.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->client, ssn->client.isn);
ssn->client.next_seq = ssn->client.isn + 1;
ssn->server.window = TCP_GET_WINDOW(p);
SCLogDebug("ssn %p: 4WHS window %" PRIu32 "", ssn,
ssn->client.window);
/* Set the timestamp values used to validate the timestamp of
* received packets. */
if ((TCP_HAS_TS(p)) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->client.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: 4WHS ssn->client.last_ts %" PRIu32" "
"ssn->server.last_ts %" PRIu32"", ssn,
ssn->client.last_ts, ssn->server.last_ts);
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
if (ssn->client.last_ts == 0)
ssn->client.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
} else {
ssn->server.last_ts = 0;
ssn->client.last_ts = 0;
ssn->server.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
ssn->server.last_ack = TCP_GET_ACK(p);
ssn->client.last_ack = ssn->client.isn + 1;
/** check for the presense of the ws ptr to determine if we
* support wscale at all */
if ((ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) &&
(TCP_HAS_WSCALE(p)))
{
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->server.wscale = 0;
}
if ((ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) &&
TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
SCLogDebug("ssn %p: SACK permitted for 4WHS session", ssn);
}
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
SCLogDebug("ssn %p: 4WHS ssn->client.next_win %" PRIu32 "", ssn,
ssn->client.next_win);
SCLogDebug("ssn %p: 4WHS ssn->server.next_win %" PRIu32 "", ssn,
ssn->server.next_win);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %" PRIu32 " "
"(ssn->server.last_ack %" PRIu32 ")", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack, ssn->server.last_ack);
/* done here */
return 0;
}
if (PKT_IS_TOSERVER(p)) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_IN_WRONG_DIRECTION);
SCLogDebug("ssn %p: SYN/ACK received in the wrong direction", ssn);
return -1;
}
/* Check if the SYN/ACK packet ack's the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.isn + 1))) {
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_WITH_WRONG_ACK);
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
return -1;
}
StreamTcp3whsSynAckUpdate(ssn, p, /* no queue override */NULL);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent", ssn);
if (ssn->flags & STREAMTCP_FLAG_4WHS) {
SCLogDebug("ssn %p: SYN packet on state SYN_SENT... resent of "
"4WHS SYN", ssn);
}
if (PKT_IS_TOCLIENT(p)) {
/** a SYN only packet in the opposite direction could be:
* http://www.breakingpointsystems.com/community/blog/tcp-
* portals-the-three-way-handshake-is-a-lie
*
* \todo improve resetting the session */
/* indicate that we're dealing with 4WHS here */
ssn->flags |= STREAMTCP_FLAG_4WHS;
SCLogDebug("ssn %p: STREAMTCP_FLAG_4WHS flag set", ssn);
/* set the sequence numbers and window for server
* We leave the ssn->client.isn in place as we will
* check the SYN/ACK pkt with that.
*/
ssn->server.isn = TCP_GET_SEQ(p);
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
/* Set the stream timestamp value, if packet has timestamp
* option enabled. */
if (TCP_HAS_TS(p)) {
ssn->server.last_ts = TCP_GET_TSVAL(p);
SCLogDebug("ssn %p: %02x", ssn, ssn->server.last_ts);
if (ssn->server.last_ts == 0)
ssn->server.flags |= STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
ssn->server.last_pkt_ts = p->ts.tv_sec;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TIMESTAMP;
}
ssn->server.window = TCP_GET_WINDOW(p);
if (TCP_HAS_WSCALE(p)) {
ssn->flags |= STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = TCP_GET_WSCALE(p);
} else {
ssn->flags &= ~STREAMTCP_FLAG_SERVER_WSCALE;
ssn->server.wscale = 0;
}
if (TCP_GET_SACKOK(p) == 1) {
ssn->flags |= STREAMTCP_FLAG_CLIENT_SACKOK;
} else {
ssn->flags &= ~STREAMTCP_FLAG_CLIENT_SACKOK;
}
SCLogDebug("ssn %p: 4WHS ssn->server.isn %" PRIu32 ", "
"ssn->server.next_seq %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.isn, ssn->server.next_seq,
ssn->server.last_ack);
SCLogDebug("ssn %p: 4WHS ssn->client.isn %" PRIu32 ", "
"ssn->client.next_seq %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.isn, ssn->client.next_seq,
ssn->client.last_ack);
}
/** \todo check if it's correct or set event */
} else if (p->tcph->th_flags & TH_ACK) {
/* Handle the asynchronous stream, when we receive a SYN packet
and now istead of receving a SYN/ACK we receive a ACK from the
same host, which sent the SYN, this suggests the ASNYC streams.*/
if (stream_config.async_oneside == FALSE)
return 0;
/* we are in AYNC (one side) mode now. */
/* one side async means we won't see a SYN/ACK, so we can
* only check the SYN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))) {
StreamTcpSetEvent(p, STREAM_3WHS_ASYNC_WRONG_SEQ);
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream",ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
return -1;
}
ssn->flags |= STREAMTCP_FLAG_ASYNC;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
ssn->client.window = TCP_GET_WINDOW(p);
ssn->client.last_ack = TCP_GET_SEQ(p);
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
/* Set the server side parameters */
ssn->server.isn = TCP_GET_ACK(p) - 1;
STREAMTCP_SET_RA_BASE_SEQ(&ssn->server, ssn->server.isn);
ssn->server.next_seq = ssn->server.isn + 1;
ssn->server.last_ack = ssn->server.next_seq;
ssn->server.next_win = ssn->server.last_ack;
SCLogDebug("ssn %p: synsent => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.next_seq %" PRIu32 ""
,ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->client.next_seq);
/* if SYN had wscale, assume it to be supported. Otherwise
* we know it not to be supported. */
if (ssn->flags & STREAMTCP_FLAG_SERVER_WSCALE) {
ssn->client.wscale = TCP_WSCALE_MAX;
}
/* Set the timestamp values used to validate the timestamp of
* received packets.*/
if (TCP_HAS_TS(p) &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_TIMESTAMP))
{
ssn->flags |= STREAMTCP_FLAG_TIMESTAMP;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_TIMESTAMP;
ssn->client.last_pkt_ts = p->ts.tv_sec;
} else {
ssn->client.last_ts = 0;
ssn->client.flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
}
if (ssn->flags & STREAMTCP_FLAG_CLIENT_SACKOK) {
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_SYN_RECV state. The function handles
* SYN, SYN/ACK, ACK, FIN, RST packets and correspondingly changes
* the connection state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 ok
* \retval -1 error
*/
static int StreamTcpPacketStateSynRecv(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
uint8_t reset = TRUE;
/* After receiveing the RST in SYN_RECV state and if detection
evasion flags has been set, then the following operating
systems will not closed the connection. As they consider the
packet as stray packet and not belonging to the current
session, for more information check
http://www.packetstan.com/2010/06/recently-ive-been-on-campaign-to-make.html */
if (ssn->flags & STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT) {
if (PKT_IS_TOSERVER(p)) {
if ((ssn->server.os_policy == OS_POLICY_LINUX) ||
(ssn->server.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->server.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
} else {
if ((ssn->client.os_policy == OS_POLICY_LINUX) ||
(ssn->client.os_policy == OS_POLICY_OLD_LINUX) ||
(ssn->client.os_policy == OS_POLICY_SOLARIS))
{
reset = FALSE;
SCLogDebug("Detection evasion has been attempted, so"
" not resetting the connection !!");
}
}
}
if (reset == TRUE) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
}
} else if (p->tcph->th_flags & TH_FIN) {
/* FIN is handled in the same way as in TCP_ESTABLISHED case */;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state SYN_RECV. resent", ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_TOSERVER_ON_SYN_RECV);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_3WHS_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN/ACK packet, server resend with different ISN. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.isn);
if (StreamTcp3whsQueueSynAck(ssn, p) == -1)
return -1;
SCLogDebug("ssn %p: queued different SYN/ACK", ssn);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state SYN_RECV... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_TOCLIENT_ON_SYN_RECV);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_SYN_RESEND_DIFF_SEQ_ON_SYN_RECV);
return -1;
}
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->queue_len) {
SCLogDebug("ssn %p: checking ACK against queued SYN/ACKs", ssn);
TcpStateQueue *q = StreamTcp3whsFindSynAckByAck(ssn, p);
if (q != NULL) {
SCLogDebug("ssn %p: here we update state against queued SYN/ACK", ssn);
StreamTcp3whsSynAckUpdate(ssn, p, /* using queue to update state */q);
} else {
SCLogDebug("ssn %p: none found, now checking ACK against original SYN/ACK (state)", ssn);
}
}
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323)*/
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!(StreamTcpValidateTimestamp(ssn, p))) {
return -1;
}
}
if ((ssn->flags & STREAMTCP_FLAG_4WHS) && PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: ACK received on 4WHS session",ssn);
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))) {
SCLogDebug("ssn %p: 4WHS wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: 4WHS invalid ack nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_4WHS_INVALID_ACK);
return -1;
}
SCLogDebug("4WHS normal pkt");
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: ssn->client.next_win %" PRIu32 ", "
"ssn->client.last_ack %"PRIu32"", ssn,
ssn->client.next_win, ssn->client.last_ack);
return 0;
}
bool ack_indicates_missed_3whs_ack_packet = false;
/* Check if the ACK received is in right direction. But when we have
* picked up a mid stream session after missing the initial SYN pkt,
* in this case the ACK packet can arrive from either client (normal
* case) or from server itself (asynchronous streams). Therefore
* the check has been avoided in this case */
if (PKT_IS_TOCLIENT(p)) {
/* special case, handle 4WHS, so SYN/ACK in the opposite
* direction */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK) {
SCLogDebug("ssn %p: ACK received on midstream SYN/ACK "
"pickup session",ssn);
/* fall through */
} else {
/* if we missed traffic between the S/SA and the current
* 'wrong direction' ACK, we could end up here. In IPS
* reject it. But in IDS mode we continue.
*
* IPS rejects as it should see all packets, so pktloss
* should lead to retransmissions. As this can also be
* pattern for MOTS/MITM injection attacks, we need to be
* careful.
*/
if (StreamTcpInlineMode()) {
if (p->payload_len > 0 &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) &&
SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
/* packet loss is possible but unlikely here */
SCLogDebug("ssn %p: possible data injection", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_DATA_INJECT);
return -1;
}
SCLogDebug("ssn %p: ACK received in the wrong direction",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_ACK_IN_WRONG_DIR);
return -1;
}
ack_indicates_missed_3whs_ack_packet = true;
}
}
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ""
", ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
/* Check both seq and ack number before accepting the packet and
changing to ESTABLISHED state */
if ((SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq)) {
SCLogDebug("normal pkt");
/* process the packet normal, No Async streams :) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.next_win = ssn->client.last_ack + ssn->client.window;
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
if (!(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)) {
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* If asynchronous stream handling is allowed then set the session,
if packet's seq number is equal the expected seq no.*/
} else if (stream_config.async_oneside == TRUE &&
(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)))
{
/*set the ASYNC flag used to indicate the session as async stream
and helps in relaxing the windows checks.*/
ssn->flags |= STREAMTCP_FLAG_ASYNC;
ssn->server.next_seq += p->payload_len;
ssn->server.last_ack = TCP_GET_SEQ(p);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
ssn->client.last_ack = TCP_GET_ACK(p);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->server.window = TCP_GET_WINDOW(p);
ssn->client.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
SCLogDebug("ssn %p: synrecv => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->server.next_seq %" PRIu32 "\n"
, ssn, TCP_GET_SEQ(p), p->payload_len, TCP_GET_SEQ(p)
+ p->payload_len, ssn->server.next_seq);
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
/* Upon receiving the packet with correct seq number and wrong
ACK number, it causes the other end to send RST. But some target
system (Linux & solaris) does not RST the connection, so it is
likely to avoid the detection */
} else if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)){
ssn->flags |= STREAMTCP_FLAG_DETECTION_EVASION_ATTEMPT;
SCLogDebug("ssn %p: wrong ack nr on packet, possible evasion!!",
ssn);
StreamTcpSetEvent(p, STREAM_3WHS_RIGHT_SEQ_WRONG_ACK_EVASION);
return -1;
/* if we get a packet with a proper ack, but a seq that is beyond
* next_seq but in-window, we probably missed some packets */
} else if (SEQ_GT(TCP_GET_SEQ(p), ssn->client.next_seq) &&
SEQ_LEQ(TCP_GET_SEQ(p),ssn->client.next_win) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.next_seq))
{
SCLogDebug("ssn %p: ACK for missing data", ssn);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ACK for missing data: ssn->client.next_seq %u", ssn, ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM) {
ssn->client.window = TCP_GET_WINDOW(p);
ssn->server.next_win = ssn->server.last_ack +
ssn->server.window;
/* window scaling for midstream pickups, we can't do much
* other than assume that it's set to the max value: 14 */
ssn->server.wscale = TCP_WSCALE_MAX;
ssn->client.wscale = TCP_WSCALE_MAX;
ssn->flags |= STREAMTCP_FLAG_SACKOK;
}
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
/* toclient packet: after having missed the 3whs's final ACK */
} else if (ack_indicates_missed_3whs_ack_packet &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack) &&
SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
{
SCLogDebug("ssn %p: packet fits perfectly after a missed 3whs-ACK", ssn);
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
StreamTcpPacketSetState(p, ssn, TCP_ESTABLISHED);
SCLogDebug("ssn %p: =~ ssn state is now TCP_ESTABLISHED", ssn);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: wrong seq nr on packet", ssn);
StreamTcpSetEvent(p, STREAM_3WHS_WRONG_SEQ_WRONG_ACK);
return -1;
}
SCLogDebug("ssn %p: ssn->server.next_win %" PRIu32 ", "
"ssn->server.last_ack %"PRIu32"", ssn,
ssn->server.next_win, ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the client to server. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly.
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToServer(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
"ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &(ssn->server), p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->client.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->client.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: server => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
"%" PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* update the last_ack to current seq number as the session is
* async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ."
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :( */
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
} else if (SEQ_EQ(ssn->client.last_ack, (ssn->client.isn + 1)) &&
(stream_config.async_oneside == TRUE) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM)) {
SCLogDebug("ssn %p: server => Asynchronous stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
/* it seems we missed SYN and SYN/ACK packets of this session.
* Update the last_ack to current seq number as the session
* is async and other stream is not updating it anymore :(*/
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_SEQ(p));
ssn->flags |= STREAMTCP_FLAG_ASYNC;
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->client.last_ack, ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->client.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->client.last_ack, ssn->client.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: server => SEQ before last_ack, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "), "
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->client.next_win);
SCLogDebug("ssn %p: rejecting because pkt before last_ack", ssn);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->client.next_seq && ssn->client.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->client.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->client.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (started before next_seq, ended after)",
ssn, ssn->client.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->client.next_seq, ssn->client.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->client.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->client.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->client.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->client.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->client.last_ack);
}
/* in window check */
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
SCLogDebug("ssn %p: ssn->server.window %"PRIu32"", ssn,
ssn->server.window);
/* Check if the ACK value is sane and inside the window limit */
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
SCLogDebug("ack %u last_ack %u next_seq %u", TCP_GET_ACK(p), ssn->server.last_ack, ssn->server.next_seq);
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
/* handle data (if any) */
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
} else {
SCLogDebug("ssn %p: toserver => SEQ out of window, packet SEQ "
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
"ssn->client.last_ack %" PRIu32 ", ssn->client.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->client.last_ack, ssn->client.next_win,
(TCP_GET_SEQ(p) + p->payload_len) - ssn->client.next_win);
SCLogDebug("ssn %p: window %u sacked %u", ssn, ssn->client.window,
StreamTcpSackedSize(&ssn->client));
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \brief Function to handle the TCP_ESTABLISHED state packets, which are
* sent by the server to client. The function handles
* ACK packets and call StreamTcpReassembleHandleSegment() to handle
* the reassembly
*
* Timestamp has already been checked at this point.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param ssn Pointer to the current TCP session
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int HandleEstablishedPacketToClient(ThreadVars *tv, TcpSession *ssn, Packet *p,
StreamTcpThread *stt, PacketQueue *pq)
{
SCLogDebug("ssn %p: =+ pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ","
" ACK %" PRIu32 ", WIN %"PRIu16"", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p), TCP_GET_WINDOW(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_EST_INVALID_ACK);
return -1;
}
/* To get the server window value from the servers packet, when connection
is picked up as midstream */
if ((ssn->flags & STREAMTCP_FLAG_MIDSTREAM) &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED))
{
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
ssn->server.next_win = ssn->server.last_ack + ssn->server.window;
ssn->flags &= ~STREAMTCP_FLAG_MIDSTREAM_ESTABLISHED;
SCLogDebug("ssn %p: adjusted midstream ssn->server.next_win to "
"%" PRIu32 "", ssn, ssn->server.next_win);
}
/* check for Keep Alive */
if ((p->payload_len == 0 || p->payload_len == 1) &&
(TCP_GET_SEQ(p) == (ssn->server.next_seq - 1))) {
SCLogDebug("ssn %p: pkt is keep alive", ssn);
/* normal pkt */
} else if (!(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len), ssn->server.last_ack))) {
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
SCLogDebug("ssn %p: client => Asynchrouns stream, packet SEQ"
" %" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->client.last_ack %" PRIu32 ", ssn->client.next_win"
" %"PRIu32"(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
ssn->server.last_ack = TCP_GET_SEQ(p);
/* if last ack is beyond next_seq, we have accepted ack's for missing data.
* In this case we do accept the data before last_ack if it is (partly)
* beyond next seq */
} else if (SEQ_GT(ssn->server.last_ack, ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len),ssn->server.next_seq))
{
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32", after next_seq %"PRIu32":"
" acked data that we haven't seen before",
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
} else {
SCLogDebug("ssn %p: PKT SEQ %"PRIu32" payload_len %"PRIu16
" before last_ack %"PRIu32". next_seq %"PRIu32,
ssn, TCP_GET_SEQ(p), p->payload_len, ssn->server.last_ack, ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_EST_PKT_BEFORE_LAST_ACK);
return -1;
}
}
int zerowindowprobe = 0;
/* zero window probe */
if (p->payload_len == 1 && TCP_GET_SEQ(p) == ssn->server.next_seq && ssn->server.window == 0) {
SCLogDebug("ssn %p: zero window probe", ssn);
zerowindowprobe = 1;
/* expected packet */
} else if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
/* not completely as expected, but valid */
} else if (SEQ_LT(TCP_GET_SEQ(p),ssn->server.next_seq) &&
SEQ_GT((TCP_GET_SEQ(p)+p->payload_len), ssn->server.next_seq))
{
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32
" (started before next_seq, ended after)",
ssn, ssn->server.next_seq);
/* if next_seq has fallen behind last_ack, we got some catching up to do */
} else if (SEQ_LT(ssn->server.next_seq, ssn->server.last_ack)) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (TCP_GET_SEQ(p) + p->payload_len));
SCLogDebug("ssn %p: ssn->server.next_seq %"PRIu32
" (next_seq had fallen behind last_ack)",
ssn, ssn->server.next_seq);
} else {
SCLogDebug("ssn %p: no update to ssn->server.next_seq %"PRIu32
" SEQ %u SEQ+ %u last_ack %u",
ssn, ssn->server.next_seq,
TCP_GET_SEQ(p), TCP_GET_SEQ(p)+p->payload_len, ssn->server.last_ack);
}
if (zerowindowprobe) {
SCLogDebug("ssn %p: zero window probe, skipping oow check", ssn);
} else if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
SCLogDebug("ssn %p: ssn->client.window %"PRIu32"", ssn,
ssn->client.window);
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpSackUpdatePacket(&ssn->client, p);
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
} else {
SCLogDebug("ssn %p: client => SEQ out of window, packet SEQ"
"%" PRIu32 ", payload size %" PRIu32 " (%" PRIu32 "),"
" ssn->server.last_ack %" PRIu32 ", ssn->server.next_win "
"%" PRIu32 "(%"PRIu32")", ssn, TCP_GET_SEQ(p),
p->payload_len, TCP_GET_SEQ(p) + p->payload_len,
ssn->server.last_ack, ssn->server.next_win,
TCP_GET_SEQ(p) + p->payload_len - ssn->server.next_win);
StreamTcpSetEvent(p, STREAM_EST_PACKET_OUT_OF_WINDOW);
return -1;
}
return 0;
}
/**
* \internal
*
* \brief Find the highest sequence number needed to consider all segments as ACK'd
*
* Used to treat all segments as ACK'd upon receiving a valid RST.
*
* \param stream stream to inspect the segments from
* \param seq sequence number to check against
*
* \retval ack highest ack we need to set
*/
static inline uint32_t StreamTcpResetGetMaxAck(TcpStream *stream, uint32_t seq)
{
uint32_t ack = seq;
if (STREAM_HAS_SEEN_DATA(stream)) {
const uint32_t tail_seq = STREAM_SEQ_RIGHT_EDGE(stream);
if (SEQ_GT(tail_seq, ack)) {
ack = tail_seq;
}
}
SCReturnUInt(ack);
}
/**
* \brief Function to handle the TCP_ESTABLISHED state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state. The function handles the data inside packets and call
* StreamTcpReassembleHandleSegment(tv, ) to handle the reassembling.
*
* \param tv Thread Variable containig input/output queue, cpu affinity etc.
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateEstablished(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
if (PKT_IS_TOSERVER(p)) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_ACK(p);
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received and state changed to "
"TCP_CLOSED", ssn);
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len + 1;
ssn->client.next_seq = TCP_GET_ACK(p);
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
/* don't return packets to pools here just yet, the pseudo
* packet will take care, otherwise the normal session
* cleanup. */
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
SCLogDebug("ssn (%p: FIN received SEQ"
" %" PRIu32 ", last ACK %" PRIu32 ", next win %"PRIu32","
" win %" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack, ssn->server.next_win,
ssn->server.window);
if ((StreamTcpHandleFin(tv, stt, ssn, p, pq)) == -1)
return -1;
/* SYN/ACK */
} else if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent",
ssn);
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: SYN/ACK-pkt to server in ESTABLISHED state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_TOSERVER);
return -1;
}
/* Check if the SYN/ACK packets ACK matches the earlier
* received SYN/ACK packet. */
if (!(SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack))) {
SCLogDebug("ssn %p: ACK mismatch, packet ACK %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFFERENT_ACK);
return -1;
}
/* Check if the SYN/ACK packet SEQ the earlier
* received SYN packet. */
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->server.isn))) {
SCLogDebug("ssn %p: SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_ACK(p),
ssn->client.isn + 1);
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND_WITH_DIFF_SEQ);
return -1;
}
if (ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED) {
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYNACK_RESEND);
return -1;
}
SCLogDebug("ssn %p: SYN/ACK packet on state ESTABLISHED... resent. "
"Likely due server not receiving final ACK in 3whs", ssn);
return 0;
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn %p: SYN packet on state ESTABLISHED... resent", ssn);
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: SYN-pkt to client in EST state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_TOCLIENT);
return -1;
}
if (!(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.isn))) {
SCLogDebug("ssn %p: SYN with different SEQ on SYN_RECV state", ssn);
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND_DIFF_SEQ);
return -1;
}
/* a resend of a SYN while we are established already -- fishy */
StreamTcpSetEvent(p, STREAM_EST_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
/* Urgent pointer size can be more than the payload size, as it tells
* the future coming data from the sender will be handled urgently
* until data of size equal to urgent offset has been processed
* (RFC 2147) */
/* If the timestamp option is enabled for both the streams, then
* validate the received packet timestamp value against the
* stream->last_ts. If the timestamp is valid then process the
* packet normally otherwise the drop the packet (RFC 1323) */
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
/* Process the received packet to server */
HandleEstablishedPacketToServer(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->client.next_seq, ssn->server.last_ack
,ssn->client.next_win, ssn->client.window);
} else { /* implied to client */
if (!(ssn->flags & STREAMTCP_FLAG_3WHS_CONFIRMED)) {
ssn->flags |= STREAMTCP_FLAG_3WHS_CONFIRMED;
SCLogDebug("3whs is now confirmed by server");
}
/* Process the received packet to client */
HandleEstablishedPacketToClient(tv, ssn, p, stt, pq);
SCLogDebug("ssn %p: next SEQ %" PRIu32 ", last ACK %" PRIu32 ","
" next win %" PRIu32 ", win %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack,
ssn->server.next_win, ssn->server.window);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the FIN packets for states TCP_SYN_RECV and
* TCP_ESTABLISHED and changes to another TCP state as required.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpHandleFin(ThreadVars *tv, StreamTcpThread *stt,
TcpSession *ssn, Packet *p, PacketQueue *pq)
{
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ %" PRIu32 ","
" ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream", ssn, TCP_GET_SEQ(p),
ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_CLOSE_WAIT);
SCLogDebug("ssn %p: state changed to TCP_CLOSE_WAIT", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq))
ssn->client.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->client.next_seq %" PRIu32 "", ssn,
ssn->client.next_seq);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->client.next_seq, ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ %" PRIu32 ", "
"ACK %" PRIu32 "", ssn, p->payload_len, TCP_GET_SEQ(p),
TCP_GET_ACK(p));
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN_INVALID_ACK);
return -1;
}
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 " != "
"%" PRIu32 " from stream (last_ack %u win %u = %u)", ssn, TCP_GET_SEQ(p),
ssn->server.next_seq, ssn->server.last_ack, ssn->server.window, (ssn->server.last_ack + ssn->server.window));
StreamTcpSetEvent(p, STREAM_FIN_OUT_OF_WINDOW);
return -1;
}
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT1);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT1", ssn);
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq))
ssn->server.next_seq = TCP_GET_SEQ(p) + p->payload_len;
SCLogDebug("ssn %p: ssn->server.next_seq %" PRIu32 "", ssn,
ssn->server.next_seq);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client packet
and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn, &ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK %" PRIu32 "",
ssn, ssn->server.next_seq, ssn->client.last_ack);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT1 state. The function handles
* ACK, FIN, RST packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*
* \retval 0 success
* \retval -1 something wrong with the packet
*/
static int StreamTcpPacketStateFinWait1(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if ((p->tcph->th_flags & (TH_FIN|TH_ACK)) == (TH_FIN|TH_ACK)) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSING);
SCLogDebug("ssn %p: state changed to TCP_CLOSING", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait1", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
if (TCP_GET_SEQ(p) == ssn->client.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN1_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
if (TCP_GET_SEQ(p) == ssn->server.next_seq) {
StreamTcpPacketSetState(p, ssn, TCP_FIN_WAIT2);
SCLogDebug("ssn %p: state changed to TCP_FIN_WAIT2", ssn);
}
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN1_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn (%p): default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_FIN_WAIT2 state. The function handles
* ACK, RST, FIN packets and correspondingly changes the connection
* state.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateFinWait2(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->server.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq - 1) &&
SEQ_EQ(TCP_GET_ACK(p), ssn->client.last_ack)) {
SCLogDebug("ssn %p: retransmission", ssn);
retransmission = 1;
} else if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ "
"%" PRIu32 " != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_FIN_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on FinWait2", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->client.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->client.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->client.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->client.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->server, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->server, (ssn->server.last_ack + ssn->server.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_FIN2_INVALID_ACK);
return -1;
}
if (!retransmission) {
if (SEQ_LEQ(TCP_GET_SEQ(p) + p->payload_len, ssn->server.next_win) ||
(ssn->flags & (STREAMTCP_FLAG_MIDSTREAM|STREAMTCP_FLAG_ASYNC)))
{
SCLogDebug("ssn %p: seq %"PRIu32" in window, ssn->server.next_win "
"%" PRIu32 "", ssn, TCP_GET_SEQ(p), ssn->server.next_win);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_FIN2_ACK_WRONG_SEQ);
return -1;
}
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
if (SEQ_EQ(ssn->server.next_seq, TCP_GET_SEQ(p))) {
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
}
StreamTcpSackUpdatePacket(&ssn->client, p);
/* update next_win */
StreamTcpUpdateNextWin(ssn, &ssn->client, (ssn->client.last_ack + ssn->client.window));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSING state. Upon arrival of ACK
* the connection goes to TCP_TIME_WAIT state. The state has been
* reached as both end application has been closed.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateClosing(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on Closing", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->client.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else { /* implied to client */
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (TCP_GET_SEQ(p) != ssn->server.next_seq) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSING_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSING_INVALID_ACK);
return -1;
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_TIME_WAIT);
SCLogDebug("ssn %p: state changed to TCP_TIME_WAIT", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("StreamTcpPacketStateClosing (%p): =+ next SEQ "
"%" PRIu32 ", last ACK %" PRIu32 "", ssn,
ssn->server.next_seq, ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_CLOSE_WAIT state. Upon arrival of FIN
* packet from server the connection goes to TCP_LAST_ACK state.
* The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateCloseWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
SCEnter();
if (ssn == NULL) {
SCReturnInt(-1);
}
if (PKT_IS_TOCLIENT(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
}
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
/* don't update to LAST_ACK here as we want a toclient FIN for that */
if (!retransmission)
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->server.next_seq) ||
SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_FIN_OUT_OF_WINDOW);
SCReturnInt(-1);
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_LAST_ACK);
SCLogDebug("ssn %p: state changed to TCP_LAST_ACK", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on CloseWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
SCReturnInt(-1);
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
SCReturnInt(-1);
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->client.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->client.last_ack + ssn->client.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->client.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->client, (ssn->client.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (p->payload_len > 0 && (SEQ_LEQ((TCP_GET_SEQ(p) + p->payload_len), ssn->server.last_ack))) {
SCLogDebug("ssn %p: -> retransmission", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_PKT_BEFORE_LAST_ACK);
SCReturnInt(-1);
} else if (SEQ_GT(TCP_GET_SEQ(p), (ssn->server.last_ack + ssn->server.window)))
{
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_ACK_OUT_OF_WINDOW);
SCReturnInt(-1);
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_CLOSEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
if (SEQ_EQ(TCP_GET_SEQ(p),ssn->server.next_seq))
StreamTcpUpdateNextSeq(ssn, &ssn->server, (ssn->server.next_seq + p->payload_len));
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
SCReturnInt(0);
}
/**
* \brief Function to handle the TCP_LAST_ACK state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool. The state is possible only for server host.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateLastAck(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
SCLogDebug("ssn (%p): FIN pkt on LastAck", ssn);
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on LastAck", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_LASTACK_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
if (SEQ_LT(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: not updating state as packet is before next_seq", ssn);
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq + 1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_LASTACK_ACK_WRONG_SEQ);
return -1;
} else {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
}
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
/**
* \brief Function to handle the TCP_TIME_WAIT state. Upon arrival of ACK
* the connection goes to TCP_CLOSED state and stream memory is
* returned back to pool.
*
* \param tv Thread Variable containig input/output queue, cpu affinity
* \param p Packet which has to be handled in this TCP state.
* \param stt Strean Thread module registered to handle the stream handling
*/
static int StreamTcpPacketStateTimeWait(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
if (!StreamTcpValidateRst(ssn, p))
return -1;
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: Reset received state changed to TCP_CLOSED",
ssn);
if (PKT_IS_TOSERVER(p)) {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->server, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
} else {
if ((p->tcph->th_flags & TH_ACK) && StreamTcpValidateAck(ssn, &ssn->client, p) == 0)
StreamTcpUpdateLastAck(ssn, &ssn->client,
StreamTcpResetGetMaxAck(&ssn->client, TCP_GET_ACK(p)));
StreamTcpUpdateLastAck(ssn, &ssn->server,
StreamTcpResetGetMaxAck(&ssn->server, TCP_GET_SEQ(p)));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
}
} else if (p->tcph->th_flags & TH_FIN) {
/** \todo */
} else if (p->tcph->th_flags & TH_SYN) {
SCLogDebug("ssn (%p): SYN pkt on TimeWait", ssn);
StreamTcpSetEvent(p, STREAM_SHUTDOWN_SYN_RESEND);
return -1;
} else if (p->tcph->th_flags & TH_ACK) {
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p))
return -1;
}
if (PKT_IS_TOSERVER(p)) {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to server: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->client, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->client.next_seq && TCP_GET_SEQ(p) != ssn->client.next_seq+1) {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->client.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
if (StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->server.window = TCP_GET_WINDOW(p) << ssn->server.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->server, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->server.next_seq, TCP_GET_ACK(p)))
ssn->server.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->client.next_seq,
ssn->server.last_ack);
} else {
SCLogDebug("ssn %p: pkt (%" PRIu32 ") is to client: SEQ "
"%" PRIu32 ", ACK %" PRIu32 "", ssn, p->payload_len,
TCP_GET_SEQ(p), TCP_GET_ACK(p));
int retransmission = 0;
if (StreamTcpPacketIsRetransmission(&ssn->server, p)) {
SCLogDebug("ssn %p: packet is retransmission", ssn);
retransmission = 1;
} else if (TCP_GET_SEQ(p) != ssn->server.next_seq && TCP_GET_SEQ(p) != ssn->server.next_seq+1) {
if (p->payload_len > 0 && TCP_GET_SEQ(p) == ssn->server.last_ack) {
SCLogDebug("ssn %p: -> retransmission", ssn);
SCReturnInt(0);
} else {
SCLogDebug("ssn %p: -> SEQ mismatch, packet SEQ %" PRIu32 ""
" != %" PRIu32 " from stream", ssn,
TCP_GET_SEQ(p), ssn->server.next_seq);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_ACK_WRONG_SEQ);
return -1;
}
}
if (StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_TIMEWAIT_INVALID_ACK);
SCReturnInt(-1);
}
if (!retransmission) {
StreamTcpPacketSetState(p, ssn, TCP_CLOSED);
SCLogDebug("ssn %p: state changed to TCP_CLOSED", ssn);
ssn->client.window = TCP_GET_WINDOW(p) << ssn->client.wscale;
}
StreamTcpUpdateLastAck(ssn, &ssn->client, TCP_GET_ACK(p));
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
StreamTcpHandleTimestamp(ssn, p);
}
/* Update the next_seq, in case if we have missed the client
packet and server has already received and acked it */
if (SEQ_LT(ssn->client.next_seq, TCP_GET_ACK(p)))
ssn->client.next_seq = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
SCLogDebug("ssn %p: =+ next SEQ %" PRIu32 ", last ACK "
"%" PRIu32 "", ssn, ssn->server.next_seq,
ssn->client.last_ack);
}
} else {
SCLogDebug("ssn %p: default case", ssn);
}
return 0;
}
static int StreamTcpPacketStateClosed(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq)
{
if (ssn == NULL)
return -1;
if (p->tcph->th_flags & TH_RST) {
SCLogDebug("RST on closed state");
return 0;
}
TcpStream *stream = NULL, *ostream = NULL;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
SCLogDebug("stream %s ostream %s",
stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV?"true":"false",
ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV ? "true":"false");
/* if we've seen a RST on our direction, but not on the other
* see if we perhaps need to continue processing anyway. */
if ((stream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) == 0) {
if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->pstate) < 0)
return -1;
}
}
return 0;
}
static void StreamTcpPacketCheckPostRst(TcpSession *ssn, Packet *p)
{
if (p->flags & PKT_PSEUDO_STREAM_END) {
return;
}
/* more RSTs are not unusual */
if ((p->tcph->th_flags & (TH_RST)) != 0) {
return;
}
TcpStream *ostream = NULL;
if (PKT_IS_TOSERVER(p)) {
ostream = &ssn->server;
} else {
ostream = &ssn->client;
}
if (ostream->flags & STREAMTCP_STREAM_FLAG_RST_RECV) {
SCLogDebug("regular packet %"PRIu64" from same sender as "
"the previous RST. Looks like it injected!", p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_RST_RECV;
StreamTcpSetEvent(p, STREAM_SUSPECTED_RST_INJECT);
return;
}
return;
}
/**
* \retval 1 packet is a keep alive pkt
* \retval 0 packet is not a keep alive pkt
*/
static int StreamTcpPacketIsKeepAlive(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/*
rfc 1122:
An implementation SHOULD send a keep-alive segment with no
data; however, it MAY be configurable to send a keep-alive
segment containing one garbage octet, for compatibility with
erroneous TCP implementations.
*/
if (p->payload_len > 1)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0) {
return 0;
}
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
if (ack == ostream->last_ack && seq == (stream->next_seq - 1)) {
SCLogDebug("packet is TCP keep-alive: %"PRIu64, p->pcap_cnt);
stream->flags |= STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, (stream->next_seq - 1), ack, ostream->last_ack);
return 0;
}
/**
* \retval 1 packet is a keep alive ACK pkt
* \retval 0 packet is not a keep alive ACK pkt
*/
static int StreamTcpPacketIsKeepAliveACK(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
/* should get a normal ACK to a Keep Alive */
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win != ostream->window)
return 0;
if ((ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) && ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP keep-aliveACK: %"PRIu64, p->pcap_cnt);
ostream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u) FLAG_KEEPALIVE: %s", seq, stream->next_seq, ack, ostream->last_ack,
ostream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE ? "set" : "not set");
return 0;
}
static void StreamTcpClearKeepAliveFlag(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL;
if (p->flags & PKT_PSEUDO_STREAM_END)
return;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
} else {
stream = &ssn->server;
}
if (stream->flags & STREAMTCP_STREAM_FLAG_KEEPALIVE) {
stream->flags &= ~STREAMTCP_STREAM_FLAG_KEEPALIVE;
SCLogDebug("FLAG_KEEPALIVE cleared");
}
}
/**
* \retval 1 packet is a window update pkt
* \retval 0 packet is not a window update pkt
*/
static int StreamTcpPacketIsWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED)
return 0;
if (p->payload_len > 0)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (TCP_GET_WINDOW(p) == 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win == ostream->window)
return 0;
if (ack == ostream->last_ack && seq == stream->next_seq) {
SCLogDebug("packet is TCP window update: %"PRIu64, p->pcap_cnt);
return 1;
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/**
* Try to detect whether a packet is a valid FIN 4whs final ack.
*
*/
static int StreamTcpPacketIsFinShutdownAck(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (!(ssn->state == TCP_TIME_WAIT || ssn->state == TCP_CLOSE_WAIT || ssn->state == TCP_LAST_ACK))
return 0;
if (p->tcph->th_flags != TH_ACK)
return 0;
if (p->payload_len != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
SCLogDebug("%"PRIu64", seq %u ack %u stream->next_seq %u ostream->next_seq %u",
p->pcap_cnt, seq, ack, stream->next_seq, ostream->next_seq);
if (SEQ_EQ(stream->next_seq + 1, seq) && SEQ_EQ(ack, ostream->next_seq + 1)) {
return 1;
}
return 0;
}
/**
* Try to detect packets doing bad window updates
*
* See bug 1238.
*
* Find packets that are unexpected, and shrink the window to the point
* where the packets we do expect are rejected for being out of window.
*
* The logic we use here is:
* - packet seq > next_seq
* - packet ack > next_seq (packet acks unseen data)
* - packet shrinks window more than it's own data size
* - packet shrinks window more than the diff between it's ack and the
* last_ack value
*
* Packets coming in after packet loss can look quite a bit like this.
*/
static int StreamTcpPacketIsBadWindowUpdate(TcpSession *ssn, Packet *p)
{
TcpStream *stream = NULL, *ostream = NULL;
uint32_t seq;
uint32_t ack;
uint32_t pkt_win;
if (p->flags & PKT_PSEUDO_STREAM_END)
return 0;
if (ssn->state < TCP_ESTABLISHED || ssn->state == TCP_CLOSED)
return 0;
if ((p->tcph->th_flags & (TH_SYN|TH_FIN|TH_RST)) != 0)
return 0;
if (PKT_IS_TOSERVER(p)) {
stream = &ssn->client;
ostream = &ssn->server;
} else {
stream = &ssn->server;
ostream = &ssn->client;
}
seq = TCP_GET_SEQ(p);
ack = TCP_GET_ACK(p);
pkt_win = TCP_GET_WINDOW(p) << ostream->wscale;
if (pkt_win < ostream->window) {
uint32_t diff = ostream->window - pkt_win;
if (diff > p->payload_len &&
SEQ_GT(ack, ostream->next_seq) &&
SEQ_GT(seq, stream->next_seq))
{
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u, diff %u, dsize %u",
p->pcap_cnt, pkt_win, ostream->window, diff, p->payload_len);
SCLogDebug("%"PRIu64", pkt_win %u, stream win %u",
p->pcap_cnt, pkt_win, ostream->window);
SCLogDebug("%"PRIu64", seq %u ack %u ostream->next_seq %u ostream->last_ack %u, ostream->next_win %u, diff %u (%u)",
p->pcap_cnt, seq, ack, ostream->next_seq, ostream->last_ack, ostream->next_win,
ostream->next_seq - ostream->last_ack, stream->next_seq - stream->last_ack);
/* get the expected window shrinking from looking at ack vs last_ack.
* Observed a lot of just a little overrunning that value. So added some
* margin that is still ok. To make sure this isn't a loophole to still
* close the window, this is limited to windows above 1024. Both values
* are rather arbitrary. */
uint32_t adiff = ack - ostream->last_ack;
if (((pkt_win > 1024) && (diff > (adiff + 32))) ||
((pkt_win <= 1024) && (diff > adiff)))
{
SCLogDebug("pkt ACK %u is %u bytes beyond last_ack %u, shrinks window by %u "
"(allowing 32 bytes extra): pkt WIN %u", ack, adiff, ostream->last_ack, diff, pkt_win);
SCLogDebug("%u - %u = %u (state %u)", diff, adiff, diff - adiff, ssn->state);
StreamTcpSetEvent(p, STREAM_PKT_BAD_WINDOW_UPDATE);
return 1;
}
}
}
SCLogDebug("seq %u (%u), ack %u (%u)", seq, stream->next_seq, ack, ostream->last_ack);
return 0;
}
/** \internal
* \brief call packet handling function for 'state'
* \param state current TCP state
*/
static inline int StreamTcpStateDispatch(ThreadVars *tv, Packet *p,
StreamTcpThread *stt, TcpSession *ssn, PacketQueue *pq,
const uint8_t state)
{
SCLogDebug("ssn: %p", ssn);
switch (state) {
case TCP_SYN_SENT:
if (StreamTcpPacketStateSynSent(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_SYN_RECV:
if (StreamTcpPacketStateSynRecv(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_ESTABLISHED:
if (StreamTcpPacketStateEstablished(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_FIN_WAIT1:
SCLogDebug("packet received on TCP_FIN_WAIT1 state");
if (StreamTcpPacketStateFinWait1(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_FIN_WAIT2:
SCLogDebug("packet received on TCP_FIN_WAIT2 state");
if (StreamTcpPacketStateFinWait2(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSING:
SCLogDebug("packet received on TCP_CLOSING state");
if (StreamTcpPacketStateClosing(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSE_WAIT:
SCLogDebug("packet received on TCP_CLOSE_WAIT state");
if (StreamTcpPacketStateCloseWait(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_LAST_ACK:
SCLogDebug("packet received on TCP_LAST_ACK state");
if (StreamTcpPacketStateLastAck(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_TIME_WAIT:
SCLogDebug("packet received on TCP_TIME_WAIT state");
if (StreamTcpPacketStateTimeWait(tv, p, stt, ssn, pq)) {
return -1;
}
break;
case TCP_CLOSED:
/* TCP session memory is not returned to pool until timeout. */
SCLogDebug("packet received on closed state");
if (StreamTcpPacketStateClosed(tv, p, stt, ssn, pq)) {
return -1;
}
break;
default:
SCLogDebug("packet received on default state");
break;
}
return 0;
}
/* flow is and stays locked */
int StreamTcpPacket (ThreadVars *tv, Packet *p, StreamTcpThread *stt,
PacketQueue *pq)
{
SCEnter();
DEBUG_ASSERT_FLOW_LOCKED(p->flow);
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
/* assign the thread id to the flow */
if (unlikely(p->flow->thread_id == 0)) {
p->flow->thread_id = (FlowThreadId)tv->id;
} else if (unlikely((FlowThreadId)tv->id != p->flow->thread_id)) {
SCLogDebug("wrong thread: flow has %u, we are %d", p->flow->thread_id, tv->id);
if (p->pkt_src == PKT_SRC_WIRE) {
StatsIncr(tv, stt->counter_tcp_wrong_thread);
if ((p->flow->flags & FLOW_WRONG_THREAD) == 0) {
p->flow->flags |= FLOW_WRONG_THREAD;
StreamTcpSetEvent(p, STREAM_WRONG_THREAD);
}
}
}
TcpSession *ssn = (TcpSession *)p->flow->protoctx;
/* track TCP flags */
if (ssn != NULL) {
ssn->tcp_packet_flags |= p->tcph->th_flags;
if (PKT_IS_TOSERVER(p))
ssn->client.tcp_flags |= p->tcph->th_flags;
else if (PKT_IS_TOCLIENT(p))
ssn->server.tcp_flags |= p->tcph->th_flags;
/* check if we need to unset the ASYNC flag */
if (ssn->flags & STREAMTCP_FLAG_ASYNC &&
ssn->client.tcp_flags != 0 &&
ssn->server.tcp_flags != 0)
{
SCLogDebug("ssn %p: removing ASYNC flag as we have packets on both sides", ssn);
ssn->flags &= ~STREAMTCP_FLAG_ASYNC;
}
}
/* update counters */
if ((p->tcph->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
StatsIncr(tv, stt->counter_tcp_synack);
} else if (p->tcph->th_flags & (TH_SYN)) {
StatsIncr(tv, stt->counter_tcp_syn);
}
if (p->tcph->th_flags & (TH_RST)) {
StatsIncr(tv, stt->counter_tcp_rst);
}
/* broken TCP http://ask.wireshark.org/questions/3183/acknowledgment-number-broken-tcp-the-acknowledge-field-is-nonzero-while-the-ack-flag-is-not-set */
if (!(p->tcph->th_flags & TH_ACK) && TCP_GET_ACK(p) != 0) {
StreamTcpSetEvent(p, STREAM_PKT_BROKEN_ACK);
goto error;
}
/* If we are on IPS mode, and got a drop action triggered from
* the IP only module, or from a reassembled msg and/or from an
* applayer detection, then drop the rest of the packets of the
* same stream and avoid inspecting it any further */
if (StreamTcpCheckFlowDrops(p) == 1) {
SCLogDebug("This flow/stream triggered a drop rule");
FlowSetNoPacketInspectionFlag(p->flow);
DecodeSetNoPacketInspectionFlag(p);
StreamTcpDisableAppLayer(p->flow);
PACKET_DROP(p);
/* return the segments to the pool */
StreamTcpSessionPktFree(p);
SCReturnInt(0);
}
if (ssn == NULL || ssn->state == TCP_NONE) {
if (StreamTcpPacketStateNone(tv, p, stt, ssn, &stt->pseudo_queue) == -1) {
goto error;
}
if (ssn != NULL)
SCLogDebug("ssn->alproto %"PRIu16"", p->flow->alproto);
} else {
/* special case for PKT_PSEUDO_STREAM_END packets:
* bypass the state handling and various packet checks,
* we care about reassembly here. */
if (p->flags & PKT_PSEUDO_STREAM_END) {
if (PKT_IS_TOCLIENT(p)) {
ssn->client.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, p, pq);
} else {
ssn->server.last_ack = TCP_GET_ACK(p);
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, p, pq);
}
/* straight to 'skip' as we already handled reassembly */
goto skip;
}
/* check if the packet is in right direction, when we missed the
SYN packet and picked up midstream session. */
if (ssn->flags & STREAMTCP_FLAG_MIDSTREAM_SYNACK)
StreamTcpPacketSwitchDir(ssn, p);
if (StreamTcpPacketIsKeepAlive(ssn, p) == 1) {
goto skip;
}
if (StreamTcpPacketIsKeepAliveACK(ssn, p) == 1) {
StreamTcpClearKeepAliveFlag(ssn, p);
goto skip;
}
StreamTcpClearKeepAliveFlag(ssn, p);
/* if packet is not a valid window update, check if it is perhaps
* a bad window update that we should ignore (and alert on) */
if (StreamTcpPacketIsFinShutdownAck(ssn, p) == 0)
if (StreamTcpPacketIsWindowUpdate(ssn, p) == 0)
if (StreamTcpPacketIsBadWindowUpdate(ssn,p))
goto skip;
/* handle the per 'state' logic */
if (StreamTcpStateDispatch(tv, p, stt, ssn, &stt->pseudo_queue, ssn->state) < 0)
goto error;
skip:
StreamTcpPacketCheckPostRst(ssn, p);
if (ssn->state >= TCP_ESTABLISHED) {
p->flags |= PKT_STREAM_EST;
}
}
/* deal with a pseudo packet that is created upon receiving a RST
* segment. To be sure we process both sides of the connection, we
* inject a fake packet into the system, forcing reassembly of the
* opposing direction.
* There should be only one, but to be sure we do a while loop. */
if (ssn != NULL) {
while (stt->pseudo_queue.len > 0) {
SCLogDebug("processing pseudo packet / stream end");
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
/* process the opposing direction of the original packet */
if (PKT_IS_TOSERVER(np)) {
SCLogDebug("pseudo packet is to server");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->client, np, NULL);
} else {
SCLogDebug("pseudo packet is to client");
StreamTcpReassembleHandleSegment(tv, stt->ra_ctx, ssn,
&ssn->server, np, NULL);
}
/* enqueue this packet so we inspect it in detect etc */
PacketEnqueue(pq, np);
}
SCLogDebug("processing pseudo packet / stream end done");
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
/* check for conditions that may make us not want to log this packet */
/* streams that hit depth */
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
}
if ((ssn->client.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED) ||
(ssn->server.flags & STREAMTCP_STREAM_FLAG_DEPTH_REACHED))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
/* encrypted packets */
if ((PKT_IS_TOSERVER(p) && (ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)) ||
(PKT_IS_TOCLIENT(p) && (ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY)))
{
p->flags |= PKT_STREAM_NOPCAPLOG;
}
if (ssn->flags & STREAMTCP_FLAG_BYPASS) {
/* we can call bypass callback, if enabled */
if (StreamTcpBypassEnabled()) {
PacketBypassCallback(p);
}
/* if stream is dead and we have no detect engine at all, bypass. */
} else if (g_detect_disabled &&
(ssn->client.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
(ssn->server.flags & STREAMTCP_STREAM_FLAG_NOREASSEMBLY) &&
StreamTcpBypassEnabled())
{
SCLogDebug("bypass as stream is dead and we have no rules");
PacketBypassCallback(p);
}
}
SCReturnInt(0);
error:
/* make sure we don't leave packets in our pseudo queue */
while (stt->pseudo_queue.len > 0) {
Packet *np = PacketDequeue(&stt->pseudo_queue);
if (np != NULL) {
PacketEnqueue(pq, np);
}
}
/* recalc the csum on the packet if it was modified */
if (p->flags & PKT_STREAM_MODIFIED) {
ReCalculateChecksum(p);
}
if (StreamTcpInlineDropInvalid()) {
/* disable payload inspection as we're dropping this packet
* anyway. Doesn't disable all detection, so we can still
* match on the stream event that was set. */
DecodeSetNoPayloadInspectionFlag(p);
PACKET_DROP(p);
}
SCReturnInt(-1);
}
/**
* \brief Function to validate the checksum of the received packet. If the
* checksum is invalid, packet will be dropped, as the end system will
* also drop the packet.
*
* \param p Packet of which checksum has to be validated
* \retval 1 if the checksum is valid, otherwise 0
*/
static inline int StreamTcpValidateChecksum(Packet *p)
{
int ret = 1;
if (p->flags & PKT_IGNORE_CHECKSUM)
return ret;
if (p->level4_comp_csum == -1) {
if (PKT_IS_IPV4(p)) {
p->level4_comp_csum = TCPChecksum(p->ip4h->s_ip_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
} else if (PKT_IS_IPV6(p)) {
p->level4_comp_csum = TCPV6Checksum(p->ip6h->s_ip6_addrs,
(uint16_t *)p->tcph,
(p->payload_len +
TCP_GET_HLEN(p)),
p->tcph->th_sum);
}
}
if (p->level4_comp_csum != 0) {
ret = 0;
if (p->livedev) {
(void) SC_ATOMIC_ADD(p->livedev->invalid_checksums, 1);
} else if (p->pcap_cnt) {
PcapIncreaseInvalidChecksum();
}
}
return ret;
}
/** \internal
* \brief check if a packet is a valid stream started
* \retval bool true/false */
static int TcpSessionPacketIsStreamStarter(const Packet *p)
{
if (p->tcph->th_flags == TH_SYN) {
SCLogDebug("packet %"PRIu64" is a stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
SCLogDebug("packet %"PRIu64" is a midstream stream starter: %02x", p->pcap_cnt, p->tcph->th_flags);
return 1;
}
}
return 0;
}
/** \internal
* \brief Check if Flow and TCP SSN allow this flow/tuple to be reused
* \retval bool true yes reuse, false no keep tracking old ssn */
static int TcpSessionReuseDoneEnoughSyn(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOSERVER) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->client.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \internal
* \brief check if ssn is done enough for reuse by syn/ack
* \note should only be called if midstream is enabled
*/
static int TcpSessionReuseDoneEnoughSynAck(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (FlowGetPacketDirection(f, p) == TOCLIENT) {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. No reuse.", p->pcap_cnt, ssn);
return 0;
}
if (SEQ_EQ(ssn->server.isn, TCP_GET_SEQ(p))) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p. Packet SEQ == Stream ISN. Retransmission. Don't reuse.", p->pcap_cnt, ssn);
return 0;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
} else {
if (ssn == NULL) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p null. Reuse.", p->pcap_cnt, ssn);
return 1;
}
if (ssn->state >= TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state >= TCP_LAST_ACK (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state == TCP_NONE) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state == TCP_NONE (%u). Reuse.", p->pcap_cnt, ssn, ssn->state);
return 1;
}
if (ssn->state < TCP_LAST_ACK) {
SCLogDebug("steam starter packet %"PRIu64", ssn %p state < TCP_LAST_ACK (%u). Don't reuse.", p->pcap_cnt, ssn, ssn->state);
return 0;
}
}
SCLogDebug("default: how did we get here?");
return 0;
}
/** \brief Check if SSN is done enough for reuse
*
* Reuse means a new TCP session reuses the tuple (flow in suri)
*
* \retval bool true if ssn can be reused, false if not */
static int TcpSessionReuseDoneEnough(const Packet *p, const Flow *f, const TcpSession *ssn)
{
if (p->tcph->th_flags == TH_SYN) {
return TcpSessionReuseDoneEnoughSyn(p, f, ssn);
}
if (stream_config.midstream == TRUE || stream_config.async_oneside == TRUE) {
if (p->tcph->th_flags == (TH_SYN|TH_ACK)) {
return TcpSessionReuseDoneEnoughSynAck(p, f, ssn);
}
}
return 0;
}
int TcpSessionPacketSsnReuse(const Packet *p, const Flow *f, const void *tcp_ssn)
{
if (p->proto == IPPROTO_TCP && p->tcph != NULL) {
if (TcpSessionPacketIsStreamStarter(p) == 1) {
if (TcpSessionReuseDoneEnough(p, f, tcp_ssn) == 1) {
return 1;
}
}
}
return 0;
}
TmEcode StreamTcp (ThreadVars *tv, Packet *p, void *data, PacketQueue *pq, PacketQueue *postpq)
{
StreamTcpThread *stt = (StreamTcpThread *)data;
SCLogDebug("p->pcap_cnt %"PRIu64, p->pcap_cnt);
if (!(PKT_IS_TCP(p))) {
return TM_ECODE_OK;
}
if (p->flow == NULL) {
StatsIncr(tv, stt->counter_tcp_no_flow);
return TM_ECODE_OK;
}
/* only TCP packets with a flow from here */
if (!(p->flags & PKT_PSEUDO_STREAM_END)) {
if (stream_config.flags & STREAMTCP_INIT_FLAG_CHECKSUM_VALIDATION) {
if (StreamTcpValidateChecksum(p) == 0) {
StatsIncr(tv, stt->counter_tcp_invalid_checksum);
return TM_ECODE_OK;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM;
}
} else {
p->flags |= PKT_IGNORE_CHECKSUM; //TODO check that this is set at creation
}
AppLayerProfilingReset(stt->ra_ctx->app_tctx);
(void)StreamTcpPacket(tv, p, stt, pq);
return TM_ECODE_OK;
}
TmEcode StreamTcpThreadInit(ThreadVars *tv, void *initdata, void **data)
{
SCEnter();
StreamTcpThread *stt = SCMalloc(sizeof(StreamTcpThread));
if (unlikely(stt == NULL))
SCReturnInt(TM_ECODE_FAILED);
memset(stt, 0, sizeof(StreamTcpThread));
stt->ssn_pool_id = -1;
*data = (void *)stt;
stt->counter_tcp_sessions = StatsRegisterCounter("tcp.sessions", tv);
stt->counter_tcp_ssn_memcap = StatsRegisterCounter("tcp.ssn_memcap_drop", tv);
stt->counter_tcp_pseudo = StatsRegisterCounter("tcp.pseudo", tv);
stt->counter_tcp_pseudo_failed = StatsRegisterCounter("tcp.pseudo_failed", tv);
stt->counter_tcp_invalid_checksum = StatsRegisterCounter("tcp.invalid_checksum", tv);
stt->counter_tcp_no_flow = StatsRegisterCounter("tcp.no_flow", tv);
stt->counter_tcp_syn = StatsRegisterCounter("tcp.syn", tv);
stt->counter_tcp_synack = StatsRegisterCounter("tcp.synack", tv);
stt->counter_tcp_rst = StatsRegisterCounter("tcp.rst", tv);
stt->counter_tcp_midstream_pickups = StatsRegisterCounter("tcp.midstream_pickups", tv);
stt->counter_tcp_wrong_thread = StatsRegisterCounter("tcp.pkt_on_wrong_thread", tv);
/* init reassembly ctx */
stt->ra_ctx = StreamTcpReassembleInitThreadCtx(tv);
if (stt->ra_ctx == NULL)
SCReturnInt(TM_ECODE_FAILED);
stt->ra_ctx->counter_tcp_segment_memcap = StatsRegisterCounter("tcp.segment_memcap_drop", tv);
stt->ra_ctx->counter_tcp_stream_depth = StatsRegisterCounter("tcp.stream_depth_reached", tv);
stt->ra_ctx->counter_tcp_reass_gap = StatsRegisterCounter("tcp.reassembly_gap", tv);
stt->ra_ctx->counter_tcp_reass_overlap = StatsRegisterCounter("tcp.overlap", tv);
stt->ra_ctx->counter_tcp_reass_overlap_diff_data = StatsRegisterCounter("tcp.overlap_diff_data", tv);
stt->ra_ctx->counter_tcp_reass_data_normal_fail = StatsRegisterCounter("tcp.insert_data_normal_fail", tv);
stt->ra_ctx->counter_tcp_reass_data_overlap_fail = StatsRegisterCounter("tcp.insert_data_overlap_fail", tv);
stt->ra_ctx->counter_tcp_reass_list_fail = StatsRegisterCounter("tcp.insert_list_fail", tv);
SCLogDebug("StreamTcp thread specific ctx online at %p, reassembly ctx %p",
stt, stt->ra_ctx);
SCMutexLock(&ssn_pool_mutex);
if (ssn_pool == NULL) {
ssn_pool = PoolThreadInit(1, /* thread */
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
stt->ssn_pool_id = 0;
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
} else {
/* grow ssn_pool until we have a element for our thread id */
stt->ssn_pool_id = PoolThreadGrow(ssn_pool,
0, /* unlimited */
stream_config.prealloc_sessions,
sizeof(TcpSession),
StreamTcpSessionPoolAlloc,
StreamTcpSessionPoolInit, NULL,
StreamTcpSessionPoolCleanup, NULL);
SCLogDebug("pool size %d, thread ssn_pool_id %d", PoolThreadSize(ssn_pool), stt->ssn_pool_id);
}
SCMutexUnlock(&ssn_pool_mutex);
if (stt->ssn_pool_id < 0 || ssn_pool == NULL) {
SCLogError(SC_ERR_MEM_ALLOC, "failed to setup/expand stream session pool. Expand stream.memcap?");
SCReturnInt(TM_ECODE_FAILED);
}
SCReturnInt(TM_ECODE_OK);
}
TmEcode StreamTcpThreadDeinit(ThreadVars *tv, void *data)
{
SCEnter();
StreamTcpThread *stt = (StreamTcpThread *)data;
if (stt == NULL) {
return TM_ECODE_OK;
}
/* XXX */
/* free reassembly ctx */
StreamTcpReassembleFreeThreadCtx(stt->ra_ctx);
/* clear memory */
memset(stt, 0, sizeof(StreamTcpThread));
SCFree(stt);
SCReturnInt(TM_ECODE_OK);
}
/**
* \brief Function to check the validity of the RST packets based on the
* target OS of the given packet.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 0 unacceptable RST
* \retval 1 acceptable RST
*
* WebSense sends RST packets that are:
* - RST flag, win 0, ack 0, seq = nextseq
*
*/
static int StreamTcpValidateRst(TcpSession *ssn, Packet *p)
{
uint8_t os_policy;
if (ssn->flags & STREAMTCP_FLAG_TIMESTAMP) {
if (!StreamTcpValidateTimestamp(ssn, p)) {
SCReturnInt(0);
}
}
/* Set up the os_policy to be used in validating the RST packets based on
target system */
if (PKT_IS_TOSERVER(p)) {
if (ssn->server.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->server, p);
os_policy = ssn->server.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->server, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
} else {
if (ssn->client.os_policy == 0)
StreamTcpSetOSPolicy(&ssn->client, p);
os_policy = ssn->client.os_policy;
if (p->tcph->th_flags & TH_ACK &&
TCP_GET_ACK(p) && StreamTcpValidateAck(ssn, &ssn->client, p) == -1) {
SCLogDebug("ssn %p: rejecting because of invalid ack value", ssn);
StreamTcpSetEvent(p, STREAM_RST_INVALID_ACK);
SCReturnInt(0);
}
}
if (ssn->flags & STREAMTCP_FLAG_ASYNC) {
if (PKT_IS_TOSERVER(p)) {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
} else {
if (SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("ssn %p: ASYNC accept RST", ssn);
return 1;
}
}
SCLogDebug("ssn %p: ASYNC reject RST", ssn);
return 0;
}
switch (os_policy) {
case OS_POLICY_HPUX11:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not Valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_LINUX:
case OS_POLICY_SOLARIS:
if(PKT_IS_TOSERVER(p)){
if(SEQ_GEQ((TCP_GET_SEQ(p)+p->payload_len),
ssn->client.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->client.next_seq + ssn->client.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if(SEQ_GEQ((TCP_GET_SEQ(p) + p->payload_len),
ssn->server.last_ack))
{ /*window base is needed !!*/
if(SEQ_LT(TCP_GET_SEQ(p),
(ssn->server.next_seq + ssn->server.window)))
{
SCLogDebug("reset is Valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
}
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->server.next_seq);
return 0;
}
}
break;
default:
case OS_POLICY_BSD:
case OS_POLICY_FIRST:
case OS_POLICY_HPUX10:
case OS_POLICY_IRIX:
case OS_POLICY_MACOS:
case OS_POLICY_LAST:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
if(PKT_IS_TOSERVER(p)) {
if(SEQ_EQ(TCP_GET_SEQ(p), ssn->client.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 "",
TCP_GET_SEQ(p));
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " "
"and server SEQ: %" PRIu32 "", TCP_GET_SEQ(p),
ssn->client.next_seq);
return 0;
}
} else { /* implied to client */
if (SEQ_EQ(TCP_GET_SEQ(p), ssn->server.next_seq)) {
SCLogDebug("reset is valid! Packet SEQ: %" PRIu32 " Stream %u",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 1;
} else {
SCLogDebug("reset is not valid! Packet SEQ: %" PRIu32 " and"
" client SEQ: %" PRIu32 "",
TCP_GET_SEQ(p), ssn->server.next_seq);
return 0;
}
}
break;
}
return 0;
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream.
*
* It's passive except for:
* 1. it sets the os policy on the stream if necessary
* 2. it sets an event in the packet if necessary
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpValidateTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
uint32_t last_pkt_ts = sender_stream->last_pkt_ts;
uint32_t last_ts = sender_stream->last_ts;
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/* HPUX11 igoners the timestamp of out of order packets */
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - last_ts) + 1);
} else {
result = (int32_t) (ts - last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (last_pkt_ts + PAWS_24DAYS))))
{
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to check the validity of the received timestamp based on
* the target OS of the given stream and update the session.
*
* \param ssn TCP session to which the given packet belongs
* \param p Packet which has to be checked for its validity
*
* \retval 1 if the timestamp is valid
* \retval 0 if the timestamp is invalid
*/
static int StreamTcpHandleTimestamp (TcpSession *ssn, Packet *p)
{
SCEnter();
TcpStream *sender_stream;
TcpStream *receiver_stream;
uint8_t ret = 1;
uint8_t check_ts = 1;
if (PKT_IS_TOSERVER(p)) {
sender_stream = &ssn->client;
receiver_stream = &ssn->server;
} else {
sender_stream = &ssn->server;
receiver_stream = &ssn->client;
}
/* Set up the os_policy to be used in validating the timestamps based on
the target system */
if (receiver_stream->os_policy == 0) {
StreamTcpSetOSPolicy(receiver_stream, p);
}
if (TCP_HAS_TS(p)) {
uint32_t ts = TCP_GET_TSVAL(p);
if (sender_stream->flags & STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP) {
/* The 3whs used the timestamp with 0 value. */
switch (receiver_stream->os_policy) {
case OS_POLICY_LINUX:
case OS_POLICY_WINDOWS2K3:
/* Linux and windows 2003 does not allow the use of 0 as
* timestamp in the 3whs. */
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
check_ts = 0;
break;
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_VISTA:
sender_stream->flags &= ~STREAMTCP_STREAM_FLAG_ZERO_TIMESTAMP;
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) {
sender_stream->last_ts = ts;
check_ts = 0; /*next packet will be checked for validity
and stream TS has been updated with this
one.*/
}
break;
default:
break;
}
}
if (receiver_stream->os_policy == OS_POLICY_HPUX11) {
/*HPUX11 igoners the timestamp of out of order packets*/
if (!SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
check_ts = 0;
}
if (ts == 0) {
switch (receiver_stream->os_policy) {
case OS_POLICY_OLD_LINUX:
case OS_POLICY_WINDOWS:
case OS_POLICY_WINDOWS2K3:
case OS_POLICY_VISTA:
case OS_POLICY_SOLARIS:
/* Old Linux and windows allowed packet with 0 timestamp. */
break;
default:
/* other OS simply drop the pakcet with 0 timestamp, when
* 3whs has valid timestamp*/
goto invalid;
}
}
if (check_ts) {
int32_t result = 0;
SCLogDebug("ts %"PRIu32", last_ts %"PRIu32"", ts, sender_stream->last_ts);
if (receiver_stream->os_policy == OS_POLICY_LINUX) {
/* Linux accepts TS which are off by one.*/
result = (int32_t) ((ts - sender_stream->last_ts) + 1);
} else {
result = (int32_t) (ts - sender_stream->last_ts);
}
SCLogDebug("result %"PRIi32", p->ts.tv_sec %"PRIuMAX"", result, (uintmax_t)p->ts.tv_sec);
if (sender_stream->last_pkt_ts == 0 &&
(ssn->flags & STREAMTCP_FLAG_MIDSTREAM))
{
sender_stream->last_pkt_ts = p->ts.tv_sec;
}
if (result < 0) {
SCLogDebug("timestamp is not valid sender_stream->last_ts "
"%" PRIu32 " p->tcpvars->ts %" PRIu32 " result "
"%" PRId32 "", sender_stream->last_ts, ts, result);
/* candidate for rejection */
ret = 0;
} else if ((sender_stream->last_ts != 0) &&
(((uint32_t) p->ts.tv_sec) >
sender_stream->last_pkt_ts + PAWS_24DAYS))
{
SCLogDebug("packet is not valid sender_stream->last_pkt_ts "
"%" PRIu32 " p->ts.tv_sec %" PRIu32 "",
sender_stream->last_pkt_ts, (uint32_t) p->ts.tv_sec);
/* candidate for rejection */
ret = 0;
}
if (ret == 1) {
/* Update the timestamp and last seen packet time for this
* stream */
if (SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p)))
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
} else if (ret == 0) {
/* if the timestamp of packet is not valid then, check if the
* current stream timestamp is not so old. if so then we need to
* accept the packet and update the stream->last_ts (RFC 1323)*/
if ((SEQ_EQ(sender_stream->next_seq, TCP_GET_SEQ(p))) &&
(((uint32_t) p->ts.tv_sec > (sender_stream->last_pkt_ts + PAWS_24DAYS))))
{
sender_stream->last_ts = ts;
sender_stream->last_pkt_ts = p->ts.tv_sec;
SCLogDebug("timestamp considered valid anyway");
} else {
goto invalid;
}
}
}
} else {
/* Solaris stops using timestamps if a packet is received
without a timestamp and timestamps were used on that stream. */
if (receiver_stream->os_policy == OS_POLICY_SOLARIS)
ssn->flags &= ~STREAMTCP_FLAG_TIMESTAMP;
}
SCReturnInt(1);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_TIMESTAMP);
SCReturnInt(0);
}
/**
* \brief Function to test the received ACK values against the stream window
* and previous ack value. ACK values should be higher than previous
* ACK value and less than the next_win value.
*
* \param ssn TcpSession for state access
* \param stream TcpStream of which last_ack needs to be tested
* \param p Packet which is used to test the last_ack
*
* \retval 0 ACK is valid, last_ack is updated if ACK was higher
* \retval -1 ACK is invalid
*/
static inline int StreamTcpValidateAck(TcpSession *ssn, TcpStream *stream, Packet *p)
{
SCEnter();
uint32_t ack = TCP_GET_ACK(p);
/* fast track */
if (SEQ_GT(ack, stream->last_ack) && SEQ_LEQ(ack, stream->next_win))
{
SCLogDebug("ACK in bounds");
SCReturnInt(0);
}
/* fast track */
else if (SEQ_EQ(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" == stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
SCReturnInt(0);
}
/* exception handling */
if (SEQ_LT(ack, stream->last_ack)) {
SCLogDebug("pkt ACK %"PRIu32" < stream last ACK %"PRIu32, TCP_GET_ACK(p), stream->last_ack);
/* This is an attempt to get a 'left edge' value that we can check against.
* It doesn't work when the window is 0, need to think of a better way. */
if (stream->window != 0 && SEQ_LT(ack, (stream->last_ack - stream->window))) {
SCLogDebug("ACK %"PRIu32" is before last_ack %"PRIu32" - window "
"%"PRIu32" = %"PRIu32, ack, stream->last_ack,
stream->window, stream->last_ack - stream->window);
goto invalid;
}
SCReturnInt(0);
}
if (ssn->state > TCP_SYN_SENT && SEQ_GT(ack, stream->next_win)) {
SCLogDebug("ACK %"PRIu32" is after next_win %"PRIu32, ack, stream->next_win);
goto invalid;
/* a toclient RST as a reponse to SYN, next_win is 0, ack will be isn+1, just like
* the syn ack */
} else if (ssn->state == TCP_SYN_SENT && PKT_IS_TOCLIENT(p) &&
p->tcph->th_flags & TH_RST &&
SEQ_EQ(ack, stream->isn + 1)) {
SCReturnInt(0);
}
SCLogDebug("default path leading to invalid: ACK %"PRIu32", last_ack %"PRIu32
" next_win %"PRIu32, ack, stream->last_ack, stream->next_win);
invalid:
StreamTcpSetEvent(p, STREAM_PKT_INVALID_ACK);
SCReturnInt(-1);
}
/** \brief disable reassembly
* Disable app layer and set raw inspect to no longer accept new data.
* Stream engine will then fully disable raw after last inspection.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionNoReassemblyFlag (TcpSession *ssn, char direction)
{
ssn->flags |= STREAMTCP_FLAG_APP_LAYER_DISABLED;
if (direction) {
ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
} else {
ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED;
}
}
/** \brief Set the No reassembly flag for the given direction in given TCP
* session.
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetDisableRawReassemblyFlag (TcpSession *ssn, char direction)
{
direction ? (ssn->server.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED) :
(ssn->client.flags |= STREAMTCP_STREAM_FLAG_NEW_RAW_DISABLED);
}
/** \brief enable bypass
*
* \param ssn TCP Session to set the flag in
* \param direction direction to set the flag in: 0 toserver, 1 toclient
*/
void StreamTcpSetSessionBypassFlag (TcpSession *ssn)
{
ssn->flags |= STREAMTCP_FLAG_BYPASS;
}
#define PSEUDO_PKT_SET_IPV4HDR(nipv4h,ipv4h) do { \
IPV4_SET_RAW_VER(nipv4h, IPV4_GET_RAW_VER(ipv4h)); \
IPV4_SET_RAW_HLEN(nipv4h, IPV4_GET_RAW_HLEN(ipv4h)); \
IPV4_SET_RAW_IPLEN(nipv4h, IPV4_GET_RAW_IPLEN(ipv4h)); \
IPV4_SET_RAW_IPTOS(nipv4h, IPV4_GET_RAW_IPTOS(ipv4h)); \
IPV4_SET_RAW_IPPROTO(nipv4h, IPV4_GET_RAW_IPPROTO(ipv4h)); \
(nipv4h)->s_ip_src = IPV4_GET_RAW_IPDST(ipv4h); \
(nipv4h)->s_ip_dst = IPV4_GET_RAW_IPSRC(ipv4h); \
} while (0)
#define PSEUDO_PKT_SET_IPV6HDR(nipv6h,ipv6h) do { \
(nipv6h)->s_ip6_src[0] = (ipv6h)->s_ip6_dst[0]; \
(nipv6h)->s_ip6_src[1] = (ipv6h)->s_ip6_dst[1]; \
(nipv6h)->s_ip6_src[2] = (ipv6h)->s_ip6_dst[2]; \
(nipv6h)->s_ip6_src[3] = (ipv6h)->s_ip6_dst[3]; \
(nipv6h)->s_ip6_dst[0] = (ipv6h)->s_ip6_src[0]; \
(nipv6h)->s_ip6_dst[1] = (ipv6h)->s_ip6_src[1]; \
(nipv6h)->s_ip6_dst[2] = (ipv6h)->s_ip6_src[2]; \
(nipv6h)->s_ip6_dst[3] = (ipv6h)->s_ip6_src[3]; \
IPV6_SET_RAW_NH(nipv6h, IPV6_GET_RAW_NH(ipv6h)); \
} while (0)
#define PSEUDO_PKT_SET_TCPHDR(ntcph,tcph) do { \
COPY_PORT((tcph)->th_dport, (ntcph)->th_sport); \
COPY_PORT((tcph)->th_sport, (ntcph)->th_dport); \
(ntcph)->th_seq = (tcph)->th_ack; \
(ntcph)->th_ack = (tcph)->th_seq; \
} while (0)
/**
* \brief Function to fetch a packet from the packet allocation queue for
* creation of the pseudo packet from the reassembled stream.
*
* @param parent Pointer to the parent of the pseudo packet
* @param pkt pointer to the raw packet of the parent
* @param len length of the packet
* @return upon success returns the pointer to the new pseudo packet
* otherwise NULL
*/
Packet *StreamTcpPseudoSetup(Packet *parent, uint8_t *pkt, uint32_t len)
{
SCEnter();
if (len == 0) {
SCReturnPtr(NULL, "Packet");
}
Packet *p = PacketGetFromQueueOrAlloc();
if (p == NULL) {
SCReturnPtr(NULL, "Packet");
}
/* set the root ptr to the lowest layer */
if (parent->root != NULL)
p->root = parent->root;
else
p->root = parent;
/* copy packet and set lenght, proto */
p->proto = parent->proto;
p->datalink = parent->datalink;
PacketCopyData(p, pkt, len);
p->recursion_level = parent->recursion_level + 1;
p->ts.tv_sec = parent->ts.tv_sec;
p->ts.tv_usec = parent->ts.tv_usec;
FlowReference(&p->flow, parent->flow);
/* set tunnel flags */
/* tell new packet it's part of a tunnel */
SET_TUNNEL_PKT(p);
/* tell parent packet it's part of a tunnel */
SET_TUNNEL_PKT(parent);
/* increment tunnel packet refcnt in the root packet */
TUNNEL_INCR_PKT_TPR(p);
return p;
}
/** \brief Create a pseudo packet injected into the engine to signal the
* opposing direction of this stream trigger detection/logging.
*
* \param parent real packet
* \param pq packet queue to store the new pseudo packet in
* \param dir 0 ts 1 tc
*/
static void StreamTcpPseudoPacketCreateDetectLogFlush(ThreadVars *tv,
StreamTcpThread *stt, Packet *parent,
TcpSession *ssn, PacketQueue *pq, int dir)
{
SCEnter();
Flow *f = parent->flow;
if (parent->flags & PKT_PSEUDO_DETECTLOG_FLUSH) {
SCReturn;
}
Packet *np = PacketPoolGetPacket();
if (np == NULL) {
SCReturn;
}
PKT_SET_SRC(np, PKT_SRC_STREAM_TCP_DETECTLOG_FLUSH);
np->tenant_id = f->tenant_id;
np->datalink = DLT_RAW;
np->proto = IPPROTO_TCP;
FlowReference(&np->flow, f);
np->flags |= PKT_STREAM_EST;
np->flags |= PKT_HAS_FLOW;
np->flags |= PKT_IGNORE_CHECKSUM;
np->flags |= PKT_PSEUDO_DETECTLOG_FLUSH;
if (f->flags & FLOW_NOPACKET_INSPECTION) {
DecodeSetNoPacketInspectionFlag(np);
}
if (f->flags & FLOW_NOPAYLOAD_INSPECTION) {
DecodeSetNoPayloadInspectionFlag(np);
}
if (dir == 0) {
SCLogDebug("pseudo is to_server");
np->flowflags |= FLOW_PKT_TOSERVER;
} else {
SCLogDebug("pseudo is to_client");
np->flowflags |= FLOW_PKT_TOCLIENT;
}
np->flowflags |= FLOW_PKT_ESTABLISHED;
np->payload = NULL;
np->payload_len = 0;
if (FLOW_IS_IPV4(f)) {
if (dir == 0) {
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->src, &np->src);
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->dst, &np->dst);
np->sp = f->sp;
np->dp = f->dp;
} else {
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->src, &np->dst);
FLOW_COPY_IPV4_ADDR_TO_PACKET(&f->dst, &np->src);
np->sp = f->dp;
np->dp = f->sp;
}
/* Check if we have enough room in direct data. We need ipv4 hdr + tcp hdr.
* Force an allocation if it is not the case.
*/
if (GET_PKT_DIRECT_MAX_SIZE(np) < 40) {
if (PacketCallocExtPkt(np, 40) == -1) {
goto error;
}
}
/* set the ip header */
np->ip4h = (IPV4Hdr *)GET_PKT_DATA(np);
/* version 4 and length 20 bytes for the tcp header */
np->ip4h->ip_verhl = 0x45;
np->ip4h->ip_tos = 0;
np->ip4h->ip_len = htons(40);
np->ip4h->ip_id = 0;
np->ip4h->ip_off = 0;
np->ip4h->ip_ttl = 64;
np->ip4h->ip_proto = IPPROTO_TCP;
if (dir == 0) {
np->ip4h->s_ip_src.s_addr = f->src.addr_data32[0];
np->ip4h->s_ip_dst.s_addr = f->dst.addr_data32[0];
} else {
np->ip4h->s_ip_src.s_addr = f->dst.addr_data32[0];
np->ip4h->s_ip_dst.s_addr = f->src.addr_data32[0];
}
/* set the tcp header */
np->tcph = (TCPHdr *)((uint8_t *)GET_PKT_DATA(np) + 20);
SET_PKT_LEN(np, 40); /* ipv4 hdr + tcp hdr */
} else if (FLOW_IS_IPV6(f)) {
if (dir == 0) {
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->src, &np->src);
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->dst, &np->dst);
np->sp = f->sp;
np->dp = f->dp;
} else {
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->src, &np->dst);
FLOW_COPY_IPV6_ADDR_TO_PACKET(&f->dst, &np->src);
np->sp = f->dp;
np->dp = f->sp;
}
/* Check if we have enough room in direct data. We need ipv6 hdr + tcp hdr.
* Force an allocation if it is not the case.
*/
if (GET_PKT_DIRECT_MAX_SIZE(np) < 60) {
if (PacketCallocExtPkt(np, 60) == -1) {
goto error;
}
}
/* set the ip header */
np->ip6h = (IPV6Hdr *)GET_PKT_DATA(np);
/* version 6 */
np->ip6h->s_ip6_vfc = 0x60;
np->ip6h->s_ip6_flow = 0;
np->ip6h->s_ip6_nxt = IPPROTO_TCP;
np->ip6h->s_ip6_plen = htons(20);
np->ip6h->s_ip6_hlim = 64;
if (dir == 0) {
np->ip6h->s_ip6_src[0] = f->src.addr_data32[0];
np->ip6h->s_ip6_src[1] = f->src.addr_data32[1];
np->ip6h->s_ip6_src[2] = f->src.addr_data32[2];
np->ip6h->s_ip6_src[3] = f->src.addr_data32[3];
np->ip6h->s_ip6_dst[0] = f->dst.addr_data32[0];
np->ip6h->s_ip6_dst[1] = f->dst.addr_data32[1];
np->ip6h->s_ip6_dst[2] = f->dst.addr_data32[2];
np->ip6h->s_ip6_dst[3] = f->dst.addr_data32[3];
} else {
np->ip6h->s_ip6_src[0] = f->dst.addr_data32[0];
np->ip6h->s_ip6_src[1] = f->dst.addr_data32[1];
np->ip6h->s_ip6_src[2] = f->dst.addr_data32[2];
np->ip6h->s_ip6_src[3] = f->dst.addr_data32[3];
np->ip6h->s_ip6_dst[0] = f->src.addr_data32[0];
np->ip6h->s_ip6_dst[1] = f->src.addr_data32[1];
np->ip6h->s_ip6_dst[2] = f->src.addr_data32[2];
np->ip6h->s_ip6_dst[3] = f->src.addr_data32[3];
}
/* set the tcp header */
np->tcph = (TCPHdr *)((uint8_t *)GET_PKT_DATA(np) + 40);
SET_PKT_LEN(np, 60); /* ipv6 hdr + tcp hdr */
}
np->tcph->th_offx2 = 0x50;
np->tcph->th_flags |= TH_ACK;
np->tcph->th_win = 10;
np->tcph->th_urp = 0;
/* to server */
if (dir == 0) {
np->tcph->th_sport = htons(f->sp);
np->tcph->th_dport = htons(f->dp);
np->tcph->th_seq = htonl(ssn->client.next_seq);
np->tcph->th_ack = htonl(ssn->server.last_ack);
/* to client */
} else {
np->tcph->th_sport = htons(f->dp);
np->tcph->th_dport = htons(f->sp);
np->tcph->th_seq = htonl(ssn->server.next_seq);
np->tcph->th_ack = htonl(ssn->client.last_ack);
}
/* use parent time stamp */
memcpy(&np->ts, &parent->ts, sizeof(struct timeval));
SCLogDebug("np %p", np);
PacketEnqueue(pq, np);
StatsIncr(tv, stt->counter_tcp_pseudo);
SCReturn;
error:
FlowDeReference(&np->flow);
SCReturn;
}
/** \brief create packets in both directions to flush out logging
* and detection before switching protocols.
* In IDS mode, create first in packet dir, 2nd in opposing
* In IPS mode, do the reverse.
* Flag TCP engine that data needs to be inspected regardless
* of how far we are wrt inspect limits.
*/
void StreamTcpDetectLogFlush(ThreadVars *tv, StreamTcpThread *stt, Flow *f, Packet *p, PacketQueue *pq)
{
TcpSession *ssn = f->protoctx;
ssn->client.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
ssn->server.flags |= STREAMTCP_STREAM_FLAG_TRIGGER_RAW;
bool ts = PKT_IS_TOSERVER(p) ? true : false;
ts ^= StreamTcpInlineMode();
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^0);
StreamTcpPseudoPacketCreateDetectLogFlush(tv, stt, p, ssn, pq, ts^1);
}
/**
* \brief Run callback function on each TCP segment
*
* \note when stream engine is running in inline mode all segments are used,
* in IDS/non-inline mode only ack'd segments are iterated.
*
* \note Must be called under flow lock.
*
* \return -1 in case of error, the number of segment in case of success
*
*/
int StreamTcpSegmentForEach(const Packet *p, uint8_t flag, StreamSegmentCallback CallbackFunc, void *data)
{
TcpSession *ssn = NULL;
TcpStream *stream = NULL;
int ret = 0;
int cnt = 0;
if (p->flow == NULL)
return 0;
ssn = (TcpSession *)p->flow->protoctx;
if (ssn == NULL) {
return 0;
}
if (flag & FLOW_PKT_TOSERVER) {
stream = &(ssn->server);
} else {
stream = &(ssn->client);
}
/* for IDS, return ack'd segments. For IPS all. */
TcpSegment *seg;
RB_FOREACH(seg, TCPSEG, &stream->seg_tree) {
if (!((stream_config.flags & STREAMTCP_INIT_FLAG_INLINE)
|| SEQ_LT(seg->seq, stream->last_ack)))
break;
const uint8_t *seg_data;
uint32_t seg_datalen;
StreamingBufferSegmentGetData(&stream->sb, &seg->sbseg, &seg_data, &seg_datalen);
ret = CallbackFunc(p, data, seg_data, seg_datalen);
if (ret != 1) {
SCLogDebug("Callback function has failed");
return -1;
}
cnt++;
}
return cnt;
}
int StreamTcpBypassEnabled(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_BYPASS);
}
/**
* \brief See if stream engine is operating in inline mode
*
* \retval 0 no
* \retval 1 yes
*/
int StreamTcpInlineMode(void)
{
return (stream_config.flags & STREAMTCP_INIT_FLAG_INLINE) ? 1 : 0;
}
void TcpSessionSetReassemblyDepth(TcpSession *ssn, uint32_t size)
{
if (size > ssn->reassembly_depth || size == 0) {
ssn->reassembly_depth = size;
}
return;
}
#ifdef UNITTESTS
#define SET_ISN(stream, setseq) \
(stream)->isn = (setseq); \
(stream)->base_seq = (setseq) + 1
/**
* \test Test the allocation of TCP session for a given packet from the
* ssn_pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest01 (void)
{
StreamTcpThread stt;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
TcpSession *ssn = StreamTcpNewSession(p, 0);
if (ssn == NULL) {
printf("Session can not be allocated: ");
goto end;
}
f.protoctx = ssn;
if (f.alparser != NULL) {
printf("AppLayer field not set to NULL: ");
goto end;
}
if (ssn->state != 0) {
printf("TCP state field not set to 0: ");
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the deallocation of TCP session for a given packet and return
* the memory back to ssn_pool and corresponding segments to segment
* pool.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest02 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->flowflags = FLOW_PKT_TOCLIENT;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
StreamTcpSessionClear(p->flow->protoctx);
//StreamTcpUTClearSession(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN packet of the session. The session is setup only if midstream
* sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest03 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 20 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* SYN/ACK packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest04 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(9);
p->tcph->th_ack = htonl(19);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 10 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 20)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we missed the intial
* 3WHS packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest05 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(13);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, 4); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(19);
p->tcph->th_ack = htonl(16);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, 4); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 16 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we have seen only the
* FIN, RST packets packet of the session. The session is setup only if
* midstream sessions are allowed to setup.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest06 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
TcpSession ssn;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&ssn, 0, sizeof (TcpSession));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_flags = TH_FIN;
p->tcph = &tcph;
/* StreamTcpPacket returns -1 on unsolicited FIN */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed: ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't: ");
goto end;
}
p->tcph->th_flags = TH_RST;
/* StreamTcpPacket returns -1 on unsolicited RST */
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("StreamTcpPacket failed (2): ");
goto end;
}
if (((TcpSession *)(p->flow->protoctx)) != NULL) {
printf("we have a ssn while we shouldn't (2): ");
goto end;
}
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the working on PAWS. The packet will be dropped by stream, as
* its timestamp is old, although the segment is in the window.
*/
static int StreamTcpTest07 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
PacketQueue pq;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 2;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) != -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working on PAWS. The packet will be accpeted by engine as
* the timestamp is valid and it is in window.
*/
static int StreamTcpTest08 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->tcpvars.ts_set = TRUE;
p->tcpvars.ts_val = 10;
p->tcpvars.ts_ecr = 11;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(20);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
p->tcpvars.ts_val = 12;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *) (p->flow->protoctx))->client.next_seq != 12);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the working of No stream reassembly flag. The stream will not
* reassemble the segment if the flag is set.
*/
static int StreamTcpTest09 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[1] = {0x42};
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof(StreamTcpThread));
memset(&tcph, 0, sizeof(TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.midstream = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->payload = payload;
p->payload_len = 1;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(12);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(p->flow->protoctx == NULL);
StreamTcpSetSessionNoReassemblyFlag(((TcpSession *)(p->flow->protoctx)), 0);
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
TcpSession *ssn = p->flow->protoctx;
FAIL_IF_NULL(ssn);
TcpSegment *seg = RB_MIN(TCPSEG, &ssn->client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCPSEG_RB_NEXT(seg) != NULL);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we see all the packets in that stream from start.
*/
static int StreamTcpTest10 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN packet of that stream.
*/
static int StreamTcpTest11 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
stream_config.async_oneside = TRUE;
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(1);
tcph.th_flags = TH_SYN|TH_ACK;
p->tcph = &tcph;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
p->tcph->th_seq = htonl(2);
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
FAIL_IF(StreamTcpPacket(&tv, p, &stt, &pq) == -1);
FAIL_IF(! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC));
FAIL_IF(((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED);
FAIL_IF(((TcpSession *)(p->flow->protoctx))->server.last_ack != 2 &&
((TcpSession *)(p->flow->protoctx))->client.next_seq != 1);
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
PASS;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest12 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 6 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 11) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session when we are seeing asynchronous
* stream, while we missed the SYN and SYN/ACK packets in that stream.
* Later, we start to receive the packet from other end stream too.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest13 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(11);
tcph.th_flags = TH_ACK;
p->tcph = &tcph;
int ret = 0;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(6);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.async_oneside != TRUE) {
ret = 1;
goto end;
}
if (! (((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_ASYNC)) {
printf("failed in setting asynchronous session\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("failed in setting state\n");
goto end;
}
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(9);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.last_ack != 9 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 14) {
printf("failed in seq %"PRIu32" match\n",
((TcpSession *)(p->flow->protoctx))->client.last_ack);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.1\n"
"\n"
" linux: 192.168.0.2\n"
"\n";
/* Dummy conf string to setup the OS policy for unit testing */
static const char *dummy_conf_string1 =
"%YAML 1.1\n"
"---\n"
"\n"
"default-log-dir: /var/log/eidps\n"
"\n"
"logging:\n"
"\n"
" default-log-level: debug\n"
"\n"
" default-format: \"<%t> - <%l>\"\n"
"\n"
" default-startup-message: Your IDS has started.\n"
"\n"
" default-output-filter:\n"
"\n"
"host-os-policy:\n"
"\n"
" windows: 192.168.0.0/24," "192.168.1.1\n"
"\n"
" linux: 192.168.1.0/24," "192.168.0.1\n"
"\n";
/**
* \brief Function to parse the dummy conf string and get the value of IP
* address for the corresponding OS policy type.
*
* \param conf_val_name Name of the OS policy type
* \retval returns IP address as string on success and NULL on failure
*/
static const char *StreamTcpParseOSPolicy (char *conf_var_name)
{
SCEnter();
char conf_var_type_name[15] = "host-os-policy";
char *conf_var_full_name = NULL;
const char *conf_var_value = NULL;
if (conf_var_name == NULL)
goto end;
/* the + 2 is for the '.' and the string termination character '\0' */
conf_var_full_name = (char *)SCMalloc(strlen(conf_var_type_name) +
strlen(conf_var_name) + 2);
if (conf_var_full_name == NULL)
goto end;
if (snprintf(conf_var_full_name,
strlen(conf_var_type_name) + strlen(conf_var_name) + 2, "%s.%s",
conf_var_type_name, conf_var_name) < 0) {
SCLogError(SC_ERR_INVALID_VALUE, "Error in making the conf full name");
goto end;
}
if (ConfGet(conf_var_full_name, &conf_var_value) != 1) {
SCLogError(SC_ERR_UNKNOWN_VALUE, "Error in getting conf value for conf name %s",
conf_var_full_name);
goto end;
}
SCLogDebug("Value obtained from the yaml conf file, for the var "
"\"%s\" is \"%s\"", conf_var_name, conf_var_value);
end:
if (conf_var_full_name != NULL)
SCFree(conf_var_full_name);
SCReturnCharPtr(conf_var_value);
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest14 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string, strlen(dummy_conf_string));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.0.2");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest01 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(10);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(21);
p->tcph->th_ack = htonl(10);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK, but the SYN/ACK does
* not have the right SEQ
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest02 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(21); /* the SYN/ACK uses the SEQ from the first SYN pkt */
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1) {
printf("SYN/ACK pkt not rejected but it should have: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test set up a TCP session using the 4WHS:
* SYN, SYN, SYN/ACK, ACK: however the SYN/ACK and ACK
* are part of a normal 3WHS
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcp4WHSTest03 (void)
{
int ret = 0;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(unlikely(p == NULL));
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
memset(p, 0, SIZE_OF_PACKET);
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
StreamTcpUTInit(&stt.ra_ctx);
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = 0;
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = 0;
p->tcph->th_flags = TH_SYN;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if ((!(((TcpSession *)(p->flow->protoctx))->flags & STREAMTCP_FLAG_4WHS))) {
printf("STREAMTCP_FLAG_4WHS flag not set: ");
goto end;
}
p->tcph->th_seq = htonl(30);
p->tcph->th_ack = htonl(11);
p->tcph->th_flags = TH_SYN|TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(11);
p->tcph->th_ack = htonl(31);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED) {
printf("state is not ESTABLISHED: ");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest15 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.20");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.20");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_WINDOWS && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_LINUX)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_WINDOWS,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_LINUX);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1"
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest16 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("192.168.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_WINDOWS)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_WINDOWS);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the setting up a OS policy. Te OS policy values are defined in
* the config string "dummy_conf_string1". To check the setting of
* Default os policy
*
* \retval On success it returns 1 and on failure 0
*/
static int StreamTcpTest17 (void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
uint8_t payload[4];
struct in_addr addr;
IPV4Hdr ipv4h;
char os_policy_name[10] = "windows";
const char *ip_addr;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&addr, 0, sizeof(addr));
memset(&ipv4h, 0, sizeof(ipv4h));
FLOW_INITIALIZE(&f);
p->flow = &f;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
strlcpy(os_policy_name, "linux\0", sizeof(os_policy_name));
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
addr.s_addr = inet_addr("192.168.0.1");
tcph.th_win = htons(5480);
tcph.th_seq = htonl(10);
tcph.th_ack = htonl(20);
tcph.th_flags = TH_ACK|TH_PUSH;
p->tcph = &tcph;
p->dst.family = AF_INET;
p->dst.address.address_un_data32[0] = addr.s_addr;
p->ip4h = &ipv4h;
StreamTcpCreateTestPacket(payload, 0x41, 3, sizeof(payload)); /*AAA*/
p->payload = payload;
p->payload_len = 3;
FLOWLOCK_WRLOCK(&f);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(20);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x42, 3, sizeof(payload)); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(15);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(14);
p->tcph->th_ack = htonl(23);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x43, 3, sizeof(payload)); /*CCC*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
addr.s_addr = inet_addr("10.1.1.1");
p->tcph->th_seq = htonl(25);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_seq = htonl(24);
p->tcph->th_ack = htonl(13);
p->tcph->th_flags = TH_ACK|TH_PUSH;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x44, 3, sizeof(payload)); /*DDD*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
if (stream_config.midstream != TRUE) {
ret = 1;
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->state != TCP_ESTABLISHED)
goto end;
if (((TcpSession *)(p->flow->protoctx))->client.next_seq != 13 &&
((TcpSession *)(p->flow->protoctx))->server.next_seq != 23) {
printf("failed in next_seq match client.next_seq %"PRIu32""
" server.next_seq %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->client.next_seq,
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->client.os_policy !=
OS_POLICY_LINUX && ((TcpSession *)
(p->flow->protoctx))->server.os_policy != OS_POLICY_DEFAULT)
{
printf("failed in setting up OS policy, client.os_policy: %"PRIu8""
" should be %"PRIu8" and server.os_policy: %"PRIu8""
" should be %"PRIu8"\n", ((TcpSession *)
(p->flow->protoctx))->client.os_policy, (uint8_t)OS_POLICY_LINUX,
((TcpSession *)(p->flow->protoctx))->server.os_policy,
(uint8_t)OS_POLICY_DEFAULT);
goto end;
}
StreamTcpSessionPktFree(p);
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
FLOWLOCK_UNLOCK(&f);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest18 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS)
goto end;
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest19 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_WINDOWS) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8": ",
(uint8_t)OS_POLICY_WINDOWS, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest20 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.0.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest21 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "linux";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("192.168.1.30");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_LINUX) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_LINUX, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the various OS policies based on different IP addresses from
confuguration defined in 'dummy_conf_string1' */
static int StreamTcpTest22 (void)
{
StreamTcpThread stt;
struct in_addr addr;
char os_policy_name[10] = "windows";
const char *ip_addr;
TcpStream stream;
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
IPV4Hdr ipv4h;
int ret = 0;
memset(&addr, 0, sizeof(addr));
memset(&stream, 0, sizeof(stream));
memset(p, 0, SIZE_OF_PACKET);
memset(&ipv4h, 0, sizeof(ipv4h));
StreamTcpUTInit(&stt.ra_ctx);
SCHInfoCleanResources();
/* Load the config string in to parser */
ConfCreateContextBackup();
ConfInit();
ConfYamlLoadString(dummy_conf_string1, strlen(dummy_conf_string1));
/* Get the IP address as string and add it to Host info tree for lookups */
ip_addr = StreamTcpParseOSPolicy(os_policy_name);
SCHInfoAddHostOSInfo(os_policy_name, ip_addr, -1);
p->dst.family = AF_INET;
p->ip4h = &ipv4h;
addr.s_addr = inet_addr("123.231.2.1");
p->dst.address.address_un_data32[0] = addr.s_addr;
StreamTcpSetOSPolicy(&stream, p);
if (stream.os_policy != OS_POLICY_DEFAULT) {
printf("expected os_policy: %"PRIu8" but received %"PRIu8"\n",
(uint8_t)OS_POLICY_DEFAULT, stream.os_policy);
goto end;
}
ret = 1;
end:
ConfDeInit();
ConfRestoreContextBackup();
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest23(void)
{
StreamTcpThread stt;
TcpSession ssn;
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF(p == NULL);
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&tv, 0, sizeof (ThreadVars));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
SET_ISN(&ssn.client, 3184324452UL);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419609UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324453UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 6;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
TcpSegment *seg = RB_MAX(TCPSEG, &ssn.client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCP_SEG_LEN(seg) != 2);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/** \test Test the stream mem leaks conditions. */
static int StreamTcpTest24(void)
{
StreamTcpThread stt;
TcpSession ssn;
Packet *p = SCMalloc(SIZE_OF_PACKET);
FAIL_IF (p == NULL);
Flow f;
TCPHdr tcph;
uint8_t packet[1460] = "";
ThreadVars tv;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
StreamTcpUTInit(&stt.ra_ctx);
StreamTcpUTSetupSession(&ssn);
memset(p, 0, SIZE_OF_PACKET);
memset(&f, 0, sizeof (Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
ssn.client.os_policy = OS_POLICY_BSD;
f.protoctx = &ssn;
p->src.family = AF_INET;
p->dst.family = AF_INET;
p->proto = IPPROTO_TCP;
p->flow = &f;
tcph.th_win = 5480;
tcph.th_flags = TH_PUSH | TH_ACK;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
p->payload = packet;
//ssn.client.ra_app_base_seq = ssn.client.ra_raw_base_seq = ssn.client.last_ack = 3184324453UL;
SET_ISN(&ssn.client, 3184324453UL);
p->tcph->th_seq = htonl(3184324455UL);
p->tcph->th_ack = htonl(3373419621UL);
p->payload_len = 4;
FAIL_IF (StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419633UL);
p->payload_len = 2;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
p->tcph->th_seq = htonl(3184324459UL);
p->tcph->th_ack = htonl(3373419657UL);
p->payload_len = 4;
FAIL_IF(StreamTcpReassembleHandleSegment(&tv, stt.ra_ctx, &ssn, &ssn.client, p, &pq) == -1);
TcpSegment *seg = RB_MAX(TCPSEG, &ssn.client.seg_tree);
FAIL_IF_NULL(seg);
FAIL_IF(TCP_SEG_LEN(seg) != 4);
StreamTcpUTClearSession(&ssn);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) > 0);
PASS;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest25(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest26(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the initialization of tcp streams with congestion flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest27(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(6);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x42, 3, 4); /*BBB*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL)
goto end;
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test Test the memcap incrementing/decrementing and memcap check */
static int StreamTcpTest28(void)
{
StreamTcpThread stt;
StreamTcpUTInit(&stt.ra_ctx);
uint32_t memuse = SC_ATOMIC_GET(st_memuse);
StreamTcpIncrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != (memuse+500));
StreamTcpDecrMemuse(500);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != memuse);
FAIL_IF(StreamTcpCheckMemcap(500) != 1);
FAIL_IF(StreamTcpCheckMemcap((memuse + SC_ATOMIC_GET(stream_config.memcap))) != 0);
StreamTcpUTDeinit(stt.ra_ctx);
FAIL_IF(SC_ATOMIC_GET(st_memuse) != 0);
PASS;
}
#if 0
/**
* \test Test the resetting of the sesison with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest29(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t packet[1460] = "";
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = packet;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
tcpvars.hlen = 20;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 119197101;
ssn.server.window = 5184;
ssn.server.next_win = 5184;
ssn.server.last_ack = 119197101;
ssn.server.ra_base_seq = 119197101;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 4;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(119197102);
p.tcph->th_ack = htonl(15);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(15);
p.tcph->th_ack = htonl(119197102);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the ssn.state should be TCP_ESTABLISHED(%"PRIu8"), not %"PRIu8""
"\n", TCP_ESTABLISHED, ssn.state);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the overlapping of the packet with bad checksum packet and later
* send the malicious contents on the session. Engine should drop the
* packet with the bad checksum.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest30(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
uint8_t payload[9] = "AAAAAAAAA";
uint8_t payload1[9] = "GET /EVIL";
uint8_t expected_content[9] = { 0x47, 0x45, 0x54, 0x20, 0x2f, 0x45, 0x56,
0x49, 0x4c };
int result = 1;
FLOW_INITIALIZE(&f);
StreamTcpInitConfig(TRUE);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_BSD;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.payload = payload;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
ssn.state = TCP_ESTABLISHED;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_PUSH | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079940);
p.payload = payload1;
p.payload_len = 9;
p.ip4h->ip_src = addr1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(20);
p.payload_len = 0;
p.ip4h->ip_src = addr;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (StreamTcpCheckStreamContents(expected_content, 9, &ssn.client) != 1) {
printf("the contents are not as expected(GET /EVIL), contents are: ");
PrintRawDataFp(stdout, ssn.client.seg_list->payload, 9);
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the multiple SYN packet handling with bad checksum and timestamp
* value. Engine should drop the bad checksum packet and establish
* TCP session correctly.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest31(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpSession ssn;
IPV4Hdr ipv4h;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
struct in_addr addr;
struct in_addr addr1;
TCPCache tcpc;
TCPVars tcpvars;
TcpStream server;
TcpStream client;
TCPOpt tcpopt;
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset (&ipv4h, 0, sizeof(IPV4Hdr));
memset (&addr, 0, sizeof(addr));
memset (&addr1, 0, sizeof(addr1));
memset (&tcpc, 0, sizeof(tcpc));
memset (&tcpvars, 0, sizeof(tcpvars));
memset(&ssn, 0, sizeof (TcpSession));
memset(&server, 0, sizeof (TcpStream));
memset(&client, 0, sizeof (TcpStream));
memset(&tcpopt, 0, sizeof (TCPOpt));
int result = 1;
StreamTcpInitConfig(TRUE);
FLOW_INITIALIZE(&f);
/* prevent L7 from kicking in */
ssn.client.os_policy = OS_POLICY_LINUX;
p.src.family = AF_INET;
p.dst.family = AF_INET;
p.proto = IPPROTO_TCP;
p.flow = &f;
tcph.th_win = 5480;
p.tcph = &tcph;
p.ip4h = &ipv4h;
p.tcpc = tcpc;
p.tcpc.level4_comp_csum = -1;
p.tcpvars = tcpvars;
p.tcpvars.ts = &tcpopt;
addr.s_addr = inet_addr("10.1.3.53");
p.dst.address.address_un_data32[0] = addr.s_addr;
addr1.s_addr = inet_addr("10.1.3.7");
p.src.address.address_un_data32[0] = addr1.s_addr;
f.protoctx = &ssn;
stt.ra_ctx = ra_ctx;
ssn.server = server;
ssn.client = client;
ssn.client.isn = 10;
ssn.client.window = 5184;
ssn.client.last_ack = 10;
ssn.client.ra_base_seq = 10;
ssn.client.next_win = 5184;
ssn.server.isn = 1351079940;
ssn.server.window = 5184;
ssn.server.next_win = 1351088132;
ssn.server.last_ack = 1351079940;
ssn.server.ra_base_seq = 1351079940;
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 100;
p.tcph->th_sum = 12345;
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(10);
p.payload_len = 0;
p.ip4h->ip_src = addr1;
p.tcpc.ts1 = 10;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
ssn.flags |= STREAMTCP_FLAG_TIMESTAMP;
tcph.th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_seq = htonl(1351079940);
p.tcph->th_ack = htonl(11);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
tcph.th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
p.tcph->th_seq = htonl(11);
p.tcph->th_ack = htonl(1351079941);
p.payload_len = 0;
p.tcpc.ts1 = 10;
p.ip4h->ip_src = addr1;
p.tcpc.level4_comp_csum = -1;
p.tcph->th_sum = TCPCalculateChecksum((uint16_t *)&(p.ip4h->ip_src),
(uint16_t *)p.tcph,
(p.payload_len +
p.tcpvars.hlen) );
if (StreamTcp(&tv, &p, (void *)&stt, NULL, NULL) != TM_ECODE_OK) {
printf("failed in segment reassmebling\n");
result &= 0;
goto end;
}
if (ssn.state != TCP_ESTABLISHED) {
printf("the should have been changed to TCP_ESTABLISHED!!\n ");
result &= 0;
goto end;
}
end:
StreamTcpReturnStreamSegments(&ssn.client);
StreamTcpFreeConfig(TRUE);
return result;
}
/**
* \test Test the initialization of tcp streams with ECN & CWR flags
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest32(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN | TH_CWR | TH_ECN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK | TH_ECN;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_ECN | TH_CWR;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.flowflags = FLOW_PKT_TOCLIENT;
p.tcph->th_flags = TH_ACK;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the same
* ports have been used to start the new session after resetting the
* previous session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest33 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_RST | TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_CLOSED) {
printf("Tcp session should have been closed\n");
goto end;
}
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_SYN;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_seq = htonl(1);
p.tcph->th_ack = htonl(2);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(2);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been ESTABLISHED\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the PUSH flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest34 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_PUSH;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the allocation of TCP session for a given packet when the SYN
* packet is sent with the URG flag set.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest35 (void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
TcpReassemblyThreadCtx ra_ctx;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(&ra_ctx, 0, sizeof(TcpReassemblyThreadCtx));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN|TH_URG;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
stt.ra_ctx = &ra_ctx;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1)
goto end;
if (((TcpSession *)(p.flow->protoctx))->state != TCP_ESTABLISHED) {
printf("Tcp session should have been establisehd\n");
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p.flow->protoctx);
StreamTcpFreeConfig(TRUE);
return ret;
}
/**
* \test Test the processing of PSH and URG flag in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest36(void)
{
Packet p;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
TcpReassemblyThreadCtx *ra_ctx = StreamTcpReassembleInitThreadCtx(NULL);
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset (&p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
stt.ra_ctx = ra_ctx;
p.flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p.tcph = &tcph;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpInitConfig(TRUE);
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_flags = TH_SYN | TH_ACK;
p.flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p.tcph->th_ack = htonl(1);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_ACK;
p.flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p.tcph->th_ack = htonl(2);
p.tcph->th_seq = htonl(1);
p.tcph->th_flags = TH_PUSH | TH_ACK | TH_URG;
p.flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p.payload = payload;
p.payload_len = 3;
if (StreamTcpPacket(&tv, &p, &stt, &pq) == -1 || (TcpSession *)p.flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p.flow->protoctx)->client.next_seq != 4) {
printf("the ssn->client.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)p.flow->protoctx)->client.next_seq);
goto end;
}
StreamTcpSessionClear(p.flow->protoctx);
ret = 1;
end:
StreamTcpFreeConfig(TRUE);
return ret;
}
#endif
/**
* \test Test the processing of out of order FIN packets in tcp session.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest37(void)
{
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
int ret = 0;
PacketQueue pq;
memset(&pq,0,sizeof(PacketQueue));
memset(p, 0, SIZE_OF_PACKET);
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_ESTABLISHED) {
printf("the TCP state should be TCP_ESTABLISEHD\n");
goto end;
}
p->tcph->th_ack = htonl(2);
p->tcph->th_seq = htonl(4);
p->tcph->th_flags = TH_ACK|TH_FIN;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
if (((TcpSession *)p->flow->protoctx)->state != TCP_CLOSE_WAIT) {
printf("the TCP state should be TCP_CLOSE_WAIT\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_ACK;
p->payload_len = 0;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1 || (TcpSession *)p->flow->protoctx == NULL) {
printf("failed in processing packet\n");
goto end;
}
TcpStream *stream = &(((TcpSession *)p->flow->protoctx)->client);
FAIL_IF(STREAM_RAW_PROGRESS(stream) != 0); // no detect no progress update
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack.
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest38 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[128];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(29847);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 1 as the previous sent ACK value is out of
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 1) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 127, 128); /*AAA*/
p->payload = payload;
p->payload_len = 127;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 128) {
printf("the server.next_seq should be 128, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(256); // in window, but beyond next_seq
p->tcph->th_seq = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256, as the previous sent ACK value
is inside window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 1, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_ack = htonl(128);
p->tcph->th_seq = htonl(8);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 256 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 256) {
printf("the server.last_ack should be 256, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/**
* \test Test the validation of the ACK number before setting up the
* stream.last_ack and update the next_seq after loosing the .
*
* \retval On success it returns 1 and on failure 0.
*/
static int StreamTcpTest39 (void)
{
Flow f;
ThreadVars tv;
StreamTcpThread stt;
uint8_t payload[4];
TCPHdr tcph;
PacketQueue pq;
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
memset(&pq,0,sizeof(PacketQueue));
Packet *p = SCMalloc(SIZE_OF_PACKET);
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
FLOW_INITIALIZE(&f);
p->flow = &f;
tcph.th_win = htons(5480);
tcph.th_flags = TH_SYN;
p->tcph = &tcph;
p->flowflags = FLOW_PKT_TOSERVER;
int ret = 0;
StreamTcpUTInit(&stt.ra_ctx);
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
p->tcph->th_ack = htonl(1);
p->tcph->th_seq = htonl(1);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 4) {
printf("the server.next_seq should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
p->tcph->th_ack = htonl(4);
p->tcph->th_seq = htonl(2);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* last_ack value should be 4 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.last_ack != 4) {
printf("the server.last_ack should be 4, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.last_ack);
goto end;
}
p->tcph->th_seq = htonl(4);
p->tcph->th_ack = htonl(5);
p->tcph->th_flags = TH_PUSH | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
StreamTcpCreateTestPacket(payload, 0x41, 3, 4); /*AAA*/
p->payload = payload;
p->payload_len = 3;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1) {
printf("failed in processing packet in StreamTcpPacket\n");
goto end;
}
/* next_seq value should be 2987 as the previous sent ACK value is inside
window */
if (((TcpSession *)(p->flow->protoctx))->server.next_seq != 7) {
printf("the server.next_seq should be 7, but it is %"PRIu32"\n",
((TcpSession *)(p->flow->protoctx))->server.next_seq);
goto end;
}
ret = 1;
end:
StreamTcpSessionClear(p->flow->protoctx);
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick first */
static int StreamTcpTest42 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(501);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 500) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 500);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick second */
static int StreamTcpTest43 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, pick neither */
static int StreamTcpTest44 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(3001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_SYN_RECV) {
SCLogDebug("state not TCP_SYN_RECV");
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
FLOW_DESTROY(&f);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
/** \test multiple different SYN/ACK, over the limit */
static int StreamTcpTest45 (void)
{
int ret = 0;
Flow f;
ThreadVars tv;
StreamTcpThread stt;
TCPHdr tcph;
PacketQueue pq;
Packet *p = SCMalloc(SIZE_OF_PACKET);
TcpSession *ssn;
if (unlikely(p == NULL))
return 0;
memset(p, 0, SIZE_OF_PACKET);
memset(&pq,0,sizeof(PacketQueue));
memset (&f, 0, sizeof(Flow));
memset(&tv, 0, sizeof (ThreadVars));
memset(&stt, 0, sizeof (StreamTcpThread));
memset(&tcph, 0, sizeof (TCPHdr));
StreamTcpUTInit(&stt.ra_ctx);
stream_config.max_synack_queued = 2;
FLOW_INITIALIZE(&f);
p->tcph = &tcph;
tcph.th_win = htons(5480);
p->flow = &f;
/* SYN pkt */
tcph.th_flags = TH_SYN;
tcph.th_seq = htonl(100);
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(500);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(1000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(2000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
/* SYN/ACK */
p->tcph->th_seq = htonl(3000);
p->tcph->th_ack = htonl(101);
p->tcph->th_flags = TH_SYN | TH_ACK;
p->flowflags = FLOW_PKT_TOCLIENT;
if (StreamTcpPacket(&tv, p, &stt, &pq) != -1)
goto end;
/* ACK */
p->tcph->th_ack = htonl(1001);
p->tcph->th_seq = htonl(101);
p->tcph->th_flags = TH_ACK;
p->flowflags = FLOW_PKT_TOSERVER;
if (StreamTcpPacket(&tv, p, &stt, &pq) == -1)
goto end;
ssn = p->flow->protoctx;
if (ssn->state != TCP_ESTABLISHED) {
printf("state not TCP_ESTABLISHED: ");
goto end;
}
if (ssn->server.isn != 1000) {
SCLogDebug("ssn->server.isn %"PRIu32" != %"PRIu32"",
ssn->server.isn, 1000);
goto end;
}
if (ssn->client.isn != 100) {
SCLogDebug("ssn->client.isn %"PRIu32" != %"PRIu32"",
ssn->client.isn, 100);
goto end;
}
StreamTcpSessionClear(p->flow->protoctx);
ret = 1;
end:
SCFree(p);
StreamTcpUTDeinit(stt.ra_ctx);
return ret;
}
#endif /* UNITTESTS */
void StreamTcpRegisterTests (void)
{
#ifdef UNITTESTS
UtRegisterTest("StreamTcpTest01 -- TCP session allocation",
StreamTcpTest01);
UtRegisterTest("StreamTcpTest02 -- TCP session deallocation",
StreamTcpTest02);
UtRegisterTest("StreamTcpTest03 -- SYN missed MidStream session",
StreamTcpTest03);
UtRegisterTest("StreamTcpTest04 -- SYN/ACK missed MidStream session",
StreamTcpTest04);
UtRegisterTest("StreamTcpTest05 -- 3WHS missed MidStream session",
StreamTcpTest05);
UtRegisterTest("StreamTcpTest06 -- FIN, RST message MidStream session",
StreamTcpTest06);
UtRegisterTest("StreamTcpTest07 -- PAWS invalid timestamp",
StreamTcpTest07);
UtRegisterTest("StreamTcpTest08 -- PAWS valid timestamp", StreamTcpTest08);
UtRegisterTest("StreamTcpTest09 -- No Client Reassembly", StreamTcpTest09);
UtRegisterTest("StreamTcpTest10 -- No missed packet Async stream",
StreamTcpTest10);
UtRegisterTest("StreamTcpTest11 -- SYN missed Async stream",
StreamTcpTest11);
UtRegisterTest("StreamTcpTest12 -- SYN/ACK missed Async stream",
StreamTcpTest12);
UtRegisterTest("StreamTcpTest13 -- opposite stream packets for Async " "stream",
StreamTcpTest13);
UtRegisterTest("StreamTcp4WHSTest01", StreamTcp4WHSTest01);
UtRegisterTest("StreamTcp4WHSTest02", StreamTcp4WHSTest02);
UtRegisterTest("StreamTcp4WHSTest03", StreamTcp4WHSTest03);
UtRegisterTest("StreamTcpTest14 -- setup OS policy", StreamTcpTest14);
UtRegisterTest("StreamTcpTest15 -- setup OS policy", StreamTcpTest15);
UtRegisterTest("StreamTcpTest16 -- setup OS policy", StreamTcpTest16);
UtRegisterTest("StreamTcpTest17 -- setup OS policy", StreamTcpTest17);
UtRegisterTest("StreamTcpTest18 -- setup OS policy", StreamTcpTest18);
UtRegisterTest("StreamTcpTest19 -- setup OS policy", StreamTcpTest19);
UtRegisterTest("StreamTcpTest20 -- setup OS policy", StreamTcpTest20);
UtRegisterTest("StreamTcpTest21 -- setup OS policy", StreamTcpTest21);
UtRegisterTest("StreamTcpTest22 -- setup OS policy", StreamTcpTest22);
UtRegisterTest("StreamTcpTest23 -- stream memory leaks", StreamTcpTest23);
UtRegisterTest("StreamTcpTest24 -- stream memory leaks", StreamTcpTest24);
UtRegisterTest("StreamTcpTest25 -- test ecn/cwr sessions",
StreamTcpTest25);
UtRegisterTest("StreamTcpTest26 -- test ecn/cwr sessions",
StreamTcpTest26);
UtRegisterTest("StreamTcpTest27 -- test ecn/cwr sessions",
StreamTcpTest27);
UtRegisterTest("StreamTcpTest28 -- Memcap Test", StreamTcpTest28);
#if 0 /* VJ 2010/09/01 disabled since they blow up on Fedora and Fedora is
* right about blowing up. The checksum functions are not used properly
* in the tests. */
UtRegisterTest("StreamTcpTest29 -- Badchecksum Reset Test", StreamTcpTest29, 1);
UtRegisterTest("StreamTcpTest30 -- Badchecksum Overlap Test", StreamTcpTest30, 1);
UtRegisterTest("StreamTcpTest31 -- MultipleSyns Test", StreamTcpTest31, 1);
UtRegisterTest("StreamTcpTest32 -- Bogus CWR Test", StreamTcpTest32, 1);
UtRegisterTest("StreamTcpTest33 -- RST-SYN Again Test", StreamTcpTest33, 1);
UtRegisterTest("StreamTcpTest34 -- SYN-PUSH Test", StreamTcpTest34, 1);
UtRegisterTest("StreamTcpTest35 -- SYN-URG Test", StreamTcpTest35, 1);
UtRegisterTest("StreamTcpTest36 -- PUSH-URG Test", StreamTcpTest36, 1);
#endif
UtRegisterTest("StreamTcpTest37 -- Out of order FIN Test",
StreamTcpTest37);
UtRegisterTest("StreamTcpTest38 -- validate ACK", StreamTcpTest38);
UtRegisterTest("StreamTcpTest39 -- update next_seq", StreamTcpTest39);
UtRegisterTest("StreamTcpTest42 -- SYN/ACK queue", StreamTcpTest42);
UtRegisterTest("StreamTcpTest43 -- SYN/ACK queue", StreamTcpTest43);
UtRegisterTest("StreamTcpTest44 -- SYN/ACK queue", StreamTcpTest44);
UtRegisterTest("StreamTcpTest45 -- SYN/ACK queue", StreamTcpTest45);
/* set up the reassembly tests as well */
StreamTcpReassembleRegisterTests();
StreamTcpSackRegisterTests ();
#endif /* UNITTESTS */
}
| ./CrossVul/dataset_final_sorted/CWE-94/c/good_1212_0 |
crossvul-cpp_data_good_2756_6 | /*
* X.509 certificate parsing and verification
*
* 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)
*/
/*
* The ITU-T X.509 standard defines a certificate format for PKI.
*
* http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs)
* http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs)
* http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10)
*
* http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf
* http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_X509_CRT_PARSE_C)
#include "mbedtls/x509_crt.h"
#include "mbedtls/oid.h"
#include <stdio.h>
#include <string.h>
#if defined(MBEDTLS_PEM_PARSE_C)
#include "mbedtls/pem.h"
#endif
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#define mbedtls_free free
#define mbedtls_calloc calloc
#define mbedtls_snprintf snprintf
#endif
#if defined(MBEDTLS_THREADING_C)
#include "mbedtls/threading.h"
#endif
#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
#include <windows.h>
#else
#include <time.h>
#endif
#if defined(MBEDTLS_FS_IO)
#include <stdio.h>
#if !defined(_WIN32) || defined(EFIX64) || defined(EFI32)
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#endif /* !_WIN32 || EFIX64 || EFI32 */
#endif
/* 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;
}
/*
* Default profile
*/
const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default =
{
#if defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES)
/* Allow SHA-1 (weak, but still safe in controlled environments) */
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA1 ) |
#endif
/* Only SHA-2 hashes */
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
0xFFFFFFF, /* Any PK alg */
0xFFFFFFF, /* Any curve */
2048,
};
/*
* Next-default profile
*/
const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next =
{
/* Hashes from SHA-256 and above */
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
0xFFFFFFF, /* Any PK alg */
#if defined(MBEDTLS_ECP_C)
/* Curves at or above 128-bit security level */
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP521R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP256R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP384R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP512R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256K1 ),
#else
0,
#endif
2048,
};
/*
* NSA Suite B Profile
*/
const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb =
{
/* Only SHA-256 and 384 */
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ),
/* Only ECDSA */
MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECDSA ),
#if defined(MBEDTLS_ECP_C)
/* Only NIST P-256 and P-384 */
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ),
#else
0,
#endif
0,
};
/*
* Check md_alg against profile
* Return 0 if md_alg acceptable for this profile, -1 otherwise
*/
static int x509_profile_check_md_alg( const mbedtls_x509_crt_profile *profile,
mbedtls_md_type_t md_alg )
{
if( ( profile->allowed_mds & MBEDTLS_X509_ID_FLAG( md_alg ) ) != 0 )
return( 0 );
return( -1 );
}
/*
* Check pk_alg against profile
* Return 0 if pk_alg acceptable for this profile, -1 otherwise
*/
static int x509_profile_check_pk_alg( const mbedtls_x509_crt_profile *profile,
mbedtls_pk_type_t pk_alg )
{
if( ( profile->allowed_pks & MBEDTLS_X509_ID_FLAG( pk_alg ) ) != 0 )
return( 0 );
return( -1 );
}
/*
* Check key against profile
* Return 0 if pk_alg acceptable for this profile, -1 otherwise
*/
static int x509_profile_check_key( const mbedtls_x509_crt_profile *profile,
mbedtls_pk_type_t pk_alg,
const mbedtls_pk_context *pk )
{
#if defined(MBEDTLS_RSA_C)
if( pk_alg == MBEDTLS_PK_RSA || pk_alg == MBEDTLS_PK_RSASSA_PSS )
{
if( mbedtls_pk_get_bitlen( pk ) >= profile->rsa_min_bitlen )
return( 0 );
return( -1 );
}
#endif
#if defined(MBEDTLS_ECP_C)
if( pk_alg == MBEDTLS_PK_ECDSA ||
pk_alg == MBEDTLS_PK_ECKEY ||
pk_alg == MBEDTLS_PK_ECKEY_DH )
{
mbedtls_ecp_group_id gid = mbedtls_pk_ec( *pk )->grp.id;
if( ( profile->allowed_curves & MBEDTLS_X509_ID_FLAG( gid ) ) != 0 )
return( 0 );
return( -1 );
}
#endif
return( -1 );
}
/*
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
*/
static int x509_get_version( unsigned char **p,
const unsigned char *end,
int *ver )
{
int ret;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
{
*ver = 0;
return( 0 );
}
return( ret );
}
end = *p + len;
if( ( ret = mbedtls_asn1_get_int( p, end, ver ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_VERSION + ret );
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_VERSION +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
/*
* Validity ::= SEQUENCE {
* notBefore Time,
* notAfter Time }
*/
static int x509_get_dates( unsigned char **p,
const unsigned char *end,
mbedtls_x509_time *from,
mbedtls_x509_time *to )
{
int ret;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_DATE + ret );
end = *p + len;
if( ( ret = mbedtls_x509_get_time( p, end, from ) ) != 0 )
return( ret );
if( ( ret = mbedtls_x509_get_time( p, end, to ) ) != 0 )
return( ret );
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_DATE +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
/*
* X.509 v2/v3 unique identifier (not parsed)
*/
static int x509_get_uid( unsigned char **p,
const unsigned char *end,
mbedtls_x509_buf *uid, int n )
{
int ret;
if( *p == end )
return( 0 );
uid->tag = **p;
if( ( ret = mbedtls_asn1_get_tag( p, end, &uid->len,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | n ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
return( 0 );
return( ret );
}
uid->p = *p;
*p += uid->len;
return( 0 );
}
static int x509_get_basic_constraints( unsigned char **p,
const unsigned char *end,
int *ca_istrue,
int *max_pathlen )
{
int ret;
size_t len;
/*
* BasicConstraints ::= SEQUENCE {
* cA BOOLEAN DEFAULT FALSE,
* pathLenConstraint INTEGER (0..MAX) OPTIONAL }
*/
*ca_istrue = 0; /* DEFAULT FALSE */
*max_pathlen = 0; /* endless */
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( *p == end )
return( 0 );
if( ( ret = mbedtls_asn1_get_bool( p, end, ca_istrue ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
ret = mbedtls_asn1_get_int( p, end, ca_istrue );
if( ret != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( *ca_istrue != 0 )
*ca_istrue = 1;
}
if( *p == end )
return( 0 );
if( ( ret = mbedtls_asn1_get_int( p, end, max_pathlen ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
(*max_pathlen)++;
return( 0 );
}
static int x509_get_ns_cert_type( unsigned char **p,
const unsigned char *end,
unsigned char *ns_cert_type)
{
int ret;
mbedtls_x509_bitstring bs = { 0, 0, NULL };
if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( bs.len != 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_INVALID_LENGTH );
/* Get actual bitstring */
*ns_cert_type = *bs.p;
return( 0 );
}
static int x509_get_key_usage( unsigned char **p,
const unsigned char *end,
unsigned int *key_usage)
{
int ret;
size_t i;
mbedtls_x509_bitstring bs = { 0, 0, NULL };
if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( bs.len < 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_INVALID_LENGTH );
/* Get actual bitstring */
*key_usage = 0;
for( i = 0; i < bs.len && i < sizeof( unsigned int ); i++ )
{
*key_usage |= (unsigned int) bs.p[i] << (8*i);
}
return( 0 );
}
/*
* ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
*
* KeyPurposeId ::= OBJECT IDENTIFIER
*/
static int x509_get_ext_key_usage( unsigned char **p,
const unsigned char *end,
mbedtls_x509_sequence *ext_key_usage)
{
int ret;
if( ( ret = mbedtls_asn1_get_sequence_of( p, end, ext_key_usage, MBEDTLS_ASN1_OID ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
/* Sequence length must be >= 1 */
if( ext_key_usage->buf.p == NULL )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_INVALID_LENGTH );
return( 0 );
}
/*
* SubjectAltName ::= GeneralNames
*
* GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
*
* GeneralName ::= CHOICE {
* otherName [0] OtherName,
* rfc822Name [1] IA5String,
* dNSName [2] IA5String,
* x400Address [3] ORAddress,
* directoryName [4] Name,
* ediPartyName [5] EDIPartyName,
* uniformResourceIdentifier [6] IA5String,
* iPAddress [7] OCTET STRING,
* registeredID [8] OBJECT IDENTIFIER }
*
* OtherName ::= SEQUENCE {
* type-id OBJECT IDENTIFIER,
* value [0] EXPLICIT ANY DEFINED BY type-id }
*
* EDIPartyName ::= SEQUENCE {
* nameAssigner [0] DirectoryString OPTIONAL,
* partyName [1] DirectoryString }
*
* NOTE: we only parse and use dNSName at this point.
*/
static int x509_get_subject_alt_name( unsigned char **p,
const unsigned char *end,
mbedtls_x509_sequence *subject_alt_name )
{
int ret;
size_t len, tag_len;
mbedtls_asn1_buf *buf;
unsigned char tag;
mbedtls_asn1_sequence *cur = subject_alt_name;
/* Get main sequence tag */
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( *p + len != end )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
while( *p < end )
{
if( ( end - *p ) < 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_OUT_OF_DATA );
tag = **p;
(*p)++;
if( ( ret = mbedtls_asn1_get_len( p, end, &tag_len ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( ( tag & MBEDTLS_ASN1_CONTEXT_SPECIFIC ) != MBEDTLS_ASN1_CONTEXT_SPECIFIC )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
/* Skip everything but DNS name */
if( tag != ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2 ) )
{
*p += tag_len;
continue;
}
/* Allocate and assign next pointer */
if( cur->buf.p != NULL )
{
if( cur->next != NULL )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
cur->next = mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) );
if( cur->next == NULL )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_ALLOC_FAILED );
cur = cur->next;
}
buf = &(cur->buf);
buf->tag = tag;
buf->p = *p;
buf->len = tag_len;
*p += buf->len;
}
/* Set final sequence entry's next pointer to NULL */
cur->next = NULL;
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
/*
* X.509 v3 extensions
*
*/
static int x509_get_crt_ext( unsigned char **p,
const unsigned char *end,
mbedtls_x509_crt *crt )
{
int ret;
size_t len;
unsigned char *end_ext_data, *end_ext_octet;
if( ( ret = mbedtls_x509_get_ext( p, end, &crt->v3_ext, 3 ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
return( 0 );
return( ret );
}
while( *p < end )
{
/*
* Extension ::= SEQUENCE {
* extnID OBJECT IDENTIFIER,
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING }
*/
mbedtls_x509_buf extn_oid = {0, 0, NULL};
int is_critical = 0; /* DEFAULT FALSE */
int ext_type = 0;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
end_ext_data = *p + len;
/* Get extension ID */
extn_oid.tag = **p;
if( ( ret = mbedtls_asn1_get_tag( p, end, &extn_oid.len, MBEDTLS_ASN1_OID ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
extn_oid.p = *p;
*p += extn_oid.len;
if( ( end - *p ) < 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_OUT_OF_DATA );
/* Get optional critical */
if( ( ret = mbedtls_asn1_get_bool( p, end_ext_data, &is_critical ) ) != 0 &&
( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
/* Data should be octet string type */
if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len,
MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
end_ext_octet = *p + len;
if( end_ext_octet != end_ext_data )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
/*
* Detect supported extensions
*/
ret = mbedtls_oid_get_x509_ext_type( &extn_oid, &ext_type );
if( ret != 0 )
{
/* No parser found, skip extension */
*p = end_ext_octet;
#if !defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION)
if( is_critical )
{
/* Data is marked as critical: fail */
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
}
#endif
continue;
}
/* Forbid repeated extensions */
if( ( crt->ext_types & ext_type ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
crt->ext_types |= ext_type;
switch( ext_type )
{
case MBEDTLS_X509_EXT_BASIC_CONSTRAINTS:
/* Parse basic constraints */
if( ( ret = x509_get_basic_constraints( p, end_ext_octet,
&crt->ca_istrue, &crt->max_pathlen ) ) != 0 )
return( ret );
break;
case MBEDTLS_X509_EXT_KEY_USAGE:
/* Parse key usage */
if( ( ret = x509_get_key_usage( p, end_ext_octet,
&crt->key_usage ) ) != 0 )
return( ret );
break;
case MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE:
/* Parse extended key usage */
if( ( ret = x509_get_ext_key_usage( p, end_ext_octet,
&crt->ext_key_usage ) ) != 0 )
return( ret );
break;
case MBEDTLS_X509_EXT_SUBJECT_ALT_NAME:
/* Parse subject alt name */
if( ( ret = x509_get_subject_alt_name( p, end_ext_octet,
&crt->subject_alt_names ) ) != 0 )
return( ret );
break;
case MBEDTLS_X509_EXT_NS_CERT_TYPE:
/* Parse netscape certificate type */
if( ( ret = x509_get_ns_cert_type( p, end_ext_octet,
&crt->ns_cert_type ) ) != 0 )
return( ret );
break;
default:
return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE );
}
}
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
/*
* Parse and fill a single X.509 certificate in DER format
*/
static int x509_crt_parse_der_core( mbedtls_x509_crt *crt, const unsigned char *buf,
size_t buflen )
{
int ret;
size_t len;
unsigned char *p, *end, *crt_end;
mbedtls_x509_buf sig_params1, sig_params2, sig_oid2;
memset( &sig_params1, 0, sizeof( mbedtls_x509_buf ) );
memset( &sig_params2, 0, sizeof( mbedtls_x509_buf ) );
memset( &sig_oid2, 0, sizeof( mbedtls_x509_buf ) );
/*
* Check for valid input
*/
if( crt == NULL || buf == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
// Use the original buffer until we figure out actual length
p = (unsigned char*) buf;
len = buflen;
end = p + len;
/*
* Certificate ::= SEQUENCE {
* tbsCertificate TBSCertificate,
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING }
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT );
}
if( len > (size_t) ( end - p ) )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
}
crt_end = p + len;
// Create and populate a new buffer for the raw field
crt->raw.len = crt_end - buf;
crt->raw.p = p = mbedtls_calloc( 1, crt->raw.len );
if( p == NULL )
return( MBEDTLS_ERR_X509_ALLOC_FAILED );
memcpy( p, buf, crt->raw.len );
// Direct pointers to the new buffer
p += crt->raw.len - len;
end = crt_end = p + len;
/*
* TBSCertificate ::= SEQUENCE {
*/
crt->tbs.p = p;
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
}
end = p + len;
crt->tbs.len = end - crt->tbs.p;
/*
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
*
* CertificateSerialNumber ::= INTEGER
*
* signature AlgorithmIdentifier
*/
if( ( ret = x509_get_version( &p, end, &crt->version ) ) != 0 ||
( ret = mbedtls_x509_get_serial( &p, end, &crt->serial ) ) != 0 ||
( ret = mbedtls_x509_get_alg( &p, end, &crt->sig_oid,
&sig_params1 ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
crt->version++;
if( crt->version > 3 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_UNKNOWN_VERSION );
}
if( ( ret = mbedtls_x509_get_sig_alg( &crt->sig_oid, &sig_params1,
&crt->sig_md, &crt->sig_pk,
&crt->sig_opts ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
/*
* issuer Name
*/
crt->issuer_raw.p = p;
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
}
if( ( ret = mbedtls_x509_get_name( &p, p + len, &crt->issuer ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
crt->issuer_raw.len = p - crt->issuer_raw.p;
/*
* Validity ::= SEQUENCE {
* notBefore Time,
* notAfter Time }
*
*/
if( ( ret = x509_get_dates( &p, end, &crt->valid_from,
&crt->valid_to ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
/*
* subject Name
*/
crt->subject_raw.p = p;
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
}
if( len && ( ret = mbedtls_x509_get_name( &p, p + len, &crt->subject ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
crt->subject_raw.len = p - crt->subject_raw.p;
/*
* SubjectPublicKeyInfo
*/
if( ( ret = mbedtls_pk_parse_subpubkey( &p, end, &crt->pk ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
/*
* issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version shall be v2 or v3
* subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version shall be v2 or v3
* extensions [3] EXPLICIT Extensions OPTIONAL
* -- If present, version shall be v3
*/
if( crt->version == 2 || crt->version == 3 )
{
ret = x509_get_uid( &p, end, &crt->issuer_id, 1 );
if( ret != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
}
if( crt->version == 2 || crt->version == 3 )
{
ret = x509_get_uid( &p, end, &crt->subject_id, 2 );
if( ret != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
}
#if !defined(MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3)
if( crt->version == 3 )
#endif
{
ret = x509_get_crt_ext( &p, end, crt );
if( ret != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
}
if( p != end )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
}
end = crt_end;
/*
* }
* -- end of TBSCertificate
*
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING
*/
if( ( ret = mbedtls_x509_get_alg( &p, end, &sig_oid2, &sig_params2 ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
if( crt->sig_oid.len != sig_oid2.len ||
memcmp( crt->sig_oid.p, sig_oid2.p, crt->sig_oid.len ) != 0 ||
sig_params1.len != sig_params2.len ||
( sig_params1.len != 0 &&
memcmp( sig_params1.p, sig_params2.p, sig_params1.len ) != 0 ) )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_SIG_MISMATCH );
}
if( ( ret = mbedtls_x509_get_sig( &p, end, &crt->sig ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
if( p != end )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
}
return( 0 );
}
/*
* Parse one X.509 certificate in DER format from a buffer and add them to a
* chained list
*/
int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf,
size_t buflen )
{
int ret;
mbedtls_x509_crt *crt = chain, *prev = NULL;
/*
* Check for valid input
*/
if( crt == NULL || buf == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
while( crt->version != 0 && crt->next != NULL )
{
prev = crt;
crt = crt->next;
}
/*
* Add new certificate on the end of the chain if needed.
*/
if( crt->version != 0 && crt->next == NULL )
{
crt->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );
if( crt->next == NULL )
return( MBEDTLS_ERR_X509_ALLOC_FAILED );
prev = crt;
mbedtls_x509_crt_init( crt->next );
crt = crt->next;
}
if( ( ret = x509_crt_parse_der_core( crt, buf, buflen ) ) != 0 )
{
if( prev )
prev->next = NULL;
if( crt != chain )
mbedtls_free( crt );
return( ret );
}
return( 0 );
}
/*
* Parse one or more PEM certificates from a buffer and add them to the chained
* list
*/
int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen )
{
#if defined(MBEDTLS_PEM_PARSE_C)
int success = 0, first_error = 0, total_failed = 0;
int buf_format = MBEDTLS_X509_FORMAT_DER;
#endif
/*
* Check for valid input
*/
if( chain == NULL || buf == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
/*
* Determine buffer content. Buffer contains either one DER certificate or
* one or more PEM certificates.
*/
#if defined(MBEDTLS_PEM_PARSE_C)
if( buflen != 0 && buf[buflen - 1] == '\0' &&
strstr( (const char *) buf, "-----BEGIN CERTIFICATE-----" ) != NULL )
{
buf_format = MBEDTLS_X509_FORMAT_PEM;
}
if( buf_format == MBEDTLS_X509_FORMAT_DER )
return mbedtls_x509_crt_parse_der( chain, buf, buflen );
#else
return mbedtls_x509_crt_parse_der( chain, buf, buflen );
#endif
#if defined(MBEDTLS_PEM_PARSE_C)
if( buf_format == MBEDTLS_X509_FORMAT_PEM )
{
int ret;
mbedtls_pem_context pem;
/* 1 rather than 0 since the terminating NULL byte is counted in */
while( buflen > 1 )
{
size_t use_len;
mbedtls_pem_init( &pem );
/* If we get there, we know the string is null-terminated */
ret = mbedtls_pem_read_buffer( &pem,
"-----BEGIN CERTIFICATE-----",
"-----END CERTIFICATE-----",
buf, NULL, 0, &use_len );
if( ret == 0 )
{
/*
* Was PEM encoded
*/
buflen -= use_len;
buf += use_len;
}
else if( ret == MBEDTLS_ERR_PEM_BAD_INPUT_DATA )
{
return( ret );
}
else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
{
mbedtls_pem_free( &pem );
/*
* PEM header and footer were found
*/
buflen -= use_len;
buf += use_len;
if( first_error == 0 )
first_error = ret;
total_failed++;
continue;
}
else
break;
ret = mbedtls_x509_crt_parse_der( chain, pem.buf, pem.buflen );
mbedtls_pem_free( &pem );
if( ret != 0 )
{
/*
* Quit parsing on a memory error
*/
if( ret == MBEDTLS_ERR_X509_ALLOC_FAILED )
return( ret );
if( first_error == 0 )
first_error = ret;
total_failed++;
continue;
}
success = 1;
}
}
if( success )
return( total_failed );
else if( first_error )
return( first_error );
else
return( MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT );
#endif /* MBEDTLS_PEM_PARSE_C */
}
#if defined(MBEDTLS_FS_IO)
/*
* Load one or more certificates and add them to the chained list
*/
int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path )
{
int ret;
size_t n;
unsigned char *buf;
if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )
return( ret );
ret = mbedtls_x509_crt_parse( chain, buf, n );
mbedtls_zeroize( buf, n );
mbedtls_free( buf );
return( ret );
}
int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path )
{
int ret = 0;
#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
int w_ret;
WCHAR szDir[MAX_PATH];
char filename[MAX_PATH];
char *p;
size_t len = strlen( path );
WIN32_FIND_DATAW file_data;
HANDLE hFind;
if( len > MAX_PATH - 3 )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
memset( szDir, 0, sizeof(szDir) );
memset( filename, 0, MAX_PATH );
memcpy( filename, path, len );
filename[len++] = '\\';
p = filename + len;
filename[len++] = '*';
w_ret = MultiByteToWideChar( CP_ACP, 0, filename, (int)len, szDir,
MAX_PATH - 3 );
if( w_ret == 0 )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
hFind = FindFirstFileW( szDir, &file_data );
if( hFind == INVALID_HANDLE_VALUE )
return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
len = MAX_PATH - len;
do
{
memset( p, 0, len );
if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
continue;
w_ret = WideCharToMultiByte( CP_ACP, 0, file_data.cFileName,
lstrlenW( file_data.cFileName ),
p, (int) len - 1,
NULL, NULL );
if( w_ret == 0 )
return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
w_ret = mbedtls_x509_crt_parse_file( chain, filename );
if( w_ret < 0 )
ret++;
else
ret += w_ret;
}
while( FindNextFileW( hFind, &file_data ) != 0 );
if( GetLastError() != ERROR_NO_MORE_FILES )
ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
FindClose( hFind );
#else /* _WIN32 */
int t_ret;
int snp_ret;
struct stat sb;
struct dirent *entry;
char entry_name[MBEDTLS_X509_MAX_FILE_PATH_LEN];
DIR *dir = opendir( path );
if( dir == NULL )
return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
#if defined(MBEDTLS_THREADING_PTHREAD)
if( ( ret = mbedtls_mutex_lock( &mbedtls_threading_readdir_mutex ) ) != 0 )
{
closedir( dir );
return( ret );
}
#endif
while( ( entry = readdir( dir ) ) != NULL )
{
snp_ret = mbedtls_snprintf( entry_name, sizeof entry_name,
"%s/%s", path, entry->d_name );
if( snp_ret < 0 || (size_t)snp_ret >= sizeof entry_name )
{
ret = MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
goto cleanup;
}
else if( stat( entry_name, &sb ) == -1 )
{
ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
goto cleanup;
}
if( !S_ISREG( sb.st_mode ) )
continue;
// Ignore parse errors
//
t_ret = mbedtls_x509_crt_parse_file( chain, entry_name );
if( t_ret < 0 )
ret++;
else
ret += t_ret;
}
cleanup:
closedir( dir );
#if defined(MBEDTLS_THREADING_PTHREAD)
if( mbedtls_mutex_unlock( &mbedtls_threading_readdir_mutex ) != 0 )
ret = MBEDTLS_ERR_THREADING_MUTEX_ERROR;
#endif
#endif /* _WIN32 */
return( ret );
}
#endif /* MBEDTLS_FS_IO */
static int x509_info_subject_alt_name( char **buf, size_t *size,
const mbedtls_x509_sequence *subject_alt_name )
{
size_t i;
size_t n = *size;
char *p = *buf;
const mbedtls_x509_sequence *cur = subject_alt_name;
const char *sep = "";
size_t sep_len = 0;
while( cur != NULL )
{
if( cur->buf.len + sep_len >= n )
{
*p = '\0';
return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL );
}
n -= cur->buf.len + sep_len;
for( i = 0; i < sep_len; i++ )
*p++ = sep[i];
for( i = 0; i < cur->buf.len; i++ )
*p++ = cur->buf.p[i];
sep = ", ";
sep_len = 2;
cur = cur->next;
}
*p = '\0';
*size = n;
*buf = p;
return( 0 );
}
#define PRINT_ITEM(i) \
{ \
ret = mbedtls_snprintf( p, n, "%s" i, sep ); \
MBEDTLS_X509_SAFE_SNPRINTF; \
sep = ", "; \
}
#define CERT_TYPE(type,name) \
if( ns_cert_type & type ) \
PRINT_ITEM( name );
static int x509_info_cert_type( char **buf, size_t *size,
unsigned char ns_cert_type )
{
int ret;
size_t n = *size;
char *p = *buf;
const char *sep = "";
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT, "SSL Client" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER, "SSL Server" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL, "Email" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING, "Object Signing" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_RESERVED, "Reserved" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CA, "SSL CA" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA, "Email CA" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA, "Object Signing CA" );
*size = n;
*buf = p;
return( 0 );
}
#define KEY_USAGE(code,name) \
if( key_usage & code ) \
PRINT_ITEM( name );
static int x509_info_key_usage( char **buf, size_t *size,
unsigned int key_usage )
{
int ret;
size_t n = *size;
char *p = *buf;
const char *sep = "";
KEY_USAGE( MBEDTLS_X509_KU_DIGITAL_SIGNATURE, "Digital Signature" );
KEY_USAGE( MBEDTLS_X509_KU_NON_REPUDIATION, "Non Repudiation" );
KEY_USAGE( MBEDTLS_X509_KU_KEY_ENCIPHERMENT, "Key Encipherment" );
KEY_USAGE( MBEDTLS_X509_KU_DATA_ENCIPHERMENT, "Data Encipherment" );
KEY_USAGE( MBEDTLS_X509_KU_KEY_AGREEMENT, "Key Agreement" );
KEY_USAGE( MBEDTLS_X509_KU_KEY_CERT_SIGN, "Key Cert Sign" );
KEY_USAGE( MBEDTLS_X509_KU_CRL_SIGN, "CRL Sign" );
KEY_USAGE( MBEDTLS_X509_KU_ENCIPHER_ONLY, "Encipher Only" );
KEY_USAGE( MBEDTLS_X509_KU_DECIPHER_ONLY, "Decipher Only" );
*size = n;
*buf = p;
return( 0 );
}
static int x509_info_ext_key_usage( char **buf, size_t *size,
const mbedtls_x509_sequence *extended_key_usage )
{
int ret;
const char *desc;
size_t n = *size;
char *p = *buf;
const mbedtls_x509_sequence *cur = extended_key_usage;
const char *sep = "";
while( cur != NULL )
{
if( mbedtls_oid_get_extended_key_usage( &cur->buf, &desc ) != 0 )
desc = "???";
ret = mbedtls_snprintf( p, n, "%s%s", sep, desc );
MBEDTLS_X509_SAFE_SNPRINTF;
sep = ", ";
cur = cur->next;
}
*size = n;
*buf = p;
return( 0 );
}
/*
* Return an informational string about the certificate.
*/
#define BEFORE_COLON 18
#define BC "18"
int mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix,
const mbedtls_x509_crt *crt )
{
int ret;
size_t n;
char *p;
char key_size_str[BEFORE_COLON];
p = buf;
n = size;
if( NULL == crt )
{
ret = mbedtls_snprintf( p, n, "\nCertificate is uninitialised!\n" );
MBEDTLS_X509_SAFE_SNPRINTF;
return( (int) ( size - n ) );
}
ret = mbedtls_snprintf( p, n, "%scert. version : %d\n",
prefix, crt->version );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "%sserial number : ",
prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_serial_gets( p, n, &crt->serial );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%sissuer name : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_dn_gets( p, n, &crt->issuer );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%ssubject name : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_dn_gets( p, n, &crt->subject );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%sissued on : " \
"%04d-%02d-%02d %02d:%02d:%02d", prefix,
crt->valid_from.year, crt->valid_from.mon,
crt->valid_from.day, crt->valid_from.hour,
crt->valid_from.min, crt->valid_from.sec );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%sexpires on : " \
"%04d-%02d-%02d %02d:%02d:%02d", prefix,
crt->valid_to.year, crt->valid_to.mon,
crt->valid_to.day, crt->valid_to.hour,
crt->valid_to.min, crt->valid_to.sec );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%ssigned using : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_sig_alg_gets( p, n, &crt->sig_oid, crt->sig_pk,
crt->sig_md, crt->sig_opts );
MBEDTLS_X509_SAFE_SNPRINTF;
/* Key size */
if( ( ret = mbedtls_x509_key_size_helper( key_size_str, BEFORE_COLON,
mbedtls_pk_get_name( &crt->pk ) ) ) != 0 )
{
return( ret );
}
ret = mbedtls_snprintf( p, n, "\n%s%-" BC "s: %d bits", prefix, key_size_str,
(int) mbedtls_pk_get_bitlen( &crt->pk ) );
MBEDTLS_X509_SAFE_SNPRINTF;
/*
* Optional extensions
*/
if( crt->ext_types & MBEDTLS_X509_EXT_BASIC_CONSTRAINTS )
{
ret = mbedtls_snprintf( p, n, "\n%sbasic constraints : CA=%s", prefix,
crt->ca_istrue ? "true" : "false" );
MBEDTLS_X509_SAFE_SNPRINTF;
if( crt->max_pathlen > 0 )
{
ret = mbedtls_snprintf( p, n, ", max_pathlen=%d", crt->max_pathlen - 1 );
MBEDTLS_X509_SAFE_SNPRINTF;
}
}
if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
{
ret = mbedtls_snprintf( p, n, "\n%ssubject alt name : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
if( ( ret = x509_info_subject_alt_name( &p, &n,
&crt->subject_alt_names ) ) != 0 )
return( ret );
}
if( crt->ext_types & MBEDTLS_X509_EXT_NS_CERT_TYPE )
{
ret = mbedtls_snprintf( p, n, "\n%scert. type : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
if( ( ret = x509_info_cert_type( &p, &n, crt->ns_cert_type ) ) != 0 )
return( ret );
}
if( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE )
{
ret = mbedtls_snprintf( p, n, "\n%skey usage : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
if( ( ret = x509_info_key_usage( &p, &n, crt->key_usage ) ) != 0 )
return( ret );
}
if( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE )
{
ret = mbedtls_snprintf( p, n, "\n%sext key usage : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
if( ( ret = x509_info_ext_key_usage( &p, &n,
&crt->ext_key_usage ) ) != 0 )
return( ret );
}
ret = mbedtls_snprintf( p, n, "\n" );
MBEDTLS_X509_SAFE_SNPRINTF;
return( (int) ( size - n ) );
}
struct x509_crt_verify_string {
int code;
const char *string;
};
static const struct x509_crt_verify_string x509_crt_verify_strings[] = {
{ MBEDTLS_X509_BADCERT_EXPIRED, "The certificate validity has expired" },
{ MBEDTLS_X509_BADCERT_REVOKED, "The certificate has been revoked (is on a CRL)" },
{ MBEDTLS_X509_BADCERT_CN_MISMATCH, "The certificate Common Name (CN) does not match with the expected CN" },
{ MBEDTLS_X509_BADCERT_NOT_TRUSTED, "The certificate is not correctly signed by the trusted CA" },
{ MBEDTLS_X509_BADCRL_NOT_TRUSTED, "The CRL is not correctly signed by the trusted CA" },
{ MBEDTLS_X509_BADCRL_EXPIRED, "The CRL is expired" },
{ MBEDTLS_X509_BADCERT_MISSING, "Certificate was missing" },
{ MBEDTLS_X509_BADCERT_SKIP_VERIFY, "Certificate verification was skipped" },
{ MBEDTLS_X509_BADCERT_OTHER, "Other reason (can be used by verify callback)" },
{ MBEDTLS_X509_BADCERT_FUTURE, "The certificate validity starts in the future" },
{ MBEDTLS_X509_BADCRL_FUTURE, "The CRL is from the future" },
{ MBEDTLS_X509_BADCERT_KEY_USAGE, "Usage does not match the keyUsage extension" },
{ MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, "Usage does not match the extendedKeyUsage extension" },
{ MBEDTLS_X509_BADCERT_NS_CERT_TYPE, "Usage does not match the nsCertType extension" },
{ MBEDTLS_X509_BADCERT_BAD_MD, "The certificate is signed with an unacceptable hash." },
{ MBEDTLS_X509_BADCERT_BAD_PK, "The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA)." },
{ MBEDTLS_X509_BADCERT_BAD_KEY, "The certificate is signed with an unacceptable key (eg bad curve, RSA too short)." },
{ MBEDTLS_X509_BADCRL_BAD_MD, "The CRL is signed with an unacceptable hash." },
{ MBEDTLS_X509_BADCRL_BAD_PK, "The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA)." },
{ MBEDTLS_X509_BADCRL_BAD_KEY, "The CRL is signed with an unacceptable key (eg bad curve, RSA too short)." },
{ 0, NULL }
};
int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
uint32_t flags )
{
int ret;
const struct x509_crt_verify_string *cur;
char *p = buf;
size_t n = size;
for( cur = x509_crt_verify_strings; cur->string != NULL ; cur++ )
{
if( ( flags & cur->code ) == 0 )
continue;
ret = mbedtls_snprintf( p, n, "%s%s\n", prefix, cur->string );
MBEDTLS_X509_SAFE_SNPRINTF;
flags ^= cur->code;
}
if( flags != 0 )
{
ret = mbedtls_snprintf( p, n, "%sUnknown reason "
"(this should not happen)\n", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
}
return( (int) ( size - n ) );
}
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
unsigned int usage )
{
unsigned int usage_must, usage_may;
unsigned int may_mask = MBEDTLS_X509_KU_ENCIPHER_ONLY
| MBEDTLS_X509_KU_DECIPHER_ONLY;
if( ( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE ) == 0 )
return( 0 );
usage_must = usage & ~may_mask;
if( ( ( crt->key_usage & ~may_mask ) & usage_must ) != usage_must )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
usage_may = usage & may_mask;
if( ( ( crt->key_usage & may_mask ) | usage_may ) != usage_may )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
return( 0 );
}
#endif
#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,
const char *usage_oid,
size_t usage_len )
{
const mbedtls_x509_sequence *cur;
/* Extension is not mandatory, absent means no restriction */
if( ( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE ) == 0 )
return( 0 );
/*
* Look for the requested usage (or wildcard ANY) in our list
*/
for( cur = &crt->ext_key_usage; cur != NULL; cur = cur->next )
{
const mbedtls_x509_buf *cur_oid = &cur->buf;
if( cur_oid->len == usage_len &&
memcmp( cur_oid->p, usage_oid, usage_len ) == 0 )
{
return( 0 );
}
if( MBEDTLS_OID_CMP( MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE, cur_oid ) == 0 )
return( 0 );
}
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
}
#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
#if defined(MBEDTLS_X509_CRL_PARSE_C)
/*
* Return 1 if the certificate is revoked, or 0 otherwise.
*/
int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl )
{
const mbedtls_x509_crl_entry *cur = &crl->entry;
while( cur != NULL && cur->serial.len != 0 )
{
if( crt->serial.len == cur->serial.len &&
memcmp( crt->serial.p, cur->serial.p, crt->serial.len ) == 0 )
{
if( mbedtls_x509_time_is_past( &cur->revocation_date ) )
return( 1 );
}
cur = cur->next;
}
return( 0 );
}
/*
* Check that the given certificate is not revoked according to the CRL.
* Skip validation is no CRL for the given CA is present.
*/
static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca,
mbedtls_x509_crl *crl_list,
const mbedtls_x509_crt_profile *profile )
{
int flags = 0;
unsigned char hash[MBEDTLS_MD_MAX_SIZE];
const mbedtls_md_info_t *md_info;
if( ca == NULL )
return( flags );
while( crl_list != NULL )
{
if( crl_list->version == 0 ||
crl_list->issuer_raw.len != ca->subject_raw.len ||
memcmp( crl_list->issuer_raw.p, ca->subject_raw.p,
crl_list->issuer_raw.len ) != 0 )
{
crl_list = crl_list->next;
continue;
}
/*
* Check if the CA is configured to sign CRLs
*/
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
if( mbedtls_x509_crt_check_key_usage( ca, MBEDTLS_X509_KU_CRL_SIGN ) != 0 )
{
flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
break;
}
#endif
/*
* Check if CRL is correctly signed by the trusted CA
*/
if( x509_profile_check_md_alg( profile, crl_list->sig_md ) != 0 )
flags |= MBEDTLS_X509_BADCRL_BAD_MD;
if( x509_profile_check_pk_alg( profile, crl_list->sig_pk ) != 0 )
flags |= MBEDTLS_X509_BADCRL_BAD_PK;
md_info = mbedtls_md_info_from_type( crl_list->sig_md );
if( md_info == NULL )
{
/*
* Cannot check 'unknown' hash
*/
flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
break;
}
mbedtls_md( md_info, crl_list->tbs.p, crl_list->tbs.len, hash );
if( x509_profile_check_key( profile, crl_list->sig_pk, &ca->pk ) != 0 )
flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
if( mbedtls_pk_verify_ext( crl_list->sig_pk, crl_list->sig_opts, &ca->pk,
crl_list->sig_md, hash, mbedtls_md_get_size( md_info ),
crl_list->sig.p, crl_list->sig.len ) != 0 )
{
flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
break;
}
/*
* Check for validity of CRL (Do not drop out)
*/
if( mbedtls_x509_time_is_past( &crl_list->next_update ) )
flags |= MBEDTLS_X509_BADCRL_EXPIRED;
if( mbedtls_x509_time_is_future( &crl_list->this_update ) )
flags |= MBEDTLS_X509_BADCRL_FUTURE;
/*
* Check if certificate is revoked
*/
if( mbedtls_x509_crt_is_revoked( crt, crl_list ) )
{
flags |= MBEDTLS_X509_BADCERT_REVOKED;
break;
}
crl_list = crl_list->next;
}
return( flags );
}
#endif /* MBEDTLS_X509_CRL_PARSE_C */
/*
* Like memcmp, but case-insensitive and always returns -1 if different
*/
static int x509_memcasecmp( const void *s1, const void *s2, size_t len )
{
size_t i;
unsigned char diff;
const unsigned char *n1 = s1, *n2 = s2;
for( i = 0; i < len; i++ )
{
diff = n1[i] ^ n2[i];
if( diff == 0 )
continue;
if( diff == 32 &&
( ( n1[i] >= 'a' && n1[i] <= 'z' ) ||
( n1[i] >= 'A' && n1[i] <= 'Z' ) ) )
{
continue;
}
return( -1 );
}
return( 0 );
}
/*
* Return 0 if name matches wildcard, -1 otherwise
*/
static int x509_check_wildcard( const char *cn, mbedtls_x509_buf *name )
{
size_t i;
size_t cn_idx = 0, cn_len = strlen( cn );
if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' )
return( 0 );
for( i = 0; i < cn_len; ++i )
{
if( cn[i] == '.' )
{
cn_idx = i;
break;
}
}
if( cn_idx == 0 )
return( -1 );
if( cn_len - cn_idx == name->len - 1 &&
x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )
{
return( 0 );
}
return( -1 );
}
/*
* Compare two X.509 strings, case-insensitive, and allowing for some encoding
* variations (but not all).
*
* Return 0 if equal, -1 otherwise.
*/
static int x509_string_cmp( const mbedtls_x509_buf *a, const mbedtls_x509_buf *b )
{
if( a->tag == b->tag &&
a->len == b->len &&
memcmp( a->p, b->p, b->len ) == 0 )
{
return( 0 );
}
if( ( a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
( b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
a->len == b->len &&
x509_memcasecmp( a->p, b->p, b->len ) == 0 )
{
return( 0 );
}
return( -1 );
}
/*
* Compare two X.509 Names (aka rdnSequence).
*
* See RFC 5280 section 7.1, though we don't implement the whole algorithm:
* we sometimes return unequal when the full algorithm would return equal,
* but never the other way. (In particular, we don't do Unicode normalisation
* or space folding.)
*
* Return 0 if equal, -1 otherwise.
*/
static int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b )
{
/* Avoid recursion, it might not be optimised by the compiler */
while( a != NULL || b != NULL )
{
if( a == NULL || b == NULL )
return( -1 );
/* type */
if( a->oid.tag != b->oid.tag ||
a->oid.len != b->oid.len ||
memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 )
{
return( -1 );
}
/* value */
if( x509_string_cmp( &a->val, &b->val ) != 0 )
return( -1 );
/* structure of the list of sets */
if( a->next_merged != b->next_merged )
return( -1 );
a = a->next;
b = b->next;
}
/* a == NULL == b */
return( 0 );
}
/*
* Check if 'parent' is a suitable parent (signing CA) for 'child'.
* Return 0 if yes, -1 if not.
*
* top means parent is a locally-trusted certificate
* bottom means child is the end entity cert
*/
static int x509_crt_check_parent( const mbedtls_x509_crt *child,
const mbedtls_x509_crt *parent,
int top, int bottom )
{
int need_ca_bit;
/* Parent must be the issuer */
if( x509_name_cmp( &child->issuer, &parent->subject ) != 0 )
return( -1 );
/* Parent must have the basicConstraints CA bit set as a general rule */
need_ca_bit = 1;
/* Exception: v1/v2 certificates that are locally trusted. */
if( top && parent->version < 3 )
need_ca_bit = 0;
/* Exception: self-signed end-entity certs that are locally trusted. */
if( top && bottom &&
child->raw.len == parent->raw.len &&
memcmp( child->raw.p, parent->raw.p, child->raw.len ) == 0 )
{
need_ca_bit = 0;
}
if( need_ca_bit && ! parent->ca_istrue )
return( -1 );
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
if( need_ca_bit &&
mbedtls_x509_crt_check_key_usage( parent, MBEDTLS_X509_KU_KEY_CERT_SIGN ) != 0 )
{
return( -1 );
}
#endif
return( 0 );
}
static int x509_crt_verify_top(
mbedtls_x509_crt *child, mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
int path_cnt, int self_cnt, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
int ret;
uint32_t ca_flags = 0;
int check_path_cnt;
unsigned char hash[MBEDTLS_MD_MAX_SIZE];
const mbedtls_md_info_t *md_info;
mbedtls_x509_crt *future_past_ca = NULL;
if( mbedtls_x509_time_is_past( &child->valid_to ) )
*flags |= MBEDTLS_X509_BADCERT_EXPIRED;
if( mbedtls_x509_time_is_future( &child->valid_from ) )
*flags |= MBEDTLS_X509_BADCERT_FUTURE;
if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_MD;
if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
/*
* Child is the top of the chain. Check against the trust_ca list.
*/
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
md_info = mbedtls_md_info_from_type( child->sig_md );
if( md_info == NULL )
{
/*
* Cannot check 'unknown', no need to try any CA
*/
trust_ca = NULL;
}
else
mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash );
for( /* trust_ca */ ; trust_ca != NULL; trust_ca = trust_ca->next )
{
if( x509_crt_check_parent( child, trust_ca, 1, path_cnt == 0 ) != 0 )
continue;
check_path_cnt = path_cnt + 1;
/*
* Reduce check_path_cnt to check against if top of the chain is
* the same as the trusted CA
*/
if( child->subject_raw.len == trust_ca->subject_raw.len &&
memcmp( child->subject_raw.p, trust_ca->subject_raw.p,
child->issuer_raw.len ) == 0 )
{
check_path_cnt--;
}
/* Self signed certificates do not count towards the limit */
if( trust_ca->max_pathlen > 0 &&
trust_ca->max_pathlen < check_path_cnt - self_cnt )
{
continue;
}
if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &trust_ca->pk,
child->sig_md, hash, mbedtls_md_get_size( md_info ),
child->sig.p, child->sig.len ) != 0 )
{
continue;
}
if( mbedtls_x509_time_is_past( &trust_ca->valid_to ) ||
mbedtls_x509_time_is_future( &trust_ca->valid_from ) )
{
if ( future_past_ca == NULL )
future_past_ca = trust_ca;
continue;
}
break;
}
if( trust_ca != NULL || ( trust_ca = future_past_ca ) != NULL )
{
/*
* Top of chain is signed by a trusted CA
*/
*flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
if( x509_profile_check_key( profile, child->sig_pk, &trust_ca->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
}
/*
* If top of chain is not the same as the trusted CA send a verify request
* to the callback for any issues with validity and CRL presence for the
* trusted CA certificate.
*/
if( trust_ca != NULL &&
( child->subject_raw.len != trust_ca->subject_raw.len ||
memcmp( child->subject_raw.p, trust_ca->subject_raw.p,
child->issuer_raw.len ) != 0 ) )
{
#if defined(MBEDTLS_X509_CRL_PARSE_C)
/* Check trusted CA's CRL for the chain's top crt */
*flags |= x509_crt_verifycrl( child, trust_ca, ca_crl, profile );
#else
((void) ca_crl);
#endif
if( mbedtls_x509_time_is_past( &trust_ca->valid_to ) )
ca_flags |= MBEDTLS_X509_BADCERT_EXPIRED;
if( mbedtls_x509_time_is_future( &trust_ca->valid_from ) )
ca_flags |= MBEDTLS_X509_BADCERT_FUTURE;
if( NULL != f_vrfy )
{
if( ( ret = f_vrfy( p_vrfy, trust_ca, path_cnt + 1,
&ca_flags ) ) != 0 )
{
return( ret );
}
}
}
/* Call callback on top cert */
if( NULL != f_vrfy )
{
if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 )
return( ret );
}
*flags |= ca_flags;
return( 0 );
}
static int x509_crt_verify_child(
mbedtls_x509_crt *child, mbedtls_x509_crt *parent,
mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
int path_cnt, int self_cnt, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
int ret;
uint32_t parent_flags = 0;
unsigned char hash[MBEDTLS_MD_MAX_SIZE];
mbedtls_x509_crt *grandparent;
const mbedtls_md_info_t *md_info;
/* Counting intermediate self signed certificates */
if( ( path_cnt != 0 ) && x509_name_cmp( &child->issuer, &child->subject ) == 0 )
self_cnt++;
/* path_cnt is 0 for the first intermediate CA */
if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA )
{
/* return immediately as the goal is to avoid unbounded recursion */
return( MBEDTLS_ERR_X509_FATAL_ERROR );
}
if( mbedtls_x509_time_is_past( &child->valid_to ) )
*flags |= MBEDTLS_X509_BADCERT_EXPIRED;
if( mbedtls_x509_time_is_future( &child->valid_from ) )
*flags |= MBEDTLS_X509_BADCERT_FUTURE;
if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_MD;
if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
md_info = mbedtls_md_info_from_type( child->sig_md );
if( md_info == NULL )
{
/*
* Cannot check 'unknown' hash
*/
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
}
else
{
mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash );
if( x509_profile_check_key( profile, child->sig_pk, &parent->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk,
child->sig_md, hash, mbedtls_md_get_size( md_info ),
child->sig.p, child->sig.len ) != 0 )
{
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
}
}
#if defined(MBEDTLS_X509_CRL_PARSE_C)
/* Check trusted CA's CRL for the given crt */
*flags |= x509_crt_verifycrl(child, parent, ca_crl, profile );
#endif
/* Look for a grandparent in trusted CAs */
for( grandparent = trust_ca;
grandparent != NULL;
grandparent = grandparent->next )
{
if( x509_crt_check_parent( parent, grandparent,
0, path_cnt == 0 ) == 0 )
break;
}
if( grandparent != NULL )
{
ret = x509_crt_verify_top( parent, grandparent, ca_crl, profile,
path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
else
{
/* Look for a grandparent upwards the chain */
for( grandparent = parent->next;
grandparent != NULL;
grandparent = grandparent->next )
{
/* +2 because the current step is not yet accounted for
* and because max_pathlen is one higher than it should be.
* Also self signed certificates do not count to the limit. */
if( grandparent->max_pathlen > 0 &&
grandparent->max_pathlen < 2 + path_cnt - self_cnt )
{
continue;
}
if( x509_crt_check_parent( parent, grandparent,
0, path_cnt == 0 ) == 0 )
break;
}
/* Is our parent part of the chain or at the top? */
if( grandparent != NULL )
{
ret = x509_crt_verify_child( parent, grandparent, trust_ca, ca_crl,
profile, path_cnt + 1, self_cnt, &parent_flags,
f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
else
{
ret = x509_crt_verify_top( parent, trust_ca, ca_crl, profile,
path_cnt + 1, self_cnt, &parent_flags,
f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
}
/* child is verified to be a child of the parent, call verify callback */
if( NULL != f_vrfy )
if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 )
return( ret );
*flags |= parent_flags;
return( 0 );
}
/*
* Verify the certificate validity
*/
int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
return( mbedtls_x509_crt_verify_with_profile( crt, trust_ca, ca_crl,
&mbedtls_x509_crt_profile_default, cn, flags, f_vrfy, p_vrfy ) );
}
/*
* Verify the certificate validity, with profile
*/
int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
size_t cn_len;
int ret;
int pathlen = 0, selfsigned = 0;
mbedtls_x509_crt *parent;
mbedtls_x509_name *name;
mbedtls_x509_sequence *cur = NULL;
mbedtls_pk_type_t pk_type;
*flags = 0;
if( profile == NULL )
{
ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA;
goto exit;
}
if( cn != NULL )
{
name = &crt->subject;
cn_len = strlen( cn );
if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
{
cur = &crt->subject_alt_names;
while( cur != NULL )
{
if( cur->buf.len == cn_len &&
x509_memcasecmp( cn, cur->buf.p, cn_len ) == 0 )
break;
if( cur->buf.len > 2 &&
memcmp( cur->buf.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &cur->buf ) == 0 )
{
break;
}
cur = cur->next;
}
if( cur == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
else
{
while( name != NULL )
{
if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 )
{
if( name->val.len == cn_len &&
x509_memcasecmp( name->val.p, cn, cn_len ) == 0 )
break;
if( name->val.len > 2 &&
memcmp( name->val.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &name->val ) == 0 )
break;
}
name = name->next;
}
if( name == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
}
/* Check the type and size of the key */
pk_type = mbedtls_pk_get_type( &crt->pk );
if( x509_profile_check_pk_alg( profile, pk_type ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
if( x509_profile_check_key( profile, pk_type, &crt->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
/* Look for a parent in trusted CAs */
for( parent = trust_ca; parent != NULL; parent = parent->next )
{
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
}
if( parent != NULL )
{
ret = x509_crt_verify_top( crt, parent, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
else
{
/* Look for a parent upwards the chain */
for( parent = crt->next; parent != NULL; parent = parent->next )
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
/* Are we part of the chain or at the top? */
if( parent != NULL )
{
ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
else
{
ret = x509_crt_verify_top( crt, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
}
exit:
/* prevent misuse of the vrfy callback */
if( ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED )
ret = MBEDTLS_ERR_X509_FATAL_ERROR;
if( ret != 0 )
{
*flags = (uint32_t) -1;
return( ret );
}
if( *flags != 0 )
return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
return( 0 );
}
/*
* Initialize a certificate chain
*/
void mbedtls_x509_crt_init( mbedtls_x509_crt *crt )
{
memset( crt, 0, sizeof(mbedtls_x509_crt) );
}
/*
* Unallocate all certificate data
*/
void mbedtls_x509_crt_free( mbedtls_x509_crt *crt )
{
mbedtls_x509_crt *cert_cur = crt;
mbedtls_x509_crt *cert_prv;
mbedtls_x509_name *name_cur;
mbedtls_x509_name *name_prv;
mbedtls_x509_sequence *seq_cur;
mbedtls_x509_sequence *seq_prv;
if( crt == NULL )
return;
do
{
mbedtls_pk_free( &cert_cur->pk );
#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
mbedtls_free( cert_cur->sig_opts );
#endif
name_cur = cert_cur->issuer.next;
while( name_cur != NULL )
{
name_prv = name_cur;
name_cur = name_cur->next;
mbedtls_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
mbedtls_free( name_prv );
}
name_cur = cert_cur->subject.next;
while( name_cur != NULL )
{
name_prv = name_cur;
name_cur = name_cur->next;
mbedtls_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
mbedtls_free( name_prv );
}
seq_cur = cert_cur->ext_key_usage.next;
while( seq_cur != NULL )
{
seq_prv = seq_cur;
seq_cur = seq_cur->next;
mbedtls_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) );
mbedtls_free( seq_prv );
}
seq_cur = cert_cur->subject_alt_names.next;
while( seq_cur != NULL )
{
seq_prv = seq_cur;
seq_cur = seq_cur->next;
mbedtls_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) );
mbedtls_free( seq_prv );
}
if( cert_cur->raw.p != NULL )
{
mbedtls_zeroize( cert_cur->raw.p, cert_cur->raw.len );
mbedtls_free( cert_cur->raw.p );
}
cert_cur = cert_cur->next;
}
while( cert_cur != NULL );
cert_cur = crt;
do
{
cert_prv = cert_cur;
cert_cur = cert_cur->next;
mbedtls_zeroize( cert_prv, sizeof( mbedtls_x509_crt ) );
if( cert_prv != crt )
mbedtls_free( cert_prv );
}
while( cert_cur != NULL );
}
#endif /* MBEDTLS_X509_CRT_PARSE_C */
| ./CrossVul/dataset_final_sorted/CWE-287/c/good_2756_6 |
crossvul-cpp_data_good_2556_1 | /*
* jabberd - Jabber Open Source Server
* Copyright (c) 2002 Jeremie Miller, Thomas Muldowney,
* Ryan Eatmon, Robert Norris
*
* 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, MA02111-1307USA
*/
/* SASL authentication handler */
#include "sx.h"
#include "sasl.h"
#include <gsasl.h>
#include <gsasl-mech.h>
#include <string.h>
/** our sasl application context */
typedef struct _sx_sasl_st {
char *appname;
Gsasl *gsasl_ctx;
sx_sasl_callback_t cb;
void *cbarg;
char *ext_id[SX_CONN_EXTERNAL_ID_MAX_COUNT];
} *_sx_sasl_t;
/** our sasl per session context */
typedef struct _sx_sasl_sess_st {
sx_t s;
_sx_sasl_t ctx;
} *_sx_sasl_sess_t;
/** utility: generate a success nad */
static nad_t _sx_sasl_success(sx_t s, const char *data, int dlen) {
nad_t nad;
int ns;
nad = nad_new();
ns = nad_add_namespace(nad, uri_SASL, NULL);
nad_append_elem(nad, ns, "success", 0);
if(data != NULL)
nad_append_cdata(nad, data, dlen, 1);
return nad;
}
/** utility: generate a failure nad */
static nad_t _sx_sasl_failure(sx_t s, const char *err, const char *text) {
nad_t nad;
int ns;
nad = nad_new();
ns = nad_add_namespace(nad, uri_SASL, NULL);
nad_append_elem(nad, ns, "failure", 0);
if(err != NULL)
nad_append_elem(nad, ns, err, 1);
if(text != NULL) {
nad_append_elem(nad, ns, "text", 1);
nad_append_cdata(nad, text, strlen(text), 2);
}
return nad;
}
/** utility: generate a challenge nad */
static nad_t _sx_sasl_challenge(sx_t s, const char *data, int dlen) {
nad_t nad;
int ns;
nad = nad_new();
ns = nad_add_namespace(nad, uri_SASL, NULL);
nad_append_elem(nad, ns, "challenge", 0);
if(data != NULL)
nad_append_cdata(nad, data, dlen, 1);
return nad;
}
/** utility: generate a response nad */
static nad_t _sx_sasl_response(sx_t s, const char *data, int dlen) {
nad_t nad;
int ns;
nad = nad_new();
ns = nad_add_namespace(nad, uri_SASL, NULL);
nad_append_elem(nad, ns, "response", 0);
if(data != NULL)
nad_append_cdata(nad, data, dlen, 1);
return nad;
}
/** utility: generate an abort nad */
static nad_t _sx_sasl_abort(sx_t s) {
nad_t nad;
int ns;
nad = nad_new();
ns = nad_add_namespace(nad, uri_SASL, NULL);
nad_append_elem(nad, ns, "abort", 0);
return nad;
}
static int _sx_sasl_wio(sx_t s, sx_plugin_t p, sx_buf_t buf) {
sx_error_t sxe;
size_t len;
int ret;
char *out;
Gsasl_session *sd = (Gsasl_session *) s->plugin_data[p->index];
_sx_debug(ZONE, "doing sasl encode");
/* encode the output */
ret = gsasl_encode(sd, buf->data, buf->len, &out, &len);
if (ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_encode failed (%d): %s", ret, gsasl_strerror (ret));
/* Fatal error */
_sx_gen_error(sxe, SX_ERR_AUTH, "SASL Stream encoding failed", (char*) gsasl_strerror (ret));
_sx_event(s, event_ERROR, (void *) &sxe);
return -1;
}
/* replace the buffer */
_sx_buffer_set(buf, out, len, NULL);
free(out);
_sx_debug(ZONE, "%d bytes encoded for sasl channel", buf->len);
return 1;
}
static int _sx_sasl_rio(sx_t s, sx_plugin_t p, sx_buf_t buf) {
sx_error_t sxe;
size_t len;
int ret;
char *out;
Gsasl_session *sd = (Gsasl_session *) s->plugin_data[p->index];
_sx_debug(ZONE, "doing sasl decode");
/* decode the input */
ret = gsasl_decode(sd, buf->data, buf->len, &out, &len);
if (ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_decode failed (%d): %s", ret, gsasl_strerror (ret));
/* Fatal error */
_sx_gen_error(sxe, SX_ERR_AUTH, "SASL Stream decoding failed", (char*) gsasl_strerror (ret));
_sx_event(s, event_ERROR, (void *) &sxe);
return -1;
}
/* replace the buffer */
_sx_buffer_set(buf, out, len, NULL);
free(out);
_sx_debug(ZONE, "%d bytes decoded from sasl channel", len);
return 1;
}
/** move the stream to the auth state */
void _sx_sasl_open(sx_t s, Gsasl_session *sd) {
char *method, *authzid;
const char *realm = NULL;
struct sx_sasl_creds_st creds = {NULL, NULL, NULL, NULL};
_sx_sasl_sess_t sctx = gsasl_session_hook_get(sd);
_sx_sasl_t ctx = sctx->ctx;
const char *mechname = gsasl_mechanism_name (sd);
/* get the method */
method = (char *) malloc(sizeof(char) * (strlen(mechname) + 6));
sprintf(method, "SASL/%s", mechname);
/* and the authorization identifier */
creds.authzid = gsasl_property_fast(sd, GSASL_AUTHZID);
creds.authnid = gsasl_property_fast(sd, GSASL_AUTHID);
creds.realm = gsasl_property_fast(sd, GSASL_REALM);
if(0 && ctx && ctx->cb) { /* not supported yet */
if((ctx->cb)(sx_sasl_cb_CHECK_AUTHZID, &creds, NULL, s, ctx->cbarg)!=sx_sasl_ret_OK) {
_sx_debug(ZONE, "stream authzid: %s verification failed, not advancing to auth state", creds.authzid);
free(method);
return;
}
} else if (NULL != gsasl_property_fast(sd, GSASL_GSSAPI_DISPLAY_NAME)) {
creds.authzid = strdup(gsasl_property_fast(sd, GSASL_GSSAPI_DISPLAY_NAME));
authzid = NULL;
} else {
/* override unchecked arbitrary authzid */
if(creds.realm && creds.realm[0] != '\0') {
realm = creds.realm;
} else {
realm = s->req_to;
}
authzid = (char *) malloc(sizeof(char) * (strlen(creds.authnid) + strlen(realm) + 2));
sprintf(authzid, "%s@%s", creds.authnid, realm);
creds.authzid = authzid;
}
/* proceed stream to authenticated state */
sx_auth(s, method, creds.authzid);
free(method);
if(authzid) free(authzid);
}
/** make the stream authenticated second time round */
static void _sx_sasl_stream(sx_t s, sx_plugin_t p) {
Gsasl_session *sd = (Gsasl_session *) s->plugin_data[p->index];
/* do nothing the first time */
if(sd == NULL)
return;
/* are we auth'd? */
if(NULL == gsasl_property_fast(sd, GSASL_AUTHID)) {
_sx_debug(ZONE, "not auth'd, not advancing to auth'd state yet");
return;
}
/* otherwise, its auth time */
_sx_sasl_open(s, sd);
}
static void _sx_sasl_features(sx_t s, sx_plugin_t p, nad_t nad) {
_sx_sasl_t ctx = (_sx_sasl_t) p->private;
Gsasl_session *sd = (Gsasl_session *) s->plugin_data[p->index];
int nmechs, ret;
char *mechs, *mech, *c;
if(s->type != type_SERVER)
return;
if(sd != NULL) {
_sx_debug(ZONE, "already auth'd, not offering sasl mechanisms");
return;
}
if(!(s->flags & SX_SASL_OFFER)) {
_sx_debug(ZONE, "application didn't ask us to offer sasl, so we won't");
return;
}
#ifdef HAVE_SSL
if((s->flags & SX_SSL_STARTTLS_REQUIRE) && s->ssf == 0) {
_sx_debug(ZONE, "ssl not established yet but the app requires it, not offering mechanisms");
return;
}
#endif
_sx_debug(ZONE, "offering sasl mechanisms");
ret = gsasl_server_mechlist(ctx->gsasl_ctx, &mechs);
if(ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_server_mechlist failed (%d): %s, not offering sasl for this conn", ret, gsasl_strerror (ret));
return;
}
mech = mechs;
nmechs = 0;
while(mech != NULL) {
c = strchr(mech, ' ');
if(c != NULL)
*c = '\0';
if ((ctx->cb)(sx_sasl_cb_CHECK_MECH, mech, NULL, s, ctx->cbarg)==sx_sasl_ret_OK) {
if (nmechs == 0) {
int ns = nad_add_namespace(nad, uri_SASL, NULL);
nad_append_elem(nad, ns, "mechanisms", 1);
}
_sx_debug(ZONE, "offering mechanism: %s", mech);
nad_append_elem(nad, -1 /*ns*/, "mechanism", 2);
nad_append_cdata(nad, mech, strlen(mech), 3);
nmechs++;
}
if(c == NULL)
mech = NULL;
else
mech = ++c;
}
free(mechs);
}
/** auth done, restart the stream */
static void _sx_sasl_notify_success(sx_t s, void *arg) {
sx_plugin_t p = (sx_plugin_t) arg;
_sx_chain_io_plugin(s, p);
_sx_debug(ZONE, "auth completed, resetting");
_sx_reset(s);
sx_server_init(s, s->flags);
}
/** process handshake packets from the client */
static void _sx_sasl_client_process(sx_t s, sx_plugin_t p, Gsasl_session *sd, const char *mech, const char *in, int inlen) {
_sx_sasl_t ctx = (_sx_sasl_t) p->private;
_sx_sasl_sess_t sctx = NULL;
char *buf = NULL, *out = NULL, *realm = NULL, **ext_id;
char hostname[256];
int ret;
#ifdef HAVE_SSL
int i;
#endif
size_t buflen, outlen;
assert(ctx);
assert(ctx->cb);
if(mech != NULL) {
_sx_debug(ZONE, "auth request from client (mechanism=%s)", mech);
if(!gsasl_server_support_p(ctx->gsasl_ctx, mech) || (ctx->cb)(sx_sasl_cb_CHECK_MECH, (void*)mech, NULL, s, ctx->cbarg) != sx_sasl_ret_OK) {
_sx_debug(ZONE, "client requested mechanism (%s) that we didn't offer", mech);
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INVALID_MECHANISM, NULL), 0);
return;
}
/* startup */
ret = gsasl_server_start(ctx->gsasl_ctx, mech, &sd);
if(ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_server_start failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_TEMPORARY_FAILURE, gsasl_strerror(ret)), 0);
return;
}
/* get the realm */
(ctx->cb)(sx_sasl_cb_GET_REALM, NULL, (void **) &realm, s, ctx->cbarg);
/* cleanup any existing session context */
sctx = gsasl_session_hook_get(sd);
if (sctx != NULL) free(sctx);
/* allocate and initialize our per session context */
sctx = (_sx_sasl_sess_t) calloc(1, sizeof(struct _sx_sasl_sess_st));
sctx->s = s;
sctx->ctx = ctx;
gsasl_session_hook_set(sd, (void *) sctx);
gsasl_property_set(sd, GSASL_SERVICE, ctx->appname);
gsasl_property_set(sd, GSASL_REALM, realm);
/* get hostname */
hostname[0] = '\0';
gethostname(hostname, 256);
hostname[255] = '\0';
gsasl_property_set(sd, GSASL_HOSTNAME, hostname);
/* get EXTERNAL data from the ssl plugin */
ext_id = NULL;
#ifdef HAVE_SSL
for(i = 0; i < s->env->nplugins; i++)
if(s->env->plugins[i]->magic == SX_SSL_MAGIC && s->plugin_data[s->env->plugins[i]->index] != NULL)
ext_id = ((_sx_ssl_conn_t) s->plugin_data[s->env->plugins[i]->index])->external_id;
if (ext_id != NULL) {
//_sx_debug(ZONE, "sasl context ext id '%s'", ext_id);
/* if there is, store it for later */
for (i = 0; i < SX_CONN_EXTERNAL_ID_MAX_COUNT; i++)
if (ext_id[i] != NULL) {
ctx->ext_id[i] = strdup(ext_id[i]);
} else {
ctx->ext_id[i] = NULL;
break;
}
}
#endif
_sx_debug(ZONE, "sasl context initialised for %d", s->tag);
s->plugin_data[p->index] = (void *) sd;
if(strcmp(mech, "ANONYMOUS") == 0) {
/*
* special case for SASL ANONYMOUS: ignore the initial
* response provided by the client and generate a random
* authid to use as the jid node for the user, as
* specified in XEP-0175
*/
(ctx->cb)(sx_sasl_cb_GEN_AUTHZID, NULL, (void **)&out, s, ctx->cbarg);
buf = strdup(out);
buflen = strlen(buf);
} else if (strstr(in, "<") != NULL && strncmp(in, "=", strstr(in, "<") - in ) == 0) {
/* XXX The above check is hackish, but `in` is just weird */
/* This is a special case for SASL External c2s. See XEP-0178 */
_sx_debug(ZONE, "gsasl auth string is empty");
buf = strdup("");
buflen = strlen(buf);
} else {
/* decode and process */
ret = gsasl_base64_from(in, inlen, &buf, &buflen);
if (ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_base64_from failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0);
if(buf != NULL) free(buf);
return;
}
}
ret = gsasl_step(sd, buf, buflen, &out, &outlen);
}
else {
/* decode and process */
ret = gsasl_base64_from(in, inlen, &buf, &buflen);
if (ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_base64_from failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0);
return;
}
if(!sd) {
_sx_debug(ZONE, "response send before auth request enabling mechanism (decoded: %.*s)", buflen, buf);
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_MECH_TOO_WEAK, "response send before auth request enabling mechanism"), 0);
if(buf != NULL) free(buf);
return;
}
_sx_debug(ZONE, "response from client (decoded: %.*s)", buflen, buf);
ret = gsasl_step(sd, buf, buflen, &out, &outlen);
}
if(buf != NULL) free(buf);
/* auth completed */
if(ret == GSASL_OK) {
_sx_debug(ZONE, "sasl handshake completed");
/* encode the leftover response */
ret = gsasl_base64_to(out, outlen, &buf, &buflen);
if (ret == GSASL_OK) {
/* send success */
_sx_nad_write(s, _sx_sasl_success(s, buf, buflen), 0);
free(buf);
/* set a notify on the success nad buffer */
((sx_buf_t) s->wbufq->front->data)->notify = _sx_sasl_notify_success;
((sx_buf_t) s->wbufq->front->data)->notify_arg = (void *) p;
}
else {
_sx_debug(ZONE, "gsasl_base64_to failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0);
if(buf != NULL) free(buf);
}
if(out != NULL) free(out);
return;
}
/* in progress */
if(ret == GSASL_NEEDS_MORE) {
_sx_debug(ZONE, "sasl handshake in progress (challenge: %.*s)", outlen, out);
/* encode the challenge */
ret = gsasl_base64_to(out, outlen, &buf, &buflen);
if (ret == GSASL_OK) {
_sx_nad_write(s, _sx_sasl_challenge(s, buf, buflen), 0);
free(buf);
}
else {
_sx_debug(ZONE, "gsasl_base64_to failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0);
if(buf != NULL) free(buf);
}
if(out != NULL) free(out);
return;
}
if(out != NULL) free(out);
/* its over */
_sx_debug(ZONE, "sasl handshake failed; (%d): %s", ret, gsasl_strerror(ret));
switch (ret) {
case GSASL_AUTHENTICATION_ERROR:
case GSASL_NO_ANONYMOUS_TOKEN:
case GSASL_NO_AUTHID:
case GSASL_NO_AUTHZID:
case GSASL_NO_PASSWORD:
case GSASL_NO_PASSCODE:
case GSASL_NO_PIN:
case GSASL_NO_SERVICE:
case GSASL_NO_HOSTNAME:
out = _sasl_err_NOT_AUTHORIZED;
break;
case GSASL_UNKNOWN_MECHANISM:
case GSASL_MECHANISM_PARSE_ERROR:
out = _sasl_err_INVALID_MECHANISM;
break;
case GSASL_BASE64_ERROR:
out = _sasl_err_INCORRECT_ENCODING;
break;
default:
out = _sasl_err_MALFORMED_REQUEST;
}
_sx_nad_write(s, _sx_sasl_failure(s, out, gsasl_strerror(ret)), 0);
}
/** process handshake packets from the server */
static void _sx_sasl_server_process(sx_t s, sx_plugin_t p, Gsasl_session *sd, const char *in, int inlen) {
char *buf = NULL, *out = NULL;
size_t buflen, outlen;
int ret;
_sx_debug(ZONE, "data from client");
/* decode the response */
ret = gsasl_base64_from(in, inlen, &buf, &buflen);
if (ret == GSASL_OK) {
_sx_debug(ZONE, "decoded data: %.*s", buflen, buf);
/* process the data */
ret = gsasl_step(sd, buf, buflen, &out, &outlen);
if(buf != NULL) free(buf);
buf = NULL;
/* in progress */
if(ret == GSASL_OK || ret == GSASL_NEEDS_MORE) {
_sx_debug(ZONE, "sasl handshake in progress (response: %.*s)", outlen, out);
/* encode the response */
ret = gsasl_base64_to(out, outlen, &buf, &buflen);
if (ret == GSASL_OK) {
_sx_nad_write(s, _sx_sasl_response(s, buf, buflen), 0);
}
if(out != NULL) free(out);
if(buf != NULL) free(buf);
return;
}
}
if(out != NULL) free(out);
if(buf != NULL) free(buf);
/* its over */
_sx_debug(ZONE, "sasl handshake aborted; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_abort(s), 0);
}
/** main nad processor */
static int _sx_sasl_process(sx_t s, sx_plugin_t p, nad_t nad) {
Gsasl_session *sd = (Gsasl_session *) s->plugin_data[p->index];
int attr;
char mech[128];
sx_error_t sxe;
int flags;
char *ns = NULL, *to = NULL, *from = NULL, *version = NULL;
/* only want sasl packets */
if(NAD_ENS(nad, 0) < 0 || NAD_NURI_L(nad, NAD_ENS(nad, 0)) != strlen(uri_SASL) || strncmp(NAD_NURI(nad, NAD_ENS(nad, 0)), uri_SASL, strlen(uri_SASL)) != 0)
return 1;
/* quietly drop it if sasl is disabled, or if not ready */
if(s->state != state_STREAM) {
_sx_debug(ZONE, "not correct state for sasl, ignoring");
nad_free(nad);
return 0;
}
/* packets from the client */
if(s->type == type_SERVER) {
if(!(s->flags & SX_SASL_OFFER)) {
_sx_debug(ZONE, "they tried to do sasl, but we never offered it, ignoring");
nad_free(nad);
return 0;
}
#ifdef HAVE_SSL
if((s->flags & SX_SSL_STARTTLS_REQUIRE) && s->ssf == 0) {
_sx_debug(ZONE, "they tried to do sasl, but they have to do starttls first, ignoring");
nad_free(nad);
return 0;
}
#endif
/* auth */
if(NAD_ENAME_L(nad, 0) == 4 && strncmp("auth", NAD_ENAME(nad, 0), NAD_ENAME_L(nad, 0)) == 0) {
/* require mechanism */
if((attr = nad_find_attr(nad, 0, -1, "mechanism", NULL)) < 0) {
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INVALID_MECHANISM, NULL), 0);
nad_free(nad);
return 0;
}
/* extract */
snprintf(mech, 127, "%.*s", NAD_AVAL_L(nad, attr), NAD_AVAL(nad, attr));
/* go */
_sx_sasl_client_process(s, p, sd, mech, NAD_CDATA(nad, 0), NAD_CDATA_L(nad, 0));
nad_free(nad);
return 0;
}
/* response */
else if(NAD_ENAME_L(nad, 0) == 8 && strncmp("response", NAD_ENAME(nad, 0), NAD_ENAME_L(nad, 0)) == 0) {
/* process it */
_sx_sasl_client_process(s, p, sd, NULL, NAD_CDATA(nad, 0), NAD_CDATA_L(nad, 0));
nad_free(nad);
return 0;
}
/* abort */
else if(NAD_ENAME_L(nad, 0) == 5 && strncmp("abort", NAD_ENAME(nad, 0), NAD_ENAME_L(nad, 0)) == 0) {
_sx_debug(ZONE, "sasl handshake aborted");
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_ABORTED, NULL), 0);
nad_free(nad);
return 0;
}
}
/* packets from the server */
else if(s->type == type_CLIENT) {
if(sd == NULL) {
_sx_debug(ZONE, "got sasl client packets, but they never started sasl, ignoring");
nad_free(nad);
return 0;
}
/* challenge */
if(NAD_ENAME_L(nad, 0) == 9 && strncmp("challenge", NAD_ENAME(nad, 0), NAD_ENAME_L(nad, 0)) == 0) {
/* process it */
_sx_sasl_server_process(s, p, sd, NAD_CDATA(nad, 0), NAD_CDATA_L(nad, 0));
nad_free(nad);
return 0;
}
/* success */
else if(NAD_ENAME_L(nad, 0) == 7 && strncmp("success", NAD_ENAME(nad, 0), NAD_ENAME_L(nad, 0)) == 0) {
_sx_debug(ZONE, "sasl handshake completed, resetting");
nad_free(nad);
/* save interesting bits */
flags = s->flags;
if(s->ns != NULL) ns = strdup(s->ns);
if(s->req_to != NULL) to = strdup(s->req_to);
if(s->req_from != NULL) from = strdup(s->req_from);
if(s->req_version != NULL) version = strdup(s->req_version);
/* reset state */
_sx_reset(s);
_sx_debug(ZONE, "restarting stream with sasl layer established");
/* second time round */
sx_client_init(s, flags, ns, to, from, version);
/* free bits */
if(ns != NULL) free(ns);
if(to != NULL) free(to);
if(from != NULL) free(from);
if(version != NULL) free(version);
return 0;
}
/* failure */
else if(NAD_ENAME_L(nad, 0) == 7 && strncmp("failure", NAD_ENAME(nad, 0), NAD_ENAME_L(nad, 0)) == 0) {
/* fire the error */
_sx_gen_error(sxe, SX_ERR_AUTH, "Authentication failed", NULL);
_sx_event(s, event_ERROR, (void *) &sxe);
/* cleanup */
gsasl_finish(sd);
s->plugin_data[p->index] = NULL;
nad_free(nad);
return 0;
}
}
/* invalid sasl command, quietly drop it */
_sx_debug(ZONE, "unknown sasl command '%.*s', ignoring", NAD_ENAME_L(nad, 0), NAD_ENAME(nad, 0));
nad_free(nad);
return 0;
}
/** cleanup */
static void _sx_sasl_free(sx_t s, sx_plugin_t p) {
Gsasl_session *sd = (Gsasl_session *) s->plugin_data[p->index];
_sx_sasl_sess_t sctx;
if(sd == NULL)
return;
_sx_debug(ZONE, "cleaning up conn state");
/* we need to clean up our per session context but keep sasl ctx */
sctx = gsasl_session_hook_get(sd);
if (sctx != NULL){
free(sctx);
gsasl_session_hook_set(sd, (void *) NULL);
}
gsasl_finish(sd);
s->plugin_data[p->index] = NULL;
}
static int _sx_sasl_gsasl_callback(Gsasl *gsasl_ctx, Gsasl_session *sd, Gsasl_property prop) {
_sx_sasl_sess_t sctx = gsasl_session_hook_get(sd);
_sx_sasl_t ctx = NULL;
struct sx_sasl_creds_st creds = {NULL, NULL, NULL, NULL};
char *value, *node, *host;
int len, i;
/*
* session hook data is not always available while its being set up,
* also not needed in many of the cases below.
*/
if(sctx != NULL) {
ctx = sctx->ctx;
}
_sx_debug(ZONE, "in _sx_sasl_gsasl_callback, property: %d", prop);
switch(prop) {
case GSASL_PASSWORD:
/* GSASL_AUTHID, GSASL_AUTHZID, GSASL_REALM */
assert(ctx);
assert(ctx->cb);
creds.authnid = gsasl_property_fast(sd, GSASL_AUTHID);
creds.realm = gsasl_property_fast(sd, GSASL_REALM);
if(!creds.authnid) return GSASL_NO_AUTHID;
if(!creds.realm) return GSASL_NO_AUTHZID;
if((ctx->cb)(sx_sasl_cb_GET_PASS, &creds, (void **)&value, sctx->s, ctx->cbarg) == sx_sasl_ret_OK) {
gsasl_property_set(sd, GSASL_PASSWORD, value);
}
return GSASL_NEEDS_MORE;
case GSASL_SERVICE:
gsasl_property_set(sd, GSASL_SERVICE, "xmpp");
return GSASL_OK;
case GSASL_HOSTNAME:
{
char hostname[256];
/* get hostname */
hostname[0] = '\0';
gethostname(hostname, 256);
hostname[255] = '\0';
gsasl_property_set(sd, GSASL_HOSTNAME, hostname);
}
return GSASL_OK;
case GSASL_VALIDATE_SIMPLE:
/* GSASL_AUTHID, GSASL_AUTHZID, GSASL_PASSWORD */
assert(ctx);
assert(ctx->cb);
creds.authnid = gsasl_property_fast(sd, GSASL_AUTHID);
creds.realm = gsasl_property_fast(sd, GSASL_REALM);
creds.pass = gsasl_property_fast(sd, GSASL_PASSWORD);
if(!creds.authnid) return GSASL_NO_AUTHID;
if(!creds.realm) return GSASL_NO_AUTHZID;
if(!creds.pass) return GSASL_NO_PASSWORD;
if((ctx->cb)(sx_sasl_cb_CHECK_PASS, &creds, NULL, sctx->s, ctx->cbarg) == sx_sasl_ret_OK)
return GSASL_OK;
else
return GSASL_AUTHENTICATION_ERROR;
case GSASL_VALIDATE_GSSAPI:
/* GSASL_AUTHZID, GSASL_GSSAPI_DISPLAY_NAME */
creds.authnid = gsasl_property_fast(sd, GSASL_GSSAPI_DISPLAY_NAME);
if(!creds.authnid) return GSASL_NO_AUTHID;
creds.authzid = gsasl_property_fast(sd, GSASL_AUTHZID);
if(!creds.authzid) return GSASL_NO_AUTHZID;
gsasl_property_set(sd, GSASL_AUTHID, creds.authnid);
return GSASL_OK;
case GSASL_VALIDATE_ANONYMOUS:
/* GSASL_ANONYMOUS_TOKEN */
creds.authnid = gsasl_property_fast(sd, GSASL_ANONYMOUS_TOKEN);
if(!creds.authnid) return GSASL_NO_ANONYMOUS_TOKEN;
/* set token as authid for later use */
gsasl_property_set(sd, GSASL_AUTHID, creds.authnid);
return GSASL_OK;
case GSASL_VALIDATE_EXTERNAL:
/* GSASL_AUTHID */
assert(ctx);
assert(ctx->ext_id);
creds.authzid = gsasl_property_fast(sd, GSASL_AUTHZID);
_sx_debug(ZONE, "sasl external");
_sx_debug(ZONE, "sasl creds.authzid is '%s'", creds.authzid);
for (i = 0; i < SX_CONN_EXTERNAL_ID_MAX_COUNT; i++) {
if (ctx->ext_id[i] == NULL)
break;
_sx_debug(ZONE, "sasl ext_id(%d) is '%s'", i, ctx->ext_id[i]);
/* XXX hackish.. detect c2s by existance of @ */
value = strstr(ctx->ext_id[i], "@");
if(value == NULL && creds.authzid != NULL && strcmp(ctx->ext_id[i], creds.authzid) == 0) {
// s2s connection and it's valid
/* TODO Handle wildcards and other thigs from XEP-0178 */
_sx_debug(ZONE, "sasl ctx->ext_id doesn't have '@' in it. Assuming s2s");
return GSASL_OK;
}
if(value != NULL &&
((creds.authzid != NULL && strcmp(ctx->ext_id[i], creds.authzid) == 0) ||
(creds.authzid == NULL)) ) {
// c2s connection
// creds.authzid == NULL condition is from XEP-0178 '=' auth reply
// This should be freed by gsasl_finish() but I'm not sure
// node = authnid
len = value - ctx->ext_id[i];
node = (char *) malloc(sizeof(char) * (len + 1)); // + null termination
strncpy(node, ctx->ext_id[i], len);
node[len] = '\0'; // null terminate the string
// host = realm
len = strlen(value) - 1 + 1; // - the @ + null termination
host = (char *) malloc(sizeof(char) * (len));
strcpy(host, value + 1); // skip the @
gsasl_property_set(sd, GSASL_AUTHID, node);
gsasl_property_set(sd, GSASL_REALM, host);
return GSASL_OK;
}
}
return GSASL_AUTHENTICATION_ERROR;
default:
break;
}
return GSASL_NO_CALLBACK;
}
static void _sx_sasl_unload(sx_plugin_t p) {
_sx_sasl_t ctx = (_sx_sasl_t) p->private;
int i;
assert(ctx);
if (ctx->gsasl_ctx != NULL) gsasl_done (ctx->gsasl_ctx);
if (ctx->appname != NULL) free(ctx->appname);
for (i = 0; i < SX_CONN_EXTERNAL_ID_MAX_COUNT; i++)
if(ctx->ext_id[i] != NULL)
free(ctx->ext_id[i]);
else
break;
free(ctx);
}
/** args: appname, callback, cb arg */
int sx_sasl_init(sx_env_t env, sx_plugin_t p, va_list args) {
const char *appname;
sx_sasl_callback_t cb;
void *cbarg;
_sx_sasl_t ctx;
int ret, i;
_sx_debug(ZONE, "initialising sasl plugin");
appname = va_arg(args, const char *);
if(appname == NULL) {
_sx_debug(ZONE, "appname was NULL, failing");
return 1;
}
cb = va_arg(args, sx_sasl_callback_t);
cbarg = va_arg(args, void *);
ctx = (_sx_sasl_t) calloc(1, sizeof(struct _sx_sasl_st));
ctx->appname = strdup(appname);
ctx->cb = cb;
ctx->cbarg = cbarg;
for (i = 0; i < SX_CONN_EXTERNAL_ID_MAX_COUNT; i++)
ctx->ext_id[i] = NULL;
ret = gsasl_init(&ctx->gsasl_ctx);
if(ret != GSASL_OK) {
_sx_debug(ZONE, "couldn't initialize libgsasl (%d): %s", ret, gsasl_strerror (ret));
free(ctx);
return 1;
}
gsasl_callback_set (ctx->gsasl_ctx, &_sx_sasl_gsasl_callback);
_sx_debug(ZONE, "sasl context initialised");
p->private = (void *) ctx;
p->unload = _sx_sasl_unload;
p->wio = _sx_sasl_wio;
p->rio = _sx_sasl_rio;
p->stream = _sx_sasl_stream;
p->features = _sx_sasl_features;
p->process = _sx_sasl_process;
p->free = _sx_sasl_free;
return 0;
}
/** kick off the auth handshake */
int sx_sasl_auth(sx_plugin_t p, sx_t s, const char *appname, const char *mech, const char *user, const char *pass) {
_sx_sasl_t ctx = (_sx_sasl_t) p->private;
_sx_sasl_sess_t sctx = NULL;
Gsasl_session *sd;
char *buf = NULL, *out = NULL;
char hostname[256];
int ret, ns;
size_t buflen, outlen;
nad_t nad;
assert((p != NULL));
assert((s != NULL));
assert((appname != NULL));
assert((mech != NULL));
assert((user != NULL));
assert((pass != NULL));
if(s->type != type_CLIENT || s->state != state_STREAM) {
_sx_debug(ZONE, "need client in stream state for sasl auth");
return 1;
}
/* handshake start */
ret = gsasl_client_start(ctx->gsasl_ctx, mech, &sd);
if(ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_client_start failed, not authing; (%d): %s", ret, gsasl_strerror(ret));
return 1;
}
/* get hostname */
hostname[0] = '\0';
gethostname(hostname, 256);
hostname[255] = '\0';
/* cleanup any existing session context */
sctx = gsasl_session_hook_get(sd);
if (sctx != NULL) free(sctx);
/* allocate and initialize our per session context */
sctx = (_sx_sasl_sess_t) calloc(1, sizeof(struct _sx_sasl_sess_st));
sctx->s = s;
sctx->ctx = ctx;
/* set user data in session handle */
gsasl_session_hook_set(sd, (void *) sctx);
gsasl_property_set(sd, GSASL_AUTHID, user);
gsasl_property_set(sd, GSASL_PASSWORD, pass);
gsasl_property_set(sd, GSASL_SERVICE, appname);
gsasl_property_set(sd, GSASL_HOSTNAME, hostname);
/* handshake step */
ret = gsasl_step(sd, NULL, 0, &out, &outlen);
if(ret != GSASL_OK && ret != GSASL_NEEDS_MORE) {
_sx_debug(ZONE, "gsasl_step failed, not authing; (%d): %s", ret, gsasl_strerror(ret));
gsasl_finish(sd);
return 1;
}
/* save userdata */
s->plugin_data[p->index] = (void *) sd;
/* in progress */
_sx_debug(ZONE, "sending auth request to server, mech '%s': %.*s", mech, outlen, out);
/* encode the challenge */
ret = gsasl_base64_to(out, outlen, &buf, &buflen);
if(ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_base64_to failed, not authing; (%d): %s", ret, gsasl_strerror(ret));
gsasl_finish(sd);
if (out != NULL) free(out);
return 1;
}
free(out);
/* build the nad */
nad = nad_new();
ns = nad_add_namespace(nad, uri_SASL, NULL);
nad_append_elem(nad, ns, "auth", 0);
nad_append_attr(nad, -1, "mechanism", mech);
if(buf != NULL) {
nad_append_cdata(nad, buf, buflen, 1);
free(buf);
}
/* its away */
sx_nad_write(s, nad);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/good_2556_1 |
crossvul-cpp_data_bad_3721_2 | /*
* NET4: Implementation of BSD Unix domain sockets.
*
* Authors: Alan Cox, <alan@lxorguk.ukuu.org.uk>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Fixes:
* Linus Torvalds : Assorted bug cures.
* Niibe Yutaka : async I/O support.
* Carsten Paeth : PF_UNIX check, address fixes.
* Alan Cox : Limit size of allocated blocks.
* Alan Cox : Fixed the stupid socketpair bug.
* Alan Cox : BSD compatibility fine tuning.
* Alan Cox : Fixed a bug in connect when interrupted.
* Alan Cox : Sorted out a proper draft version of
* file descriptor passing hacked up from
* Mike Shaver's work.
* Marty Leisner : Fixes to fd passing
* Nick Nevin : recvmsg bugfix.
* Alan Cox : Started proper garbage collector
* Heiko EiBfeldt : Missing verify_area check
* Alan Cox : Started POSIXisms
* Andreas Schwab : Replace inode by dentry for proper
* reference counting
* Kirk Petersen : Made this a module
* Christoph Rohland : Elegant non-blocking accept/connect algorithm.
* Lots of bug fixes.
* Alexey Kuznetosv : Repaired (I hope) bugs introduces
* by above two patches.
* Andrea Arcangeli : If possible we block in connect(2)
* if the max backlog of the listen socket
* is been reached. This won't break
* old apps and it will avoid huge amount
* of socks hashed (this for unix_gc()
* performances reasons).
* Security fix that limits the max
* number of socks to 2*max_files and
* the number of skb queueable in the
* dgram receiver.
* Artur Skawina : Hash function optimizations
* Alexey Kuznetsov : Full scale SMP. Lot of bugs are introduced 8)
* Malcolm Beattie : Set peercred for socketpair
* Michal Ostrowski : Module initialization cleanup.
* Arnaldo C. Melo : Remove MOD_{INC,DEC}_USE_COUNT,
* the core infrastructure is doing that
* for all net proto families now (2.5.69+)
*
*
* Known differences from reference BSD that was tested:
*
* [TO FIX]
* ECONNREFUSED is not returned from one end of a connected() socket to the
* other the moment one end closes.
* fstat() doesn't return st_dev=0, and give the blksize as high water mark
* and a fake inode identifier (nor the BSD first socket fstat twice bug).
* [NOT TO FIX]
* accept() returns a path name even if the connecting socket has closed
* in the meantime (BSD loses the path and gives up).
* accept() returns 0 length path for an unbound connector. BSD returns 16
* and a null first byte in the path (but not for gethost/peername - BSD bug ??)
* socketpair(...SOCK_RAW..) doesn't panic the kernel.
* BSD af_unix apparently has connect forgetting to block properly.
* (need to check this with the POSIX spec in detail)
*
* Differences from 2.0.0-11-... (ANK)
* Bug fixes and improvements.
* - client shutdown killed server socket.
* - removed all useless cli/sti pairs.
*
* Semantic changes/extensions.
* - generic control message passing.
* - SCM_CREDENTIALS control message.
* - "Abstract" (not FS based) socket bindings.
* Abstract names are sequences of bytes (not zero terminated)
* started by 0, so that this name space does not intersect
* with BSD names.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/stat.h>
#include <linux/dcache.h>
#include <linux/namei.h>
#include <linux/socket.h>
#include <linux/un.h>
#include <linux/fcntl.h>
#include <linux/termios.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/in.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <net/af_unix.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <net/scm.h>
#include <linux/init.h>
#include <linux/poll.h>
#include <linux/rtnetlink.h>
#include <linux/mount.h>
#include <net/checksum.h>
#include <linux/security.h>
struct hlist_head unix_socket_table[2 * UNIX_HASH_SIZE];
EXPORT_SYMBOL_GPL(unix_socket_table);
DEFINE_SPINLOCK(unix_table_lock);
EXPORT_SYMBOL_GPL(unix_table_lock);
static atomic_long_t unix_nr_socks;
static struct hlist_head *unix_sockets_unbound(void *addr)
{
unsigned long hash = (unsigned long)addr;
hash ^= hash >> 16;
hash ^= hash >> 8;
hash %= UNIX_HASH_SIZE;
return &unix_socket_table[UNIX_HASH_SIZE + hash];
}
#define UNIX_ABSTRACT(sk) (unix_sk(sk)->addr->hash < UNIX_HASH_SIZE)
#ifdef CONFIG_SECURITY_NETWORK
static void unix_get_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{
memcpy(UNIXSID(skb), &scm->secid, sizeof(u32));
}
static inline void unix_set_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{
scm->secid = *UNIXSID(skb);
}
#else
static inline void unix_get_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{ }
static inline void unix_set_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{ }
#endif /* CONFIG_SECURITY_NETWORK */
/*
* SMP locking strategy:
* hash table is protected with spinlock unix_table_lock
* each socket state is protected by separate spin lock.
*/
static inline unsigned int unix_hash_fold(__wsum n)
{
unsigned int hash = (__force unsigned int)n;
hash ^= hash>>16;
hash ^= hash>>8;
return hash&(UNIX_HASH_SIZE-1);
}
#define unix_peer(sk) (unix_sk(sk)->peer)
static inline int unix_our_peer(struct sock *sk, struct sock *osk)
{
return unix_peer(osk) == sk;
}
static inline int unix_may_send(struct sock *sk, struct sock *osk)
{
return unix_peer(osk) == NULL || unix_our_peer(sk, osk);
}
static inline int unix_recvq_full(struct sock const *sk)
{
return skb_queue_len(&sk->sk_receive_queue) > sk->sk_max_ack_backlog;
}
struct sock *unix_peer_get(struct sock *s)
{
struct sock *peer;
unix_state_lock(s);
peer = unix_peer(s);
if (peer)
sock_hold(peer);
unix_state_unlock(s);
return peer;
}
EXPORT_SYMBOL_GPL(unix_peer_get);
static inline void unix_release_addr(struct unix_address *addr)
{
if (atomic_dec_and_test(&addr->refcnt))
kfree(addr);
}
/*
* Check unix socket name:
* - should be not zero length.
* - if started by not zero, should be NULL terminated (FS object)
* - if started by zero, it is abstract name.
*/
static int unix_mkname(struct sockaddr_un *sunaddr, int len, unsigned int *hashp)
{
if (len <= sizeof(short) || len > sizeof(*sunaddr))
return -EINVAL;
if (!sunaddr || sunaddr->sun_family != AF_UNIX)
return -EINVAL;
if (sunaddr->sun_path[0]) {
/*
* This may look like an off by one error but it is a bit more
* subtle. 108 is the longest valid AF_UNIX path for a binding.
* sun_path[108] doesn't as such exist. However in kernel space
* we are guaranteed that it is a valid memory location in our
* kernel address buffer.
*/
((char *)sunaddr)[len] = 0;
len = strlen(sunaddr->sun_path)+1+sizeof(short);
return len;
}
*hashp = unix_hash_fold(csum_partial(sunaddr, len, 0));
return len;
}
static void __unix_remove_socket(struct sock *sk)
{
sk_del_node_init(sk);
}
static void __unix_insert_socket(struct hlist_head *list, struct sock *sk)
{
WARN_ON(!sk_unhashed(sk));
sk_add_node(sk, list);
}
static inline void unix_remove_socket(struct sock *sk)
{
spin_lock(&unix_table_lock);
__unix_remove_socket(sk);
spin_unlock(&unix_table_lock);
}
static inline void unix_insert_socket(struct hlist_head *list, struct sock *sk)
{
spin_lock(&unix_table_lock);
__unix_insert_socket(list, sk);
spin_unlock(&unix_table_lock);
}
static struct sock *__unix_find_socket_byname(struct net *net,
struct sockaddr_un *sunname,
int len, int type, unsigned int hash)
{
struct sock *s;
struct hlist_node *node;
sk_for_each(s, node, &unix_socket_table[hash ^ type]) {
struct unix_sock *u = unix_sk(s);
if (!net_eq(sock_net(s), net))
continue;
if (u->addr->len == len &&
!memcmp(u->addr->name, sunname, len))
goto found;
}
s = NULL;
found:
return s;
}
static inline struct sock *unix_find_socket_byname(struct net *net,
struct sockaddr_un *sunname,
int len, int type,
unsigned int hash)
{
struct sock *s;
spin_lock(&unix_table_lock);
s = __unix_find_socket_byname(net, sunname, len, type, hash);
if (s)
sock_hold(s);
spin_unlock(&unix_table_lock);
return s;
}
static struct sock *unix_find_socket_byinode(struct inode *i)
{
struct sock *s;
struct hlist_node *node;
spin_lock(&unix_table_lock);
sk_for_each(s, node,
&unix_socket_table[i->i_ino & (UNIX_HASH_SIZE - 1)]) {
struct dentry *dentry = unix_sk(s)->path.dentry;
if (dentry && dentry->d_inode == i) {
sock_hold(s);
goto found;
}
}
s = NULL;
found:
spin_unlock(&unix_table_lock);
return s;
}
static inline int unix_writable(struct sock *sk)
{
return (atomic_read(&sk->sk_wmem_alloc) << 2) <= sk->sk_sndbuf;
}
static void unix_write_space(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
if (unix_writable(sk)) {
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait,
POLLOUT | POLLWRNORM | POLLWRBAND);
sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
}
rcu_read_unlock();
}
/* When dgram socket disconnects (or changes its peer), we clear its receive
* queue of packets arrived from previous peer. First, it allows to do
* flow control based only on wmem_alloc; second, sk connected to peer
* may receive messages only from that peer. */
static void unix_dgram_disconnected(struct sock *sk, struct sock *other)
{
if (!skb_queue_empty(&sk->sk_receive_queue)) {
skb_queue_purge(&sk->sk_receive_queue);
wake_up_interruptible_all(&unix_sk(sk)->peer_wait);
/* If one link of bidirectional dgram pipe is disconnected,
* we signal error. Messages are lost. Do not make this,
* when peer was not connected to us.
*/
if (!sock_flag(other, SOCK_DEAD) && unix_peer(other) == sk) {
other->sk_err = ECONNRESET;
other->sk_error_report(other);
}
}
}
static void unix_sock_destructor(struct sock *sk)
{
struct unix_sock *u = unix_sk(sk);
skb_queue_purge(&sk->sk_receive_queue);
WARN_ON(atomic_read(&sk->sk_wmem_alloc));
WARN_ON(!sk_unhashed(sk));
WARN_ON(sk->sk_socket);
if (!sock_flag(sk, SOCK_DEAD)) {
printk(KERN_INFO "Attempt to release alive unix socket: %p\n", sk);
return;
}
if (u->addr)
unix_release_addr(u->addr);
atomic_long_dec(&unix_nr_socks);
local_bh_disable();
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
local_bh_enable();
#ifdef UNIX_REFCNT_DEBUG
printk(KERN_DEBUG "UNIX %p is destroyed, %ld are still alive.\n", sk,
atomic_long_read(&unix_nr_socks));
#endif
}
static int unix_release_sock(struct sock *sk, int embrion)
{
struct unix_sock *u = unix_sk(sk);
struct path path;
struct sock *skpair;
struct sk_buff *skb;
int state;
unix_remove_socket(sk);
/* Clear state */
unix_state_lock(sk);
sock_orphan(sk);
sk->sk_shutdown = SHUTDOWN_MASK;
path = u->path;
u->path.dentry = NULL;
u->path.mnt = NULL;
state = sk->sk_state;
sk->sk_state = TCP_CLOSE;
unix_state_unlock(sk);
wake_up_interruptible_all(&u->peer_wait);
skpair = unix_peer(sk);
if (skpair != NULL) {
if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) {
unix_state_lock(skpair);
/* No more writes */
skpair->sk_shutdown = SHUTDOWN_MASK;
if (!skb_queue_empty(&sk->sk_receive_queue) || embrion)
skpair->sk_err = ECONNRESET;
unix_state_unlock(skpair);
skpair->sk_state_change(skpair);
sk_wake_async(skpair, SOCK_WAKE_WAITD, POLL_HUP);
}
sock_put(skpair); /* It may now die */
unix_peer(sk) = NULL;
}
/* Try to flush out this socket. Throw out buffers at least */
while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) {
if (state == TCP_LISTEN)
unix_release_sock(skb->sk, 1);
/* passed fds are erased in the kfree_skb hook */
kfree_skb(skb);
}
if (path.dentry)
path_put(&path);
sock_put(sk);
/* ---- Socket is dead now and most probably destroyed ---- */
/*
* Fixme: BSD difference: In BSD all sockets connected to use get
* ECONNRESET and we die on the spot. In Linux we behave
* like files and pipes do and wait for the last
* dereference.
*
* Can't we simply set sock->err?
*
* What the above comment does talk about? --ANK(980817)
*/
if (unix_tot_inflight)
unix_gc(); /* Garbage collect fds */
return 0;
}
static void init_peercred(struct sock *sk)
{
put_pid(sk->sk_peer_pid);
if (sk->sk_peer_cred)
put_cred(sk->sk_peer_cred);
sk->sk_peer_pid = get_pid(task_tgid(current));
sk->sk_peer_cred = get_current_cred();
}
static void copy_peercred(struct sock *sk, struct sock *peersk)
{
put_pid(sk->sk_peer_pid);
if (sk->sk_peer_cred)
put_cred(sk->sk_peer_cred);
sk->sk_peer_pid = get_pid(peersk->sk_peer_pid);
sk->sk_peer_cred = get_cred(peersk->sk_peer_cred);
}
static int unix_listen(struct socket *sock, int backlog)
{
int err;
struct sock *sk = sock->sk;
struct unix_sock *u = unix_sk(sk);
struct pid *old_pid = NULL;
const struct cred *old_cred = NULL;
err = -EOPNOTSUPP;
if (sock->type != SOCK_STREAM && sock->type != SOCK_SEQPACKET)
goto out; /* Only stream/seqpacket sockets accept */
err = -EINVAL;
if (!u->addr)
goto out; /* No listens on an unbound socket */
unix_state_lock(sk);
if (sk->sk_state != TCP_CLOSE && sk->sk_state != TCP_LISTEN)
goto out_unlock;
if (backlog > sk->sk_max_ack_backlog)
wake_up_interruptible_all(&u->peer_wait);
sk->sk_max_ack_backlog = backlog;
sk->sk_state = TCP_LISTEN;
/* set credentials so connect can copy them */
init_peercred(sk);
err = 0;
out_unlock:
unix_state_unlock(sk);
put_pid(old_pid);
if (old_cred)
put_cred(old_cred);
out:
return err;
}
static int unix_release(struct socket *);
static int unix_bind(struct socket *, struct sockaddr *, int);
static int unix_stream_connect(struct socket *, struct sockaddr *,
int addr_len, int flags);
static int unix_socketpair(struct socket *, struct socket *);
static int unix_accept(struct socket *, struct socket *, int);
static int unix_getname(struct socket *, struct sockaddr *, int *, int);
static unsigned int unix_poll(struct file *, struct socket *, poll_table *);
static unsigned int unix_dgram_poll(struct file *, struct socket *,
poll_table *);
static int unix_ioctl(struct socket *, unsigned int, unsigned long);
static int unix_shutdown(struct socket *, int);
static int unix_stream_sendmsg(struct kiocb *, struct socket *,
struct msghdr *, size_t);
static int unix_stream_recvmsg(struct kiocb *, struct socket *,
struct msghdr *, size_t, int);
static int unix_dgram_sendmsg(struct kiocb *, struct socket *,
struct msghdr *, size_t);
static int unix_dgram_recvmsg(struct kiocb *, struct socket *,
struct msghdr *, size_t, int);
static int unix_dgram_connect(struct socket *, struct sockaddr *,
int, int);
static int unix_seqpacket_sendmsg(struct kiocb *, struct socket *,
struct msghdr *, size_t);
static int unix_seqpacket_recvmsg(struct kiocb *, struct socket *,
struct msghdr *, size_t, int);
static void unix_set_peek_off(struct sock *sk, int val)
{
struct unix_sock *u = unix_sk(sk);
mutex_lock(&u->readlock);
sk->sk_peek_off = val;
mutex_unlock(&u->readlock);
}
static const struct proto_ops unix_stream_ops = {
.family = PF_UNIX,
.owner = THIS_MODULE,
.release = unix_release,
.bind = unix_bind,
.connect = unix_stream_connect,
.socketpair = unix_socketpair,
.accept = unix_accept,
.getname = unix_getname,
.poll = unix_poll,
.ioctl = unix_ioctl,
.listen = unix_listen,
.shutdown = unix_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = unix_stream_sendmsg,
.recvmsg = unix_stream_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
.set_peek_off = unix_set_peek_off,
};
static const struct proto_ops unix_dgram_ops = {
.family = PF_UNIX,
.owner = THIS_MODULE,
.release = unix_release,
.bind = unix_bind,
.connect = unix_dgram_connect,
.socketpair = unix_socketpair,
.accept = sock_no_accept,
.getname = unix_getname,
.poll = unix_dgram_poll,
.ioctl = unix_ioctl,
.listen = sock_no_listen,
.shutdown = unix_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = unix_dgram_sendmsg,
.recvmsg = unix_dgram_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
.set_peek_off = unix_set_peek_off,
};
static const struct proto_ops unix_seqpacket_ops = {
.family = PF_UNIX,
.owner = THIS_MODULE,
.release = unix_release,
.bind = unix_bind,
.connect = unix_stream_connect,
.socketpair = unix_socketpair,
.accept = unix_accept,
.getname = unix_getname,
.poll = unix_dgram_poll,
.ioctl = unix_ioctl,
.listen = unix_listen,
.shutdown = unix_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = unix_seqpacket_sendmsg,
.recvmsg = unix_seqpacket_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
.set_peek_off = unix_set_peek_off,
};
static struct proto unix_proto = {
.name = "UNIX",
.owner = THIS_MODULE,
.obj_size = sizeof(struct unix_sock),
};
/*
* AF_UNIX sockets do not interact with hardware, hence they
* dont trigger interrupts - so it's safe for them to have
* bh-unsafe locking for their sk_receive_queue.lock. Split off
* this special lock-class by reinitializing the spinlock key:
*/
static struct lock_class_key af_unix_sk_receive_queue_lock_key;
static struct sock *unix_create1(struct net *net, struct socket *sock)
{
struct sock *sk = NULL;
struct unix_sock *u;
atomic_long_inc(&unix_nr_socks);
if (atomic_long_read(&unix_nr_socks) > 2 * get_max_files())
goto out;
sk = sk_alloc(net, PF_UNIX, GFP_KERNEL, &unix_proto);
if (!sk)
goto out;
sock_init_data(sock, sk);
lockdep_set_class(&sk->sk_receive_queue.lock,
&af_unix_sk_receive_queue_lock_key);
sk->sk_write_space = unix_write_space;
sk->sk_max_ack_backlog = net->unx.sysctl_max_dgram_qlen;
sk->sk_destruct = unix_sock_destructor;
u = unix_sk(sk);
u->path.dentry = NULL;
u->path.mnt = NULL;
spin_lock_init(&u->lock);
atomic_long_set(&u->inflight, 0);
INIT_LIST_HEAD(&u->link);
mutex_init(&u->readlock); /* single task reading lock */
init_waitqueue_head(&u->peer_wait);
unix_insert_socket(unix_sockets_unbound(sk), sk);
out:
if (sk == NULL)
atomic_long_dec(&unix_nr_socks);
else {
local_bh_disable();
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
local_bh_enable();
}
return sk;
}
static int unix_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
if (protocol && protocol != PF_UNIX)
return -EPROTONOSUPPORT;
sock->state = SS_UNCONNECTED;
switch (sock->type) {
case SOCK_STREAM:
sock->ops = &unix_stream_ops;
break;
/*
* Believe it or not BSD has AF_UNIX, SOCK_RAW though
* nothing uses it.
*/
case SOCK_RAW:
sock->type = SOCK_DGRAM;
case SOCK_DGRAM:
sock->ops = &unix_dgram_ops;
break;
case SOCK_SEQPACKET:
sock->ops = &unix_seqpacket_ops;
break;
default:
return -ESOCKTNOSUPPORT;
}
return unix_create1(net, sock) ? 0 : -ENOMEM;
}
static int unix_release(struct socket *sock)
{
struct sock *sk = sock->sk;
if (!sk)
return 0;
sock->sk = NULL;
return unix_release_sock(sk, 0);
}
static int unix_autobind(struct socket *sock)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk);
static u32 ordernum = 1;
struct unix_address *addr;
int err;
unsigned int retries = 0;
mutex_lock(&u->readlock);
err = 0;
if (u->addr)
goto out;
err = -ENOMEM;
addr = kzalloc(sizeof(*addr) + sizeof(short) + 16, GFP_KERNEL);
if (!addr)
goto out;
addr->name->sun_family = AF_UNIX;
atomic_set(&addr->refcnt, 1);
retry:
addr->len = sprintf(addr->name->sun_path+1, "%05x", ordernum) + 1 + sizeof(short);
addr->hash = unix_hash_fold(csum_partial(addr->name, addr->len, 0));
spin_lock(&unix_table_lock);
ordernum = (ordernum+1)&0xFFFFF;
if (__unix_find_socket_byname(net, addr->name, addr->len, sock->type,
addr->hash)) {
spin_unlock(&unix_table_lock);
/*
* __unix_find_socket_byname() may take long time if many names
* are already in use.
*/
cond_resched();
/* Give up if all names seems to be in use. */
if (retries++ == 0xFFFFF) {
err = -ENOSPC;
kfree(addr);
goto out;
}
goto retry;
}
addr->hash ^= sk->sk_type;
__unix_remove_socket(sk);
u->addr = addr;
__unix_insert_socket(&unix_socket_table[addr->hash], sk);
spin_unlock(&unix_table_lock);
err = 0;
out: mutex_unlock(&u->readlock);
return err;
}
static struct sock *unix_find_other(struct net *net,
struct sockaddr_un *sunname, int len,
int type, unsigned int hash, int *error)
{
struct sock *u;
struct path path;
int err = 0;
if (sunname->sun_path[0]) {
struct inode *inode;
err = kern_path(sunname->sun_path, LOOKUP_FOLLOW, &path);
if (err)
goto fail;
inode = path.dentry->d_inode;
err = inode_permission(inode, MAY_WRITE);
if (err)
goto put_fail;
err = -ECONNREFUSED;
if (!S_ISSOCK(inode->i_mode))
goto put_fail;
u = unix_find_socket_byinode(inode);
if (!u)
goto put_fail;
if (u->sk_type == type)
touch_atime(&path);
path_put(&path);
err = -EPROTOTYPE;
if (u->sk_type != type) {
sock_put(u);
goto fail;
}
} else {
err = -ECONNREFUSED;
u = unix_find_socket_byname(net, sunname, len, type, hash);
if (u) {
struct dentry *dentry;
dentry = unix_sk(u)->path.dentry;
if (dentry)
touch_atime(&unix_sk(u)->path);
} else
goto fail;
}
return u;
put_fail:
path_put(&path);
fail:
*error = err;
return NULL;
}
static int unix_mknod(const char *sun_path, umode_t mode, struct path *res)
{
struct dentry *dentry;
struct path path;
int err = 0;
/*
* Get the parent directory, calculate the hash for last
* component.
*/
dentry = kern_path_create(AT_FDCWD, sun_path, &path, 0);
err = PTR_ERR(dentry);
if (IS_ERR(dentry))
return err;
/*
* All right, let's create it.
*/
err = security_path_mknod(&path, dentry, mode, 0);
if (!err) {
err = vfs_mknod(path.dentry->d_inode, dentry, mode, 0);
if (!err) {
res->mnt = mntget(path.mnt);
res->dentry = dget(dentry);
}
}
done_path_create(&path, dentry);
return err;
}
static int unix_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk);
struct sockaddr_un *sunaddr = (struct sockaddr_un *)uaddr;
char *sun_path = sunaddr->sun_path;
int err;
unsigned int hash;
struct unix_address *addr;
struct hlist_head *list;
err = -EINVAL;
if (sunaddr->sun_family != AF_UNIX)
goto out;
if (addr_len == sizeof(short)) {
err = unix_autobind(sock);
goto out;
}
err = unix_mkname(sunaddr, addr_len, &hash);
if (err < 0)
goto out;
addr_len = err;
mutex_lock(&u->readlock);
err = -EINVAL;
if (u->addr)
goto out_up;
err = -ENOMEM;
addr = kmalloc(sizeof(*addr)+addr_len, GFP_KERNEL);
if (!addr)
goto out_up;
memcpy(addr->name, sunaddr, addr_len);
addr->len = addr_len;
addr->hash = hash ^ sk->sk_type;
atomic_set(&addr->refcnt, 1);
if (sun_path[0]) {
struct path path;
umode_t mode = S_IFSOCK |
(SOCK_INODE(sock)->i_mode & ~current_umask());
err = unix_mknod(sun_path, mode, &path);
if (err) {
if (err == -EEXIST)
err = -EADDRINUSE;
unix_release_addr(addr);
goto out_up;
}
addr->hash = UNIX_HASH_SIZE;
hash = path.dentry->d_inode->i_ino & (UNIX_HASH_SIZE-1);
spin_lock(&unix_table_lock);
u->path = path;
list = &unix_socket_table[hash];
} else {
spin_lock(&unix_table_lock);
err = -EADDRINUSE;
if (__unix_find_socket_byname(net, sunaddr, addr_len,
sk->sk_type, hash)) {
unix_release_addr(addr);
goto out_unlock;
}
list = &unix_socket_table[addr->hash];
}
err = 0;
__unix_remove_socket(sk);
u->addr = addr;
__unix_insert_socket(list, sk);
out_unlock:
spin_unlock(&unix_table_lock);
out_up:
mutex_unlock(&u->readlock);
out:
return err;
}
static void unix_state_double_lock(struct sock *sk1, struct sock *sk2)
{
if (unlikely(sk1 == sk2) || !sk2) {
unix_state_lock(sk1);
return;
}
if (sk1 < sk2) {
unix_state_lock(sk1);
unix_state_lock_nested(sk2);
} else {
unix_state_lock(sk2);
unix_state_lock_nested(sk1);
}
}
static void unix_state_double_unlock(struct sock *sk1, struct sock *sk2)
{
if (unlikely(sk1 == sk2) || !sk2) {
unix_state_unlock(sk1);
return;
}
unix_state_unlock(sk1);
unix_state_unlock(sk2);
}
static int unix_dgram_connect(struct socket *sock, struct sockaddr *addr,
int alen, int flags)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct sockaddr_un *sunaddr = (struct sockaddr_un *)addr;
struct sock *other;
unsigned int hash;
int err;
if (addr->sa_family != AF_UNSPEC) {
err = unix_mkname(sunaddr, alen, &hash);
if (err < 0)
goto out;
alen = err;
if (test_bit(SOCK_PASSCRED, &sock->flags) &&
!unix_sk(sk)->addr && (err = unix_autobind(sock)) != 0)
goto out;
restart:
other = unix_find_other(net, sunaddr, alen, sock->type, hash, &err);
if (!other)
goto out;
unix_state_double_lock(sk, other);
/* Apparently VFS overslept socket death. Retry. */
if (sock_flag(other, SOCK_DEAD)) {
unix_state_double_unlock(sk, other);
sock_put(other);
goto restart;
}
err = -EPERM;
if (!unix_may_send(sk, other))
goto out_unlock;
err = security_unix_may_send(sk->sk_socket, other->sk_socket);
if (err)
goto out_unlock;
} else {
/*
* 1003.1g breaking connected state with AF_UNSPEC
*/
other = NULL;
unix_state_double_lock(sk, other);
}
/*
* If it was connected, reconnect.
*/
if (unix_peer(sk)) {
struct sock *old_peer = unix_peer(sk);
unix_peer(sk) = other;
unix_state_double_unlock(sk, other);
if (other != old_peer)
unix_dgram_disconnected(sk, old_peer);
sock_put(old_peer);
} else {
unix_peer(sk) = other;
unix_state_double_unlock(sk, other);
}
return 0;
out_unlock:
unix_state_double_unlock(sk, other);
sock_put(other);
out:
return err;
}
static long unix_wait_for_peer(struct sock *other, long timeo)
{
struct unix_sock *u = unix_sk(other);
int sched;
DEFINE_WAIT(wait);
prepare_to_wait_exclusive(&u->peer_wait, &wait, TASK_INTERRUPTIBLE);
sched = !sock_flag(other, SOCK_DEAD) &&
!(other->sk_shutdown & RCV_SHUTDOWN) &&
unix_recvq_full(other);
unix_state_unlock(other);
if (sched)
timeo = schedule_timeout(timeo);
finish_wait(&u->peer_wait, &wait);
return timeo;
}
static int unix_stream_connect(struct socket *sock, struct sockaddr *uaddr,
int addr_len, int flags)
{
struct sockaddr_un *sunaddr = (struct sockaddr_un *)uaddr;
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk), *newu, *otheru;
struct sock *newsk = NULL;
struct sock *other = NULL;
struct sk_buff *skb = NULL;
unsigned int hash;
int st;
int err;
long timeo;
err = unix_mkname(sunaddr, addr_len, &hash);
if (err < 0)
goto out;
addr_len = err;
if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr &&
(err = unix_autobind(sock)) != 0)
goto out;
timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
/* First of all allocate resources.
If we will make it after state is locked,
we will have to recheck all again in any case.
*/
err = -ENOMEM;
/* create new sock for complete connection */
newsk = unix_create1(sock_net(sk), NULL);
if (newsk == NULL)
goto out;
/* Allocate skb for sending to listening sock */
skb = sock_wmalloc(newsk, 1, 0, GFP_KERNEL);
if (skb == NULL)
goto out;
restart:
/* Find listening sock. */
other = unix_find_other(net, sunaddr, addr_len, sk->sk_type, hash, &err);
if (!other)
goto out;
/* Latch state of peer */
unix_state_lock(other);
/* Apparently VFS overslept socket death. Retry. */
if (sock_flag(other, SOCK_DEAD)) {
unix_state_unlock(other);
sock_put(other);
goto restart;
}
err = -ECONNREFUSED;
if (other->sk_state != TCP_LISTEN)
goto out_unlock;
if (other->sk_shutdown & RCV_SHUTDOWN)
goto out_unlock;
if (unix_recvq_full(other)) {
err = -EAGAIN;
if (!timeo)
goto out_unlock;
timeo = unix_wait_for_peer(other, timeo);
err = sock_intr_errno(timeo);
if (signal_pending(current))
goto out;
sock_put(other);
goto restart;
}
/* Latch our state.
It is tricky place. We need to grab our state lock and cannot
drop lock on peer. It is dangerous because deadlock is
possible. Connect to self case and simultaneous
attempt to connect are eliminated by checking socket
state. other is TCP_LISTEN, if sk is TCP_LISTEN we
check this before attempt to grab lock.
Well, and we have to recheck the state after socket locked.
*/
st = sk->sk_state;
switch (st) {
case TCP_CLOSE:
/* This is ok... continue with connect */
break;
case TCP_ESTABLISHED:
/* Socket is already connected */
err = -EISCONN;
goto out_unlock;
default:
err = -EINVAL;
goto out_unlock;
}
unix_state_lock_nested(sk);
if (sk->sk_state != st) {
unix_state_unlock(sk);
unix_state_unlock(other);
sock_put(other);
goto restart;
}
err = security_unix_stream_connect(sk, other, newsk);
if (err) {
unix_state_unlock(sk);
goto out_unlock;
}
/* The way is open! Fastly set all the necessary fields... */
sock_hold(sk);
unix_peer(newsk) = sk;
newsk->sk_state = TCP_ESTABLISHED;
newsk->sk_type = sk->sk_type;
init_peercred(newsk);
newu = unix_sk(newsk);
RCU_INIT_POINTER(newsk->sk_wq, &newu->peer_wq);
otheru = unix_sk(other);
/* copy address information from listening to new sock*/
if (otheru->addr) {
atomic_inc(&otheru->addr->refcnt);
newu->addr = otheru->addr;
}
if (otheru->path.dentry) {
path_get(&otheru->path);
newu->path = otheru->path;
}
/* Set credentials */
copy_peercred(sk, other);
sock->state = SS_CONNECTED;
sk->sk_state = TCP_ESTABLISHED;
sock_hold(newsk);
smp_mb__after_atomic_inc(); /* sock_hold() does an atomic_inc() */
unix_peer(sk) = newsk;
unix_state_unlock(sk);
/* take ten and and send info to listening sock */
spin_lock(&other->sk_receive_queue.lock);
__skb_queue_tail(&other->sk_receive_queue, skb);
spin_unlock(&other->sk_receive_queue.lock);
unix_state_unlock(other);
other->sk_data_ready(other, 0);
sock_put(other);
return 0;
out_unlock:
if (other)
unix_state_unlock(other);
out:
kfree_skb(skb);
if (newsk)
unix_release_sock(newsk, 0);
if (other)
sock_put(other);
return err;
}
static int unix_socketpair(struct socket *socka, struct socket *sockb)
{
struct sock *ska = socka->sk, *skb = sockb->sk;
/* Join our sockets back to back */
sock_hold(ska);
sock_hold(skb);
unix_peer(ska) = skb;
unix_peer(skb) = ska;
init_peercred(ska);
init_peercred(skb);
if (ska->sk_type != SOCK_DGRAM) {
ska->sk_state = TCP_ESTABLISHED;
skb->sk_state = TCP_ESTABLISHED;
socka->state = SS_CONNECTED;
sockb->state = SS_CONNECTED;
}
return 0;
}
static int unix_accept(struct socket *sock, struct socket *newsock, int flags)
{
struct sock *sk = sock->sk;
struct sock *tsk;
struct sk_buff *skb;
int err;
err = -EOPNOTSUPP;
if (sock->type != SOCK_STREAM && sock->type != SOCK_SEQPACKET)
goto out;
err = -EINVAL;
if (sk->sk_state != TCP_LISTEN)
goto out;
/* If socket state is TCP_LISTEN it cannot change (for now...),
* so that no locks are necessary.
*/
skb = skb_recv_datagram(sk, 0, flags&O_NONBLOCK, &err);
if (!skb) {
/* This means receive shutdown. */
if (err == 0)
err = -EINVAL;
goto out;
}
tsk = skb->sk;
skb_free_datagram(sk, skb);
wake_up_interruptible(&unix_sk(sk)->peer_wait);
/* attach accepted sock to socket */
unix_state_lock(tsk);
newsock->state = SS_CONNECTED;
sock_graft(tsk, newsock);
unix_state_unlock(tsk);
return 0;
out:
return err;
}
static int unix_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer)
{
struct sock *sk = sock->sk;
struct unix_sock *u;
DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, uaddr);
int err = 0;
if (peer) {
sk = unix_peer_get(sk);
err = -ENOTCONN;
if (!sk)
goto out;
err = 0;
} else {
sock_hold(sk);
}
u = unix_sk(sk);
unix_state_lock(sk);
if (!u->addr) {
sunaddr->sun_family = AF_UNIX;
sunaddr->sun_path[0] = 0;
*uaddr_len = sizeof(short);
} else {
struct unix_address *addr = u->addr;
*uaddr_len = addr->len;
memcpy(sunaddr, addr->name, *uaddr_len);
}
unix_state_unlock(sk);
sock_put(sk);
out:
return err;
}
static void unix_detach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
scm->fp = UNIXCB(skb).fp;
UNIXCB(skb).fp = NULL;
for (i = scm->fp->count-1; i >= 0; i--)
unix_notinflight(scm->fp->fp[i]);
}
static void unix_destruct_scm(struct sk_buff *skb)
{
struct scm_cookie scm;
memset(&scm, 0, sizeof(scm));
scm.pid = UNIXCB(skb).pid;
scm.cred = UNIXCB(skb).cred;
if (UNIXCB(skb).fp)
unix_detach_fds(&scm, skb);
/* Alas, it calls VFS */
/* So fscking what? fput() had been SMP-safe since the last Summer */
scm_destroy(&scm);
sock_wfree(skb);
}
#define MAX_RECURSION_LEVEL 4
static int unix_attach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
unsigned char max_level = 0;
int unix_sock_count = 0;
for (i = scm->fp->count - 1; i >= 0; i--) {
struct sock *sk = unix_get_socket(scm->fp->fp[i]);
if (sk) {
unix_sock_count++;
max_level = max(max_level,
unix_sk(sk)->recursion_level);
}
}
if (unlikely(max_level > MAX_RECURSION_LEVEL))
return -ETOOMANYREFS;
/*
* Need to duplicate file references for the sake of garbage
* collection. Otherwise a socket in the fps might become a
* candidate for GC while the skb is not yet queued.
*/
UNIXCB(skb).fp = scm_fp_dup(scm->fp);
if (!UNIXCB(skb).fp)
return -ENOMEM;
if (unix_sock_count) {
for (i = scm->fp->count - 1; i >= 0; i--)
unix_inflight(scm->fp->fp[i]);
}
return max_level;
}
static int unix_scm_to_skb(struct scm_cookie *scm, struct sk_buff *skb, bool send_fds)
{
int err = 0;
UNIXCB(skb).pid = get_pid(scm->pid);
if (scm->cred)
UNIXCB(skb).cred = get_cred(scm->cred);
UNIXCB(skb).fp = NULL;
if (scm->fp && send_fds)
err = unix_attach_fds(scm, skb);
skb->destructor = unix_destruct_scm;
return err;
}
/*
* Some apps rely on write() giving SCM_CREDENTIALS
* We include credentials if source or destination socket
* asserted SOCK_PASSCRED.
*/
static void maybe_add_creds(struct sk_buff *skb, const struct socket *sock,
const struct sock *other)
{
if (UNIXCB(skb).cred)
return;
if (test_bit(SOCK_PASSCRED, &sock->flags) ||
!other->sk_socket ||
test_bit(SOCK_PASSCRED, &other->sk_socket->flags)) {
UNIXCB(skb).pid = get_pid(task_tgid(current));
UNIXCB(skb).cred = get_current_cred();
}
}
/*
* Send AF_UNIX data.
*/
static int unix_dgram_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk);
struct sockaddr_un *sunaddr = msg->msg_name;
struct sock *other = NULL;
int namelen = 0; /* fake GCC */
int err;
unsigned int hash;
struct sk_buff *skb;
long timeo;
struct scm_cookie tmp_scm;
int max_level;
int data_len = 0;
if (NULL == siocb->scm)
siocb->scm = &tmp_scm;
wait_for_unix_gc();
err = scm_send(sock, msg, siocb->scm);
if (err < 0)
return err;
err = -EOPNOTSUPP;
if (msg->msg_flags&MSG_OOB)
goto out;
if (msg->msg_namelen) {
err = unix_mkname(sunaddr, msg->msg_namelen, &hash);
if (err < 0)
goto out;
namelen = err;
} else {
sunaddr = NULL;
err = -ENOTCONN;
other = unix_peer_get(sk);
if (!other)
goto out;
}
if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr
&& (err = unix_autobind(sock)) != 0)
goto out;
err = -EMSGSIZE;
if (len > sk->sk_sndbuf - 32)
goto out;
if (len > SKB_MAX_ALLOC)
data_len = min_t(size_t,
len - SKB_MAX_ALLOC,
MAX_SKB_FRAGS * PAGE_SIZE);
skb = sock_alloc_send_pskb(sk, len - data_len, data_len,
msg->msg_flags & MSG_DONTWAIT, &err);
if (skb == NULL)
goto out;
err = unix_scm_to_skb(siocb->scm, skb, true);
if (err < 0)
goto out_free;
max_level = err + 1;
unix_get_secdata(siocb->scm, skb);
skb_put(skb, len - data_len);
skb->data_len = data_len;
skb->len = len;
err = skb_copy_datagram_from_iovec(skb, 0, msg->msg_iov, 0, len);
if (err)
goto out_free;
timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
restart:
if (!other) {
err = -ECONNRESET;
if (sunaddr == NULL)
goto out_free;
other = unix_find_other(net, sunaddr, namelen, sk->sk_type,
hash, &err);
if (other == NULL)
goto out_free;
}
if (sk_filter(other, skb) < 0) {
/* Toss the packet but do not return any error to the sender */
err = len;
goto out_free;
}
unix_state_lock(other);
err = -EPERM;
if (!unix_may_send(sk, other))
goto out_unlock;
if (sock_flag(other, SOCK_DEAD)) {
/*
* Check with 1003.1g - what should
* datagram error
*/
unix_state_unlock(other);
sock_put(other);
err = 0;
unix_state_lock(sk);
if (unix_peer(sk) == other) {
unix_peer(sk) = NULL;
unix_state_unlock(sk);
unix_dgram_disconnected(sk, other);
sock_put(other);
err = -ECONNREFUSED;
} else {
unix_state_unlock(sk);
}
other = NULL;
if (err)
goto out_free;
goto restart;
}
err = -EPIPE;
if (other->sk_shutdown & RCV_SHUTDOWN)
goto out_unlock;
if (sk->sk_type != SOCK_SEQPACKET) {
err = security_unix_may_send(sk->sk_socket, other->sk_socket);
if (err)
goto out_unlock;
}
if (unix_peer(other) != sk && unix_recvq_full(other)) {
if (!timeo) {
err = -EAGAIN;
goto out_unlock;
}
timeo = unix_wait_for_peer(other, timeo);
err = sock_intr_errno(timeo);
if (signal_pending(current))
goto out_free;
goto restart;
}
if (sock_flag(other, SOCK_RCVTSTAMP))
__net_timestamp(skb);
maybe_add_creds(skb, sock, other);
skb_queue_tail(&other->sk_receive_queue, skb);
if (max_level > unix_sk(other)->recursion_level)
unix_sk(other)->recursion_level = max_level;
unix_state_unlock(other);
other->sk_data_ready(other, len);
sock_put(other);
scm_destroy(siocb->scm);
return len;
out_unlock:
unix_state_unlock(other);
out_free:
kfree_skb(skb);
out:
if (other)
sock_put(other);
scm_destroy(siocb->scm);
return err;
}
static int unix_stream_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct sock *sk = sock->sk;
struct sock *other = NULL;
int err, size;
struct sk_buff *skb;
int sent = 0;
struct scm_cookie tmp_scm;
bool fds_sent = false;
int max_level;
if (NULL == siocb->scm)
siocb->scm = &tmp_scm;
wait_for_unix_gc();
err = scm_send(sock, msg, siocb->scm);
if (err < 0)
return err;
err = -EOPNOTSUPP;
if (msg->msg_flags&MSG_OOB)
goto out_err;
if (msg->msg_namelen) {
err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
goto out_err;
} else {
err = -ENOTCONN;
other = unix_peer(sk);
if (!other)
goto out_err;
}
if (sk->sk_shutdown & SEND_SHUTDOWN)
goto pipe_err;
while (sent < len) {
/*
* Optimisation for the fact that under 0.01% of X
* messages typically need breaking up.
*/
size = len-sent;
/* Keep two messages in the pipe so it schedules better */
if (size > ((sk->sk_sndbuf >> 1) - 64))
size = (sk->sk_sndbuf >> 1) - 64;
if (size > SKB_MAX_ALLOC)
size = SKB_MAX_ALLOC;
/*
* Grab a buffer
*/
skb = sock_alloc_send_skb(sk, size, msg->msg_flags&MSG_DONTWAIT,
&err);
if (skb == NULL)
goto out_err;
/*
* If you pass two values to the sock_alloc_send_skb
* it tries to grab the large buffer with GFP_NOFS
* (which can fail easily), and if it fails grab the
* fallback size buffer which is under a page and will
* succeed. [Alan]
*/
size = min_t(int, size, skb_tailroom(skb));
/* Only send the fds in the first buffer */
err = unix_scm_to_skb(siocb->scm, skb, !fds_sent);
if (err < 0) {
kfree_skb(skb);
goto out_err;
}
max_level = err + 1;
fds_sent = true;
err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size);
if (err) {
kfree_skb(skb);
goto out_err;
}
unix_state_lock(other);
if (sock_flag(other, SOCK_DEAD) ||
(other->sk_shutdown & RCV_SHUTDOWN))
goto pipe_err_free;
maybe_add_creds(skb, sock, other);
skb_queue_tail(&other->sk_receive_queue, skb);
if (max_level > unix_sk(other)->recursion_level)
unix_sk(other)->recursion_level = max_level;
unix_state_unlock(other);
other->sk_data_ready(other, size);
sent += size;
}
scm_destroy(siocb->scm);
siocb->scm = NULL;
return sent;
pipe_err_free:
unix_state_unlock(other);
kfree_skb(skb);
pipe_err:
if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL))
send_sig(SIGPIPE, current, 0);
err = -EPIPE;
out_err:
scm_destroy(siocb->scm);
siocb->scm = NULL;
return sent ? : err;
}
static int unix_seqpacket_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
int err;
struct sock *sk = sock->sk;
err = sock_error(sk);
if (err)
return err;
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
if (msg->msg_namelen)
msg->msg_namelen = 0;
return unix_dgram_sendmsg(kiocb, sock, msg, len);
}
static int unix_seqpacket_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size,
int flags)
{
struct sock *sk = sock->sk;
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
return unix_dgram_recvmsg(iocb, sock, msg, size, flags);
}
static void unix_copy_addr(struct msghdr *msg, struct sock *sk)
{
struct unix_sock *u = unix_sk(sk);
msg->msg_namelen = 0;
if (u->addr) {
msg->msg_namelen = u->addr->len;
memcpy(msg->msg_name, u->addr->name, u->addr->len);
}
}
static int unix_dgram_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size,
int flags)
{
struct sock_iocb *siocb = kiocb_to_siocb(iocb);
struct scm_cookie tmp_scm;
struct sock *sk = sock->sk;
struct unix_sock *u = unix_sk(sk);
int noblock = flags & MSG_DONTWAIT;
struct sk_buff *skb;
int err;
int peeked, skip;
err = -EOPNOTSUPP;
if (flags&MSG_OOB)
goto out;
msg->msg_namelen = 0;
err = mutex_lock_interruptible(&u->readlock);
if (err) {
err = sock_intr_errno(sock_rcvtimeo(sk, noblock));
goto out;
}
skip = sk_peek_offset(sk, flags);
skb = __skb_recv_datagram(sk, flags, &peeked, &skip, &err);
if (!skb) {
unix_state_lock(sk);
/* Signal EOF on disconnected non-blocking SEQPACKET socket. */
if (sk->sk_type == SOCK_SEQPACKET && err == -EAGAIN &&
(sk->sk_shutdown & RCV_SHUTDOWN))
err = 0;
unix_state_unlock(sk);
goto out_unlock;
}
wake_up_interruptible_sync_poll(&u->peer_wait,
POLLOUT | POLLWRNORM | POLLWRBAND);
if (msg->msg_name)
unix_copy_addr(msg, skb->sk);
if (size > skb->len - skip)
size = skb->len - skip;
else if (size < skb->len - skip)
msg->msg_flags |= MSG_TRUNC;
err = skb_copy_datagram_iovec(skb, skip, msg->msg_iov, size);
if (err)
goto out_free;
if (sock_flag(sk, SOCK_RCVTSTAMP))
__sock_recv_timestamp(msg, sk, skb);
if (!siocb->scm) {
siocb->scm = &tmp_scm;
memset(&tmp_scm, 0, sizeof(tmp_scm));
}
scm_set_cred(siocb->scm, UNIXCB(skb).pid, UNIXCB(skb).cred);
unix_set_secdata(siocb->scm, skb);
if (!(flags & MSG_PEEK)) {
if (UNIXCB(skb).fp)
unix_detach_fds(siocb->scm, skb);
sk_peek_offset_bwd(sk, skb->len);
} else {
/* It is questionable: on PEEK we could:
- do not return fds - good, but too simple 8)
- return fds, and do not return them on read (old strategy,
apparently wrong)
- clone fds (I chose it for now, it is the most universal
solution)
POSIX 1003.1g does not actually define this clearly
at all. POSIX 1003.1g doesn't define a lot of things
clearly however!
*/
sk_peek_offset_fwd(sk, size);
if (UNIXCB(skb).fp)
siocb->scm->fp = scm_fp_dup(UNIXCB(skb).fp);
}
err = (flags & MSG_TRUNC) ? skb->len - skip : size;
scm_recv(sock, msg, siocb->scm, flags);
out_free:
skb_free_datagram(sk, skb);
out_unlock:
mutex_unlock(&u->readlock);
out:
return err;
}
/*
* Sleep until data has arrive. But check for races..
*/
static long unix_stream_data_wait(struct sock *sk, long timeo)
{
DEFINE_WAIT(wait);
unix_state_lock(sk);
for (;;) {
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
if (!skb_queue_empty(&sk->sk_receive_queue) ||
sk->sk_err ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
signal_pending(current) ||
!timeo)
break;
set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
unix_state_unlock(sk);
timeo = schedule_timeout(timeo);
unix_state_lock(sk);
clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
}
finish_wait(sk_sleep(sk), &wait);
unix_state_unlock(sk);
return timeo;
}
static int unix_stream_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size,
int flags)
{
struct sock_iocb *siocb = kiocb_to_siocb(iocb);
struct scm_cookie tmp_scm;
struct sock *sk = sock->sk;
struct unix_sock *u = unix_sk(sk);
struct sockaddr_un *sunaddr = msg->msg_name;
int copied = 0;
int check_creds = 0;
int target;
int err = 0;
long timeo;
int skip;
err = -EINVAL;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
err = -EOPNOTSUPP;
if (flags&MSG_OOB)
goto out;
target = sock_rcvlowat(sk, flags&MSG_WAITALL, size);
timeo = sock_rcvtimeo(sk, flags&MSG_DONTWAIT);
msg->msg_namelen = 0;
/* Lock the socket to prevent queue disordering
* while sleeps in memcpy_tomsg
*/
if (!siocb->scm) {
siocb->scm = &tmp_scm;
memset(&tmp_scm, 0, sizeof(tmp_scm));
}
err = mutex_lock_interruptible(&u->readlock);
if (err) {
err = sock_intr_errno(timeo);
goto out;
}
skip = sk_peek_offset(sk, flags);
do {
int chunk;
struct sk_buff *skb;
unix_state_lock(sk);
skb = skb_peek(&sk->sk_receive_queue);
again:
if (skb == NULL) {
unix_sk(sk)->recursion_level = 0;
if (copied >= target)
goto unlock;
/*
* POSIX 1003.1g mandates this order.
*/
err = sock_error(sk);
if (err)
goto unlock;
if (sk->sk_shutdown & RCV_SHUTDOWN)
goto unlock;
unix_state_unlock(sk);
err = -EAGAIN;
if (!timeo)
break;
mutex_unlock(&u->readlock);
timeo = unix_stream_data_wait(sk, timeo);
if (signal_pending(current)
|| mutex_lock_interruptible(&u->readlock)) {
err = sock_intr_errno(timeo);
goto out;
}
continue;
unlock:
unix_state_unlock(sk);
break;
}
if (skip >= skb->len) {
skip -= skb->len;
skb = skb_peek_next(skb, &sk->sk_receive_queue);
goto again;
}
unix_state_unlock(sk);
if (check_creds) {
/* Never glue messages from different writers */
if ((UNIXCB(skb).pid != siocb->scm->pid) ||
(UNIXCB(skb).cred != siocb->scm->cred))
break;
} else {
/* Copy credentials */
scm_set_cred(siocb->scm, UNIXCB(skb).pid, UNIXCB(skb).cred);
check_creds = 1;
}
/* Copy address just once */
if (sunaddr) {
unix_copy_addr(msg, skb->sk);
sunaddr = NULL;
}
chunk = min_t(unsigned int, skb->len - skip, size);
if (memcpy_toiovec(msg->msg_iov, skb->data + skip, chunk)) {
if (copied == 0)
copied = -EFAULT;
break;
}
copied += chunk;
size -= chunk;
/* Mark read part of skb as used */
if (!(flags & MSG_PEEK)) {
skb_pull(skb, chunk);
sk_peek_offset_bwd(sk, chunk);
if (UNIXCB(skb).fp)
unix_detach_fds(siocb->scm, skb);
if (skb->len)
break;
skb_unlink(skb, &sk->sk_receive_queue);
consume_skb(skb);
if (siocb->scm->fp)
break;
} else {
/* It is questionable, see note in unix_dgram_recvmsg.
*/
if (UNIXCB(skb).fp)
siocb->scm->fp = scm_fp_dup(UNIXCB(skb).fp);
sk_peek_offset_fwd(sk, chunk);
break;
}
} while (size);
mutex_unlock(&u->readlock);
scm_recv(sock, msg, siocb->scm, flags);
out:
return copied ? : err;
}
static int unix_shutdown(struct socket *sock, int mode)
{
struct sock *sk = sock->sk;
struct sock *other;
mode = (mode+1)&(RCV_SHUTDOWN|SEND_SHUTDOWN);
if (!mode)
return 0;
unix_state_lock(sk);
sk->sk_shutdown |= mode;
other = unix_peer(sk);
if (other)
sock_hold(other);
unix_state_unlock(sk);
sk->sk_state_change(sk);
if (other &&
(sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET)) {
int peer_mode = 0;
if (mode&RCV_SHUTDOWN)
peer_mode |= SEND_SHUTDOWN;
if (mode&SEND_SHUTDOWN)
peer_mode |= RCV_SHUTDOWN;
unix_state_lock(other);
other->sk_shutdown |= peer_mode;
unix_state_unlock(other);
other->sk_state_change(other);
if (peer_mode == SHUTDOWN_MASK)
sk_wake_async(other, SOCK_WAKE_WAITD, POLL_HUP);
else if (peer_mode & RCV_SHUTDOWN)
sk_wake_async(other, SOCK_WAKE_WAITD, POLL_IN);
}
if (other)
sock_put(other);
return 0;
}
long unix_inq_len(struct sock *sk)
{
struct sk_buff *skb;
long amount = 0;
if (sk->sk_state == TCP_LISTEN)
return -EINVAL;
spin_lock(&sk->sk_receive_queue.lock);
if (sk->sk_type == SOCK_STREAM ||
sk->sk_type == SOCK_SEQPACKET) {
skb_queue_walk(&sk->sk_receive_queue, skb)
amount += skb->len;
} else {
skb = skb_peek(&sk->sk_receive_queue);
if (skb)
amount = skb->len;
}
spin_unlock(&sk->sk_receive_queue.lock);
return amount;
}
EXPORT_SYMBOL_GPL(unix_inq_len);
long unix_outq_len(struct sock *sk)
{
return sk_wmem_alloc_get(sk);
}
EXPORT_SYMBOL_GPL(unix_outq_len);
static int unix_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk = sock->sk;
long amount = 0;
int err;
switch (cmd) {
case SIOCOUTQ:
amount = unix_outq_len(sk);
err = put_user(amount, (int __user *)arg);
break;
case SIOCINQ:
amount = unix_inq_len(sk);
if (amount < 0)
err = amount;
else
err = put_user(amount, (int __user *)arg);
break;
default:
err = -ENOIOCTLCMD;
break;
}
return err;
}
static unsigned int unix_poll(struct file *file, struct socket *sock, poll_table *wait)
{
struct sock *sk = sock->sk;
unsigned int mask;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
/* exceptional events? */
if (sk->sk_err)
mask |= POLLERR;
if (sk->sk_shutdown == SHUTDOWN_MASK)
mask |= POLLHUP;
if (sk->sk_shutdown & RCV_SHUTDOWN)
mask |= POLLRDHUP | POLLIN | POLLRDNORM;
/* readable? */
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
/* Connection-based need to check for termination and startup */
if ((sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) &&
sk->sk_state == TCP_CLOSE)
mask |= POLLHUP;
/*
* we set writable also when the other side has shut down the
* connection. This prevents stuck sockets.
*/
if (unix_writable(sk))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
return mask;
}
static unsigned int unix_dgram_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk, *other;
unsigned int mask, writable;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
/* exceptional events? */
if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
mask |= POLLERR;
if (sk->sk_shutdown & RCV_SHUTDOWN)
mask |= POLLRDHUP | POLLIN | POLLRDNORM;
if (sk->sk_shutdown == SHUTDOWN_MASK)
mask |= POLLHUP;
/* readable? */
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
/* Connection-based need to check for termination and startup */
if (sk->sk_type == SOCK_SEQPACKET) {
if (sk->sk_state == TCP_CLOSE)
mask |= POLLHUP;
/* connection hasn't started yet? */
if (sk->sk_state == TCP_SYN_SENT)
return mask;
}
/* No write status requested, avoid expensive OUT tests. */
if (!(poll_requested_events(wait) & (POLLWRBAND|POLLWRNORM|POLLOUT)))
return mask;
writable = unix_writable(sk);
other = unix_peer_get(sk);
if (other) {
if (unix_peer(other) != sk) {
sock_poll_wait(file, &unix_sk(other)->peer_wait, wait);
if (unix_recvq_full(other))
writable = 0;
}
sock_put(other);
}
if (writable)
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
else
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
return mask;
}
#ifdef CONFIG_PROC_FS
#define BUCKET_SPACE (BITS_PER_LONG - (UNIX_HASH_BITS + 1) - 1)
#define get_bucket(x) ((x) >> BUCKET_SPACE)
#define get_offset(x) ((x) & ((1L << BUCKET_SPACE) - 1))
#define set_bucket_offset(b, o) ((b) << BUCKET_SPACE | (o))
static struct sock *unix_from_bucket(struct seq_file *seq, loff_t *pos)
{
unsigned long offset = get_offset(*pos);
unsigned long bucket = get_bucket(*pos);
struct sock *sk;
unsigned long count = 0;
for (sk = sk_head(&unix_socket_table[bucket]); sk; sk = sk_next(sk)) {
if (sock_net(sk) != seq_file_net(seq))
continue;
if (++count == offset)
break;
}
return sk;
}
static struct sock *unix_next_socket(struct seq_file *seq,
struct sock *sk,
loff_t *pos)
{
unsigned long bucket;
while (sk > (struct sock *)SEQ_START_TOKEN) {
sk = sk_next(sk);
if (!sk)
goto next_bucket;
if (sock_net(sk) == seq_file_net(seq))
return sk;
}
do {
sk = unix_from_bucket(seq, pos);
if (sk)
return sk;
next_bucket:
bucket = get_bucket(*pos) + 1;
*pos = set_bucket_offset(bucket, 1);
} while (bucket < ARRAY_SIZE(unix_socket_table));
return NULL;
}
static void *unix_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(unix_table_lock)
{
spin_lock(&unix_table_lock);
if (!*pos)
return SEQ_START_TOKEN;
if (get_bucket(*pos) >= ARRAY_SIZE(unix_socket_table))
return NULL;
return unix_next_socket(seq, NULL, pos);
}
static void *unix_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
++*pos;
return unix_next_socket(seq, v, pos);
}
static void unix_seq_stop(struct seq_file *seq, void *v)
__releases(unix_table_lock)
{
spin_unlock(&unix_table_lock);
}
static int unix_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq, "Num RefCount Protocol Flags Type St "
"Inode Path\n");
else {
struct sock *s = v;
struct unix_sock *u = unix_sk(s);
unix_state_lock(s);
seq_printf(seq, "%pK: %08X %08X %08X %04X %02X %5lu",
s,
atomic_read(&s->sk_refcnt),
0,
s->sk_state == TCP_LISTEN ? __SO_ACCEPTCON : 0,
s->sk_type,
s->sk_socket ?
(s->sk_state == TCP_ESTABLISHED ? SS_CONNECTED : SS_UNCONNECTED) :
(s->sk_state == TCP_ESTABLISHED ? SS_CONNECTING : SS_DISCONNECTING),
sock_i_ino(s));
if (u->addr) {
int i, len;
seq_putc(seq, ' ');
i = 0;
len = u->addr->len - sizeof(short);
if (!UNIX_ABSTRACT(s))
len--;
else {
seq_putc(seq, '@');
i++;
}
for ( ; i < len; i++)
seq_putc(seq, u->addr->name->sun_path[i]);
}
unix_state_unlock(s);
seq_putc(seq, '\n');
}
return 0;
}
static const struct seq_operations unix_seq_ops = {
.start = unix_seq_start,
.next = unix_seq_next,
.stop = unix_seq_stop,
.show = unix_seq_show,
};
static int unix_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &unix_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations unix_seq_fops = {
.owner = THIS_MODULE,
.open = unix_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
static const struct net_proto_family unix_family_ops = {
.family = PF_UNIX,
.create = unix_create,
.owner = THIS_MODULE,
};
static int __net_init unix_net_init(struct net *net)
{
int error = -ENOMEM;
net->unx.sysctl_max_dgram_qlen = 10;
if (unix_sysctl_register(net))
goto out;
#ifdef CONFIG_PROC_FS
if (!proc_net_fops_create(net, "unix", 0, &unix_seq_fops)) {
unix_sysctl_unregister(net);
goto out;
}
#endif
error = 0;
out:
return error;
}
static void __net_exit unix_net_exit(struct net *net)
{
unix_sysctl_unregister(net);
proc_net_remove(net, "unix");
}
static struct pernet_operations unix_net_ops = {
.init = unix_net_init,
.exit = unix_net_exit,
};
static int __init af_unix_init(void)
{
int rc = -1;
struct sk_buff *dummy_skb;
BUILD_BUG_ON(sizeof(struct unix_skb_parms) > sizeof(dummy_skb->cb));
rc = proto_register(&unix_proto, 1);
if (rc != 0) {
printk(KERN_CRIT "%s: Cannot create unix_sock SLAB cache!\n",
__func__);
goto out;
}
sock_register(&unix_family_ops);
register_pernet_subsys(&unix_net_ops);
out:
return rc;
}
static void __exit af_unix_exit(void)
{
sock_unregister(PF_UNIX);
proto_unregister(&unix_proto);
unregister_pernet_subsys(&unix_net_ops);
}
/* Earlier than device_initcall() so that other drivers invoking
request_module() don't end up in a loop when modprobe tries
to use a UNIX socket. But later than subsys_initcall() because
we depend on stuff initialised there */
fs_initcall(af_unix_init);
module_exit(af_unix_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_UNIX);
| ./CrossVul/dataset_final_sorted/CWE-287/c/bad_3721_2 |
crossvul-cpp_data_good_2556_0 | /*
* jabberd - Jabber Open Source Server
* Copyright (c) 2002 Jeremie Miller, Thomas Muldowney,
* Ryan Eatmon, Robert Norris
*
* 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, MA02111-1307USA
*/
#include "c2s.h"
#include <stringprep.h>
#include <string.h>
#include <ctype.h>
static sig_atomic_t c2s_shutdown = 0;
sig_atomic_t c2s_lost_router = 0;
static sig_atomic_t c2s_logrotate = 0;
static sig_atomic_t c2s_sighup = 0;
static void _c2s_signal(int signum)
{
c2s_shutdown = 1;
c2s_lost_router = 0;
}
static void _c2s_signal_hup(int signum)
{
c2s_logrotate = 1;
c2s_sighup = 1;
}
static void _c2s_signal_usr1(int signum)
{
set_debug_flag(0);
}
static void _c2s_signal_usr2(int signum)
{
set_debug_flag(1);
}
/** store the process id */
static void _c2s_pidfile(c2s_t c2s) {
const char *pidfile;
FILE *f;
pid_t pid;
pidfile = config_get_one(c2s->config, "pidfile", 0);
if(pidfile == NULL)
return;
pid = getpid();
if((f = fopen(pidfile, "w+")) == NULL) {
log_write(c2s->log, LOG_ERR, "couldn't open %s for writing: %s", pidfile, strerror(errno));
return;
}
if(fprintf(f, "%d", pid) < 0) {
log_write(c2s->log, LOG_ERR, "couldn't write to %s: %s", pidfile, strerror(errno));
fclose(f);
return;
}
fclose(f);
log_write(c2s->log, LOG_INFO, "process id is %d, written to %s", pid, pidfile);
}
/** pull values out of the config file */
static void _c2s_config_expand(c2s_t c2s)
{
const char *str, *ip, *mask;
char *req_domain, *to_address, *to_port;
config_elem_t elem;
int i;
stream_redirect_t sr;
set_debug_log_from_config(c2s->config);
c2s->id = config_get_one(c2s->config, "id", 0);
if(c2s->id == NULL)
c2s->id = "c2s";
c2s->router_ip = config_get_one(c2s->config, "router.ip", 0);
if(c2s->router_ip == NULL)
c2s->router_ip = "127.0.0.1";
c2s->router_port = j_atoi(config_get_one(c2s->config, "router.port", 0), 5347);
c2s->router_user = config_get_one(c2s->config, "router.user", 0);
if(c2s->router_user == NULL)
c2s->router_user = "jabberd";
c2s->router_pass = config_get_one(c2s->config, "router.pass", 0);
if(c2s->router_pass == NULL)
c2s->router_pass = "secret";
c2s->router_pemfile = config_get_one(c2s->config, "router.pemfile", 0);
c2s->router_cachain = config_get_one(c2s->config, "router.cachain", 0);
c2s->router_private_key_password = config_get_one(c2s->config, "router.private_key_password", 0);
c2s->router_ciphers = config_get_one(c2s->config, "router.ciphers", 0);
c2s->retry_init = j_atoi(config_get_one(c2s->config, "router.retry.init", 0), 3);
c2s->retry_lost = j_atoi(config_get_one(c2s->config, "router.retry.lost", 0), 3);
if((c2s->retry_sleep = j_atoi(config_get_one(c2s->config, "router.retry.sleep", 0), 2)) < 1)
c2s->retry_sleep = 1;
c2s->log_type = log_STDOUT;
if(config_get(c2s->config, "log") != NULL) {
if((str = config_get_attr(c2s->config, "log", 0, "type")) != NULL) {
if(strcmp(str, "file") == 0)
c2s->log_type = log_FILE;
else if(strcmp(str, "syslog") == 0)
c2s->log_type = log_SYSLOG;
}
}
if(c2s->log_type == log_SYSLOG) {
c2s->log_facility = config_get_one(c2s->config, "log.facility", 0);
c2s->log_ident = config_get_one(c2s->config, "log.ident", 0);
if(c2s->log_ident == NULL)
c2s->log_ident = "jabberd/c2s";
} else if(c2s->log_type == log_FILE)
c2s->log_ident = config_get_one(c2s->config, "log.file", 0);
c2s->packet_stats = config_get_one(c2s->config, "stats.packet", 0);
c2s->local_ip = config_get_one(c2s->config, "local.ip", 0);
if(c2s->local_ip == NULL)
c2s->local_ip = "0.0.0.0";
c2s->local_port = j_atoi(config_get_one(c2s->config, "local.port", 0), 0);
c2s->local_pemfile = config_get_one(c2s->config, "local.pemfile", 0);
c2s->local_cachain = config_get_one(c2s->config, "local.cachain", 0);
c2s->local_private_key_password = config_get_one(c2s->config, "local.private_key_password", 0);
c2s->local_verify_mode = j_atoi(config_get_one(c2s->config, "local.verify-mode", 0), 0);
c2s->local_ciphers = config_get_one(c2s->config, "local.ciphers", 0);
c2s->local_ssl_port = j_atoi(config_get_one(c2s->config, "local.ssl-port", 0), 0);
c2s->http_forward = config_get_one(c2s->config, "local.httpforward", 0);
c2s->websocket = (config_get(c2s->config, "io.websocket") != NULL);
c2s->io_max_fds = j_atoi(config_get_one(c2s->config, "io.max_fds", 0), 1024);
c2s->compression = (config_get(c2s->config, "io.compression") != NULL);
c2s->io_check_interval = j_atoi(config_get_one(c2s->config, "io.check.interval", 0), 0);
c2s->io_check_idle = j_atoi(config_get_one(c2s->config, "io.check.idle", 0), 0);
c2s->io_check_keepalive = j_atoi(config_get_one(c2s->config, "io.check.keepalive", 0), 0);
c2s->pbx_pipe = config_get_one(c2s->config, "pbx.pipe", 0);
elem = config_get(c2s->config, "stream_redirect.redirect");
if(elem != NULL)
{
for(i = 0; i < elem->nvalues; i++)
{
sr = (stream_redirect_t) pmalloco(xhash_pool(c2s->stream_redirects), sizeof(struct stream_redirect_st));
if(!sr) {
log_write(c2s->log, LOG_ERR, "cannot allocate memory for new stream redirection record, aborting");
exit(1);
}
req_domain = j_attr((const char **) elem->attrs[i], "requested_domain");
to_address = j_attr((const char **) elem->attrs[i], "to_address");
to_port = j_attr((const char **) elem->attrs[i], "to_port");
if(req_domain == NULL || to_address == NULL || to_port == NULL) {
log_write(c2s->log, LOG_ERR, "Error reading a stream_redirect.redirect element from file, skipping");
continue;
}
// Note that to_address should be RFC 3986 compliant
sr->to_address = to_address;
sr->to_port = to_port;
xhash_put(c2s->stream_redirects, pstrdup(xhash_pool(c2s->stream_redirects), req_domain), sr);
}
}
c2s->ar_module_name = config_get_one(c2s->config, "authreg.module", 0);
if(config_get(c2s->config, "authreg.mechanisms.traditional.plain") != NULL) c2s->ar_mechanisms |= AR_MECH_TRAD_PLAIN;
if(config_get(c2s->config, "authreg.mechanisms.traditional.digest") != NULL) c2s->ar_mechanisms |= AR_MECH_TRAD_DIGEST;
if(config_get(c2s->config, "authreg.mechanisms.traditional.cram-md5") != NULL) c2s->ar_mechanisms |= AR_MECH_TRAD_CRAMMD5;
if(config_get(c2s->config, "authreg.ssl-mechanisms.traditional.plain") != NULL) c2s->ar_ssl_mechanisms |= AR_MECH_TRAD_PLAIN;
if(config_get(c2s->config, "authreg.ssl-mechanisms.traditional.digest") != NULL) c2s->ar_ssl_mechanisms |= AR_MECH_TRAD_DIGEST;
if(config_get(c2s->config, "authreg.ssl-mechanisms.traditional.cram-md5") != NULL) c2s->ar_ssl_mechanisms |= AR_MECH_TRAD_CRAMMD5;
elem = config_get(c2s->config, "io.limits.bytes");
if(elem != NULL)
{
c2s->byte_rate_total = j_atoi(elem->values[0], 0);
if(c2s->byte_rate_total != 0)
{
c2s->byte_rate_seconds = j_atoi(j_attr((const char **) elem->attrs[0], "seconds"), 1);
c2s->byte_rate_wait = j_atoi(j_attr((const char **) elem->attrs[0], "throttle"), 5);
}
}
elem = config_get(c2s->config, "io.limits.stanzas");
if(elem != NULL)
{
c2s->stanza_rate_total = j_atoi(elem->values[0], 0);
if(c2s->stanza_rate_total != 0)
{
c2s->stanza_rate_seconds = j_atoi(j_attr((const char **) elem->attrs[0], "seconds"), 1);
c2s->stanza_rate_wait = j_atoi(j_attr((const char **) elem->attrs[0], "throttle"), 5);
}
}
elem = config_get(c2s->config, "io.limits.connects");
if(elem != NULL)
{
c2s->conn_rate_total = j_atoi(elem->values[0], 0);
if(c2s->conn_rate_total != 0)
{
c2s->conn_rate_seconds = j_atoi(j_attr((const char **) elem->attrs[0], "seconds"), 5);
c2s->conn_rate_wait = j_atoi(j_attr((const char **) elem->attrs[0], "throttle"), 5);
}
}
c2s->stanza_size_limit = j_atoi(config_get_one(c2s->config, "io.limits.stanzasize", 0), 0);
/* tweak timed checks with rate times */
if(c2s->io_check_interval == 0) {
if(c2s->byte_rate_total != 0)
c2s->io_check_interval = c2s->byte_rate_wait;
if(c2s->stanza_rate_total != 0 && c2s->io_check_interval > c2s->stanza_rate_wait)
c2s->io_check_interval = c2s->stanza_rate_wait;
}
str = config_get_one(c2s->config, "io.access.order", 0);
if(str == NULL || strcmp(str, "deny,allow") != 0)
c2s->access = access_new(0);
else
c2s->access = access_new(1);
elem = config_get(c2s->config, "io.access.allow");
if(elem != NULL)
{
for(i = 0; i < elem->nvalues; i++)
{
ip = j_attr((const char **) elem->attrs[i], "ip");
mask = j_attr((const char **) elem->attrs[i], "mask");
if(ip == NULL)
continue;
if(mask == NULL)
mask = "255.255.255.255";
access_allow(c2s->access, ip, mask);
}
}
elem = config_get(c2s->config, "io.access.deny");
if(elem != NULL)
{
for(i = 0; i < elem->nvalues; i++)
{
ip = j_attr((const char **) elem->attrs[i], "ip");
mask = j_attr((const char **) elem->attrs[i], "mask");
if(ip == NULL)
continue;
if(mask == NULL)
mask = "255.255.255.255";
access_deny(c2s->access, ip, mask);
}
}
}
static void _c2s_hosts_expand(c2s_t c2s)
{
char *realm;
config_elem_t elem;
char id[1024];
int i;
elem = config_get(c2s->config, "local.id");
if(!elem) {
log_write(c2s->log, LOG_NOTICE, "no local.id configured - skipping local domains configuration");
return;
}
for(i = 0; i < elem->nvalues; i++) {
host_t host = (host_t) pmalloco(xhash_pool(c2s->hosts), sizeof(struct host_st));
if(!host) {
log_write(c2s->log, LOG_ERR, "cannot allocate memory for new host, aborting");
exit(1);
}
realm = j_attr((const char **) elem->attrs[i], "realm");
/* stringprep ids (domain names) so that they are in canonical form */
strncpy(id, elem->values[i], 1024);
id[1023] = '\0';
if (stringprep_nameprep(id, 1024) != 0) {
log_write(c2s->log, LOG_ERR, "cannot stringprep id %s, aborting", id);
exit(1);
}
host->realm = (realm != NULL) ? realm : pstrdup(xhash_pool(c2s->hosts), id);
host->host_pemfile = j_attr((const char **) elem->attrs[i], "pemfile");
host->host_cachain = j_attr((const char **) elem->attrs[i], "cachain");
host->host_verify_mode = j_atoi(j_attr((const char **) elem->attrs[i], "verify-mode"), 0);
host->host_private_key_password = j_attr((const char **) elem->attrs[i], "private-key-password");
host->host_ciphers = j_attr((const char **) elem->attrs[i], "ciphers");
#ifdef HAVE_SSL
if(host->host_pemfile != NULL) {
if(c2s->sx_ssl == NULL) {
c2s->sx_ssl = sx_env_plugin(c2s->sx_env, sx_ssl_init, host->realm, host->host_pemfile, host->host_cachain, host->host_verify_mode, host->host_private_key_password, host->host_ciphers);
if(c2s->sx_ssl == NULL) {
log_write(c2s->log, LOG_ERR, "failed to load %s SSL pemfile", host->realm);
host->host_pemfile = NULL;
}
} else {
if(sx_ssl_server_addcert(c2s->sx_ssl, host->realm, host->host_pemfile, host->host_cachain, host->host_verify_mode, host->host_private_key_password, host->host_ciphers) != 0) {
log_write(c2s->log, LOG_ERR, "failed to load %s SSL pemfile", host->realm);
host->host_pemfile = NULL;
}
}
}
#endif
host->host_require_starttls = (j_attr((const char **) elem->attrs[i], "require-starttls") != NULL);
host->ar_module_name = j_attr((const char **) elem->attrs[i], "authreg-module");
if(host->ar_module_name) {
if((host->ar = authreg_init(c2s, host->ar_module_name)) == NULL) {
log_write(c2s->log, LOG_NOTICE, "failed to load %s authreg module - using default", host->realm);
host->ar = c2s->ar;
}
} else
host->ar = c2s->ar;
host->ar_register_enable = (j_attr((const char **) elem->attrs[i], "register-enable") != NULL);
host->ar_register_oob = j_attr((const char **) elem->attrs[i], "register-oob");
if(host->ar_register_enable || host->ar_register_oob) {
host->ar_register_instructions = j_attr((const char **) elem->attrs[i], "instructions");
if(host->ar_register_instructions == NULL) {
if(host->ar_register_oob)
host->ar_register_instructions = "Only web based registration is possible with this server.";
else
host->ar_register_instructions = "Enter a username and password to register with this server.";
}
} else
host->ar_register_password = (j_attr((const char **) elem->attrs[i], "password-change") != NULL);
/* check for empty <id/> CDATA - XXX this "1" is VERY config.c dependant !!! */
if(! strcmp(id, "1")) {
/* remove the realm even if set */
host->realm = NULL;
/* skip if vHost already configured */
if(! c2s->vhost)
c2s->vhost = host;
/* add meaningful log "id" */
strcpy(id, "default vHost");
} else {
/* insert into vHosts xhash */
xhash_put(c2s->hosts, pstrdup(xhash_pool(c2s->hosts), id), host);
}
log_write(c2s->log, LOG_NOTICE, "[%s] configured; realm=%s, authreg=%s, registration %s, using PEM:%s",
id, (host->realm != NULL ? host->realm : "no realm set"),
(host->ar_module_name ? host->ar_module_name : c2s->ar_module_name),
(host->ar_register_enable ? "enabled" : "disabled"),
(host->host_pemfile ? host->host_pemfile : "Default"));
}
}
static int _c2s_router_connect(c2s_t c2s) {
log_write(c2s->log, LOG_NOTICE, "attempting connection to router at %s, port=%d", c2s->router_ip, c2s->router_port);
c2s->fd = mio_connect(c2s->mio, c2s->router_port, c2s->router_ip, NULL, c2s_router_mio_callback, (void *) c2s);
if(c2s->fd == NULL) {
if(errno == ECONNREFUSED)
c2s_lost_router = 1;
log_write(c2s->log, LOG_NOTICE, "connection attempt to router failed: %s (%d)", MIO_STRERROR(MIO_ERROR), MIO_ERROR);
return 1;
}
c2s->router = sx_new(c2s->sx_env, c2s->fd->fd, c2s_router_sx_callback, (void *) c2s);
sx_client_init(c2s->router, 0, NULL, NULL, NULL, "1.0");
return 0;
}
static int _c2s_sx_sasl_callback(int cb, void *arg, void **res, sx_t s, void *cbarg) {
c2s_t c2s = (c2s_t) cbarg;
const char *my_realm, *mech;
sx_sasl_creds_t creds;
static char buf[3072];
char mechbuf[256];
struct jid_st jid;
jid_static_buf jid_buf;
int i, r;
sess_t sess;
char skey[44];
host_t host;
/* init static jid */
jid_static(&jid,&jid_buf);
/* retrieve our session */
assert(s != NULL);
sprintf(skey, "%d", s->tag);
/*
* Retrieve the session, note that depending on the operation,
* session may be null.
*/
sess = xhash_get(c2s->sessions, skey);
switch(cb) {
case sx_sasl_cb_GET_REALM:
if(s->req_to == NULL) /* this shouldn't happen */
my_realm = "";
else {
/* get host for request */
host = xhash_get(c2s->hosts, s->req_to);
if(host == NULL) {
log_write(c2s->log, LOG_ERR, "SASL callback for non-existing host: %s", s->req_to);
*res = (void *)NULL;
return sx_sasl_ret_FAIL;
}
my_realm = host->realm;
if(my_realm == NULL)
my_realm = s->req_to;
}
strncpy(buf, my_realm, 256);
*res = (void *)buf;
log_debug(ZONE, "sx sasl callback: get realm: realm is '%s'", buf);
return sx_sasl_ret_OK;
break;
case sx_sasl_cb_GET_PASS:
assert(sess != NULL);
creds = (sx_sasl_creds_t) arg;
log_debug(ZONE, "sx sasl callback: get pass (authnid=%s, realm=%s)", creds->authnid, creds->realm);
if(sess->host->ar->get_password && (sess->host->ar->get_password)(
sess->host->ar, sess, (char *)creds->authnid, (creds->realm != NULL) ? (char *)creds->realm: "", buf) == 0) {
*res = buf;
return sx_sasl_ret_OK;
}
return sx_sasl_ret_FAIL;
case sx_sasl_cb_CHECK_PASS:
assert(sess != NULL);
creds = (sx_sasl_creds_t) arg;
log_debug(ZONE, "sx sasl callback: check pass (authnid=%s, realm=%s)", creds->authnid, creds->realm);
if(sess->host->ar->check_password != NULL) {
if ((sess->host->ar->check_password)(
sess->host->ar, sess, (char *)creds->authnid, (creds->realm != NULL) ? (char *)creds->realm : "", (char *)creds->pass) == 0)
return sx_sasl_ret_OK;
else
return sx_sasl_ret_FAIL;
}
if(sess->host->ar->get_password != NULL) {
if ((sess->host->ar->get_password)(sess->host->ar, sess, (char *)creds->authnid, (creds->realm != NULL) ? (char *)creds->realm : "", buf) != 0)
return sx_sasl_ret_FAIL;
if (strcmp(creds->pass, buf)==0)
return sx_sasl_ret_OK;
}
return sx_sasl_ret_FAIL;
break;
case sx_sasl_cb_CHECK_AUTHZID:
assert(sess != NULL);
creds = (sx_sasl_creds_t) arg;
/* we need authzid to validate */
if(creds->authzid == NULL || creds->authzid[0] == '\0')
return sx_sasl_ret_FAIL;
/* authzid must be a valid jid */
if(jid_reset(&jid, creds->authzid, -1) == NULL)
return sx_sasl_ret_FAIL;
/* and have domain == stream to addr */
if(!s->req_to || (strcmp(jid.domain, s->req_to) != 0))
return sx_sasl_ret_FAIL;
/* and have no resource */
if(jid.resource[0] != '\0')
return sx_sasl_ret_FAIL;
/* and user has right to authorize as */
if (sess->host->ar->user_authz_allowed) {
if (sess->host->ar->user_authz_allowed(sess->host->ar, sess, (char *)creds->authnid, (char *)creds->realm, (char *)creds->authzid))
return sx_sasl_ret_OK;
} else {
if (strcmp(creds->authnid, jid.node) == 0 &&
(sess->host->ar->user_exists)(sess->host->ar, sess, jid.node, jid.domain))
return sx_sasl_ret_OK;
}
return sx_sasl_ret_FAIL;
case sx_sasl_cb_GEN_AUTHZID:
/* generate a jid for SASL ANONYMOUS */
jid_reset(&jid, s->req_to, -1);
/* make node a random string */
jid_random_part(&jid, jid_NODE);
strcpy(buf, jid.node);
*res = (void *)buf;
return sx_sasl_ret_OK;
break;
case sx_sasl_cb_CHECK_MECH:
mech = (char *)arg;
strncpy(mechbuf, mech, sizeof(mechbuf));
mechbuf[sizeof(mechbuf)-1]='\0';
for(i = 0; mechbuf[i]; i++) mechbuf[i] = tolower(mechbuf[i]);
log_debug(ZONE, "sx sasl callback: check mech (mech=%s)", mechbuf);
/* get host for request */
host = xhash_get(c2s->hosts, s->req_to);
if(host == NULL) {
log_write(c2s->log, LOG_WARNING, "SASL callback for non-existing host: %s", s->req_to);
return sx_sasl_ret_FAIL;
}
/* Determine if our configuration will let us use this mechanism.
* We support different mechanisms for both SSL and normal use */
if (strcmp(mechbuf, "digest-md5") == 0) {
/* digest-md5 requires that our authreg support get_password */
if (host->ar->get_password == NULL)
return sx_sasl_ret_FAIL;
} else if (strcmp(mechbuf, "plain") == 0) {
/* plain requires either get_password or check_password */
if (host->ar->get_password == NULL && host->ar->check_password == NULL)
return sx_sasl_ret_FAIL;
}
/* Using SSF is potentially dangerous, as SASL can also set the
* SSF of the connection. However, SASL shouldn't do so until after
* we've finished mechanism establishment
*/
if (s->ssf>0) {
r = snprintf(buf, sizeof(buf), "authreg.ssl-mechanisms.sasl.%s",mechbuf);
if (r < -1 || r > sizeof(buf))
return sx_sasl_ret_FAIL;
if(config_get(c2s->config,buf) != NULL)
return sx_sasl_ret_OK;
}
r = snprintf(buf, sizeof(buf), "authreg.mechanisms.sasl.%s",mechbuf);
if (r < -1 || r > sizeof(buf))
return sx_sasl_ret_FAIL;
/* Work out if our configuration will let us use this mechanism */
if(config_get(c2s->config,buf) != NULL)
return sx_sasl_ret_OK;
else
return sx_sasl_ret_FAIL;
default:
break;
}
return sx_sasl_ret_FAIL;
}
static void _c2s_time_checks(c2s_t c2s) {
sess_t sess;
time_t now;
union xhashv xhv;
now = time(NULL);
if(xhash_iter_first(c2s->sessions))
do {
xhv.sess_val = &sess;
xhash_iter_get(c2s->sessions, NULL, NULL, xhv.val);
if(!sess->s) continue;
if(c2s->io_check_idle > 0 && now > sess->last_activity + c2s->io_check_idle) {
log_write(c2s->log, LOG_NOTICE, "[%d] [%s, port=%d] timed out", sess->fd->fd, sess->ip, sess->port);
sx_error(sess->s, stream_err_HOST_GONE, "connection timed out");
sx_close(sess->s);
continue;
}
if(c2s->io_check_keepalive > 0 && now > sess->last_activity + c2s->io_check_keepalive && sess->s->state >= state_STREAM) {
log_debug(ZONE, "sending keepalive for %d", sess->fd->fd);
sx_raw_write(sess->s, " ", 1);
}
if(sess->rate != NULL && sess->rate->bad != 0 && rate_check(sess->rate) != 0) {
/* read the pending bytes when rate limit is no longer in effect */
log_debug(ZONE, "reading throttled %d", sess->fd->fd);
sess->s->want_read = 1;
sx_can_read(sess->s);
}
} while(xhash_iter_next(c2s->sessions));
}
static void _c2s_ar_free(const char *module, int modulelen, void *val, void *arg) {
authreg_t ar = (authreg_t) val;
authreg_free(ar);
}
JABBER_MAIN("jabberd2c2s", "Jabber 2 C2S", "Jabber Open Source Server: Client to Server", "jabberd2router\0")
{
c2s_t c2s;
char *config_file;
int optchar;
int mio_timeout;
sess_t sess;
bres_t res;
union xhashv xhv;
time_t check_time = 0;
const char *cli_id = 0;
#ifdef HAVE_UMASK
umask((mode_t) 0027);
#endif
srand(time(NULL));
#ifdef HAVE_WINSOCK2_H
/* get winsock running */
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
/* !!! tell user that we couldn't find a usable winsock dll */
return 0;
}
}
#endif
jabber_signal(SIGINT, _c2s_signal);
jabber_signal(SIGTERM, _c2s_signal);
#ifdef SIGHUP
jabber_signal(SIGHUP, _c2s_signal_hup);
#endif
#ifdef SIGPIPE
jabber_signal(SIGPIPE, SIG_IGN);
#endif
jabber_signal(SIGUSR1, _c2s_signal_usr1);
jabber_signal(SIGUSR2, _c2s_signal_usr2);
c2s = (c2s_t) calloc(1, sizeof(struct c2s_st));
/* load our config */
c2s->config = config_new();
config_file = CONFIG_DIR "/c2s.xml";
/* cmdline parsing */
while((optchar = getopt(argc, argv, "Dc:hi:?")) >= 0)
{
switch(optchar)
{
case 'c':
config_file = optarg;
break;
case 'D':
#ifdef DEBUG
set_debug_flag(1);
#else
printf("WARN: Debugging not enabled. Ignoring -D.\n");
#endif
break;
case 'i':
cli_id = optarg;
break;
case 'h': case '?': default:
fputs(
"c2s - jabberd client-to-server connector (" VERSION ")\n"
"Usage: c2s <options>\n"
"Options are:\n"
" -c <config> config file to use [default: " CONFIG_DIR "/c2s.xml]\n"
" -i id Override <id> config element\n"
#ifdef DEBUG
" -D Show debug output\n"
#endif
,
stdout);
config_free(c2s->config);
free(c2s);
return 1;
}
}
if(config_load_with_id(c2s->config, config_file, cli_id) != 0)
{
fputs("c2s: couldn't load config, aborting\n", stderr);
config_free(c2s->config);
free(c2s);
return 2;
}
c2s->stream_redirects = xhash_new(11);
_c2s_config_expand(c2s);
c2s->log = log_new(c2s->log_type, c2s->log_ident, c2s->log_facility);
c2s->ar_modules = xhash_new(5);
if(c2s->ar_module_name == NULL) {
log_write(c2s->log, LOG_NOTICE, "no default authreg module specified in config file");
}
else if((c2s->ar = authreg_init(c2s, c2s->ar_module_name)) == NULL) {
access_free(c2s->access);
config_free(c2s->config);
log_free(c2s->log);
free(c2s);
exit(1);
}
log_write(c2s->log, LOG_NOTICE, "starting up");
_c2s_pidfile(c2s);
c2s->sessions = xhash_new(1023);
c2s->conn_rates = xhash_new(101);
c2s->dead = jqueue_new();
c2s->dead_sess = jqueue_new();
c2s->sx_env = sx_env_new();
#ifdef HAVE_SSL
/* get the ssl context up and running */
if(c2s->local_pemfile != NULL) {
c2s->sx_ssl = sx_env_plugin(c2s->sx_env, sx_ssl_init, NULL, c2s->local_pemfile, c2s->local_cachain, c2s->local_verify_mode, c2s->local_private_key_password, c2s->local_ciphers);
if(c2s->sx_ssl == NULL) {
log_write(c2s->log, LOG_ERR, "failed to load local SSL pemfile, SSL will not be available to clients");
c2s->local_pemfile = NULL;
}
}
/* try and get something online, so at least we can encrypt to the router */
if(c2s->sx_ssl == NULL && c2s->router_pemfile != NULL) {
c2s->sx_ssl = sx_env_plugin(c2s->sx_env, sx_ssl_init, NULL, c2s->router_pemfile, c2s->router_cachain, NULL, c2s->router_private_key_password, c2s->router_ciphers);
if(c2s->sx_ssl == NULL) {
log_write(c2s->log, LOG_ERR, "failed to load router SSL pemfile, channel to router will not be SSL encrypted");
c2s->router_pemfile = NULL;
}
}
#endif
#ifdef USE_WEBSOCKET
/* possibly wrap in websocket */
if(c2s->websocket) {
sx_env_plugin(c2s->sx_env, sx_websocket_init, c2s->http_forward);
}
#else
if(c2s->websocket) {
log_write(c2s->log, LOG_ERR, "websocket support not built-in - not enabling");
}
if(c2s->http_forward) {
log_write(c2s->log, LOG_ERR, "httpforward available only with websocket support built-in");
}
#endif
#ifdef HAVE_LIBZ
/* get compression up and running */
if(c2s->compression) {
sx_env_plugin(c2s->sx_env, sx_compress_init);
}
#endif
/* get stanza ack up */
sx_env_plugin(c2s->sx_env, sx_ack_init);
/* and user IP address plugin */
sx_env_plugin(c2s->sx_env, address_init);
/* get sasl online */
c2s->sx_sasl = sx_env_plugin(c2s->sx_env, sx_sasl_init, "xmpp", _c2s_sx_sasl_callback, (void *) c2s);
if(c2s->sx_sasl == NULL) {
log_write(c2s->log, LOG_ERR, "failed to initialise SASL context, aborting");
exit(1);
}
/* get bind up */
sx_env_plugin(c2s->sx_env, bind_init, c2s);
c2s->mio = mio_new(c2s->io_max_fds);
if(c2s->mio == NULL) {
log_write(c2s->log, LOG_ERR, "failed to create MIO, aborting");
exit(1);
}
/* hosts mapping */
c2s->hosts = xhash_new(1021);
_c2s_hosts_expand(c2s);
c2s->sm_avail = xhash_new(1021);
c2s->retry_left = c2s->retry_init;
_c2s_router_connect(c2s);
mio_timeout = ((c2s->io_check_interval != 0 && c2s->io_check_interval < 5) ?
c2s->io_check_interval : 5);
while(!c2s_shutdown) {
mio_run(c2s->mio, mio_timeout);
if(c2s_logrotate) {
set_debug_log_from_config(c2s->config);
log_write(c2s->log, LOG_NOTICE, "reopening log ...");
log_free(c2s->log);
c2s->log = log_new(c2s->log_type, c2s->log_ident, c2s->log_facility);
log_write(c2s->log, LOG_NOTICE, "log started");
c2s_logrotate = 0;
}
if(c2s_sighup) {
log_write(c2s->log, LOG_NOTICE, "reloading some configuration items ...");
config_t conf;
conf = config_new();
if (conf && config_load(conf, config_file) == 0) {
xhash_free(c2s->stream_redirects);
c2s->stream_redirects = xhash_new(11);
char *req_domain, *to_address, *to_port;
config_elem_t elem;
int i;
stream_redirect_t sr;
elem = config_get(conf, "stream_redirect.redirect");
if(elem != NULL)
{
for(i = 0; i < elem->nvalues; i++)
{
sr = (stream_redirect_t) pmalloco(xhash_pool(c2s->stream_redirects), sizeof(struct stream_redirect_st));
if(!sr) {
log_write(c2s->log, LOG_ERR, "cannot allocate memory for new stream redirection record, aborting");
exit(1);
}
req_domain = j_attr((const char **) elem->attrs[i], "requested_domain");
to_address = j_attr((const char **) elem->attrs[i], "to_address");
to_port = j_attr((const char **) elem->attrs[i], "to_port");
if(req_domain == NULL || to_address == NULL || to_port == NULL) {
log_write(c2s->log, LOG_ERR, "Error reading a stream_redirect.redirect element from file, skipping");
continue;
}
// Note that to_address should be RFC 3986 compliant
sr->to_address = to_address;
sr->to_port = to_port;
xhash_put(c2s->stream_redirects, pstrdup(xhash_pool(c2s->stream_redirects), req_domain), sr);
}
}
config_free(conf);
} else {
log_write(c2s->log, LOG_WARNING, "couldn't reload config (%s)", config_file);
if (conf) config_free(conf);
}
c2s_sighup = 0;
}
if(c2s_lost_router) {
if(c2s->retry_left < 0) {
log_write(c2s->log, LOG_NOTICE, "attempting reconnect");
sleep(c2s->retry_sleep);
c2s_lost_router = 0;
if (c2s->router) sx_free(c2s->router);
_c2s_router_connect(c2s);
}
else if(c2s->retry_left == 0) {
c2s_shutdown = 1;
}
else {
log_write(c2s->log, LOG_NOTICE, "attempting reconnect (%d left)", c2s->retry_left);
c2s->retry_left--;
sleep(c2s->retry_sleep);
c2s_lost_router = 0;
if (c2s->router) sx_free(c2s->router);
_c2s_router_connect(c2s);
}
}
/* cleanup dead sess (before sx_t as sess->result uses sx_t nad cache) */
while(jqueue_size(c2s->dead_sess) > 0) {
sess = (sess_t) jqueue_pull(c2s->dead_sess);
/* free sess data */
if(sess->ip != NULL) free((void*)sess->ip);
if(sess->smcomp != NULL) free((void*)sess->smcomp);
if(sess->result != NULL) nad_free(sess->result);
if(sess->resources != NULL)
for(res = sess->resources; res != NULL;) {
bres_t tmp = res->next;
jid_free(res->jid);
free(res);
res = tmp;
}
if(sess->rate != NULL) rate_free(sess->rate);
if(sess->stanza_rate != NULL) rate_free(sess->stanza_rate);
free(sess);
}
/* cleanup dead sx_ts */
while(jqueue_size(c2s->dead) > 0)
sx_free((sx_t) jqueue_pull(c2s->dead));
/* time checks */
if(c2s->io_check_interval > 0 && time(NULL) >= c2s->next_check) {
log_debug(ZONE, "running time checks");
_c2s_time_checks(c2s);
c2s->next_check = time(NULL) + c2s->io_check_interval;
log_debug(ZONE, "next time check at %d", c2s->next_check);
}
if(time(NULL) > check_time + 60) {
#ifdef POOL_DEBUG
pool_stat(1);
#endif
if(c2s->packet_stats != NULL) {
int fd = open(c2s->packet_stats, O_TRUNC | O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP);
if (fd >= 0) {
char buf[100];
int len = snprintf(buf, 100, "%lld\n", c2s->packet_count);
if (write(fd, buf, len) != len) {
close(fd);
fd = -1;
} else close(fd);
}
if (fd < 0) {
log_write(c2s->log, LOG_ERR, "failed to write packet statistics to: %s", c2s->packet_stats);
c2s_shutdown = 1;
}
}
check_time = time(NULL);
}
}
log_write(c2s->log, LOG_NOTICE, "shutting down");
if(xhash_iter_first(c2s->sessions))
do {
xhv.sess_val = &sess;
xhash_iter_get(c2s->sessions, NULL, NULL, xhv.val);
if(sess->active && sess->s)
sx_close(sess->s);
} while(xhash_iter_next(c2s->sessions));
/* cleanup dead sess */
while(jqueue_size(c2s->dead_sess) > 0) {
sess = (sess_t) jqueue_pull(c2s->dead_sess);
/* free sess data */
if(sess->ip != NULL) free((void*)sess->ip);
if(sess->result != NULL) nad_free(sess->result);
if(sess->resources != NULL)
for(res = sess->resources; res != NULL;) {
bres_t tmp = res->next;
jid_free(res->jid);
free(res);
res = tmp;
}
free(sess);
}
while(jqueue_size(c2s->dead) > 0)
sx_free((sx_t) jqueue_pull(c2s->dead));
if (c2s->fd != NULL) mio_close(c2s->mio, c2s->fd);
sx_free(c2s->router);
sx_env_free(c2s->sx_env);
mio_free(c2s->mio);
xhash_free(c2s->sessions);
xhash_walk(c2s->ar_modules, _c2s_ar_free, NULL);
xhash_free(c2s->ar_modules);
xhash_free(c2s->conn_rates);
xhash_free(c2s->stream_redirects);
xhash_free(c2s->sm_avail);
xhash_free(c2s->hosts);
jqueue_free(c2s->dead);
jqueue_free(c2s->dead_sess);
access_free(c2s->access);
log_free(c2s->log);
config_free(c2s->config);
free(c2s);
#ifdef POOL_DEBUG
pool_stat(1);
#endif
#ifdef HAVE_WINSOCK2_H
WSACleanup();
#endif
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/good_2556_0 |
crossvul-cpp_data_good_3281_1 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* COPYRIGHT (C) 2006,2007
* THE REGENTS OF THE UNIVERSITY OF MICHIGAN
* ALL RIGHTS RESERVED
*
* Permission is granted to use, copy, create derivative works
* and redistribute this software and such derivative works
* for any purpose, so long as the name of The University of
* Michigan is not used in any advertising or publicity
* pertaining to the use of distribution of this software
* without specific, written prior authorization. If the
* above copyright notice or any other identification of the
* University of Michigan is included in any copy of any
* portion of this software, then the disclaimer below must
* also be included.
*
* THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION
* FROM THE UNIVERSITY OF MICHIGAN AS TO ITS FITNESS FOR ANY
* PURPOSE, AND WITHOUT WARRANTY BY THE UNIVERSITY OF
* MICHIGAN OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
* REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE LIABLE
* FOR ANY DAMAGES, INCLUDING SPECIAL, INDIRECT, INCIDENTAL, OR
* CONSEQUENTIAL DAMAGES, WITH RESPECT TO ANY CLAIM ARISING
* OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, EVEN
* IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
*/
#include <k5-int.h>
#include "pkinit.h"
#include "krb5/certauth_plugin.h"
/* Aliases used by the built-in certauth modules */
struct certauth_req_opts {
krb5_kdcpreauth_callbacks cb;
krb5_kdcpreauth_rock rock;
pkinit_kdc_context plgctx;
pkinit_kdc_req_context reqctx;
};
typedef struct certauth_module_handle_st {
struct krb5_certauth_vtable_st vt;
krb5_certauth_moddata moddata;
} *certauth_handle;
struct krb5_kdcpreauth_moddata_st {
pkinit_kdc_context *realm_contexts;
certauth_handle *certauth_modules;
};
static krb5_error_code
pkinit_init_kdc_req_context(krb5_context, pkinit_kdc_req_context *blob);
static void
pkinit_fini_kdc_req_context(krb5_context context, void *blob);
static void
pkinit_server_plugin_fini_realm(krb5_context context,
pkinit_kdc_context plgctx);
static void
pkinit_server_plugin_fini(krb5_context context,
krb5_kdcpreauth_moddata moddata);
static pkinit_kdc_context
pkinit_find_realm_context(krb5_context context,
krb5_kdcpreauth_moddata moddata,
krb5_principal princ);
static void
free_realm_contexts(krb5_context context, pkinit_kdc_context *realm_contexts)
{
int i;
if (realm_contexts == NULL)
return;
for (i = 0; realm_contexts[i] != NULL; i++)
pkinit_server_plugin_fini_realm(context, realm_contexts[i]);
pkiDebug("%s: freeing context at %p\n", __FUNCTION__, realm_contexts);
free(realm_contexts);
}
static void
free_certauth_handles(krb5_context context, certauth_handle *list)
{
int i;
if (list == NULL)
return;
for (i = 0; list[i] != NULL; i++) {
if (list[i]->vt.fini != NULL)
list[i]->vt.fini(context, list[i]->moddata);
free(list[i]);
}
free(list);
}
static krb5_error_code
pkinit_create_edata(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
pkinit_plg_opts *opts,
krb5_error_code err_code,
krb5_pa_data ***e_data_out)
{
krb5_error_code retval = KRB5KRB_ERR_GENERIC;
pkiDebug("pkinit_create_edata: creating edata for error %d (%s)\n",
err_code, error_message(err_code));
switch(err_code) {
case KRB5KDC_ERR_CANT_VERIFY_CERTIFICATE:
retval = pkinit_create_td_trusted_certifiers(context,
plg_cryptoctx, req_cryptoctx, id_cryptoctx, e_data_out);
break;
case KRB5KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED:
retval = pkinit_create_td_dh_parameters(context, plg_cryptoctx,
req_cryptoctx, id_cryptoctx, opts, e_data_out);
break;
case KRB5KDC_ERR_INVALID_CERTIFICATE:
case KRB5KDC_ERR_REVOKED_CERTIFICATE:
retval = pkinit_create_td_invalid_certificate(context,
plg_cryptoctx, req_cryptoctx, id_cryptoctx, e_data_out);
break;
default:
pkiDebug("no edata needed for error %d (%s)\n",
err_code, error_message(err_code));
retval = 0;
goto cleanup;
}
cleanup:
return retval;
}
static void
pkinit_server_get_edata(krb5_context context,
krb5_kdc_req *request,
krb5_kdcpreauth_callbacks cb,
krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata,
krb5_preauthtype pa_type,
krb5_kdcpreauth_edata_respond_fn respond,
void *arg)
{
krb5_error_code retval = 0;
pkinit_kdc_context plgctx = NULL;
pkiDebug("pkinit_server_get_edata: entered!\n");
/*
* If we don't have a realm context for the given realm,
* don't tell the client that we support pkinit!
*/
plgctx = pkinit_find_realm_context(context, moddata, request->server);
if (plgctx == NULL)
retval = EINVAL;
(*respond)(arg, retval, NULL);
}
static krb5_error_code
verify_client_san(krb5_context context,
pkinit_kdc_context plgctx,
pkinit_kdc_req_context reqctx,
krb5_kdcpreauth_callbacks cb,
krb5_kdcpreauth_rock rock,
krb5_const_principal client,
int *valid_san)
{
krb5_error_code retval;
krb5_principal *princs = NULL;
krb5_principal *upns = NULL;
int i;
#ifdef DEBUG_SAN_INFO
char *client_string = NULL, *san_string;
#endif
*valid_san = 0;
retval = crypto_retrieve_cert_sans(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
&princs,
plgctx->opts->allow_upn ? &upns : NULL,
NULL);
if (retval) {
pkiDebug("%s: error from retrieve_certificate_sans()\n", __FUNCTION__);
retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
goto out;
}
if (princs == NULL && upns == NULL) {
TRACE_PKINIT_SERVER_NO_SAN(context);
retval = ENOENT;
goto out;
}
/* XXX Verify this is consistent with client side XXX */
#if 0
retval = call_san_checking_plugins(context, plgctx, reqctx, princs,
upns, NULL, &plugin_decision, &ignore);
pkiDebug("%s: call_san_checking_plugins() returned retval %d\n",
__FUNCTION__);
if (retval) {
retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
goto cleanup;
}
pkiDebug("%s: call_san_checking_plugins() returned decision %d\n",
__FUNCTION__, plugin_decision);
if (plugin_decision != NO_DECISION) {
retval = plugin_decision;
goto out;
}
#endif
#ifdef DEBUG_SAN_INFO
krb5_unparse_name(context, client, &client_string);
#endif
pkiDebug("%s: Checking pkinit sans\n", __FUNCTION__);
for (i = 0; princs != NULL && princs[i] != NULL; i++) {
#ifdef DEBUG_SAN_INFO
krb5_unparse_name(context, princs[i], &san_string);
pkiDebug("%s: Comparing client '%s' to pkinit san value '%s'\n",
__FUNCTION__, client_string, san_string);
krb5_free_unparsed_name(context, san_string);
#endif
if (cb->match_client(context, rock, princs[i])) {
TRACE_PKINIT_SERVER_MATCHING_SAN_FOUND(context);
*valid_san = 1;
retval = 0;
goto out;
}
}
pkiDebug("%s: no pkinit san match found\n", __FUNCTION__);
/*
* XXX if cert has names but none match, should we
* be returning KRB5KDC_ERR_CLIENT_NAME_MISMATCH here?
*/
if (upns == NULL) {
pkiDebug("%s: no upn sans (or we wouldn't accept them anyway)\n",
__FUNCTION__);
retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
goto out;
}
pkiDebug("%s: Checking upn sans\n", __FUNCTION__);
for (i = 0; upns[i] != NULL; i++) {
#ifdef DEBUG_SAN_INFO
krb5_unparse_name(context, upns[i], &san_string);
pkiDebug("%s: Comparing client '%s' to upn san value '%s'\n",
__FUNCTION__, client_string, san_string);
krb5_free_unparsed_name(context, san_string);
#endif
if (cb->match_client(context, rock, upns[i])) {
TRACE_PKINIT_SERVER_MATCHING_UPN_FOUND(context);
*valid_san = 1;
retval = 0;
goto out;
}
}
pkiDebug("%s: no upn san match found\n", __FUNCTION__);
/* We found no match */
if (princs != NULL || upns != NULL) {
*valid_san = 0;
/* XXX ??? If there was one or more name in the cert, but
* none matched the client name, then return mismatch? */
retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
}
retval = 0;
out:
if (princs != NULL) {
for (i = 0; princs[i] != NULL; i++)
krb5_free_principal(context, princs[i]);
free(princs);
}
if (upns != NULL) {
for (i = 0; upns[i] != NULL; i++)
krb5_free_principal(context, upns[i]);
free(upns);
}
#ifdef DEBUG_SAN_INFO
if (client_string != NULL)
krb5_free_unparsed_name(context, client_string);
#endif
pkiDebug("%s: returning retval %d, valid_san %d\n",
__FUNCTION__, retval, *valid_san);
return retval;
}
static krb5_error_code
verify_client_eku(krb5_context context,
pkinit_kdc_context plgctx,
pkinit_kdc_req_context reqctx,
int *eku_accepted)
{
krb5_error_code retval;
*eku_accepted = 0;
if (plgctx->opts->require_eku == 0) {
TRACE_PKINIT_SERVER_EKU_SKIP(context);
*eku_accepted = 1;
retval = 0;
goto out;
}
retval = crypto_check_cert_eku(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
0, /* kdc cert */
plgctx->opts->accept_secondary_eku,
eku_accepted);
if (retval) {
pkiDebug("%s: Error from crypto_check_cert_eku %d (%s)\n",
__FUNCTION__, retval, error_message(retval));
goto out;
}
out:
pkiDebug("%s: returning retval %d, eku_accepted %d\n",
__FUNCTION__, retval, *eku_accepted);
return retval;
}
/* Run the received, verified certificate through certauth modules, to verify
* that it is authorized to authenticate as client. */
static krb5_error_code
authorize_cert(krb5_context context, certauth_handle *certauth_modules,
pkinit_kdc_context plgctx, pkinit_kdc_req_context reqctx,
krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock,
krb5_principal client)
{
krb5_error_code ret;
certauth_handle h;
struct certauth_req_opts opts;
krb5_boolean accepted = FALSE;
uint8_t *cert;
size_t i, cert_len;
void *db_ent = NULL;
char **ais = NULL, **ai = NULL;
/* Re-encode the received certificate into DER, which is extra work, but
* avoids creating an X.509 library dependency in the interface. */
ret = crypto_encode_der_cert(context, reqctx->cryptoctx, &cert, &cert_len);
if (ret)
goto cleanup;
/* Set options for the builtin module. */
opts.plgctx = plgctx;
opts.reqctx = reqctx;
opts.cb = cb;
opts.rock = rock;
db_ent = cb->client_entry(context, rock);
/*
* Check the certificate against each certauth module. For the certificate
* to be authorized at least one module must return 0, and no module can an
* error code other than KRB5_PLUGIN_NO_HANDLE (pass). Add indicators from
* modules that return 0 or pass.
*/
ret = KRB5_PLUGIN_NO_HANDLE;
for (i = 0; certauth_modules != NULL && certauth_modules[i] != NULL; i++) {
h = certauth_modules[i];
TRACE_PKINIT_SERVER_CERT_AUTH(context, h->vt.name);
ret = h->vt.authorize(context, h->moddata, cert, cert_len, client,
&opts, db_ent, &ais);
if (ret == 0)
accepted = TRUE;
else if (ret != KRB5_PLUGIN_NO_HANDLE)
goto cleanup;
if (ais != NULL) {
/* Assert authentication indicators from the module. */
for (ai = ais; *ai != NULL; ai++) {
ret = cb->add_auth_indicator(context, rock, *ai);
if (ret)
goto cleanup;
}
h->vt.free_ind(context, h->moddata, ais);
ais = NULL;
}
}
ret = accepted ? 0 : KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
cleanup:
free(cert);
return ret;
}
static void
pkinit_server_verify_padata(krb5_context context,
krb5_data *req_pkt,
krb5_kdc_req * request,
krb5_enc_tkt_part * enc_tkt_reply,
krb5_pa_data * data,
krb5_kdcpreauth_callbacks cb,
krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata,
krb5_kdcpreauth_verify_respond_fn respond,
void *arg)
{
krb5_error_code retval = 0;
krb5_data authp_data = {0, 0, NULL}, krb5_authz = {0, 0, NULL};
krb5_pa_pk_as_req *reqp = NULL;
krb5_pa_pk_as_req_draft9 *reqp9 = NULL;
krb5_auth_pack *auth_pack = NULL;
krb5_auth_pack_draft9 *auth_pack9 = NULL;
pkinit_kdc_context plgctx = NULL;
pkinit_kdc_req_context reqctx = NULL;
krb5_checksum cksum = {0, 0, 0, NULL};
krb5_data *der_req = NULL;
krb5_data k5data;
int is_signed = 1;
krb5_pa_data **e_data = NULL;
krb5_kdcpreauth_modreq modreq = NULL;
char **sp;
pkiDebug("pkinit_verify_padata: entered!\n");
if (data == NULL || data->length <= 0 || data->contents == NULL) {
(*respond)(arg, EINVAL, NULL, NULL, NULL);
return;
}
if (moddata == NULL) {
(*respond)(arg, EINVAL, NULL, NULL, NULL);
return;
}
plgctx = pkinit_find_realm_context(context, moddata, request->server);
if (plgctx == NULL) {
(*respond)(arg, EINVAL, NULL, NULL, NULL);
return;
}
#ifdef DEBUG_ASN1
print_buffer_bin(data->contents, data->length, "/tmp/kdc_as_req");
#endif
/* create a per-request context */
retval = pkinit_init_kdc_req_context(context, &reqctx);
if (retval)
goto cleanup;
reqctx->pa_type = data->pa_type;
PADATA_TO_KRB5DATA(data, &k5data);
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
TRACE_PKINIT_SERVER_PADATA_VERIFY(context);
retval = k5int_decode_krb5_pa_pk_as_req(&k5data, &reqp);
if (retval) {
pkiDebug("decode_krb5_pa_pk_as_req failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin(reqp->signedAuthPack.data,
reqp->signedAuthPack.length,
"/tmp/kdc_signed_data");
#endif
retval = cms_signeddata_verify(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_CLIENT,
plgctx->opts->require_crl_checking,
(unsigned char *)
reqp->signedAuthPack.data, reqp->signedAuthPack.length,
(unsigned char **)&authp_data.data,
&authp_data.length,
(unsigned char **)&krb5_authz.data,
&krb5_authz.length, &is_signed);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
TRACE_PKINIT_SERVER_PADATA_VERIFY_OLD(context);
retval = k5int_decode_krb5_pa_pk_as_req_draft9(&k5data, &reqp9);
if (retval) {
pkiDebug("decode_krb5_pa_pk_as_req_draft9 failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin(reqp9->signedAuthPack.data,
reqp9->signedAuthPack.length,
"/tmp/kdc_signed_data_draft9");
#endif
retval = cms_signeddata_verify(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_DRAFT9,
plgctx->opts->require_crl_checking,
(unsigned char *)
reqp9->signedAuthPack.data, reqp9->signedAuthPack.length,
(unsigned char **)&authp_data.data,
&authp_data.length,
(unsigned char **)&krb5_authz.data,
&krb5_authz.length, NULL);
break;
default:
pkiDebug("unrecognized pa_type = %d\n", data->pa_type);
retval = EINVAL;
goto cleanup;
}
if (retval) {
TRACE_PKINIT_SERVER_PADATA_VERIFY_FAIL(context);
goto cleanup;
}
if (is_signed) {
retval = authorize_cert(context, moddata->certauth_modules, plgctx,
reqctx, cb, rock, request->client);
if (retval)
goto cleanup;
} else { /* !is_signed */
if (!krb5_principal_compare(context, request->client,
krb5_anonymous_principal())) {
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval,
_("Pkinit request not signed, but client "
"not anonymous."));
goto cleanup;
}
}
#ifdef DEBUG_ASN1
print_buffer_bin(authp_data.data, authp_data.length, "/tmp/kdc_auth_pack");
#endif
OCTETDATA_TO_KRB5DATA(&authp_data, &k5data);
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
retval = k5int_decode_krb5_auth_pack(&k5data, &auth_pack);
if (retval) {
pkiDebug("failed to decode krb5_auth_pack\n");
goto cleanup;
}
retval = krb5_check_clockskew(context,
auth_pack->pkAuthenticator.ctime);
if (retval)
goto cleanup;
/* check dh parameters */
if (auth_pack->clientPublicValue != NULL) {
retval = server_check_dh(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
&auth_pack->clientPublicValue->algorithm.parameters,
plgctx->opts->dh_min_bits);
if (retval) {
pkiDebug("bad dh parameters\n");
goto cleanup;
}
} else if (!is_signed) {
/*Anonymous pkinit requires DH*/
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval,
_("Anonymous pkinit without DH public "
"value not supported."));
goto cleanup;
}
der_req = cb->request_body(context, rock);
retval = krb5_c_make_checksum(context, CKSUMTYPE_NIST_SHA, NULL,
0, der_req, &cksum);
if (retval) {
pkiDebug("unable to calculate AS REQ checksum\n");
goto cleanup;
}
if (cksum.length != auth_pack->pkAuthenticator.paChecksum.length ||
k5_bcmp(cksum.contents,
auth_pack->pkAuthenticator.paChecksum.contents,
cksum.length) != 0) {
pkiDebug("failed to match the checksum\n");
#ifdef DEBUG_CKSUM
pkiDebug("calculating checksum on buf size (%d)\n",
req_pkt->length);
print_buffer(req_pkt->data, req_pkt->length);
pkiDebug("received checksum type=%d size=%d ",
auth_pack->pkAuthenticator.paChecksum.checksum_type,
auth_pack->pkAuthenticator.paChecksum.length);
print_buffer(auth_pack->pkAuthenticator.paChecksum.contents,
auth_pack->pkAuthenticator.paChecksum.length);
pkiDebug("expected checksum type=%d size=%d ",
cksum.checksum_type, cksum.length);
print_buffer(cksum.contents, cksum.length);
#endif
retval = KRB5KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED;
goto cleanup;
}
/* check if kdcPkId present and match KDC's subjectIdentifier */
if (reqp->kdcPkId.data != NULL) {
int valid_kdcPkId = 0;
retval = pkinit_check_kdc_pkid(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
(unsigned char *)reqp->kdcPkId.data,
reqp->kdcPkId.length, &valid_kdcPkId);
if (retval)
goto cleanup;
if (!valid_kdcPkId)
pkiDebug("kdcPkId in AS_REQ does not match KDC's cert"
"RFC says to ignore and proceed\n");
}
/* remember the decoded auth_pack for verify_padata routine */
reqctx->rcv_auth_pack = auth_pack;
auth_pack = NULL;
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = k5int_decode_krb5_auth_pack_draft9(&k5data, &auth_pack9);
if (retval) {
pkiDebug("failed to decode krb5_auth_pack_draft9\n");
goto cleanup;
}
if (auth_pack9->clientPublicValue != NULL) {
retval = server_check_dh(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
&auth_pack9->clientPublicValue->algorithm.parameters,
plgctx->opts->dh_min_bits);
if (retval) {
pkiDebug("bad dh parameters\n");
goto cleanup;
}
}
/* remember the decoded auth_pack for verify_padata routine */
reqctx->rcv_auth_pack9 = auth_pack9;
auth_pack9 = NULL;
break;
}
if (is_signed && plgctx->auth_indicators != NULL) {
/* Assert configured authentication indicators. */
for (sp = plgctx->auth_indicators; *sp != NULL; sp++) {
retval = cb->add_auth_indicator(context, rock, *sp);
if (retval)
goto cleanup;
}
}
/* remember to set the PREAUTH flag in the reply */
enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH;
modreq = (krb5_kdcpreauth_modreq)reqctx;
reqctx = NULL;
cleanup:
if (retval && data->pa_type == KRB5_PADATA_PK_AS_REQ) {
pkiDebug("pkinit_verify_padata failed: creating e-data\n");
if (pkinit_create_edata(context, plgctx->cryptoctx, reqctx->cryptoctx,
plgctx->idctx, plgctx->opts, retval, &e_data))
pkiDebug("pkinit_create_edata failed\n");
}
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
free_krb5_pa_pk_as_req(&reqp);
free(cksum.contents);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
free_krb5_pa_pk_as_req_draft9(&reqp9);
}
free(authp_data.data);
free(krb5_authz.data);
if (reqctx != NULL)
pkinit_fini_kdc_req_context(context, reqctx);
free_krb5_auth_pack(&auth_pack);
free_krb5_auth_pack_draft9(context, &auth_pack9);
(*respond)(arg, retval, modreq, e_data, NULL);
}
static krb5_error_code
return_pkinit_kx(krb5_context context, krb5_kdc_req *request,
krb5_kdc_rep *reply, krb5_keyblock *encrypting_key,
krb5_pa_data **out_padata)
{
krb5_error_code ret = 0;
krb5_keyblock *session = reply->ticket->enc_part2->session;
krb5_keyblock *new_session = NULL;
krb5_pa_data *pa = NULL;
krb5_enc_data enc;
krb5_data *scratch = NULL;
*out_padata = NULL;
enc.ciphertext.data = NULL;
if (!krb5_principal_compare(context, request->client,
krb5_anonymous_principal()))
return 0;
/*
* The KDC contribution key needs to be a fresh key of an enctype supported
* by the client and server. The existing session key meets these
* requirements so we use it.
*/
ret = krb5_c_fx_cf2_simple(context, session, "PKINIT",
encrypting_key, "KEYEXCHANGE",
&new_session);
if (ret)
goto cleanup;
ret = encode_krb5_encryption_key( session, &scratch);
if (ret)
goto cleanup;
ret = krb5_encrypt_helper(context, encrypting_key,
KRB5_KEYUSAGE_PA_PKINIT_KX, scratch, &enc);
if (ret)
goto cleanup;
memset(scratch->data, 0, scratch->length);
krb5_free_data(context, scratch);
scratch = NULL;
ret = encode_krb5_enc_data(&enc, &scratch);
if (ret)
goto cleanup;
pa = malloc(sizeof(krb5_pa_data));
if (pa == NULL) {
ret = ENOMEM;
goto cleanup;
}
pa->pa_type = KRB5_PADATA_PKINIT_KX;
pa->length = scratch->length;
pa->contents = (krb5_octet *) scratch->data;
*out_padata = pa;
scratch->data = NULL;
memset(session->contents, 0, session->length);
krb5_free_keyblock_contents(context, session);
*session = *new_session;
new_session->contents = NULL;
cleanup:
krb5_free_data_contents(context, &enc.ciphertext);
krb5_free_keyblock(context, new_session);
krb5_free_data(context, scratch);
return ret;
}
static krb5_error_code
pkinit_pick_kdf_alg(krb5_context context, krb5_data **kdf_list,
krb5_data **alg_oid)
{
krb5_error_code retval = 0;
krb5_data *req_oid = NULL;
const krb5_data *supp_oid = NULL;
krb5_data *tmp_oid = NULL;
int i, j = 0;
/* if we don't find a match, return NULL value */
*alg_oid = NULL;
/* for each of the OIDs that the server supports... */
for (i = 0; NULL != (supp_oid = supported_kdf_alg_ids[i]); i++) {
/* if the requested OID is in the client's list, use it. */
for (j = 0; NULL != (req_oid = kdf_list[j]); j++) {
if ((req_oid->length == supp_oid->length) &&
(0 == memcmp(req_oid->data, supp_oid->data, req_oid->length))) {
tmp_oid = k5alloc(sizeof(krb5_data), &retval);
if (retval)
goto cleanup;
tmp_oid->data = k5memdup(supp_oid->data, supp_oid->length,
&retval);
if (retval)
goto cleanup;
tmp_oid->length = supp_oid->length;
*alg_oid = tmp_oid;
/* don't free the OID in clean-up if we are returning it */
tmp_oid = NULL;
goto cleanup;
}
}
}
cleanup:
if (tmp_oid)
krb5_free_data(context, tmp_oid);
return retval;
}
static krb5_error_code
pkinit_server_return_padata(krb5_context context,
krb5_pa_data * padata,
krb5_data *req_pkt,
krb5_kdc_req * request,
krb5_kdc_rep * reply,
krb5_keyblock * encrypting_key,
krb5_pa_data ** send_pa,
krb5_kdcpreauth_callbacks cb,
krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata,
krb5_kdcpreauth_modreq modreq)
{
krb5_error_code retval = 0;
krb5_data scratch = {0, 0, NULL};
krb5_pa_pk_as_req *reqp = NULL;
krb5_pa_pk_as_req_draft9 *reqp9 = NULL;
int i = 0;
unsigned char *subjectPublicKey = NULL;
unsigned char *dh_pubkey = NULL, *server_key = NULL;
unsigned int subjectPublicKey_len = 0;
unsigned int server_key_len = 0, dh_pubkey_len = 0;
krb5_kdc_dh_key_info dhkey_info;
krb5_data *encoded_dhkey_info = NULL;
krb5_pa_pk_as_rep *rep = NULL;
krb5_pa_pk_as_rep_draft9 *rep9 = NULL;
krb5_data *out_data = NULL;
krb5_data secret;
krb5_enctype enctype = -1;
krb5_reply_key_pack *key_pack = NULL;
krb5_reply_key_pack_draft9 *key_pack9 = NULL;
krb5_data *encoded_key_pack = NULL;
pkinit_kdc_context plgctx;
pkinit_kdc_req_context reqctx;
int fixed_keypack = 0;
*send_pa = NULL;
if (padata->pa_type == KRB5_PADATA_PKINIT_KX) {
return return_pkinit_kx(context, request, reply,
encrypting_key, send_pa);
}
if (padata->length <= 0 || padata->contents == NULL)
return 0;
if (modreq == NULL) {
pkiDebug("missing request context \n");
return EINVAL;
}
plgctx = pkinit_find_realm_context(context, moddata, request->server);
if (plgctx == NULL) {
pkiDebug("Unable to locate correct realm context\n");
return ENOENT;
}
TRACE_PKINIT_SERVER_RETURN_PADATA(context);
reqctx = (pkinit_kdc_req_context)modreq;
if (encrypting_key->contents) {
free(encrypting_key->contents);
encrypting_key->length = 0;
encrypting_key->contents = NULL;
}
for(i = 0; i < request->nktypes; i++) {
enctype = request->ktype[i];
if (!krb5_c_valid_enctype(enctype))
continue;
else {
pkiDebug("KDC picked etype = %d\n", enctype);
break;
}
}
if (i == request->nktypes) {
retval = KRB5KDC_ERR_ETYPE_NOSUPP;
goto cleanup;
}
switch((int)reqctx->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
init_krb5_pa_pk_as_rep(&rep);
if (rep == NULL) {
retval = ENOMEM;
goto cleanup;
}
/* let's assume it's RSA. we'll reset it to DH if needed */
rep->choice = choice_pa_pk_as_rep_encKeyPack;
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
init_krb5_pa_pk_as_rep_draft9(&rep9);
if (rep9 == NULL) {
retval = ENOMEM;
goto cleanup;
}
rep9->choice = choice_pa_pk_as_rep_draft9_encKeyPack;
break;
default:
retval = KRB5KDC_ERR_PREAUTH_FAILED;
goto cleanup;
}
if (reqctx->rcv_auth_pack != NULL &&
reqctx->rcv_auth_pack->clientPublicValue != NULL) {
subjectPublicKey = (unsigned char *)
reqctx->rcv_auth_pack->clientPublicValue->subjectPublicKey.data;
subjectPublicKey_len =
reqctx->rcv_auth_pack->clientPublicValue->subjectPublicKey.length;
rep->choice = choice_pa_pk_as_rep_dhInfo;
} else if (reqctx->rcv_auth_pack9 != NULL &&
reqctx->rcv_auth_pack9->clientPublicValue != NULL) {
subjectPublicKey = (unsigned char *)
reqctx->rcv_auth_pack9->clientPublicValue->subjectPublicKey.data;
subjectPublicKey_len =
reqctx->rcv_auth_pack9->clientPublicValue->subjectPublicKey.length;
rep9->choice = choice_pa_pk_as_rep_draft9_dhSignedData;
}
/* if this DH, then process finish computing DH key */
if (rep != NULL && (rep->choice == choice_pa_pk_as_rep_dhInfo ||
rep->choice == choice_pa_pk_as_rep_draft9_dhSignedData)) {
pkiDebug("received DH key delivery AS REQ\n");
retval = server_process_dh(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, subjectPublicKey,
subjectPublicKey_len, &dh_pubkey, &dh_pubkey_len,
&server_key, &server_key_len);
if (retval) {
pkiDebug("failed to process/create dh paramters\n");
goto cleanup;
}
}
if ((rep9 != NULL &&
rep9->choice == choice_pa_pk_as_rep_draft9_dhSignedData) ||
(rep != NULL && rep->choice == choice_pa_pk_as_rep_dhInfo)) {
/*
* This is DH, so don't generate the key until after we
* encode the reply, because the encoded reply is needed
* to generate the key in some cases.
*/
dhkey_info.subjectPublicKey.length = dh_pubkey_len;
dhkey_info.subjectPublicKey.data = (char *)dh_pubkey;
dhkey_info.nonce = request->nonce;
dhkey_info.dhKeyExpiration = 0;
retval = k5int_encode_krb5_kdc_dh_key_info(&dhkey_info,
&encoded_dhkey_info);
if (retval) {
pkiDebug("encode_krb5_kdc_dh_key_info failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)encoded_dhkey_info->data,
encoded_dhkey_info->length,
"/tmp/kdc_dh_key_info");
#endif
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
retval = cms_signeddata_create(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_SERVER, 1,
(unsigned char *)
encoded_dhkey_info->data,
encoded_dhkey_info->length,
(unsigned char **)
&rep->u.dh_Info.dhSignedData.data,
&rep->u.dh_Info.dhSignedData.length);
if (retval) {
pkiDebug("failed to create pkcs7 signed data\n");
goto cleanup;
}
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = cms_signeddata_create(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_DRAFT9, 1,
(unsigned char *)
encoded_dhkey_info->data,
encoded_dhkey_info->length,
(unsigned char **)
&rep9->u.dhSignedData.data,
&rep9->u.dhSignedData.length);
if (retval) {
pkiDebug("failed to create pkcs7 signed data\n");
goto cleanup;
}
break;
}
} else {
pkiDebug("received RSA key delivery AS REQ\n");
retval = krb5_c_make_random_key(context, enctype, encrypting_key);
if (retval) {
pkiDebug("unable to make a session key\n");
goto cleanup;
}
/* check if PA_TYPE of KRB5_PADATA_AS_CHECKSUM (132) is present which
* means the client is requesting that a checksum is send back instead
* of the nonce.
*/
for (i = 0; request->padata[i] != NULL; i++) {
pkiDebug("%s: Checking pa_type 0x%08x\n",
__FUNCTION__, request->padata[i]->pa_type);
if (request->padata[i]->pa_type == KRB5_PADATA_AS_CHECKSUM)
fixed_keypack = 1;
}
pkiDebug("%s: return checksum instead of nonce = %d\n",
__FUNCTION__, fixed_keypack);
/* if this is an RFC reply or draft9 client requested a checksum
* in the reply instead of the nonce, create an RFC-style keypack
*/
if ((int)padata->pa_type == KRB5_PADATA_PK_AS_REQ || fixed_keypack) {
init_krb5_reply_key_pack(&key_pack);
if (key_pack == NULL) {
retval = ENOMEM;
goto cleanup;
}
retval = krb5_c_make_checksum(context, 0,
encrypting_key, KRB5_KEYUSAGE_TGS_REQ_AUTH_CKSUM,
req_pkt, &key_pack->asChecksum);
if (retval) {
pkiDebug("unable to calculate AS REQ checksum\n");
goto cleanup;
}
#ifdef DEBUG_CKSUM
pkiDebug("calculating checksum on buf size = %d\n", req_pkt->length);
print_buffer(req_pkt->data, req_pkt->length);
pkiDebug("checksum size = %d\n", key_pack->asChecksum.length);
print_buffer(key_pack->asChecksum.contents,
key_pack->asChecksum.length);
pkiDebug("encrypting key (%d)\n", encrypting_key->length);
print_buffer(encrypting_key->contents, encrypting_key->length);
#endif
krb5_copy_keyblock_contents(context, encrypting_key,
&key_pack->replyKey);
retval = k5int_encode_krb5_reply_key_pack(key_pack,
&encoded_key_pack);
if (retval) {
pkiDebug("failed to encode reply_key_pack\n");
goto cleanup;
}
}
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
rep->choice = choice_pa_pk_as_rep_encKeyPack;
retval = cms_envelopeddata_create(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, padata->pa_type, 1,
(unsigned char *)
encoded_key_pack->data,
encoded_key_pack->length,
(unsigned char **)
&rep->u.encKeyPack.data,
&rep->u.encKeyPack.length);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
/* if the request is from the broken draft9 client that
* expects back a nonce, create it now
*/
if (!fixed_keypack) {
init_krb5_reply_key_pack_draft9(&key_pack9);
if (key_pack9 == NULL) {
retval = ENOMEM;
goto cleanup;
}
key_pack9->nonce = reqctx->rcv_auth_pack9->pkAuthenticator.nonce;
krb5_copy_keyblock_contents(context, encrypting_key,
&key_pack9->replyKey);
retval = k5int_encode_krb5_reply_key_pack_draft9(key_pack9,
&encoded_key_pack);
if (retval) {
pkiDebug("failed to encode reply_key_pack\n");
goto cleanup;
}
}
rep9->choice = choice_pa_pk_as_rep_draft9_encKeyPack;
retval = cms_envelopeddata_create(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, padata->pa_type, 1,
(unsigned char *)
encoded_key_pack->data,
encoded_key_pack->length,
(unsigned char **)
&rep9->u.encKeyPack.data, &rep9->u.encKeyPack.length);
break;
}
if (retval) {
pkiDebug("failed to create pkcs7 enveloped data: %s\n",
error_message(retval));
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)encoded_key_pack->data,
encoded_key_pack->length,
"/tmp/kdc_key_pack");
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
print_buffer_bin(rep->u.encKeyPack.data,
rep->u.encKeyPack.length,
"/tmp/kdc_enc_key_pack");
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
print_buffer_bin(rep9->u.encKeyPack.data,
rep9->u.encKeyPack.length,
"/tmp/kdc_enc_key_pack");
break;
}
#endif
}
if ((rep != NULL && rep->choice == choice_pa_pk_as_rep_dhInfo) &&
((reqctx->rcv_auth_pack != NULL &&
reqctx->rcv_auth_pack->supportedKDFs != NULL))) {
/* If using the alg-agility KDF, put the algorithm in the reply
* before encoding it.
*/
if (reqctx->rcv_auth_pack != NULL &&
reqctx->rcv_auth_pack->supportedKDFs != NULL) {
retval = pkinit_pick_kdf_alg(context, reqctx->rcv_auth_pack->supportedKDFs,
&(rep->u.dh_Info.kdfID));
if (retval) {
pkiDebug("pkinit_pick_kdf_alg failed: %s\n",
error_message(retval));
goto cleanup;
}
}
}
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
retval = k5int_encode_krb5_pa_pk_as_rep(rep, &out_data);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = k5int_encode_krb5_pa_pk_as_rep_draft9(rep9, &out_data);
break;
}
if (retval) {
pkiDebug("failed to encode AS_REP\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
if (out_data != NULL)
print_buffer_bin((unsigned char *)out_data->data, out_data->length,
"/tmp/kdc_as_rep");
#endif
/* If this is DH, we haven't computed the key yet, so do it now. */
if ((rep9 != NULL &&
rep9->choice == choice_pa_pk_as_rep_draft9_dhSignedData) ||
(rep != NULL && rep->choice == choice_pa_pk_as_rep_dhInfo)) {
/* If we're not doing draft 9, and mutually supported KDFs were found,
* use the algorithm agility KDF. */
if (rep != NULL && rep->u.dh_Info.kdfID) {
secret.data = (char *)server_key;
secret.length = server_key_len;
retval = pkinit_alg_agility_kdf(context, &secret,
rep->u.dh_Info.kdfID,
request->client, request->server,
enctype, req_pkt, out_data,
encrypting_key);
if (retval) {
pkiDebug("pkinit_alg_agility_kdf failed: %s\n",
error_message(retval));
goto cleanup;
}
/* Otherwise, use the older octetstring2key() function */
} else {
retval = pkinit_octetstring2key(context, enctype, server_key,
server_key_len, encrypting_key);
if (retval) {
pkiDebug("pkinit_octetstring2key failed: %s\n",
error_message(retval));
goto cleanup;
}
}
}
*send_pa = malloc(sizeof(krb5_pa_data));
if (*send_pa == NULL) {
retval = ENOMEM;
free(out_data->data);
free(out_data);
out_data = NULL;
goto cleanup;
}
(*send_pa)->magic = KV5M_PA_DATA;
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
(*send_pa)->pa_type = KRB5_PADATA_PK_AS_REP;
break;
case KRB5_PADATA_PK_AS_REQ_OLD:
case KRB5_PADATA_PK_AS_REP_OLD:
(*send_pa)->pa_type = KRB5_PADATA_PK_AS_REP_OLD;
break;
}
(*send_pa)->length = out_data->length;
(*send_pa)->contents = (krb5_octet *) out_data->data;
cleanup:
pkinit_fini_kdc_req_context(context, reqctx);
free(scratch.data);
free(out_data);
if (encoded_dhkey_info != NULL)
krb5_free_data(context, encoded_dhkey_info);
if (encoded_key_pack != NULL)
krb5_free_data(context, encoded_key_pack);
free(dh_pubkey);
free(server_key);
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
free_krb5_pa_pk_as_req(&reqp);
free_krb5_pa_pk_as_rep(&rep);
free_krb5_reply_key_pack(&key_pack);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
free_krb5_pa_pk_as_req_draft9(&reqp9);
free_krb5_pa_pk_as_rep_draft9(&rep9);
if (!fixed_keypack)
free_krb5_reply_key_pack_draft9(&key_pack9);
else
free_krb5_reply_key_pack(&key_pack);
break;
}
if (retval)
pkiDebug("pkinit_verify_padata failure");
return retval;
}
static int
pkinit_server_get_flags(krb5_context kcontext, krb5_preauthtype patype)
{
if (patype == KRB5_PADATA_PKINIT_KX)
return PA_INFO;
return PA_SUFFICIENT | PA_REPLACES_KEY | PA_TYPED_E_DATA;
}
static krb5_preauthtype supported_server_pa_types[] = {
KRB5_PADATA_PK_AS_REQ,
KRB5_PADATA_PK_AS_REQ_OLD,
KRB5_PADATA_PK_AS_REP_OLD,
KRB5_PADATA_PKINIT_KX,
0
};
static void
pkinit_fini_kdc_profile(krb5_context context, pkinit_kdc_context plgctx)
{
/*
* There is nothing currently allocated by pkinit_init_kdc_profile()
* which needs to be freed here.
*/
}
static krb5_error_code
pkinit_init_kdc_profile(krb5_context context, pkinit_kdc_context plgctx)
{
krb5_error_code retval;
char *eku_string = NULL, *ocsp_check = NULL;
pkiDebug("%s: entered for realm %s\n", __FUNCTION__, plgctx->realmname);
retval = pkinit_kdcdefault_string(context, plgctx->realmname,
KRB5_CONF_PKINIT_IDENTITY,
&plgctx->idopts->identity);
if (retval != 0 || NULL == plgctx->idopts->identity) {
retval = EINVAL;
krb5_set_error_message(context, retval,
_("No pkinit_identity supplied for realm %s"),
plgctx->realmname);
goto errout;
}
retval = pkinit_kdcdefault_strings(context, plgctx->realmname,
KRB5_CONF_PKINIT_ANCHORS,
&plgctx->idopts->anchors);
if (retval != 0 || NULL == plgctx->idopts->anchors) {
retval = EINVAL;
krb5_set_error_message(context, retval,
_("No pkinit_anchors supplied for realm %s"),
plgctx->realmname);
goto errout;
}
pkinit_kdcdefault_strings(context, plgctx->realmname,
KRB5_CONF_PKINIT_POOL,
&plgctx->idopts->intermediates);
pkinit_kdcdefault_strings(context, plgctx->realmname,
KRB5_CONF_PKINIT_REVOKE,
&plgctx->idopts->crls);
pkinit_kdcdefault_string(context, plgctx->realmname,
KRB5_CONF_PKINIT_KDC_OCSP,
&ocsp_check);
if (ocsp_check != NULL) {
free(ocsp_check);
retval = ENOTSUP;
krb5_set_error_message(context, retval,
_("OCSP is not supported: (realm: %s)"),
plgctx->realmname);
goto errout;
}
pkinit_kdcdefault_integer(context, plgctx->realmname,
KRB5_CONF_PKINIT_DH_MIN_BITS,
PKINIT_DEFAULT_DH_MIN_BITS,
&plgctx->opts->dh_min_bits);
if (plgctx->opts->dh_min_bits < PKINIT_DH_MIN_CONFIG_BITS) {
pkiDebug("%s: invalid value (%d < %d) for pkinit_dh_min_bits, "
"using default value (%d) instead\n", __FUNCTION__,
plgctx->opts->dh_min_bits, PKINIT_DH_MIN_CONFIG_BITS,
PKINIT_DEFAULT_DH_MIN_BITS);
plgctx->opts->dh_min_bits = PKINIT_DEFAULT_DH_MIN_BITS;
}
pkinit_kdcdefault_boolean(context, plgctx->realmname,
KRB5_CONF_PKINIT_ALLOW_UPN,
0, &plgctx->opts->allow_upn);
pkinit_kdcdefault_boolean(context, plgctx->realmname,
KRB5_CONF_PKINIT_REQUIRE_CRL_CHECKING,
0, &plgctx->opts->require_crl_checking);
pkinit_kdcdefault_string(context, plgctx->realmname,
KRB5_CONF_PKINIT_EKU_CHECKING,
&eku_string);
if (eku_string != NULL) {
if (strcasecmp(eku_string, "kpClientAuth") == 0) {
plgctx->opts->require_eku = 1;
plgctx->opts->accept_secondary_eku = 0;
} else if (strcasecmp(eku_string, "scLogin") == 0) {
plgctx->opts->require_eku = 1;
plgctx->opts->accept_secondary_eku = 1;
} else if (strcasecmp(eku_string, "none") == 0) {
plgctx->opts->require_eku = 0;
plgctx->opts->accept_secondary_eku = 0;
} else {
pkiDebug("%s: Invalid value for pkinit_eku_checking: '%s'\n",
__FUNCTION__, eku_string);
}
free(eku_string);
}
pkinit_kdcdefault_strings(context, plgctx->realmname,
KRB5_CONF_PKINIT_INDICATOR,
&plgctx->auth_indicators);
return 0;
errout:
pkinit_fini_kdc_profile(context, plgctx);
return retval;
}
static pkinit_kdc_context
pkinit_find_realm_context(krb5_context context,
krb5_kdcpreauth_moddata moddata,
krb5_principal princ)
{
int i;
pkinit_kdc_context *realm_contexts;
if (moddata == NULL)
return NULL;
realm_contexts = moddata->realm_contexts;
if (realm_contexts == NULL)
return NULL;
for (i = 0; realm_contexts[i] != NULL; i++) {
pkinit_kdc_context p = realm_contexts[i];
if ((p->realmname_len == princ->realm.length) &&
(strncmp(p->realmname, princ->realm.data, p->realmname_len) == 0)) {
pkiDebug("%s: returning context at %p for realm '%s'\n",
__FUNCTION__, p, p->realmname);
return p;
}
}
pkiDebug("%s: unable to find realm context for realm '%.*s'\n",
__FUNCTION__, princ->realm.length, princ->realm.data);
return NULL;
}
static int
pkinit_server_plugin_init_realm(krb5_context context, const char *realmname,
pkinit_kdc_context *pplgctx)
{
krb5_error_code retval = ENOMEM;
pkinit_kdc_context plgctx = NULL;
*pplgctx = NULL;
plgctx = calloc(1, sizeof(*plgctx));
if (plgctx == NULL)
goto errout;
pkiDebug("%s: initializing context at %p for realm '%s'\n",
__FUNCTION__, plgctx, realmname);
memset(plgctx, 0, sizeof(*plgctx));
plgctx->magic = PKINIT_CTX_MAGIC;
plgctx->realmname = strdup(realmname);
if (plgctx->realmname == NULL)
goto errout;
plgctx->realmname_len = strlen(plgctx->realmname);
retval = pkinit_init_plg_crypto(&plgctx->cryptoctx);
if (retval)
goto errout;
retval = pkinit_init_plg_opts(&plgctx->opts);
if (retval)
goto errout;
retval = pkinit_init_identity_crypto(&plgctx->idctx);
if (retval)
goto errout;
retval = pkinit_init_identity_opts(&plgctx->idopts);
if (retval)
goto errout;
retval = pkinit_init_kdc_profile(context, plgctx);
if (retval)
goto errout;
retval = pkinit_identity_initialize(context, plgctx->cryptoctx, NULL,
plgctx->idopts, plgctx->idctx,
NULL, NULL, NULL);
if (retval)
goto errout;
retval = pkinit_identity_prompt(context, plgctx->cryptoctx, NULL,
plgctx->idopts, plgctx->idctx,
NULL, NULL, 0, NULL);
if (retval)
goto errout;
pkiDebug("%s: returning context at %p for realm '%s'\n",
__FUNCTION__, plgctx, realmname);
*pplgctx = plgctx;
retval = 0;
errout:
if (retval)
pkinit_server_plugin_fini_realm(context, plgctx);
return retval;
}
static krb5_error_code
pkinit_san_authorize(krb5_context context, krb5_certauth_moddata moddata,
const uint8_t *cert, size_t cert_len,
krb5_const_principal princ, const void *opts,
const struct _krb5_db_entry_new *db_entry,
char ***authinds_out)
{
krb5_error_code ret;
int valid_san;
const struct certauth_req_opts *req_opts = opts;
*authinds_out = NULL;
ret = verify_client_san(context, req_opts->plgctx, req_opts->reqctx,
req_opts->cb, req_opts->rock, princ, &valid_san);
if (ret == ENOENT)
return KRB5_PLUGIN_NO_HANDLE;
else if (ret)
return ret;
if (!valid_san) {
TRACE_PKINIT_SERVER_SAN_REJECT(context);
return KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
}
return 0;
}
static krb5_error_code
pkinit_eku_authorize(krb5_context context, krb5_certauth_moddata moddata,
const uint8_t *cert, size_t cert_len,
krb5_const_principal princ, const void *opts,
const struct _krb5_db_entry_new *db_entry,
char ***authinds_out)
{
krb5_error_code ret;
int valid_eku;
const struct certauth_req_opts *req_opts = opts;
*authinds_out = NULL;
/* Verify the client EKU. */
ret = verify_client_eku(context, req_opts->plgctx, req_opts->reqctx,
&valid_eku);
if (ret)
return ret;
if (!valid_eku) {
TRACE_PKINIT_SERVER_EKU_REJECT(context);
return KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE;
}
return KRB5_PLUGIN_NO_HANDLE;
}
static krb5_error_code
certauth_pkinit_san_initvt(krb5_context context, int maj_ver, int min_ver,
krb5_plugin_vtable vtable)
{
krb5_certauth_vtable vt;
if (maj_ver != 1)
return KRB5_PLUGIN_VER_NOTSUPP;
vt = (krb5_certauth_vtable)vtable;
vt->name = "pkinit_san";
vt->authorize = pkinit_san_authorize;
return 0;
}
static krb5_error_code
certauth_pkinit_eku_initvt(krb5_context context, int maj_ver, int min_ver,
krb5_plugin_vtable vtable)
{
krb5_certauth_vtable vt;
if (maj_ver != 1)
return KRB5_PLUGIN_VER_NOTSUPP;
vt = (krb5_certauth_vtable)vtable;
vt->name = "pkinit_eku";
vt->authorize = pkinit_eku_authorize;
return 0;
}
/*
* Do certificate auth based on a match expression in the pkinit_cert_match
* attribute string. An expression should be in the same form as those used
* for the pkinit_cert_match configuration option.
*/
static krb5_error_code
dbmatch_authorize(krb5_context context, krb5_certauth_moddata moddata,
const uint8_t *cert, size_t cert_len,
krb5_const_principal princ, const void *opts,
const struct _krb5_db_entry_new *db_entry,
char ***authinds_out)
{
krb5_error_code ret;
const struct certauth_req_opts *req_opts = opts;
char *pattern;
krb5_boolean matched;
*authinds_out = NULL;
/* Fetch the matching pattern. Pass if it isn't specified. */
ret = req_opts->cb->get_string(context, req_opts->rock,
"pkinit_cert_match", &pattern);
if (ret)
return ret;
if (pattern == NULL)
return KRB5_PLUGIN_NO_HANDLE;
/* Check the certificate against the match expression. */
ret = pkinit_client_cert_match(context, req_opts->plgctx->cryptoctx,
req_opts->reqctx->cryptoctx, pattern,
&matched);
req_opts->cb->free_string(context, req_opts->rock, pattern);
if (ret)
return ret;
return matched ? 0 : KRB5KDC_ERR_CERTIFICATE_MISMATCH;
}
static krb5_error_code
certauth_dbmatch_initvt(krb5_context context, int maj_ver, int min_ver,
krb5_plugin_vtable vtable)
{
krb5_certauth_vtable vt;
if (maj_ver != 1)
return KRB5_PLUGIN_VER_NOTSUPP;
vt = (krb5_certauth_vtable)vtable;
vt->name = "dbmatch";
vt->authorize = dbmatch_authorize;
return 0;
}
static krb5_error_code
load_certauth_plugins(krb5_context context, certauth_handle **handle_out)
{
krb5_error_code ret;
krb5_plugin_initvt_fn *modules = NULL, *mod;
certauth_handle *list = NULL, h;
size_t count;
/* Register the builtin modules. */
ret = k5_plugin_register(context, PLUGIN_INTERFACE_CERTAUTH,
"pkinit_san", certauth_pkinit_san_initvt);
if (ret)
goto cleanup;
ret = k5_plugin_register(context, PLUGIN_INTERFACE_CERTAUTH,
"pkinit_eku", certauth_pkinit_eku_initvt);
if (ret)
goto cleanup;
ret = k5_plugin_register(context, PLUGIN_INTERFACE_CERTAUTH, "dbmatch",
certauth_dbmatch_initvt);
if (ret)
goto cleanup;
ret = k5_plugin_load_all(context, PLUGIN_INTERFACE_CERTAUTH, &modules);
if (ret)
goto cleanup;
/* Allocate handle list. */
for (count = 0; modules[count]; count++);
list = k5calloc(count + 1, sizeof(*list), &ret);
if (list == NULL)
goto cleanup;
/* Initialize each module, ignoring ones that fail. */
count = 0;
for (mod = modules; *mod != NULL; mod++) {
h = k5calloc(1, sizeof(*h), &ret);
if (h == NULL)
goto cleanup;
ret = (*mod)(context, 1, 1, (krb5_plugin_vtable)&h->vt);
if (ret) {
TRACE_CERTAUTH_VTINIT_FAIL(context, ret);
free(h);
continue;
}
h->moddata = NULL;
if (h->vt.init != NULL) {
ret = h->vt.init(context, &h->moddata);
if (ret) {
TRACE_CERTAUTH_INIT_FAIL(context, h->vt.name, ret);
free(h);
continue;
}
}
list[count++] = h;
list[count] = NULL;
}
list[count] = NULL;
ret = 0;
*handle_out = list;
list = NULL;
cleanup:
k5_plugin_free_modules(context, modules);
free_certauth_handles(context, list);
return ret;
}
static int
pkinit_server_plugin_init(krb5_context context,
krb5_kdcpreauth_moddata *moddata_out,
const char **realmnames)
{
krb5_error_code retval = ENOMEM;
pkinit_kdc_context plgctx, *realm_contexts = NULL;
certauth_handle *certauth_modules = NULL;
krb5_kdcpreauth_moddata moddata;
size_t i, j;
size_t numrealms;
retval = pkinit_accessor_init();
if (retval)
return retval;
/* Determine how many realms we may need to support */
for (i = 0; realmnames[i] != NULL; i++) {};
numrealms = i;
realm_contexts = calloc(numrealms+1, sizeof(pkinit_kdc_context));
if (realm_contexts == NULL)
return ENOMEM;
for (i = 0, j = 0; i < numrealms; i++) {
TRACE_PKINIT_SERVER_INIT_REALM(context, realmnames[i]);
retval = pkinit_server_plugin_init_realm(context, realmnames[i], &plgctx);
if (retval == 0 && plgctx != NULL)
realm_contexts[j++] = plgctx;
}
if (j == 0) {
retval = EINVAL;
krb5_set_error_message(context, retval,
_("No realms configured correctly for pkinit "
"support"));
goto errout;
}
retval = load_certauth_plugins(context, &certauth_modules);
if (retval)
goto errout;
moddata = k5calloc(1, sizeof(*moddata), &retval);
if (moddata == NULL)
goto errout;
moddata->realm_contexts = realm_contexts;
moddata->certauth_modules = certauth_modules;
*moddata_out = moddata;
pkiDebug("%s: returning context at %p\n", __FUNCTION__, moddata);
return 0;
errout:
free_realm_contexts(context, realm_contexts);
free_certauth_handles(context, certauth_modules);
return retval;
}
static void
pkinit_server_plugin_fini_realm(krb5_context context, pkinit_kdc_context plgctx)
{
char **sp;
if (plgctx == NULL)
return;
pkinit_fini_kdc_profile(context, plgctx);
pkinit_fini_identity_opts(plgctx->idopts);
pkinit_fini_identity_crypto(plgctx->idctx);
pkinit_fini_plg_crypto(plgctx->cryptoctx);
pkinit_fini_plg_opts(plgctx->opts);
for (sp = plgctx->auth_indicators; sp != NULL && *sp != NULL; sp++)
free(*sp);
free(plgctx->auth_indicators);
free(plgctx->realmname);
free(plgctx);
}
static void
pkinit_server_plugin_fini(krb5_context context,
krb5_kdcpreauth_moddata moddata)
{
if (moddata == NULL)
return;
free_realm_contexts(context, moddata->realm_contexts);
free_certauth_handles(context, moddata->certauth_modules);
free(moddata);
}
static krb5_error_code
pkinit_init_kdc_req_context(krb5_context context, pkinit_kdc_req_context *ctx)
{
krb5_error_code retval = ENOMEM;
pkinit_kdc_req_context reqctx = NULL;
reqctx = malloc(sizeof(*reqctx));
if (reqctx == NULL)
return retval;
memset(reqctx, 0, sizeof(*reqctx));
reqctx->magic = PKINIT_CTX_MAGIC;
retval = pkinit_init_req_crypto(&reqctx->cryptoctx);
if (retval)
goto cleanup;
reqctx->rcv_auth_pack = NULL;
reqctx->rcv_auth_pack9 = NULL;
pkiDebug("%s: returning reqctx at %p\n", __FUNCTION__, reqctx);
*ctx = reqctx;
retval = 0;
cleanup:
if (retval)
pkinit_fini_kdc_req_context(context, reqctx);
return retval;
}
static void
pkinit_fini_kdc_req_context(krb5_context context, void *ctx)
{
pkinit_kdc_req_context reqctx = (pkinit_kdc_req_context)ctx;
if (reqctx == NULL || reqctx->magic != PKINIT_CTX_MAGIC) {
pkiDebug("pkinit_fini_kdc_req_context: got bad reqctx (%p)!\n", reqctx);
return;
}
pkiDebug("%s: freeing reqctx at %p\n", __FUNCTION__, reqctx);
pkinit_fini_req_crypto(reqctx->cryptoctx);
if (reqctx->rcv_auth_pack != NULL)
free_krb5_auth_pack(&reqctx->rcv_auth_pack);
if (reqctx->rcv_auth_pack9 != NULL)
free_krb5_auth_pack_draft9(context, &reqctx->rcv_auth_pack9);
free(reqctx);
}
krb5_error_code
kdcpreauth_pkinit_initvt(krb5_context context, int maj_ver, int min_ver,
krb5_plugin_vtable vtable);
krb5_error_code
kdcpreauth_pkinit_initvt(krb5_context context, int maj_ver, int min_ver,
krb5_plugin_vtable vtable)
{
krb5_kdcpreauth_vtable vt;
if (maj_ver != 1)
return KRB5_PLUGIN_VER_NOTSUPP;
vt = (krb5_kdcpreauth_vtable)vtable;
vt->name = "pkinit";
vt->pa_type_list = supported_server_pa_types;
vt->init = pkinit_server_plugin_init;
vt->fini = pkinit_server_plugin_fini;
vt->flags = pkinit_server_get_flags;
vt->edata = pkinit_server_get_edata;
vt->verify = pkinit_server_verify_padata;
vt->return_padata = pkinit_server_return_padata;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/good_3281_1 |
crossvul-cpp_data_good_2222_0 | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/* Cherokee
*
* Authors:
* Alvaro Lopez Ortega <alvaro@alobbs.com>
*
* Copyright (C) 2001-2014 Alvaro Lopez Ortega
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include "common-internal.h"
#include <errno.h>
#include "plugin_loader.h"
#include "validator_ldap.h"
#include "connection-protected.h"
#include "util.h"
#define ENTRIES "validator,ldap"
#define LDAP_DEFAULT_PORT 389
#ifndef LDAP_OPT_SUCCESS
# define LDAP_OPT_SUCCESS 0
#endif
/* Plug-in initialization
*/
PLUGIN_INFO_VALIDATOR_EASIEST_INIT (ldap, http_auth_basic);
static ret_t
props_free (cherokee_validator_ldap_props_t *props)
{
cherokee_buffer_mrproper (&props->server);
cherokee_buffer_mrproper (&props->binddn);
cherokee_buffer_mrproper (&props->bindpw);
cherokee_buffer_mrproper (&props->basedn);
cherokee_buffer_mrproper (&props->filter);
cherokee_buffer_mrproper (&props->ca_file);
return cherokee_validator_props_free_base (VALIDATOR_PROPS(props));
}
ret_t
cherokee_validator_ldap_configure (cherokee_config_node_t *conf, cherokee_server_t *srv, cherokee_module_props_t **_props)
{
ret_t ret;
cherokee_list_t *i;
cherokee_validator_ldap_props_t *props;
UNUSED(srv);
if (*_props == NULL) {
CHEROKEE_NEW_STRUCT (n, validator_ldap_props);
cherokee_validator_props_init_base (VALIDATOR_PROPS(n), MODULE_PROPS_FREE(props_free));
n->port = LDAP_DEFAULT_PORT;
n->tls = false;
cherokee_buffer_init (&n->server);
cherokee_buffer_init (&n->binddn);
cherokee_buffer_init (&n->bindpw);
cherokee_buffer_init (&n->basedn);
cherokee_buffer_init (&n->filter);
cherokee_buffer_init (&n->ca_file);
*_props = MODULE_PROPS(n);
}
props = PROP_LDAP(*_props);
cherokee_config_node_foreach (i, conf) {
cherokee_config_node_t *subconf = CONFIG_NODE(i);
if (equal_buf_str (&subconf->key, "server")) {
cherokee_buffer_add_buffer (&props->server, &subconf->val);
} else if (equal_buf_str (&subconf->key, "port")) {
ret = cherokee_atoi (subconf->val.buf, &props->port);
if (ret != ret_ok) return ret_error;
} else if (equal_buf_str (&subconf->key, "bind_dn")) {
cherokee_buffer_add_buffer (&props->binddn, &subconf->val);
} else if (equal_buf_str (&subconf->key, "bind_pw")) {
cherokee_buffer_add_buffer (&props->bindpw, &subconf->val);
} else if (equal_buf_str (&subconf->key, "base_dn")) {
cherokee_buffer_add_buffer (&props->basedn, &subconf->val);
} else if (equal_buf_str (&subconf->key, "filter")) {
cherokee_buffer_add_buffer (&props->filter, &subconf->val);
} else if (equal_buf_str (&subconf->key, "tls")) {
ret = cherokee_atob (subconf->val.buf, &props->tls);
if (ret != ret_ok) return ret_error;
} else if (equal_buf_str (&subconf->key, "ca_file")) {
cherokee_buffer_add_buffer (&props->ca_file, &subconf->val);
} else if (equal_buf_str (&subconf->key, "methods") ||
equal_buf_str (&subconf->key, "realm") ||
equal_buf_str (&subconf->key, "users")) {
/* Handled in validator.c
*/
} else {
LOG_WARNING (CHEROKEE_ERROR_VALIDATOR_LDAP_KEY, subconf->key.buf);
}
}
/* Checks
*/
if (cherokee_buffer_is_empty (&props->basedn)) {
LOG_ERROR (CHEROKEE_ERROR_VALIDATOR_LDAP_PROPERTY, "base_dn");
return ret_error;
}
if (cherokee_buffer_is_empty (&props->server)) {
LOG_ERROR (CHEROKEE_ERROR_VALIDATOR_LDAP_PROPERTY, "server");
return ret_error;
}
if ((cherokee_buffer_is_empty (&props->bindpw) &&
(! cherokee_buffer_is_empty (&props->basedn))))
{
LOG_ERROR_S (CHEROKEE_ERROR_VALIDATOR_LDAP_SECURITY);
return ret_error;
}
return ret_ok;
}
static ret_t
init_ldap_connection (cherokee_validator_ldap_t *ldap, cherokee_validator_ldap_props_t *props)
{
int re;
int val;
/* Connect
*/
ldap->conn = ldap_init (props->server.buf, props->port);
if (ldap->conn == NULL) {
LOG_ERRNO (errno, cherokee_err_critical,
CHEROKEE_ERROR_VALIDATOR_LDAP_CONNECT,
props->server.buf, props->port);
return ret_error;
}
TRACE (ENTRIES, "Connected to %s:%d\n", props->server.buf, props->port);
/* Set LDAP protocol version
*/
val = LDAP_VERSION3;
re = ldap_set_option (ldap->conn, LDAP_OPT_PROTOCOL_VERSION, &val);
if (re != LDAP_OPT_SUCCESS) {
LOG_ERROR (CHEROKEE_ERROR_VALIDATOR_LDAP_V3, ldap_err2string(re));
return ret_error;
}
TRACE (ENTRIES, "LDAP protocol version %d set\n", LDAP_VERSION3);
/* Secure connections
*/
if (props->tls) {
#ifdef LDAP_OPT_X_TLS
if (! cherokee_buffer_is_empty (&props->ca_file)) {
re = ldap_set_option (NULL, LDAP_OPT_X_TLS_CACERTFILE, props->ca_file.buf);
if (re != LDAP_OPT_SUCCESS) {
LOG_CRITICAL (CHEROKEE_ERROR_VALIDATOR_LDAP_CA,
props->ca_file.buf, ldap_err2string (re));
return ret_error;
}
}
#else
LOG_ERROR_S (CHEROKEE_ERROR_VALIDATOR_LDAP_STARTTLS);
#endif
}
/* Bind
*/
if (cherokee_buffer_is_empty (&props->binddn)) {
TRACE (ENTRIES, "anonymous bind %s", "\n");
re = ldap_simple_bind_s (ldap->conn, NULL, NULL);
} else {
TRACE (ENTRIES, "bind user=%s password=%s\n",
props->binddn.buf, props->bindpw.buf);
re = ldap_simple_bind_s (ldap->conn, props->binddn.buf, props->bindpw.buf);
}
if (re != LDAP_SUCCESS) {
LOG_CRITICAL (CHEROKEE_ERROR_VALIDATOR_LDAP_BIND,
props->server.buf, props->port, props->binddn.buf,
props->bindpw.buf, ldap_err2string(re));
return ret_error;
}
return ret_ok;
}
ret_t
cherokee_validator_ldap_new (cherokee_validator_ldap_t **ldap, cherokee_module_props_t *props)
{
ret_t ret;
CHEROKEE_NEW_STRUCT(n,validator_ldap);
/* Init
*/
cherokee_validator_init_base (VALIDATOR(n), VALIDATOR_PROPS(props), PLUGIN_INFO_VALIDATOR_PTR(ldap));
VALIDATOR(n)->support = http_auth_basic;
MODULE(n)->free = (module_func_free_t) cherokee_validator_ldap_free;
VALIDATOR(n)->check = (validator_func_check_t) cherokee_validator_ldap_check;
VALIDATOR(n)->add_headers = (validator_func_add_headers_t) cherokee_validator_ldap_add_headers;
/* Init properties
*/
cherokee_buffer_init (&n->filter);
/* Connect to the LDAP server
*/
ret = init_ldap_connection (n, PROP_LDAP(props));
if (ret != ret_ok) {
cherokee_validator_free (VALIDATOR(n));
return ret;
}
*ldap = n;
return ret_ok;
}
ret_t
cherokee_validator_ldap_free (cherokee_validator_ldap_t *ldap)
{
cherokee_buffer_mrproper (&ldap->filter);
if (ldap->conn)
ldap_unbind (ldap->conn);
return ret_ok;
}
static ret_t
validate_dn (cherokee_validator_ldap_props_t *props, char *dn, char *password)
{
int re;
int val;
LDAP *conn;
conn = ldap_init (props->server.buf, props->port);
if (conn == NULL) return ret_error;
val = LDAP_VERSION3;
re = ldap_set_option (conn, LDAP_OPT_PROTOCOL_VERSION, &val);
if (re != LDAP_OPT_SUCCESS)
goto error;
if (props->tls) {
#ifdef LDAP_HAVE_START_TLS_S
re = ldap_start_tls_s (conn, NULL, NULL);
if (re != LDAP_OPT_SUCCESS) {
TRACE (ENTRIES, "Couldn't StartTLS\n");
goto error;
}
#else
LOG_ERROR_S (CHEROKEE_ERROR_VALIDATOR_LDAP_STARTTLS);
#endif
}
re = ldap_simple_bind_s (conn, dn, password);
if (re != LDAP_SUCCESS)
goto error;
return ret_ok;
error:
ldap_unbind_s (conn);
return ret_error;
}
static ret_t
init_filter (cherokee_validator_ldap_t *ldap,
cherokee_validator_ldap_props_t *props,
cherokee_connection_t *conn)
{
if (cherokee_buffer_is_empty (&props->filter)) {
TRACE (ENTRIES, "Empty filter: %s\n", "Ignoring it");
return ret_ok;
}
cherokee_buffer_ensure_size (&ldap->filter, props->filter.len + conn->validator->user.len);
cherokee_buffer_add_buffer (&ldap->filter, &props->filter);
cherokee_buffer_replace_string (&ldap->filter, "${user}", 7, conn->validator->user.buf, conn->validator->user.len);
TRACE (ENTRIES, "filter %s\n", ldap->filter.buf);
return ret_ok;
}
ret_t
cherokee_validator_ldap_check (cherokee_validator_ldap_t *ldap,
cherokee_connection_t *conn)
{
int re;
ret_t ret;
size_t size;
char *dn;
LDAPMessage *message;
LDAPMessage *first;
char *attrs[] = { LDAP_NO_ATTRS, NULL };
cherokee_validator_ldap_props_t *props = VAL_LDAP_PROP(ldap);
/* Sanity checks
*/
if ((conn->validator == NULL) ||
cherokee_buffer_is_empty (&conn->validator->user) ||
cherokee_buffer_is_empty (&conn->validator->passwd))
return ret_error;
size = cherokee_buffer_cnt_cspn (&conn->validator->user, 0, "*()");
if (size != conn->validator->user.len)
return ret_error;
/* Build filter
*/
ret = init_filter (ldap, props, conn);
if (ret != ret_ok)
return ret;
/* Search
*/
re = ldap_search_s (ldap->conn, props->basedn.buf, LDAP_SCOPE_SUBTREE, ldap->filter.buf, attrs, 0, &message);
if (re != LDAP_SUCCESS) {
LOG_ERROR (CHEROKEE_ERROR_VALIDATOR_LDAP_SEARCH,
props->filter.buf ? props->filter.buf : "");
return ret_error;
}
TRACE (ENTRIES, "subtree search (%s): done\n", ldap->filter.buf ? ldap->filter.buf : "");
/* Check that there a single entry
*/
re = ldap_count_entries (ldap->conn, message);
if (re != 1) {
ldap_msgfree (message);
return ret_not_found;
}
/* Pick up the first one
*/
first = ldap_first_entry (ldap->conn, message);
if (first == NULL) {
ldap_msgfree (message);
return ret_not_found;
}
/* Get DN
*/
dn = ldap_get_dn (ldap->conn, first);
if (dn == NULL) {
ldap_msgfree (message);
return ret_error;
}
ldap_msgfree (message);
/* Check that it's right
*/
ret = validate_dn (props, dn, conn->validator->passwd.buf);
if (ret != ret_ok)
return ret;
/* Disconnect from the LDAP server
*/
re = ldap_unbind_s (ldap->conn);
if (re != LDAP_SUCCESS)
return ret_error;
/* Validated!
*/
TRACE (ENTRIES, "Access to use %s has been granted\n", conn->validator->user.buf);
return ret_ok;
}
ret_t
cherokee_validator_ldap_add_headers (cherokee_validator_ldap_t *ldap, cherokee_connection_t *conn, cherokee_buffer_t *buf)
{
UNUSED(ldap);
UNUSED(conn);
UNUSED(buf);
return ret_ok;
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/good_2222_0 |
crossvul-cpp_data_bad_2757_1 | /*
* X.509 certificate parsing and verification
*
* 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)
*/
/*
* The ITU-T X.509 standard defines a certificate format for PKI.
*
* http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs)
* http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs)
* http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10)
*
* http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf
* http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_X509_CRT_PARSE_C)
#include "mbedtls/x509_crt.h"
#include "mbedtls/oid.h"
#include <stdio.h>
#include <string.h>
#if defined(MBEDTLS_PEM_PARSE_C)
#include "mbedtls/pem.h"
#endif
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#define mbedtls_free free
#define mbedtls_calloc calloc
#define mbedtls_snprintf snprintf
#endif
#if defined(MBEDTLS_THREADING_C)
#include "mbedtls/threading.h"
#endif
#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
#include <windows.h>
#else
#include <time.h>
#endif
#if defined(MBEDTLS_FS_IO)
#include <stdio.h>
#if !defined(_WIN32) || defined(EFIX64) || defined(EFI32)
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#endif /* !_WIN32 || EFIX64 || EFI32 */
#endif
/* 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;
}
/*
* Default profile
*/
const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default =
{
#if defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES)
/* Allow SHA-1 (weak, but still safe in controlled environments) */
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA1 ) |
#endif
/* Only SHA-2 hashes */
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
0xFFFFFFF, /* Any PK alg */
0xFFFFFFF, /* Any curve */
2048,
};
/*
* Next-default profile
*/
const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next =
{
/* Hashes from SHA-256 and above */
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
0xFFFFFFF, /* Any PK alg */
#if defined(MBEDTLS_ECP_C)
/* Curves at or above 128-bit security level */
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP521R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP256R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP384R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP512R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256K1 ),
#else
0,
#endif
2048,
};
/*
* NSA Suite B Profile
*/
const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb =
{
/* Only SHA-256 and 384 */
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ),
/* Only ECDSA */
MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECDSA ),
#if defined(MBEDTLS_ECP_C)
/* Only NIST P-256 and P-384 */
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ),
#else
0,
#endif
0,
};
/*
* Check md_alg against profile
* Return 0 if md_alg acceptable for this profile, -1 otherwise
*/
static int x509_profile_check_md_alg( const mbedtls_x509_crt_profile *profile,
mbedtls_md_type_t md_alg )
{
if( ( profile->allowed_mds & MBEDTLS_X509_ID_FLAG( md_alg ) ) != 0 )
return( 0 );
return( -1 );
}
/*
* Check pk_alg against profile
* Return 0 if pk_alg acceptable for this profile, -1 otherwise
*/
static int x509_profile_check_pk_alg( const mbedtls_x509_crt_profile *profile,
mbedtls_pk_type_t pk_alg )
{
if( ( profile->allowed_pks & MBEDTLS_X509_ID_FLAG( pk_alg ) ) != 0 )
return( 0 );
return( -1 );
}
/*
* Check key against profile
* Return 0 if pk_alg acceptable for this profile, -1 otherwise
*/
static int x509_profile_check_key( const mbedtls_x509_crt_profile *profile,
mbedtls_pk_type_t pk_alg,
const mbedtls_pk_context *pk )
{
#if defined(MBEDTLS_RSA_C)
if( pk_alg == MBEDTLS_PK_RSA || pk_alg == MBEDTLS_PK_RSASSA_PSS )
{
if( mbedtls_pk_get_bitlen( pk ) >= profile->rsa_min_bitlen )
return( 0 );
return( -1 );
}
#endif
#if defined(MBEDTLS_ECP_C)
if( pk_alg == MBEDTLS_PK_ECDSA ||
pk_alg == MBEDTLS_PK_ECKEY ||
pk_alg == MBEDTLS_PK_ECKEY_DH )
{
mbedtls_ecp_group_id gid = mbedtls_pk_ec( *pk )->grp.id;
if( ( profile->allowed_curves & MBEDTLS_X509_ID_FLAG( gid ) ) != 0 )
return( 0 );
return( -1 );
}
#endif
return( -1 );
}
/*
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
*/
static int x509_get_version( unsigned char **p,
const unsigned char *end,
int *ver )
{
int ret;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
{
*ver = 0;
return( 0 );
}
return( ret );
}
end = *p + len;
if( ( ret = mbedtls_asn1_get_int( p, end, ver ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_VERSION + ret );
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_VERSION +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
/*
* Validity ::= SEQUENCE {
* notBefore Time,
* notAfter Time }
*/
static int x509_get_dates( unsigned char **p,
const unsigned char *end,
mbedtls_x509_time *from,
mbedtls_x509_time *to )
{
int ret;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_DATE + ret );
end = *p + len;
if( ( ret = mbedtls_x509_get_time( p, end, from ) ) != 0 )
return( ret );
if( ( ret = mbedtls_x509_get_time( p, end, to ) ) != 0 )
return( ret );
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_DATE +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
/*
* X.509 v2/v3 unique identifier (not parsed)
*/
static int x509_get_uid( unsigned char **p,
const unsigned char *end,
mbedtls_x509_buf *uid, int n )
{
int ret;
if( *p == end )
return( 0 );
uid->tag = **p;
if( ( ret = mbedtls_asn1_get_tag( p, end, &uid->len,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | n ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
return( 0 );
return( ret );
}
uid->p = *p;
*p += uid->len;
return( 0 );
}
static int x509_get_basic_constraints( unsigned char **p,
const unsigned char *end,
int *ca_istrue,
int *max_pathlen )
{
int ret;
size_t len;
/*
* BasicConstraints ::= SEQUENCE {
* cA BOOLEAN DEFAULT FALSE,
* pathLenConstraint INTEGER (0..MAX) OPTIONAL }
*/
*ca_istrue = 0; /* DEFAULT FALSE */
*max_pathlen = 0; /* endless */
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( *p == end )
return( 0 );
if( ( ret = mbedtls_asn1_get_bool( p, end, ca_istrue ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
ret = mbedtls_asn1_get_int( p, end, ca_istrue );
if( ret != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( *ca_istrue != 0 )
*ca_istrue = 1;
}
if( *p == end )
return( 0 );
if( ( ret = mbedtls_asn1_get_int( p, end, max_pathlen ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
(*max_pathlen)++;
return( 0 );
}
static int x509_get_ns_cert_type( unsigned char **p,
const unsigned char *end,
unsigned char *ns_cert_type)
{
int ret;
mbedtls_x509_bitstring bs = { 0, 0, NULL };
if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( bs.len != 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_INVALID_LENGTH );
/* Get actual bitstring */
*ns_cert_type = *bs.p;
return( 0 );
}
static int x509_get_key_usage( unsigned char **p,
const unsigned char *end,
unsigned int *key_usage)
{
int ret;
size_t i;
mbedtls_x509_bitstring bs = { 0, 0, NULL };
if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( bs.len < 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_INVALID_LENGTH );
/* Get actual bitstring */
*key_usage = 0;
for( i = 0; i < bs.len && i < sizeof( unsigned int ); i++ )
{
*key_usage |= (unsigned int) bs.p[i] << (8*i);
}
return( 0 );
}
/*
* ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
*
* KeyPurposeId ::= OBJECT IDENTIFIER
*/
static int x509_get_ext_key_usage( unsigned char **p,
const unsigned char *end,
mbedtls_x509_sequence *ext_key_usage)
{
int ret;
if( ( ret = mbedtls_asn1_get_sequence_of( p, end, ext_key_usage, MBEDTLS_ASN1_OID ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
/* Sequence length must be >= 1 */
if( ext_key_usage->buf.p == NULL )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_INVALID_LENGTH );
return( 0 );
}
/*
* SubjectAltName ::= GeneralNames
*
* GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
*
* GeneralName ::= CHOICE {
* otherName [0] OtherName,
* rfc822Name [1] IA5String,
* dNSName [2] IA5String,
* x400Address [3] ORAddress,
* directoryName [4] Name,
* ediPartyName [5] EDIPartyName,
* uniformResourceIdentifier [6] IA5String,
* iPAddress [7] OCTET STRING,
* registeredID [8] OBJECT IDENTIFIER }
*
* OtherName ::= SEQUENCE {
* type-id OBJECT IDENTIFIER,
* value [0] EXPLICIT ANY DEFINED BY type-id }
*
* EDIPartyName ::= SEQUENCE {
* nameAssigner [0] DirectoryString OPTIONAL,
* partyName [1] DirectoryString }
*
* NOTE: we only parse and use dNSName at this point.
*/
static int x509_get_subject_alt_name( unsigned char **p,
const unsigned char *end,
mbedtls_x509_sequence *subject_alt_name )
{
int ret;
size_t len, tag_len;
mbedtls_asn1_buf *buf;
unsigned char tag;
mbedtls_asn1_sequence *cur = subject_alt_name;
/* Get main sequence tag */
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( *p + len != end )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
while( *p < end )
{
if( ( end - *p ) < 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_OUT_OF_DATA );
tag = **p;
(*p)++;
if( ( ret = mbedtls_asn1_get_len( p, end, &tag_len ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( ( tag & MBEDTLS_ASN1_CONTEXT_SPECIFIC ) != MBEDTLS_ASN1_CONTEXT_SPECIFIC )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
/* Skip everything but DNS name */
if( tag != ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2 ) )
{
*p += tag_len;
continue;
}
/* Allocate and assign next pointer */
if( cur->buf.p != NULL )
{
if( cur->next != NULL )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
cur->next = mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) );
if( cur->next == NULL )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_ALLOC_FAILED );
cur = cur->next;
}
buf = &(cur->buf);
buf->tag = tag;
buf->p = *p;
buf->len = tag_len;
*p += buf->len;
}
/* Set final sequence entry's next pointer to NULL */
cur->next = NULL;
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
/*
* X.509 v3 extensions
*
*/
static int x509_get_crt_ext( unsigned char **p,
const unsigned char *end,
mbedtls_x509_crt *crt )
{
int ret;
size_t len;
unsigned char *end_ext_data, *end_ext_octet;
if( ( ret = mbedtls_x509_get_ext( p, end, &crt->v3_ext, 3 ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
return( 0 );
return( ret );
}
while( *p < end )
{
/*
* Extension ::= SEQUENCE {
* extnID OBJECT IDENTIFIER,
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING }
*/
mbedtls_x509_buf extn_oid = {0, 0, NULL};
int is_critical = 0; /* DEFAULT FALSE */
int ext_type = 0;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
end_ext_data = *p + len;
/* Get extension ID */
extn_oid.tag = **p;
if( ( ret = mbedtls_asn1_get_tag( p, end, &extn_oid.len, MBEDTLS_ASN1_OID ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
extn_oid.p = *p;
*p += extn_oid.len;
if( ( end - *p ) < 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_OUT_OF_DATA );
/* Get optional critical */
if( ( ret = mbedtls_asn1_get_bool( p, end_ext_data, &is_critical ) ) != 0 &&
( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
/* Data should be octet string type */
if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len,
MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
end_ext_octet = *p + len;
if( end_ext_octet != end_ext_data )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
/*
* Detect supported extensions
*/
ret = mbedtls_oid_get_x509_ext_type( &extn_oid, &ext_type );
if( ret != 0 )
{
/* No parser found, skip extension */
*p = end_ext_octet;
#if !defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION)
if( is_critical )
{
/* Data is marked as critical: fail */
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
}
#endif
continue;
}
/* Forbid repeated extensions */
if( ( crt->ext_types & ext_type ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
crt->ext_types |= ext_type;
switch( ext_type )
{
case MBEDTLS_X509_EXT_BASIC_CONSTRAINTS:
/* Parse basic constraints */
if( ( ret = x509_get_basic_constraints( p, end_ext_octet,
&crt->ca_istrue, &crt->max_pathlen ) ) != 0 )
return( ret );
break;
case MBEDTLS_X509_EXT_KEY_USAGE:
/* Parse key usage */
if( ( ret = x509_get_key_usage( p, end_ext_octet,
&crt->key_usage ) ) != 0 )
return( ret );
break;
case MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE:
/* Parse extended key usage */
if( ( ret = x509_get_ext_key_usage( p, end_ext_octet,
&crt->ext_key_usage ) ) != 0 )
return( ret );
break;
case MBEDTLS_X509_EXT_SUBJECT_ALT_NAME:
/* Parse subject alt name */
if( ( ret = x509_get_subject_alt_name( p, end_ext_octet,
&crt->subject_alt_names ) ) != 0 )
return( ret );
break;
case MBEDTLS_X509_EXT_NS_CERT_TYPE:
/* Parse netscape certificate type */
if( ( ret = x509_get_ns_cert_type( p, end_ext_octet,
&crt->ns_cert_type ) ) != 0 )
return( ret );
break;
default:
return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE );
}
}
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
/*
* Parse and fill a single X.509 certificate in DER format
*/
static int x509_crt_parse_der_core( mbedtls_x509_crt *crt, const unsigned char *buf,
size_t buflen )
{
int ret;
size_t len;
unsigned char *p, *end, *crt_end;
mbedtls_x509_buf sig_params1, sig_params2, sig_oid2;
memset( &sig_params1, 0, sizeof( mbedtls_x509_buf ) );
memset( &sig_params2, 0, sizeof( mbedtls_x509_buf ) );
memset( &sig_oid2, 0, sizeof( mbedtls_x509_buf ) );
/*
* Check for valid input
*/
if( crt == NULL || buf == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
// Use the original buffer until we figure out actual length
p = (unsigned char*) buf;
len = buflen;
end = p + len;
/*
* Certificate ::= SEQUENCE {
* tbsCertificate TBSCertificate,
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING }
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT );
}
if( len > (size_t) ( end - p ) )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
}
crt_end = p + len;
// Create and populate a new buffer for the raw field
crt->raw.len = crt_end - buf;
crt->raw.p = p = mbedtls_calloc( 1, crt->raw.len );
if( p == NULL )
return( MBEDTLS_ERR_X509_ALLOC_FAILED );
memcpy( p, buf, crt->raw.len );
// Direct pointers to the new buffer
p += crt->raw.len - len;
end = crt_end = p + len;
/*
* TBSCertificate ::= SEQUENCE {
*/
crt->tbs.p = p;
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
}
end = p + len;
crt->tbs.len = end - crt->tbs.p;
/*
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
*
* CertificateSerialNumber ::= INTEGER
*
* signature AlgorithmIdentifier
*/
if( ( ret = x509_get_version( &p, end, &crt->version ) ) != 0 ||
( ret = mbedtls_x509_get_serial( &p, end, &crt->serial ) ) != 0 ||
( ret = mbedtls_x509_get_alg( &p, end, &crt->sig_oid,
&sig_params1 ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
crt->version++;
if( crt->version > 3 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_UNKNOWN_VERSION );
}
if( ( ret = mbedtls_x509_get_sig_alg( &crt->sig_oid, &sig_params1,
&crt->sig_md, &crt->sig_pk,
&crt->sig_opts ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
/*
* issuer Name
*/
crt->issuer_raw.p = p;
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
}
if( ( ret = mbedtls_x509_get_name( &p, p + len, &crt->issuer ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
crt->issuer_raw.len = p - crt->issuer_raw.p;
/*
* Validity ::= SEQUENCE {
* notBefore Time,
* notAfter Time }
*
*/
if( ( ret = x509_get_dates( &p, end, &crt->valid_from,
&crt->valid_to ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
/*
* subject Name
*/
crt->subject_raw.p = p;
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
}
if( len && ( ret = mbedtls_x509_get_name( &p, p + len, &crt->subject ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
crt->subject_raw.len = p - crt->subject_raw.p;
/*
* SubjectPublicKeyInfo
*/
if( ( ret = mbedtls_pk_parse_subpubkey( &p, end, &crt->pk ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
/*
* issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version shall be v2 or v3
* subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version shall be v2 or v3
* extensions [3] EXPLICIT Extensions OPTIONAL
* -- If present, version shall be v3
*/
if( crt->version == 2 || crt->version == 3 )
{
ret = x509_get_uid( &p, end, &crt->issuer_id, 1 );
if( ret != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
}
if( crt->version == 2 || crt->version == 3 )
{
ret = x509_get_uid( &p, end, &crt->subject_id, 2 );
if( ret != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
}
#if !defined(MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3)
if( crt->version == 3 )
#endif
{
ret = x509_get_crt_ext( &p, end, crt );
if( ret != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
}
if( p != end )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
}
end = crt_end;
/*
* }
* -- end of TBSCertificate
*
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING
*/
if( ( ret = mbedtls_x509_get_alg( &p, end, &sig_oid2, &sig_params2 ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
if( crt->sig_oid.len != sig_oid2.len ||
memcmp( crt->sig_oid.p, sig_oid2.p, crt->sig_oid.len ) != 0 ||
sig_params1.len != sig_params2.len ||
( sig_params1.len != 0 &&
memcmp( sig_params1.p, sig_params2.p, sig_params1.len ) != 0 ) )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_SIG_MISMATCH );
}
if( ( ret = mbedtls_x509_get_sig( &p, end, &crt->sig ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
if( p != end )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
}
return( 0 );
}
/*
* Parse one X.509 certificate in DER format from a buffer and add them to a
* chained list
*/
int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf,
size_t buflen )
{
int ret;
mbedtls_x509_crt *crt = chain, *prev = NULL;
/*
* Check for valid input
*/
if( crt == NULL || buf == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
while( crt->version != 0 && crt->next != NULL )
{
prev = crt;
crt = crt->next;
}
/*
* Add new certificate on the end of the chain if needed.
*/
if( crt->version != 0 && crt->next == NULL )
{
crt->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );
if( crt->next == NULL )
return( MBEDTLS_ERR_X509_ALLOC_FAILED );
prev = crt;
mbedtls_x509_crt_init( crt->next );
crt = crt->next;
}
if( ( ret = x509_crt_parse_der_core( crt, buf, buflen ) ) != 0 )
{
if( prev )
prev->next = NULL;
if( crt != chain )
mbedtls_free( crt );
return( ret );
}
return( 0 );
}
/*
* Parse one or more PEM certificates from a buffer and add them to the chained
* list
*/
int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen )
{
#if defined(MBEDTLS_PEM_PARSE_C)
int success = 0, first_error = 0, total_failed = 0;
int buf_format = MBEDTLS_X509_FORMAT_DER;
#endif
/*
* Check for valid input
*/
if( chain == NULL || buf == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
/*
* Determine buffer content. Buffer contains either one DER certificate or
* one or more PEM certificates.
*/
#if defined(MBEDTLS_PEM_PARSE_C)
if( buflen != 0 && buf[buflen - 1] == '\0' &&
strstr( (const char *) buf, "-----BEGIN CERTIFICATE-----" ) != NULL )
{
buf_format = MBEDTLS_X509_FORMAT_PEM;
}
if( buf_format == MBEDTLS_X509_FORMAT_DER )
return mbedtls_x509_crt_parse_der( chain, buf, buflen );
#else
return mbedtls_x509_crt_parse_der( chain, buf, buflen );
#endif
#if defined(MBEDTLS_PEM_PARSE_C)
if( buf_format == MBEDTLS_X509_FORMAT_PEM )
{
int ret;
mbedtls_pem_context pem;
/* 1 rather than 0 since the terminating NULL byte is counted in */
while( buflen > 1 )
{
size_t use_len;
mbedtls_pem_init( &pem );
/* If we get there, we know the string is null-terminated */
ret = mbedtls_pem_read_buffer( &pem,
"-----BEGIN CERTIFICATE-----",
"-----END CERTIFICATE-----",
buf, NULL, 0, &use_len );
if( ret == 0 )
{
/*
* Was PEM encoded
*/
buflen -= use_len;
buf += use_len;
}
else if( ret == MBEDTLS_ERR_PEM_BAD_INPUT_DATA )
{
return( ret );
}
else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
{
mbedtls_pem_free( &pem );
/*
* PEM header and footer were found
*/
buflen -= use_len;
buf += use_len;
if( first_error == 0 )
first_error = ret;
total_failed++;
continue;
}
else
break;
ret = mbedtls_x509_crt_parse_der( chain, pem.buf, pem.buflen );
mbedtls_pem_free( &pem );
if( ret != 0 )
{
/*
* Quit parsing on a memory error
*/
if( ret == MBEDTLS_ERR_X509_ALLOC_FAILED )
return( ret );
if( first_error == 0 )
first_error = ret;
total_failed++;
continue;
}
success = 1;
}
}
if( success )
return( total_failed );
else if( first_error )
return( first_error );
else
return( MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT );
#endif /* MBEDTLS_PEM_PARSE_C */
}
#if defined(MBEDTLS_FS_IO)
/*
* Load one or more certificates and add them to the chained list
*/
int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path )
{
int ret;
size_t n;
unsigned char *buf;
if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )
return( ret );
ret = mbedtls_x509_crt_parse( chain, buf, n );
mbedtls_zeroize( buf, n );
mbedtls_free( buf );
return( ret );
}
int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path )
{
int ret = 0;
#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
int w_ret;
WCHAR szDir[MAX_PATH];
char filename[MAX_PATH];
char *p;
size_t len = strlen( path );
WIN32_FIND_DATAW file_data;
HANDLE hFind;
if( len > MAX_PATH - 3 )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
memset( szDir, 0, sizeof(szDir) );
memset( filename, 0, MAX_PATH );
memcpy( filename, path, len );
filename[len++] = '\\';
p = filename + len;
filename[len++] = '*';
w_ret = MultiByteToWideChar( CP_ACP, 0, filename, (int)len, szDir,
MAX_PATH - 3 );
if( w_ret == 0 )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
hFind = FindFirstFileW( szDir, &file_data );
if( hFind == INVALID_HANDLE_VALUE )
return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
len = MAX_PATH - len;
do
{
memset( p, 0, len );
if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
continue;
w_ret = WideCharToMultiByte( CP_ACP, 0, file_data.cFileName,
lstrlenW( file_data.cFileName ),
p, (int) len - 1,
NULL, NULL );
if( w_ret == 0 )
return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
w_ret = mbedtls_x509_crt_parse_file( chain, filename );
if( w_ret < 0 )
ret++;
else
ret += w_ret;
}
while( FindNextFileW( hFind, &file_data ) != 0 );
if( GetLastError() != ERROR_NO_MORE_FILES )
ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
FindClose( hFind );
#else /* _WIN32 */
int t_ret;
int snp_ret;
struct stat sb;
struct dirent *entry;
char entry_name[MBEDTLS_X509_MAX_FILE_PATH_LEN];
DIR *dir = opendir( path );
if( dir == NULL )
return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
#if defined(MBEDTLS_THREADING_PTHREAD)
if( ( ret = mbedtls_mutex_lock( &mbedtls_threading_readdir_mutex ) ) != 0 )
{
closedir( dir );
return( ret );
}
#endif
while( ( entry = readdir( dir ) ) != NULL )
{
snp_ret = mbedtls_snprintf( entry_name, sizeof entry_name,
"%s/%s", path, entry->d_name );
if( snp_ret < 0 || (size_t)snp_ret >= sizeof entry_name )
{
ret = MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
goto cleanup;
}
else if( stat( entry_name, &sb ) == -1 )
{
ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
goto cleanup;
}
if( !S_ISREG( sb.st_mode ) )
continue;
// Ignore parse errors
//
t_ret = mbedtls_x509_crt_parse_file( chain, entry_name );
if( t_ret < 0 )
ret++;
else
ret += t_ret;
}
cleanup:
closedir( dir );
#if defined(MBEDTLS_THREADING_PTHREAD)
if( mbedtls_mutex_unlock( &mbedtls_threading_readdir_mutex ) != 0 )
ret = MBEDTLS_ERR_THREADING_MUTEX_ERROR;
#endif
#endif /* _WIN32 */
return( ret );
}
#endif /* MBEDTLS_FS_IO */
static int x509_info_subject_alt_name( char **buf, size_t *size,
const mbedtls_x509_sequence *subject_alt_name )
{
size_t i;
size_t n = *size;
char *p = *buf;
const mbedtls_x509_sequence *cur = subject_alt_name;
const char *sep = "";
size_t sep_len = 0;
while( cur != NULL )
{
if( cur->buf.len + sep_len >= n )
{
*p = '\0';
return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL );
}
n -= cur->buf.len + sep_len;
for( i = 0; i < sep_len; i++ )
*p++ = sep[i];
for( i = 0; i < cur->buf.len; i++ )
*p++ = cur->buf.p[i];
sep = ", ";
sep_len = 2;
cur = cur->next;
}
*p = '\0';
*size = n;
*buf = p;
return( 0 );
}
#define PRINT_ITEM(i) \
{ \
ret = mbedtls_snprintf( p, n, "%s" i, sep ); \
MBEDTLS_X509_SAFE_SNPRINTF; \
sep = ", "; \
}
#define CERT_TYPE(type,name) \
if( ns_cert_type & type ) \
PRINT_ITEM( name );
static int x509_info_cert_type( char **buf, size_t *size,
unsigned char ns_cert_type )
{
int ret;
size_t n = *size;
char *p = *buf;
const char *sep = "";
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT, "SSL Client" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER, "SSL Server" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL, "Email" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING, "Object Signing" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_RESERVED, "Reserved" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CA, "SSL CA" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA, "Email CA" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA, "Object Signing CA" );
*size = n;
*buf = p;
return( 0 );
}
#define KEY_USAGE(code,name) \
if( key_usage & code ) \
PRINT_ITEM( name );
static int x509_info_key_usage( char **buf, size_t *size,
unsigned int key_usage )
{
int ret;
size_t n = *size;
char *p = *buf;
const char *sep = "";
KEY_USAGE( MBEDTLS_X509_KU_DIGITAL_SIGNATURE, "Digital Signature" );
KEY_USAGE( MBEDTLS_X509_KU_NON_REPUDIATION, "Non Repudiation" );
KEY_USAGE( MBEDTLS_X509_KU_KEY_ENCIPHERMENT, "Key Encipherment" );
KEY_USAGE( MBEDTLS_X509_KU_DATA_ENCIPHERMENT, "Data Encipherment" );
KEY_USAGE( MBEDTLS_X509_KU_KEY_AGREEMENT, "Key Agreement" );
KEY_USAGE( MBEDTLS_X509_KU_KEY_CERT_SIGN, "Key Cert Sign" );
KEY_USAGE( MBEDTLS_X509_KU_CRL_SIGN, "CRL Sign" );
KEY_USAGE( MBEDTLS_X509_KU_ENCIPHER_ONLY, "Encipher Only" );
KEY_USAGE( MBEDTLS_X509_KU_DECIPHER_ONLY, "Decipher Only" );
*size = n;
*buf = p;
return( 0 );
}
static int x509_info_ext_key_usage( char **buf, size_t *size,
const mbedtls_x509_sequence *extended_key_usage )
{
int ret;
const char *desc;
size_t n = *size;
char *p = *buf;
const mbedtls_x509_sequence *cur = extended_key_usage;
const char *sep = "";
while( cur != NULL )
{
if( mbedtls_oid_get_extended_key_usage( &cur->buf, &desc ) != 0 )
desc = "???";
ret = mbedtls_snprintf( p, n, "%s%s", sep, desc );
MBEDTLS_X509_SAFE_SNPRINTF;
sep = ", ";
cur = cur->next;
}
*size = n;
*buf = p;
return( 0 );
}
/*
* Return an informational string about the certificate.
*/
#define BEFORE_COLON 18
#define BC "18"
int mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix,
const mbedtls_x509_crt *crt )
{
int ret;
size_t n;
char *p;
char key_size_str[BEFORE_COLON];
p = buf;
n = size;
if( NULL == crt )
{
ret = mbedtls_snprintf( p, n, "\nCertificate is uninitialised!\n" );
MBEDTLS_X509_SAFE_SNPRINTF;
return( (int) ( size - n ) );
}
ret = mbedtls_snprintf( p, n, "%scert. version : %d\n",
prefix, crt->version );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "%sserial number : ",
prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_serial_gets( p, n, &crt->serial );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%sissuer name : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_dn_gets( p, n, &crt->issuer );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%ssubject name : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_dn_gets( p, n, &crt->subject );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%sissued on : " \
"%04d-%02d-%02d %02d:%02d:%02d", prefix,
crt->valid_from.year, crt->valid_from.mon,
crt->valid_from.day, crt->valid_from.hour,
crt->valid_from.min, crt->valid_from.sec );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%sexpires on : " \
"%04d-%02d-%02d %02d:%02d:%02d", prefix,
crt->valid_to.year, crt->valid_to.mon,
crt->valid_to.day, crt->valid_to.hour,
crt->valid_to.min, crt->valid_to.sec );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%ssigned using : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_sig_alg_gets( p, n, &crt->sig_oid, crt->sig_pk,
crt->sig_md, crt->sig_opts );
MBEDTLS_X509_SAFE_SNPRINTF;
/* Key size */
if( ( ret = mbedtls_x509_key_size_helper( key_size_str, BEFORE_COLON,
mbedtls_pk_get_name( &crt->pk ) ) ) != 0 )
{
return( ret );
}
ret = mbedtls_snprintf( p, n, "\n%s%-" BC "s: %d bits", prefix, key_size_str,
(int) mbedtls_pk_get_bitlen( &crt->pk ) );
MBEDTLS_X509_SAFE_SNPRINTF;
/*
* Optional extensions
*/
if( crt->ext_types & MBEDTLS_X509_EXT_BASIC_CONSTRAINTS )
{
ret = mbedtls_snprintf( p, n, "\n%sbasic constraints : CA=%s", prefix,
crt->ca_istrue ? "true" : "false" );
MBEDTLS_X509_SAFE_SNPRINTF;
if( crt->max_pathlen > 0 )
{
ret = mbedtls_snprintf( p, n, ", max_pathlen=%d", crt->max_pathlen - 1 );
MBEDTLS_X509_SAFE_SNPRINTF;
}
}
if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
{
ret = mbedtls_snprintf( p, n, "\n%ssubject alt name : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
if( ( ret = x509_info_subject_alt_name( &p, &n,
&crt->subject_alt_names ) ) != 0 )
return( ret );
}
if( crt->ext_types & MBEDTLS_X509_EXT_NS_CERT_TYPE )
{
ret = mbedtls_snprintf( p, n, "\n%scert. type : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
if( ( ret = x509_info_cert_type( &p, &n, crt->ns_cert_type ) ) != 0 )
return( ret );
}
if( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE )
{
ret = mbedtls_snprintf( p, n, "\n%skey usage : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
if( ( ret = x509_info_key_usage( &p, &n, crt->key_usage ) ) != 0 )
return( ret );
}
if( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE )
{
ret = mbedtls_snprintf( p, n, "\n%sext key usage : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
if( ( ret = x509_info_ext_key_usage( &p, &n,
&crt->ext_key_usage ) ) != 0 )
return( ret );
}
ret = mbedtls_snprintf( p, n, "\n" );
MBEDTLS_X509_SAFE_SNPRINTF;
return( (int) ( size - n ) );
}
struct x509_crt_verify_string {
int code;
const char *string;
};
static const struct x509_crt_verify_string x509_crt_verify_strings[] = {
{ MBEDTLS_X509_BADCERT_EXPIRED, "The certificate validity has expired" },
{ MBEDTLS_X509_BADCERT_REVOKED, "The certificate has been revoked (is on a CRL)" },
{ MBEDTLS_X509_BADCERT_CN_MISMATCH, "The certificate Common Name (CN) does not match with the expected CN" },
{ MBEDTLS_X509_BADCERT_NOT_TRUSTED, "The certificate is not correctly signed by the trusted CA" },
{ MBEDTLS_X509_BADCRL_NOT_TRUSTED, "The CRL is not correctly signed by the trusted CA" },
{ MBEDTLS_X509_BADCRL_EXPIRED, "The CRL is expired" },
{ MBEDTLS_X509_BADCERT_MISSING, "Certificate was missing" },
{ MBEDTLS_X509_BADCERT_SKIP_VERIFY, "Certificate verification was skipped" },
{ MBEDTLS_X509_BADCERT_OTHER, "Other reason (can be used by verify callback)" },
{ MBEDTLS_X509_BADCERT_FUTURE, "The certificate validity starts in the future" },
{ MBEDTLS_X509_BADCRL_FUTURE, "The CRL is from the future" },
{ MBEDTLS_X509_BADCERT_KEY_USAGE, "Usage does not match the keyUsage extension" },
{ MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, "Usage does not match the extendedKeyUsage extension" },
{ MBEDTLS_X509_BADCERT_NS_CERT_TYPE, "Usage does not match the nsCertType extension" },
{ MBEDTLS_X509_BADCERT_BAD_MD, "The certificate is signed with an unacceptable hash." },
{ MBEDTLS_X509_BADCERT_BAD_PK, "The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA)." },
{ MBEDTLS_X509_BADCERT_BAD_KEY, "The certificate is signed with an unacceptable key (eg bad curve, RSA too short)." },
{ MBEDTLS_X509_BADCRL_BAD_MD, "The CRL is signed with an unacceptable hash." },
{ MBEDTLS_X509_BADCRL_BAD_PK, "The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA)." },
{ MBEDTLS_X509_BADCRL_BAD_KEY, "The CRL is signed with an unacceptable key (eg bad curve, RSA too short)." },
{ 0, NULL }
};
int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
uint32_t flags )
{
int ret;
const struct x509_crt_verify_string *cur;
char *p = buf;
size_t n = size;
for( cur = x509_crt_verify_strings; cur->string != NULL ; cur++ )
{
if( ( flags & cur->code ) == 0 )
continue;
ret = mbedtls_snprintf( p, n, "%s%s\n", prefix, cur->string );
MBEDTLS_X509_SAFE_SNPRINTF;
flags ^= cur->code;
}
if( flags != 0 )
{
ret = mbedtls_snprintf( p, n, "%sUnknown reason "
"(this should not happen)\n", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
}
return( (int) ( size - n ) );
}
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
unsigned int usage )
{
unsigned int usage_must, usage_may;
unsigned int may_mask = MBEDTLS_X509_KU_ENCIPHER_ONLY
| MBEDTLS_X509_KU_DECIPHER_ONLY;
if( ( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE ) == 0 )
return( 0 );
usage_must = usage & ~may_mask;
if( ( ( crt->key_usage & ~may_mask ) & usage_must ) != usage_must )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
usage_may = usage & may_mask;
if( ( ( crt->key_usage & may_mask ) | usage_may ) != usage_may )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
return( 0 );
}
#endif
#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,
const char *usage_oid,
size_t usage_len )
{
const mbedtls_x509_sequence *cur;
/* Extension is not mandatory, absent means no restriction */
if( ( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE ) == 0 )
return( 0 );
/*
* Look for the requested usage (or wildcard ANY) in our list
*/
for( cur = &crt->ext_key_usage; cur != NULL; cur = cur->next )
{
const mbedtls_x509_buf *cur_oid = &cur->buf;
if( cur_oid->len == usage_len &&
memcmp( cur_oid->p, usage_oid, usage_len ) == 0 )
{
return( 0 );
}
if( MBEDTLS_OID_CMP( MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE, cur_oid ) == 0 )
return( 0 );
}
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
}
#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
#if defined(MBEDTLS_X509_CRL_PARSE_C)
/*
* Return 1 if the certificate is revoked, or 0 otherwise.
*/
int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl )
{
const mbedtls_x509_crl_entry *cur = &crl->entry;
while( cur != NULL && cur->serial.len != 0 )
{
if( crt->serial.len == cur->serial.len &&
memcmp( crt->serial.p, cur->serial.p, crt->serial.len ) == 0 )
{
if( mbedtls_x509_time_is_past( &cur->revocation_date ) )
return( 1 );
}
cur = cur->next;
}
return( 0 );
}
/*
* Check that the given certificate is not revoked according to the CRL.
* Skip validation is no CRL for the given CA is present.
*/
static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca,
mbedtls_x509_crl *crl_list,
const mbedtls_x509_crt_profile *profile )
{
int flags = 0;
unsigned char hash[MBEDTLS_MD_MAX_SIZE];
const mbedtls_md_info_t *md_info;
if( ca == NULL )
return( flags );
while( crl_list != NULL )
{
if( crl_list->version == 0 ||
crl_list->issuer_raw.len != ca->subject_raw.len ||
memcmp( crl_list->issuer_raw.p, ca->subject_raw.p,
crl_list->issuer_raw.len ) != 0 )
{
crl_list = crl_list->next;
continue;
}
/*
* Check if the CA is configured to sign CRLs
*/
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
if( mbedtls_x509_crt_check_key_usage( ca, MBEDTLS_X509_KU_CRL_SIGN ) != 0 )
{
flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
break;
}
#endif
/*
* Check if CRL is correctly signed by the trusted CA
*/
if( x509_profile_check_md_alg( profile, crl_list->sig_md ) != 0 )
flags |= MBEDTLS_X509_BADCRL_BAD_MD;
if( x509_profile_check_pk_alg( profile, crl_list->sig_pk ) != 0 )
flags |= MBEDTLS_X509_BADCRL_BAD_PK;
md_info = mbedtls_md_info_from_type( crl_list->sig_md );
if( md_info == NULL )
{
/*
* Cannot check 'unknown' hash
*/
flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
break;
}
mbedtls_md( md_info, crl_list->tbs.p, crl_list->tbs.len, hash );
if( x509_profile_check_key( profile, crl_list->sig_pk, &ca->pk ) != 0 )
flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
if( mbedtls_pk_verify_ext( crl_list->sig_pk, crl_list->sig_opts, &ca->pk,
crl_list->sig_md, hash, mbedtls_md_get_size( md_info ),
crl_list->sig.p, crl_list->sig.len ) != 0 )
{
flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
break;
}
/*
* Check for validity of CRL (Do not drop out)
*/
if( mbedtls_x509_time_is_past( &crl_list->next_update ) )
flags |= MBEDTLS_X509_BADCRL_EXPIRED;
if( mbedtls_x509_time_is_future( &crl_list->this_update ) )
flags |= MBEDTLS_X509_BADCRL_FUTURE;
/*
* Check if certificate is revoked
*/
if( mbedtls_x509_crt_is_revoked( crt, crl_list ) )
{
flags |= MBEDTLS_X509_BADCERT_REVOKED;
break;
}
crl_list = crl_list->next;
}
return( flags );
}
#endif /* MBEDTLS_X509_CRL_PARSE_C */
/*
* Like memcmp, but case-insensitive and always returns -1 if different
*/
static int x509_memcasecmp( const void *s1, const void *s2, size_t len )
{
size_t i;
unsigned char diff;
const unsigned char *n1 = s1, *n2 = s2;
for( i = 0; i < len; i++ )
{
diff = n1[i] ^ n2[i];
if( diff == 0 )
continue;
if( diff == 32 &&
( ( n1[i] >= 'a' && n1[i] <= 'z' ) ||
( n1[i] >= 'A' && n1[i] <= 'Z' ) ) )
{
continue;
}
return( -1 );
}
return( 0 );
}
/*
* Return 0 if name matches wildcard, -1 otherwise
*/
static int x509_check_wildcard( const char *cn, mbedtls_x509_buf *name )
{
size_t i;
size_t cn_idx = 0, cn_len = strlen( cn );
if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' )
return( 0 );
for( i = 0; i < cn_len; ++i )
{
if( cn[i] == '.' )
{
cn_idx = i;
break;
}
}
if( cn_idx == 0 )
return( -1 );
if( cn_len - cn_idx == name->len - 1 &&
x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )
{
return( 0 );
}
return( -1 );
}
/*
* Compare two X.509 strings, case-insensitive, and allowing for some encoding
* variations (but not all).
*
* Return 0 if equal, -1 otherwise.
*/
static int x509_string_cmp( const mbedtls_x509_buf *a, const mbedtls_x509_buf *b )
{
if( a->tag == b->tag &&
a->len == b->len &&
memcmp( a->p, b->p, b->len ) == 0 )
{
return( 0 );
}
if( ( a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
( b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
a->len == b->len &&
x509_memcasecmp( a->p, b->p, b->len ) == 0 )
{
return( 0 );
}
return( -1 );
}
/*
* Compare two X.509 Names (aka rdnSequence).
*
* See RFC 5280 section 7.1, though we don't implement the whole algorithm:
* we sometimes return unequal when the full algorithm would return equal,
* but never the other way. (In particular, we don't do Unicode normalisation
* or space folding.)
*
* Return 0 if equal, -1 otherwise.
*/
static int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b )
{
/* Avoid recursion, it might not be optimised by the compiler */
while( a != NULL || b != NULL )
{
if( a == NULL || b == NULL )
return( -1 );
/* type */
if( a->oid.tag != b->oid.tag ||
a->oid.len != b->oid.len ||
memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 )
{
return( -1 );
}
/* value */
if( x509_string_cmp( &a->val, &b->val ) != 0 )
return( -1 );
/* structure of the list of sets */
if( a->next_merged != b->next_merged )
return( -1 );
a = a->next;
b = b->next;
}
/* a == NULL == b */
return( 0 );
}
/*
* Check if 'parent' is a suitable parent (signing CA) for 'child'.
* Return 0 if yes, -1 if not.
*
* top means parent is a locally-trusted certificate
* bottom means child is the end entity cert
*/
static int x509_crt_check_parent( const mbedtls_x509_crt *child,
const mbedtls_x509_crt *parent,
int top, int bottom )
{
int need_ca_bit;
/* Parent must be the issuer */
if( x509_name_cmp( &child->issuer, &parent->subject ) != 0 )
return( -1 );
/* Parent must have the basicConstraints CA bit set as a general rule */
need_ca_bit = 1;
/* Exception: v1/v2 certificates that are locally trusted. */
if( top && parent->version < 3 )
need_ca_bit = 0;
/* Exception: self-signed end-entity certs that are locally trusted. */
if( top && bottom &&
child->raw.len == parent->raw.len &&
memcmp( child->raw.p, parent->raw.p, child->raw.len ) == 0 )
{
need_ca_bit = 0;
}
if( need_ca_bit && ! parent->ca_istrue )
return( -1 );
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
if( need_ca_bit &&
mbedtls_x509_crt_check_key_usage( parent, MBEDTLS_X509_KU_KEY_CERT_SIGN ) != 0 )
{
return( -1 );
}
#endif
return( 0 );
}
static int x509_crt_verify_top(
mbedtls_x509_crt *child, mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
int path_cnt, int self_cnt, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
int ret;
uint32_t ca_flags = 0;
int check_path_cnt;
unsigned char hash[MBEDTLS_MD_MAX_SIZE];
const mbedtls_md_info_t *md_info;
mbedtls_x509_crt *future_past_ca = NULL;
if( mbedtls_x509_time_is_past( &child->valid_to ) )
*flags |= MBEDTLS_X509_BADCERT_EXPIRED;
if( mbedtls_x509_time_is_future( &child->valid_from ) )
*flags |= MBEDTLS_X509_BADCERT_FUTURE;
if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_MD;
if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
/*
* Child is the top of the chain. Check against the trust_ca list.
*/
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
md_info = mbedtls_md_info_from_type( child->sig_md );
if( md_info == NULL )
{
/*
* Cannot check 'unknown', no need to try any CA
*/
trust_ca = NULL;
}
else
mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash );
for( /* trust_ca */ ; trust_ca != NULL; trust_ca = trust_ca->next )
{
if( x509_crt_check_parent( child, trust_ca, 1, path_cnt == 0 ) != 0 )
continue;
check_path_cnt = path_cnt + 1;
/*
* Reduce check_path_cnt to check against if top of the chain is
* the same as the trusted CA
*/
if( child->subject_raw.len == trust_ca->subject_raw.len &&
memcmp( child->subject_raw.p, trust_ca->subject_raw.p,
child->issuer_raw.len ) == 0 )
{
check_path_cnt--;
}
/* Self signed certificates do not count towards the limit */
if( trust_ca->max_pathlen > 0 &&
trust_ca->max_pathlen < check_path_cnt - self_cnt )
{
continue;
}
if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &trust_ca->pk,
child->sig_md, hash, mbedtls_md_get_size( md_info ),
child->sig.p, child->sig.len ) != 0 )
{
continue;
}
if( mbedtls_x509_time_is_past( &trust_ca->valid_to ) ||
mbedtls_x509_time_is_future( &trust_ca->valid_from ) )
{
if ( future_past_ca == NULL )
future_past_ca = trust_ca;
continue;
}
break;
}
if( trust_ca != NULL || ( trust_ca = future_past_ca ) != NULL )
{
/*
* Top of chain is signed by a trusted CA
*/
*flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
if( x509_profile_check_key( profile, child->sig_pk, &trust_ca->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
}
/*
* If top of chain is not the same as the trusted CA send a verify request
* to the callback for any issues with validity and CRL presence for the
* trusted CA certificate.
*/
if( trust_ca != NULL &&
( child->subject_raw.len != trust_ca->subject_raw.len ||
memcmp( child->subject_raw.p, trust_ca->subject_raw.p,
child->issuer_raw.len ) != 0 ) )
{
#if defined(MBEDTLS_X509_CRL_PARSE_C)
/* Check trusted CA's CRL for the chain's top crt */
*flags |= x509_crt_verifycrl( child, trust_ca, ca_crl, profile );
#else
((void) ca_crl);
#endif
if( mbedtls_x509_time_is_past( &trust_ca->valid_to ) )
ca_flags |= MBEDTLS_X509_BADCERT_EXPIRED;
if( mbedtls_x509_time_is_future( &trust_ca->valid_from ) )
ca_flags |= MBEDTLS_X509_BADCERT_FUTURE;
if( NULL != f_vrfy )
{
if( ( ret = f_vrfy( p_vrfy, trust_ca, path_cnt + 1,
&ca_flags ) ) != 0 )
{
return( ret );
}
}
}
/* Call callback on top cert */
if( NULL != f_vrfy )
{
if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 )
return( ret );
}
*flags |= ca_flags;
return( 0 );
}
static int x509_crt_verify_child(
mbedtls_x509_crt *child, mbedtls_x509_crt *parent,
mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
int path_cnt, int self_cnt, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
int ret;
uint32_t parent_flags = 0;
unsigned char hash[MBEDTLS_MD_MAX_SIZE];
mbedtls_x509_crt *grandparent;
const mbedtls_md_info_t *md_info;
/* Counting intermediate self signed certificates */
if( ( path_cnt != 0 ) && x509_name_cmp( &child->issuer, &child->subject ) == 0 )
self_cnt++;
/* path_cnt is 0 for the first intermediate CA */
if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA )
{
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
}
if( mbedtls_x509_time_is_past( &child->valid_to ) )
*flags |= MBEDTLS_X509_BADCERT_EXPIRED;
if( mbedtls_x509_time_is_future( &child->valid_from ) )
*flags |= MBEDTLS_X509_BADCERT_FUTURE;
if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_MD;
if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
md_info = mbedtls_md_info_from_type( child->sig_md );
if( md_info == NULL )
{
/*
* Cannot check 'unknown' hash
*/
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
}
else
{
mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash );
if( x509_profile_check_key( profile, child->sig_pk, &parent->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk,
child->sig_md, hash, mbedtls_md_get_size( md_info ),
child->sig.p, child->sig.len ) != 0 )
{
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
}
}
#if defined(MBEDTLS_X509_CRL_PARSE_C)
/* Check trusted CA's CRL for the given crt */
*flags |= x509_crt_verifycrl(child, parent, ca_crl, profile );
#endif
/* Look for a grandparent in trusted CAs */
for( grandparent = trust_ca;
grandparent != NULL;
grandparent = grandparent->next )
{
if( x509_crt_check_parent( parent, grandparent,
0, path_cnt == 0 ) == 0 )
break;
}
if( grandparent != NULL )
{
ret = x509_crt_verify_top( parent, grandparent, ca_crl, profile,
path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
else
{
/* Look for a grandparent upwards the chain */
for( grandparent = parent->next;
grandparent != NULL;
grandparent = grandparent->next )
{
/* +2 because the current step is not yet accounted for
* and because max_pathlen is one higher than it should be.
* Also self signed certificates do not count to the limit. */
if( grandparent->max_pathlen > 0 &&
grandparent->max_pathlen < 2 + path_cnt - self_cnt )
{
continue;
}
if( x509_crt_check_parent( parent, grandparent,
0, path_cnt == 0 ) == 0 )
break;
}
/* Is our parent part of the chain or at the top? */
if( grandparent != NULL )
{
ret = x509_crt_verify_child( parent, grandparent, trust_ca, ca_crl,
profile, path_cnt + 1, self_cnt, &parent_flags,
f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
else
{
ret = x509_crt_verify_top( parent, trust_ca, ca_crl, profile,
path_cnt + 1, self_cnt, &parent_flags,
f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
}
/* child is verified to be a child of the parent, call verify callback */
if( NULL != f_vrfy )
if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 )
return( ret );
*flags |= parent_flags;
return( 0 );
}
/*
* Verify the certificate validity
*/
int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
return( mbedtls_x509_crt_verify_with_profile( crt, trust_ca, ca_crl,
&mbedtls_x509_crt_profile_default, cn, flags, f_vrfy, p_vrfy ) );
}
/*
* Verify the certificate validity, with profile
*/
int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
size_t cn_len;
int ret;
int pathlen = 0, selfsigned = 0;
mbedtls_x509_crt *parent;
mbedtls_x509_name *name;
mbedtls_x509_sequence *cur = NULL;
mbedtls_pk_type_t pk_type;
if( profile == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
*flags = 0;
if( cn != NULL )
{
name = &crt->subject;
cn_len = strlen( cn );
if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
{
cur = &crt->subject_alt_names;
while( cur != NULL )
{
if( cur->buf.len == cn_len &&
x509_memcasecmp( cn, cur->buf.p, cn_len ) == 0 )
break;
if( cur->buf.len > 2 &&
memcmp( cur->buf.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &cur->buf ) == 0 )
{
break;
}
cur = cur->next;
}
if( cur == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
else
{
while( name != NULL )
{
if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 )
{
if( name->val.len == cn_len &&
x509_memcasecmp( name->val.p, cn, cn_len ) == 0 )
break;
if( name->val.len > 2 &&
memcmp( name->val.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &name->val ) == 0 )
break;
}
name = name->next;
}
if( name == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
}
/* Check the type and size of the key */
pk_type = mbedtls_pk_get_type( &crt->pk );
if( x509_profile_check_pk_alg( profile, pk_type ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
if( x509_profile_check_key( profile, pk_type, &crt->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
/* Look for a parent in trusted CAs */
for( parent = trust_ca; parent != NULL; parent = parent->next )
{
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
}
if( parent != NULL )
{
ret = x509_crt_verify_top( crt, parent, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
else
{
/* Look for a parent upwards the chain */
for( parent = crt->next; parent != NULL; parent = parent->next )
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
/* Are we part of the chain or at the top? */
if( parent != NULL )
{
ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
else
{
ret = x509_crt_verify_top( crt, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
}
if( *flags != 0 )
return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
return( 0 );
}
/*
* Initialize a certificate chain
*/
void mbedtls_x509_crt_init( mbedtls_x509_crt *crt )
{
memset( crt, 0, sizeof(mbedtls_x509_crt) );
}
/*
* Unallocate all certificate data
*/
void mbedtls_x509_crt_free( mbedtls_x509_crt *crt )
{
mbedtls_x509_crt *cert_cur = crt;
mbedtls_x509_crt *cert_prv;
mbedtls_x509_name *name_cur;
mbedtls_x509_name *name_prv;
mbedtls_x509_sequence *seq_cur;
mbedtls_x509_sequence *seq_prv;
if( crt == NULL )
return;
do
{
mbedtls_pk_free( &cert_cur->pk );
#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
mbedtls_free( cert_cur->sig_opts );
#endif
name_cur = cert_cur->issuer.next;
while( name_cur != NULL )
{
name_prv = name_cur;
name_cur = name_cur->next;
mbedtls_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
mbedtls_free( name_prv );
}
name_cur = cert_cur->subject.next;
while( name_cur != NULL )
{
name_prv = name_cur;
name_cur = name_cur->next;
mbedtls_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
mbedtls_free( name_prv );
}
seq_cur = cert_cur->ext_key_usage.next;
while( seq_cur != NULL )
{
seq_prv = seq_cur;
seq_cur = seq_cur->next;
mbedtls_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) );
mbedtls_free( seq_prv );
}
seq_cur = cert_cur->subject_alt_names.next;
while( seq_cur != NULL )
{
seq_prv = seq_cur;
seq_cur = seq_cur->next;
mbedtls_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) );
mbedtls_free( seq_prv );
}
if( cert_cur->raw.p != NULL )
{
mbedtls_zeroize( cert_cur->raw.p, cert_cur->raw.len );
mbedtls_free( cert_cur->raw.p );
}
cert_cur = cert_cur->next;
}
while( cert_cur != NULL );
cert_cur = crt;
do
{
cert_prv = cert_cur;
cert_cur = cert_cur->next;
mbedtls_zeroize( cert_prv, sizeof( mbedtls_x509_crt ) );
if( cert_prv != crt )
mbedtls_free( cert_prv );
}
while( cert_cur != NULL );
}
#endif /* MBEDTLS_X509_CRT_PARSE_C */
| ./CrossVul/dataset_final_sorted/CWE-287/c/bad_2757_1 |
crossvul-cpp_data_good_5264_1 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/*
* Source file for all NSS-specific code for the TLS/SSL layer. No code
* but vtls.c should ever call or use these functions.
*/
#include "curl_setup.h"
#ifdef USE_NSS
#include "urldata.h"
#include "sendf.h"
#include "formdata.h" /* for the boundary function */
#include "url.h" /* for the ssl config check function */
#include "connect.h"
#include "strequal.h"
#include "select.h"
#include "vtls.h"
#include "llist.h"
#include "curl_printf.h"
#include "nssg.h"
#include <nspr.h>
#include <nss.h>
#include <ssl.h>
#include <sslerr.h>
#include <secerr.h>
#include <secmod.h>
#include <sslproto.h>
#include <prtypes.h>
#include <pk11pub.h>
#include <prio.h>
#include <secitem.h>
#include <secport.h>
#include <certdb.h>
#include <base64.h>
#include <cert.h>
#include <prerror.h>
#include <keyhi.h> /* for SECKEY_DestroyPublicKey() */
#define NSSVERNUM ((NSS_VMAJOR<<16)|(NSS_VMINOR<<8)|NSS_VPATCH)
#if NSSVERNUM >= 0x030f00 /* 3.15.0 */
#include <ocsp.h>
#endif
#include "rawstr.h"
#include "warnless.h"
#include "x509asn1.h"
/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"
#define SSL_DIR "/etc/pki/nssdb"
/* enough to fit the string "PEM Token #[0|1]" */
#define SLOTSIZE 13
PRFileDesc *PR_ImportTCPSocket(PRInt32 osfd);
static PRLock *nss_initlock = NULL;
static PRLock *nss_crllock = NULL;
static struct curl_llist *nss_crl_list = NULL;
static NSSInitContext *nss_context = NULL;
static volatile int initialized = 0;
typedef struct {
const char *name;
int num;
} cipher_s;
#define PK11_SETATTRS(_attr, _idx, _type, _val, _len) do { \
CK_ATTRIBUTE *ptr = (_attr) + ((_idx)++); \
ptr->type = (_type); \
ptr->pValue = (_val); \
ptr->ulValueLen = (_len); \
} WHILE_FALSE
#define CERT_NewTempCertificate __CERT_NewTempCertificate
#define NUM_OF_CIPHERS sizeof(cipherlist)/sizeof(cipherlist[0])
static const cipher_s cipherlist[] = {
/* SSL2 cipher suites */
{"rc4", SSL_EN_RC4_128_WITH_MD5},
{"rc4-md5", SSL_EN_RC4_128_WITH_MD5},
{"rc4export", SSL_EN_RC4_128_EXPORT40_WITH_MD5},
{"rc2", SSL_EN_RC2_128_CBC_WITH_MD5},
{"rc2export", SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5},
{"des", SSL_EN_DES_64_CBC_WITH_MD5},
{"desede3", SSL_EN_DES_192_EDE3_CBC_WITH_MD5},
/* SSL3/TLS cipher suites */
{"rsa_rc4_128_md5", SSL_RSA_WITH_RC4_128_MD5},
{"rsa_rc4_128_sha", SSL_RSA_WITH_RC4_128_SHA},
{"rsa_3des_sha", SSL_RSA_WITH_3DES_EDE_CBC_SHA},
{"rsa_des_sha", SSL_RSA_WITH_DES_CBC_SHA},
{"rsa_rc4_40_md5", SSL_RSA_EXPORT_WITH_RC4_40_MD5},
{"rsa_rc2_40_md5", SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5},
{"rsa_null_md5", SSL_RSA_WITH_NULL_MD5},
{"rsa_null_sha", SSL_RSA_WITH_NULL_SHA},
{"fips_3des_sha", SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA},
{"fips_des_sha", SSL_RSA_FIPS_WITH_DES_CBC_SHA},
{"fortezza", SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA},
{"fortezza_rc4_128_sha", SSL_FORTEZZA_DMS_WITH_RC4_128_SHA},
{"fortezza_null", SSL_FORTEZZA_DMS_WITH_NULL_SHA},
/* TLS 1.0: Exportable 56-bit Cipher Suites. */
{"rsa_des_56_sha", TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA},
{"rsa_rc4_56_sha", TLS_RSA_EXPORT1024_WITH_RC4_56_SHA},
/* AES ciphers. */
{"dhe_dss_aes_128_cbc_sha", TLS_DHE_DSS_WITH_AES_128_CBC_SHA},
{"dhe_dss_aes_256_cbc_sha", TLS_DHE_DSS_WITH_AES_256_CBC_SHA},
{"dhe_rsa_aes_128_cbc_sha", TLS_DHE_RSA_WITH_AES_128_CBC_SHA},
{"dhe_rsa_aes_256_cbc_sha", TLS_DHE_RSA_WITH_AES_256_CBC_SHA},
{"rsa_aes_128_sha", TLS_RSA_WITH_AES_128_CBC_SHA},
{"rsa_aes_256_sha", TLS_RSA_WITH_AES_256_CBC_SHA},
/* ECC ciphers. */
{"ecdh_ecdsa_null_sha", TLS_ECDH_ECDSA_WITH_NULL_SHA},
{"ecdh_ecdsa_rc4_128_sha", TLS_ECDH_ECDSA_WITH_RC4_128_SHA},
{"ecdh_ecdsa_3des_sha", TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA},
{"ecdh_ecdsa_aes_128_sha", TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA},
{"ecdh_ecdsa_aes_256_sha", TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA},
{"ecdhe_ecdsa_null_sha", TLS_ECDHE_ECDSA_WITH_NULL_SHA},
{"ecdhe_ecdsa_rc4_128_sha", TLS_ECDHE_ECDSA_WITH_RC4_128_SHA},
{"ecdhe_ecdsa_3des_sha", TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA},
{"ecdhe_ecdsa_aes_128_sha", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA},
{"ecdhe_ecdsa_aes_256_sha", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
{"ecdh_rsa_null_sha", TLS_ECDH_RSA_WITH_NULL_SHA},
{"ecdh_rsa_128_sha", TLS_ECDH_RSA_WITH_RC4_128_SHA},
{"ecdh_rsa_3des_sha", TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA},
{"ecdh_rsa_aes_128_sha", TLS_ECDH_RSA_WITH_AES_128_CBC_SHA},
{"ecdh_rsa_aes_256_sha", TLS_ECDH_RSA_WITH_AES_256_CBC_SHA},
{"echde_rsa_null", TLS_ECDHE_RSA_WITH_NULL_SHA},
{"ecdhe_rsa_rc4_128_sha", TLS_ECDHE_RSA_WITH_RC4_128_SHA},
{"ecdhe_rsa_3des_sha", TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA},
{"ecdhe_rsa_aes_128_sha", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
{"ecdhe_rsa_aes_256_sha", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
{"ecdh_anon_null_sha", TLS_ECDH_anon_WITH_NULL_SHA},
{"ecdh_anon_rc4_128sha", TLS_ECDH_anon_WITH_RC4_128_SHA},
{"ecdh_anon_3des_sha", TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA},
{"ecdh_anon_aes_128_sha", TLS_ECDH_anon_WITH_AES_128_CBC_SHA},
{"ecdh_anon_aes_256_sha", TLS_ECDH_anon_WITH_AES_256_CBC_SHA},
#ifdef TLS_RSA_WITH_NULL_SHA256
/* new HMAC-SHA256 cipher suites specified in RFC */
{"rsa_null_sha_256", TLS_RSA_WITH_NULL_SHA256},
{"rsa_aes_128_cbc_sha_256", TLS_RSA_WITH_AES_128_CBC_SHA256},
{"rsa_aes_256_cbc_sha_256", TLS_RSA_WITH_AES_256_CBC_SHA256},
{"dhe_rsa_aes_128_cbc_sha_256", TLS_DHE_RSA_WITH_AES_128_CBC_SHA256},
{"dhe_rsa_aes_256_cbc_sha_256", TLS_DHE_RSA_WITH_AES_256_CBC_SHA256},
{"ecdhe_ecdsa_aes_128_cbc_sha_256", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256},
{"ecdhe_rsa_aes_128_cbc_sha_256", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256},
#endif
#ifdef TLS_RSA_WITH_AES_128_GCM_SHA256
/* AES GCM cipher suites in RFC 5288 and RFC 5289 */
{"rsa_aes_128_gcm_sha_256", TLS_RSA_WITH_AES_128_GCM_SHA256},
{"dhe_rsa_aes_128_gcm_sha_256", TLS_DHE_RSA_WITH_AES_128_GCM_SHA256},
{"dhe_dss_aes_128_gcm_sha_256", TLS_DHE_DSS_WITH_AES_128_GCM_SHA256},
{"ecdhe_ecdsa_aes_128_gcm_sha_256", TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
{"ecdh_ecdsa_aes_128_gcm_sha_256", TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256},
{"ecdhe_rsa_aes_128_gcm_sha_256", TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
{"ecdh_rsa_aes_128_gcm_sha_256", TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256},
#endif
};
static const char* pem_library = "libnsspem.so";
static SECMODModule* mod = NULL;
/* NSPR I/O layer we use to detect blocking direction during SSL handshake */
static PRDescIdentity nspr_io_identity = PR_INVALID_IO_LAYER;
static PRIOMethods nspr_io_methods;
static const char* nss_error_to_name(PRErrorCode code)
{
const char *name = PR_ErrorToName(code);
if(name)
return name;
return "unknown error";
}
static void nss_print_error_message(struct Curl_easy *data, PRUint32 err)
{
failf(data, "%s", PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));
}
static SECStatus set_ciphers(struct Curl_easy *data, PRFileDesc * model,
char *cipher_list)
{
unsigned int i;
PRBool cipher_state[NUM_OF_CIPHERS];
PRBool found;
char *cipher;
/* use accessors to avoid dynamic linking issues after an update of NSS */
const PRUint16 num_implemented_ciphers = SSL_GetNumImplementedCiphers();
const PRUint16 *implemented_ciphers = SSL_GetImplementedCiphers();
if(!implemented_ciphers)
return SECFailure;
/* First disable all ciphers. This uses a different max value in case
* NSS adds more ciphers later we don't want them available by
* accident
*/
for(i = 0; i < num_implemented_ciphers; i++) {
SSL_CipherPrefSet(model, implemented_ciphers[i], PR_FALSE);
}
/* Set every entry in our list to false */
for(i = 0; i < NUM_OF_CIPHERS; i++) {
cipher_state[i] = PR_FALSE;
}
cipher = cipher_list;
while(cipher_list && (cipher_list[0])) {
while((*cipher) && (ISSPACE(*cipher)))
++cipher;
if((cipher_list = strchr(cipher, ','))) {
*cipher_list++ = '\0';
}
found = PR_FALSE;
for(i=0; i<NUM_OF_CIPHERS; i++) {
if(Curl_raw_equal(cipher, cipherlist[i].name)) {
cipher_state[i] = PR_TRUE;
found = PR_TRUE;
break;
}
}
if(found == PR_FALSE) {
failf(data, "Unknown cipher in list: %s", cipher);
return SECFailure;
}
if(cipher_list) {
cipher = cipher_list;
}
}
/* Finally actually enable the selected ciphers */
for(i=0; i<NUM_OF_CIPHERS; i++) {
if(!cipher_state[i])
continue;
if(SSL_CipherPrefSet(model, cipherlist[i].num, PR_TRUE) != SECSuccess) {
failf(data, "cipher-suite not supported by NSS: %s", cipherlist[i].name);
return SECFailure;
}
}
return SECSuccess;
}
/*
* Return true if at least one cipher-suite is enabled. Used to determine
* if we need to call NSS_SetDomesticPolicy() to enable the default ciphers.
*/
static bool any_cipher_enabled(void)
{
unsigned int i;
for(i=0; i<NUM_OF_CIPHERS; i++) {
PRInt32 policy = 0;
SSL_CipherPolicyGet(cipherlist[i].num, &policy);
if(policy)
return TRUE;
}
return FALSE;
}
/*
* Determine whether the nickname passed in is a filename that needs to
* be loaded as a PEM or a regular NSS nickname.
*
* returns 1 for a file
* returns 0 for not a file (NSS nickname)
*/
static int is_file(const char *filename)
{
struct_stat st;
if(filename == NULL)
return 0;
if(stat(filename, &st) == 0)
if(S_ISREG(st.st_mode))
return 1;
return 0;
}
/* Check if the given string is filename or nickname of a certificate. If the
* given string is recognized as filename, return NULL. If the given string is
* recognized as nickname, return a duplicated string. The returned string
* should be later deallocated using free(). If the OOM failure occurs, we
* return NULL, too.
*/
static char* dup_nickname(struct Curl_easy *data, enum dupstring cert_kind)
{
const char *str = data->set.str[cert_kind];
const char *n;
if(!is_file(str))
/* no such file exists, use the string as nickname */
return strdup(str);
/* search the first slash; we require at least one slash in a file name */
n = strchr(str, '/');
if(!n) {
infof(data, "warning: certificate file name \"%s\" handled as nickname; "
"please use \"./%s\" to force file name\n", str, str);
return strdup(str);
}
/* we'll use the PEM reader to read the certificate from file */
return NULL;
}
/* Call PK11_CreateGenericObject() with the given obj_class and filename. If
* the call succeeds, append the object handle to the list of objects so that
* the object can be destroyed in Curl_nss_close(). */
static CURLcode nss_create_object(struct ssl_connect_data *ssl,
CK_OBJECT_CLASS obj_class,
const char *filename, bool cacert)
{
PK11SlotInfo *slot;
PK11GenericObject *obj;
CK_BBOOL cktrue = CK_TRUE;
CK_BBOOL ckfalse = CK_FALSE;
CK_ATTRIBUTE attrs[/* max count of attributes */ 4];
int attr_cnt = 0;
CURLcode result = (cacert)
? CURLE_SSL_CACERT_BADFILE
: CURLE_SSL_CERTPROBLEM;
const int slot_id = (cacert) ? 0 : 1;
char *slot_name = aprintf("PEM Token #%d", slot_id);
if(!slot_name)
return CURLE_OUT_OF_MEMORY;
slot = PK11_FindSlotByName(slot_name);
free(slot_name);
if(!slot)
return result;
PK11_SETATTRS(attrs, attr_cnt, CKA_CLASS, &obj_class, sizeof(obj_class));
PK11_SETATTRS(attrs, attr_cnt, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL));
PK11_SETATTRS(attrs, attr_cnt, CKA_LABEL, (unsigned char *)filename,
strlen(filename) + 1);
if(CKO_CERTIFICATE == obj_class) {
CK_BBOOL *pval = (cacert) ? (&cktrue) : (&ckfalse);
PK11_SETATTRS(attrs, attr_cnt, CKA_TRUST, pval, sizeof(*pval));
}
obj = PK11_CreateGenericObject(slot, attrs, attr_cnt, PR_FALSE);
PK11_FreeSlot(slot);
if(!obj)
return result;
if(!Curl_llist_insert_next(ssl->obj_list, ssl->obj_list->tail, obj)) {
PK11_DestroyGenericObject(obj);
return CURLE_OUT_OF_MEMORY;
}
if(!cacert && CKO_CERTIFICATE == obj_class)
/* store reference to a client certificate */
ssl->obj_clicert = obj;
return CURLE_OK;
}
/* Destroy the NSS object whose handle is given by ptr. This function is
* a callback of Curl_llist_alloc() used by Curl_llist_destroy() to destroy
* NSS objects in Curl_nss_close() */
static void nss_destroy_object(void *user, void *ptr)
{
PK11GenericObject *obj = (PK11GenericObject *)ptr;
(void) user;
PK11_DestroyGenericObject(obj);
}
/* same as nss_destroy_object() but for CRL items */
static void nss_destroy_crl_item(void *user, void *ptr)
{
SECItem *crl_der = (SECItem *)ptr;
(void) user;
SECITEM_FreeItem(crl_der, PR_TRUE);
}
static CURLcode nss_load_cert(struct ssl_connect_data *ssl,
const char *filename, PRBool cacert)
{
CURLcode result = (cacert)
? CURLE_SSL_CACERT_BADFILE
: CURLE_SSL_CERTPROBLEM;
/* libnsspem.so leaks memory if the requested file does not exist. For more
* details, go to <https://bugzilla.redhat.com/734760>. */
if(is_file(filename))
result = nss_create_object(ssl, CKO_CERTIFICATE, filename, cacert);
if(!result && !cacert) {
/* we have successfully loaded a client certificate */
CERTCertificate *cert;
char *nickname = NULL;
char *n = strrchr(filename, '/');
if(n)
n++;
/* The following undocumented magic helps to avoid a SIGSEGV on call
* of PK11_ReadRawAttribute() from SelectClientCert() when using an
* immature version of libnsspem.so. For more details, go to
* <https://bugzilla.redhat.com/733685>. */
nickname = aprintf("PEM Token #1:%s", n);
if(nickname) {
cert = PK11_FindCertFromNickname(nickname, NULL);
if(cert)
CERT_DestroyCertificate(cert);
free(nickname);
}
}
return result;
}
/* add given CRL to cache if it is not already there */
static CURLcode nss_cache_crl(SECItem *crl_der)
{
CERTCertDBHandle *db = CERT_GetDefaultCertDB();
CERTSignedCrl *crl = SEC_FindCrlByDERCert(db, crl_der, 0);
if(crl) {
/* CRL already cached */
SEC_DestroyCrl(crl);
SECITEM_FreeItem(crl_der, PR_TRUE);
return CURLE_OK;
}
/* acquire lock before call of CERT_CacheCRL() and accessing nss_crl_list */
PR_Lock(nss_crllock);
/* store the CRL item so that we can free it in Curl_nss_cleanup() */
if(!Curl_llist_insert_next(nss_crl_list, nss_crl_list->tail, crl_der)) {
SECITEM_FreeItem(crl_der, PR_TRUE);
PR_Unlock(nss_crllock);
return CURLE_OUT_OF_MEMORY;
}
if(SECSuccess != CERT_CacheCRL(db, crl_der)) {
/* unable to cache CRL */
PR_Unlock(nss_crllock);
return CURLE_SSL_CRL_BADFILE;
}
/* we need to clear session cache, so that the CRL could take effect */
SSL_ClearSessionCache();
PR_Unlock(nss_crllock);
return CURLE_OK;
}
static CURLcode nss_load_crl(const char* crlfilename)
{
PRFileDesc *infile;
PRFileInfo info;
SECItem filedata = { 0, NULL, 0 };
SECItem *crl_der = NULL;
char *body;
infile = PR_Open(crlfilename, PR_RDONLY, 0);
if(!infile)
return CURLE_SSL_CRL_BADFILE;
if(PR_SUCCESS != PR_GetOpenFileInfo(infile, &info))
goto fail;
if(!SECITEM_AllocItem(NULL, &filedata, info.size + /* zero ended */ 1))
goto fail;
if(info.size != PR_Read(infile, filedata.data, info.size))
goto fail;
crl_der = SECITEM_AllocItem(NULL, NULL, 0U);
if(!crl_der)
goto fail;
/* place a trailing zero right after the visible data */
body = (char*)filedata.data;
body[--filedata.len] = '\0';
body = strstr(body, "-----BEGIN");
if(body) {
/* assume ASCII */
char *trailer;
char *begin = PORT_Strchr(body, '\n');
if(!begin)
begin = PORT_Strchr(body, '\r');
if(!begin)
goto fail;
trailer = strstr(++begin, "-----END");
if(!trailer)
goto fail;
/* retrieve DER from ASCII */
*trailer = '\0';
if(ATOB_ConvertAsciiToItem(crl_der, begin))
goto fail;
SECITEM_FreeItem(&filedata, PR_FALSE);
}
else
/* assume DER */
*crl_der = filedata;
PR_Close(infile);
return nss_cache_crl(crl_der);
fail:
PR_Close(infile);
SECITEM_FreeItem(crl_der, PR_TRUE);
SECITEM_FreeItem(&filedata, PR_FALSE);
return CURLE_SSL_CRL_BADFILE;
}
static CURLcode nss_load_key(struct connectdata *conn, int sockindex,
char *key_file)
{
PK11SlotInfo *slot;
SECStatus status;
CURLcode result;
struct ssl_connect_data *ssl = conn->ssl;
(void)sockindex; /* unused */
result = nss_create_object(ssl, CKO_PRIVATE_KEY, key_file, FALSE);
if(result) {
PR_SetError(SEC_ERROR_BAD_KEY, 0);
return result;
}
slot = PK11_FindSlotByName("PEM Token #1");
if(!slot)
return CURLE_SSL_CERTPROBLEM;
/* This will force the token to be seen as re-inserted */
SECMOD_WaitForAnyTokenEvent(mod, 0, 0);
PK11_IsPresent(slot);
status = PK11_Authenticate(slot, PR_TRUE,
conn->data->set.str[STRING_KEY_PASSWD]);
PK11_FreeSlot(slot);
return (SECSuccess == status) ? CURLE_OK : CURLE_SSL_CERTPROBLEM;
}
static int display_error(struct connectdata *conn, PRInt32 err,
const char *filename)
{
switch(err) {
case SEC_ERROR_BAD_PASSWORD:
failf(conn->data, "Unable to load client key: Incorrect password");
return 1;
case SEC_ERROR_UNKNOWN_CERT:
failf(conn->data, "Unable to load certificate %s", filename);
return 1;
default:
break;
}
return 0; /* The caller will print a generic error */
}
static CURLcode cert_stuff(struct connectdata *conn, int sockindex,
char *cert_file, char *key_file)
{
struct Curl_easy *data = conn->data;
CURLcode result;
if(cert_file) {
result = nss_load_cert(&conn->ssl[sockindex], cert_file, PR_FALSE);
if(result) {
const PRErrorCode err = PR_GetError();
if(!display_error(conn, err, cert_file)) {
const char *err_name = nss_error_to_name(err);
failf(data, "unable to load client cert: %d (%s)", err, err_name);
}
return result;
}
}
if(key_file || (is_file(cert_file))) {
if(key_file)
result = nss_load_key(conn, sockindex, key_file);
else
/* In case the cert file also has the key */
result = nss_load_key(conn, sockindex, cert_file);
if(result) {
const PRErrorCode err = PR_GetError();
if(!display_error(conn, err, key_file)) {
const char *err_name = nss_error_to_name(err);
failf(data, "unable to load client key: %d (%s)", err, err_name);
}
return result;
}
}
return CURLE_OK;
}
static char * nss_get_password(PK11SlotInfo * slot, PRBool retry, void *arg)
{
(void)slot; /* unused */
if(retry || NULL == arg)
return NULL;
else
return (char *)PORT_Strdup((char *)arg);
}
/* bypass the default SSL_AuthCertificate() hook in case we do not want to
* verify peer */
static SECStatus nss_auth_cert_hook(void *arg, PRFileDesc *fd, PRBool checksig,
PRBool isServer)
{
struct connectdata *conn = (struct connectdata *)arg;
#ifdef SSL_ENABLE_OCSP_STAPLING
if(conn->data->set.ssl.verifystatus) {
SECStatus cacheResult;
const SECItemArray *csa = SSL_PeerStapledOCSPResponses(fd);
if(!csa) {
failf(conn->data, "Invalid OCSP response");
return SECFailure;
}
if(csa->len == 0) {
failf(conn->data, "No OCSP response received");
return SECFailure;
}
cacheResult = CERT_CacheOCSPResponseFromSideChannel(
CERT_GetDefaultCertDB(), SSL_PeerCertificate(fd),
PR_Now(), &csa->items[0], arg
);
if(cacheResult != SECSuccess) {
failf(conn->data, "Invalid OCSP response");
return cacheResult;
}
}
#endif
if(!conn->data->set.ssl.verifypeer) {
infof(conn->data, "skipping SSL peer certificate verification\n");
return SECSuccess;
}
return SSL_AuthCertificate(CERT_GetDefaultCertDB(), fd, checksig, isServer);
}
/**
* Inform the application that the handshake is complete.
*/
static void HandshakeCallback(PRFileDesc *sock, void *arg)
{
struct connectdata *conn = (struct connectdata*) arg;
unsigned int buflenmax = 50;
unsigned char buf[50];
unsigned int buflen;
SSLNextProtoState state;
if(!conn->bits.tls_enable_npn && !conn->bits.tls_enable_alpn) {
return;
}
if(SSL_GetNextProto(sock, &state, buf, &buflen, buflenmax) == SECSuccess) {
switch(state) {
case SSL_NEXT_PROTO_NO_SUPPORT:
case SSL_NEXT_PROTO_NO_OVERLAP:
infof(conn->data, "ALPN/NPN, server did not agree to a protocol\n");
return;
#ifdef SSL_ENABLE_ALPN
case SSL_NEXT_PROTO_SELECTED:
infof(conn->data, "ALPN, server accepted to use %.*s\n", buflen, buf);
break;
#endif
case SSL_NEXT_PROTO_NEGOTIATED:
infof(conn->data, "NPN, server accepted to use %.*s\n", buflen, buf);
break;
}
#ifdef USE_NGHTTP2
if(buflen == NGHTTP2_PROTO_VERSION_ID_LEN &&
!memcmp(NGHTTP2_PROTO_VERSION_ID, buf, NGHTTP2_PROTO_VERSION_ID_LEN)) {
conn->negnpn = CURL_HTTP_VERSION_2;
}
else
#endif
if(buflen == ALPN_HTTP_1_1_LENGTH &&
!memcmp(ALPN_HTTP_1_1, buf, ALPN_HTTP_1_1_LENGTH)) {
conn->negnpn = CURL_HTTP_VERSION_1_1;
}
}
}
#if NSSVERNUM >= 0x030f04 /* 3.15.4 */
static SECStatus CanFalseStartCallback(PRFileDesc *sock, void *client_data,
PRBool *canFalseStart)
{
struct connectdata *conn = client_data;
struct Curl_easy *data = conn->data;
SSLChannelInfo channelInfo;
SSLCipherSuiteInfo cipherInfo;
SECStatus rv;
PRBool negotiatedExtension;
*canFalseStart = PR_FALSE;
if(SSL_GetChannelInfo(sock, &channelInfo, sizeof(channelInfo)) != SECSuccess)
return SECFailure;
if(SSL_GetCipherSuiteInfo(channelInfo.cipherSuite, &cipherInfo,
sizeof(cipherInfo)) != SECSuccess)
return SECFailure;
/* Prevent version downgrade attacks from TLS 1.2, and avoid False Start for
* TLS 1.3 and later. See https://bugzilla.mozilla.org/show_bug.cgi?id=861310
*/
if(channelInfo.protocolVersion != SSL_LIBRARY_VERSION_TLS_1_2)
goto end;
/* Only allow ECDHE key exchange algorithm.
* See https://bugzilla.mozilla.org/show_bug.cgi?id=952863 */
if(cipherInfo.keaType != ssl_kea_ecdh)
goto end;
/* Prevent downgrade attacks on the symmetric cipher. We do not allow CBC
* mode due to BEAST, POODLE, and other attacks on the MAC-then-Encrypt
* design. See https://bugzilla.mozilla.org/show_bug.cgi?id=1109766 */
if(cipherInfo.symCipher != ssl_calg_aes_gcm)
goto end;
/* Enforce ALPN or NPN to do False Start, as an indicator of server
* compatibility. */
rv = SSL_HandshakeNegotiatedExtension(sock, ssl_app_layer_protocol_xtn,
&negotiatedExtension);
if(rv != SECSuccess || !negotiatedExtension) {
rv = SSL_HandshakeNegotiatedExtension(sock, ssl_next_proto_nego_xtn,
&negotiatedExtension);
}
if(rv != SECSuccess || !negotiatedExtension)
goto end;
*canFalseStart = PR_TRUE;
infof(data, "Trying TLS False Start\n");
end:
return SECSuccess;
}
#endif
static void display_cert_info(struct Curl_easy *data,
CERTCertificate *cert)
{
char *subject, *issuer, *common_name;
PRExplodedTime printableTime;
char timeString[256];
PRTime notBefore, notAfter;
subject = CERT_NameToAscii(&cert->subject);
issuer = CERT_NameToAscii(&cert->issuer);
common_name = CERT_GetCommonName(&cert->subject);
infof(data, "\tsubject: %s\n", subject);
CERT_GetCertTimes(cert, ¬Before, ¬After);
PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime);
PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
infof(data, "\tstart date: %s\n", timeString);
PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime);
PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
infof(data, "\texpire date: %s\n", timeString);
infof(data, "\tcommon name: %s\n", common_name);
infof(data, "\tissuer: %s\n", issuer);
PR_Free(subject);
PR_Free(issuer);
PR_Free(common_name);
}
static CURLcode display_conn_info(struct connectdata *conn, PRFileDesc *sock)
{
CURLcode result = CURLE_OK;
SSLChannelInfo channel;
SSLCipherSuiteInfo suite;
CERTCertificate *cert;
CERTCertificate *cert2;
CERTCertificate *cert3;
PRTime now;
int i;
if(SSL_GetChannelInfo(sock, &channel, sizeof channel) ==
SECSuccess && channel.length == sizeof channel &&
channel.cipherSuite) {
if(SSL_GetCipherSuiteInfo(channel.cipherSuite,
&suite, sizeof suite) == SECSuccess) {
infof(conn->data, "SSL connection using %s\n", suite.cipherSuiteName);
}
}
cert = SSL_PeerCertificate(sock);
if(cert) {
infof(conn->data, "Server certificate:\n");
if(!conn->data->set.ssl.certinfo) {
display_cert_info(conn->data, cert);
CERT_DestroyCertificate(cert);
}
else {
/* Count certificates in chain. */
now = PR_Now();
i = 1;
if(!cert->isRoot) {
cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
while(cert2) {
i++;
if(cert2->isRoot) {
CERT_DestroyCertificate(cert2);
break;
}
cert3 = CERT_FindCertIssuer(cert2, now, certUsageSSLCA);
CERT_DestroyCertificate(cert2);
cert2 = cert3;
}
}
result = Curl_ssl_init_certinfo(conn->data, i);
if(!result) {
for(i = 0; cert; cert = cert2) {
result = Curl_extract_certinfo(conn, i++, (char *)cert->derCert.data,
(char *)cert->derCert.data +
cert->derCert.len);
if(result)
break;
if(cert->isRoot) {
CERT_DestroyCertificate(cert);
break;
}
cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
CERT_DestroyCertificate(cert);
}
}
}
}
return result;
}
static SECStatus BadCertHandler(void *arg, PRFileDesc *sock)
{
struct connectdata *conn = (struct connectdata *)arg;
struct Curl_easy *data = conn->data;
PRErrorCode err = PR_GetError();
CERTCertificate *cert;
/* remember the cert verification result */
data->set.ssl.certverifyresult = err;
if(err == SSL_ERROR_BAD_CERT_DOMAIN && !data->set.ssl.verifyhost)
/* we are asked not to verify the host name */
return SECSuccess;
/* print only info about the cert, the error is printed off the callback */
cert = SSL_PeerCertificate(sock);
if(cert) {
infof(data, "Server certificate:\n");
display_cert_info(data, cert);
CERT_DestroyCertificate(cert);
}
return SECFailure;
}
/**
*
* Check that the Peer certificate's issuer certificate matches the one found
* by issuer_nickname. This is not exactly the way OpenSSL and GNU TLS do the
* issuer check, so we provide comments that mimic the OpenSSL
* X509_check_issued function (in x509v3/v3_purp.c)
*/
static SECStatus check_issuer_cert(PRFileDesc *sock,
char *issuer_nickname)
{
CERTCertificate *cert, *cert_issuer, *issuer;
SECStatus res=SECSuccess;
void *proto_win = NULL;
cert = SSL_PeerCertificate(sock);
cert_issuer = CERT_FindCertIssuer(cert, PR_Now(), certUsageObjectSigner);
proto_win = SSL_RevealPinArg(sock);
issuer = PK11_FindCertFromNickname(issuer_nickname, proto_win);
if((!cert_issuer) || (!issuer))
res = SECFailure;
else if(SECITEM_CompareItem(&cert_issuer->derCert,
&issuer->derCert)!=SECEqual)
res = SECFailure;
CERT_DestroyCertificate(cert);
CERT_DestroyCertificate(issuer);
CERT_DestroyCertificate(cert_issuer);
return res;
}
static CURLcode cmp_peer_pubkey(struct ssl_connect_data *connssl,
const char *pinnedpubkey)
{
CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
struct Curl_easy *data = connssl->data;
CERTCertificate *cert;
if(!pinnedpubkey)
/* no pinned public key specified */
return CURLE_OK;
/* get peer certificate */
cert = SSL_PeerCertificate(connssl->handle);
if(cert) {
/* extract public key from peer certificate */
SECKEYPublicKey *pubkey = CERT_ExtractPublicKey(cert);
if(pubkey) {
/* encode the public key as DER */
SECItem *cert_der = PK11_DEREncodePublicKey(pubkey);
if(cert_der) {
/* compare the public key with the pinned public key */
result = Curl_pin_peer_pubkey(data, pinnedpubkey, cert_der->data,
cert_der->len);
SECITEM_FreeItem(cert_der, PR_TRUE);
}
SECKEY_DestroyPublicKey(pubkey);
}
CERT_DestroyCertificate(cert);
}
/* report the resulting status */
switch(result) {
case CURLE_OK:
infof(data, "pinned public key verified successfully!\n");
break;
case CURLE_SSL_PINNEDPUBKEYNOTMATCH:
failf(data, "failed to verify pinned public key");
break;
default:
/* OOM, etc. */
break;
}
return result;
}
/**
*
* Callback to pick the SSL client certificate.
*/
static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
struct CERTDistNamesStr *caNames,
struct CERTCertificateStr **pRetCert,
struct SECKEYPrivateKeyStr **pRetKey)
{
struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
struct Curl_easy *data = connssl->data;
const char *nickname = connssl->client_nickname;
static const char pem_slotname[] = "PEM Token #1";
if(connssl->obj_clicert) {
/* use the cert/key provided by PEM reader */
SECItem cert_der = { 0, NULL, 0 };
void *proto_win = SSL_RevealPinArg(sock);
struct CERTCertificateStr *cert;
struct SECKEYPrivateKeyStr *key;
PK11SlotInfo *slot = PK11_FindSlotByName(pem_slotname);
if(NULL == slot) {
failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
return SECFailure;
}
if(PK11_ReadRawAttribute(PK11_TypeGeneric, connssl->obj_clicert, CKA_VALUE,
&cert_der) != SECSuccess) {
failf(data, "NSS: CKA_VALUE not found in PK11 generic object");
PK11_FreeSlot(slot);
return SECFailure;
}
cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win);
SECITEM_FreeItem(&cert_der, PR_FALSE);
if(NULL == cert) {
failf(data, "NSS: client certificate from file not found");
PK11_FreeSlot(slot);
return SECFailure;
}
key = PK11_FindPrivateKeyFromCert(slot, cert, NULL);
PK11_FreeSlot(slot);
if(NULL == key) {
failf(data, "NSS: private key from file not found");
CERT_DestroyCertificate(cert);
return SECFailure;
}
infof(data, "NSS: client certificate from file\n");
display_cert_info(data, cert);
*pRetCert = cert;
*pRetKey = key;
return SECSuccess;
}
/* use the default NSS hook */
if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
pRetCert, pRetKey)
|| NULL == *pRetCert) {
if(NULL == nickname)
failf(data, "NSS: client certificate not found (nickname not "
"specified)");
else
failf(data, "NSS: client certificate not found: %s", nickname);
return SECFailure;
}
/* get certificate nickname if any */
nickname = (*pRetCert)->nickname;
if(NULL == nickname)
nickname = "[unknown]";
if(!strncmp(nickname, pem_slotname, sizeof(pem_slotname) - 1U)) {
failf(data, "NSS: refusing previously loaded certificate from file: %s",
nickname);
return SECFailure;
}
if(NULL == *pRetKey) {
failf(data, "NSS: private key not found for certificate: %s", nickname);
return SECFailure;
}
infof(data, "NSS: using client certificate: %s\n", nickname);
display_cert_info(data, *pRetCert);
return SECSuccess;
}
/* update blocking direction in case of PR_WOULD_BLOCK_ERROR */
static void nss_update_connecting_state(ssl_connect_state state, void *secret)
{
struct ssl_connect_data *connssl = (struct ssl_connect_data *)secret;
if(PR_GetError() != PR_WOULD_BLOCK_ERROR)
/* an unrelated error is passing by */
return;
switch(connssl->connecting_state) {
case ssl_connect_2:
case ssl_connect_2_reading:
case ssl_connect_2_writing:
break;
default:
/* we are not called from an SSL handshake */
return;
}
/* update the state accordingly */
connssl->connecting_state = state;
}
/* recv() wrapper we use to detect blocking direction during SSL handshake */
static PRInt32 nspr_io_recv(PRFileDesc *fd, void *buf, PRInt32 amount,
PRIntn flags, PRIntervalTime timeout)
{
const PRRecvFN recv_fn = fd->lower->methods->recv;
const PRInt32 rv = recv_fn(fd->lower, buf, amount, flags, timeout);
if(rv < 0)
/* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
nss_update_connecting_state(ssl_connect_2_reading, fd->secret);
return rv;
}
/* send() wrapper we use to detect blocking direction during SSL handshake */
static PRInt32 nspr_io_send(PRFileDesc *fd, const void *buf, PRInt32 amount,
PRIntn flags, PRIntervalTime timeout)
{
const PRSendFN send_fn = fd->lower->methods->send;
const PRInt32 rv = send_fn(fd->lower, buf, amount, flags, timeout);
if(rv < 0)
/* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
nss_update_connecting_state(ssl_connect_2_writing, fd->secret);
return rv;
}
/* close() wrapper to avoid assertion failure due to fd->secret != NULL */
static PRStatus nspr_io_close(PRFileDesc *fd)
{
const PRCloseFN close_fn = PR_GetDefaultIOMethods()->close;
fd->secret = NULL;
return close_fn(fd);
}
/* data might be NULL */
static CURLcode nss_init_core(struct Curl_easy *data, const char *cert_dir)
{
NSSInitParameters initparams;
if(nss_context != NULL)
return CURLE_OK;
memset((void *) &initparams, '\0', sizeof(initparams));
initparams.length = sizeof(initparams);
if(cert_dir) {
char *certpath = aprintf("sql:%s", cert_dir);
if(!certpath)
return CURLE_OUT_OF_MEMORY;
infof(data, "Initializing NSS with certpath: %s\n", certpath);
nss_context = NSS_InitContext(certpath, "", "", "", &initparams,
NSS_INIT_READONLY | NSS_INIT_PK11RELOAD);
free(certpath);
if(nss_context != NULL)
return CURLE_OK;
infof(data, "Unable to initialize NSS database\n");
}
infof(data, "Initializing NSS with certpath: none\n");
nss_context = NSS_InitContext("", "", "", "", &initparams, NSS_INIT_READONLY
| NSS_INIT_NOCERTDB | NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN
| NSS_INIT_NOROOTINIT | NSS_INIT_OPTIMIZESPACE | NSS_INIT_PK11RELOAD);
if(nss_context != NULL)
return CURLE_OK;
infof(data, "Unable to initialize NSS\n");
return CURLE_SSL_CACERT_BADFILE;
}
/* data might be NULL */
static CURLcode nss_init(struct Curl_easy *data)
{
char *cert_dir;
struct_stat st;
CURLcode result;
if(initialized)
return CURLE_OK;
/* list of all CRL items we need to destroy in Curl_nss_cleanup() */
nss_crl_list = Curl_llist_alloc(nss_destroy_crl_item);
if(!nss_crl_list)
return CURLE_OUT_OF_MEMORY;
/* First we check if $SSL_DIR points to a valid dir */
cert_dir = getenv("SSL_DIR");
if(cert_dir) {
if((stat(cert_dir, &st) != 0) ||
(!S_ISDIR(st.st_mode))) {
cert_dir = NULL;
}
}
/* Now we check if the default location is a valid dir */
if(!cert_dir) {
if((stat(SSL_DIR, &st) == 0) &&
(S_ISDIR(st.st_mode))) {
cert_dir = (char *)SSL_DIR;
}
}
if(nspr_io_identity == PR_INVALID_IO_LAYER) {
/* allocate an identity for our own NSPR I/O layer */
nspr_io_identity = PR_GetUniqueIdentity("libcurl");
if(nspr_io_identity == PR_INVALID_IO_LAYER)
return CURLE_OUT_OF_MEMORY;
/* the default methods just call down to the lower I/O layer */
memcpy(&nspr_io_methods, PR_GetDefaultIOMethods(), sizeof nspr_io_methods);
/* override certain methods in the table by our wrappers */
nspr_io_methods.recv = nspr_io_recv;
nspr_io_methods.send = nspr_io_send;
nspr_io_methods.close = nspr_io_close;
}
result = nss_init_core(data, cert_dir);
if(result)
return result;
if(!any_cipher_enabled())
NSS_SetDomesticPolicy();
initialized = 1;
return CURLE_OK;
}
/**
* Global SSL init
*
* @retval 0 error initializing SSL
* @retval 1 SSL initialized successfully
*/
int Curl_nss_init(void)
{
/* curl_global_init() is not thread-safe so this test is ok */
if(nss_initlock == NULL) {
PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256);
nss_initlock = PR_NewLock();
nss_crllock = PR_NewLock();
}
/* We will actually initialize NSS later */
return 1;
}
/* data might be NULL */
CURLcode Curl_nss_force_init(struct Curl_easy *data)
{
CURLcode result;
if(!nss_initlock) {
if(data)
failf(data, "unable to initialize NSS, curl_global_init() should have "
"been called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL");
return CURLE_FAILED_INIT;
}
PR_Lock(nss_initlock);
result = nss_init(data);
PR_Unlock(nss_initlock);
return result;
}
/* Global cleanup */
void Curl_nss_cleanup(void)
{
/* This function isn't required to be threadsafe and this is only done
* as a safety feature.
*/
PR_Lock(nss_initlock);
if(initialized) {
/* Free references to client certificates held in the SSL session cache.
* Omitting this hampers destruction of the security module owning
* the certificates. */
SSL_ClearSessionCache();
if(mod && SECSuccess == SECMOD_UnloadUserModule(mod)) {
SECMOD_DestroyModule(mod);
mod = NULL;
}
NSS_ShutdownContext(nss_context);
nss_context = NULL;
}
/* destroy all CRL items */
Curl_llist_destroy(nss_crl_list, NULL);
nss_crl_list = NULL;
PR_Unlock(nss_initlock);
PR_DestroyLock(nss_initlock);
PR_DestroyLock(nss_crllock);
nss_initlock = NULL;
initialized = 0;
}
/*
* This function uses SSL_peek to determine connection status.
*
* Return codes:
* 1 means the connection is still in place
* 0 means the connection has been closed
* -1 means the connection status is unknown
*/
int
Curl_nss_check_cxn(struct connectdata *conn)
{
int rc;
char buf;
rc =
PR_Recv(conn->ssl[FIRSTSOCKET].handle, (void *)&buf, 1, PR_MSG_PEEK,
PR_SecondsToInterval(1));
if(rc > 0)
return 1; /* connection still in place */
if(rc == 0)
return 0; /* connection has been closed */
return -1; /* connection status unknown */
}
/*
* This function is called when an SSL connection is closed.
*/
void Curl_nss_close(struct connectdata *conn, int sockindex)
{
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
if(connssl->handle) {
/* NSS closes the socket we previously handed to it, so we must mark it
as closed to avoid double close */
fake_sclose(conn->sock[sockindex]);
conn->sock[sockindex] = CURL_SOCKET_BAD;
if((connssl->client_nickname != NULL) || (connssl->obj_clicert != NULL))
/* A server might require different authentication based on the
* particular path being requested by the client. To support this
* scenario, we must ensure that a connection will never reuse the
* authentication data from a previous connection. */
SSL_InvalidateSession(connssl->handle);
free(connssl->client_nickname);
connssl->client_nickname = NULL;
/* destroy all NSS objects in order to avoid failure of NSS shutdown */
Curl_llist_destroy(connssl->obj_list, NULL);
connssl->obj_list = NULL;
connssl->obj_clicert = NULL;
PR_Close(connssl->handle);
connssl->handle = NULL;
}
}
/* return true if NSS can provide error code (and possibly msg) for the
error */
static bool is_nss_error(CURLcode err)
{
switch(err) {
case CURLE_PEER_FAILED_VERIFICATION:
case CURLE_SSL_CACERT:
case CURLE_SSL_CERTPROBLEM:
case CURLE_SSL_CONNECT_ERROR:
case CURLE_SSL_ISSUER_ERROR:
return true;
default:
return false;
}
}
/* return true if the given error code is related to a client certificate */
static bool is_cc_error(PRInt32 err)
{
switch(err) {
case SSL_ERROR_BAD_CERT_ALERT:
case SSL_ERROR_EXPIRED_CERT_ALERT:
case SSL_ERROR_REVOKED_CERT_ALERT:
return true;
default:
return false;
}
}
static Curl_recv nss_recv;
static Curl_send nss_send;
static CURLcode nss_load_ca_certificates(struct connectdata *conn,
int sockindex)
{
struct Curl_easy *data = conn->data;
const char *cafile = data->set.ssl.CAfile;
const char *capath = data->set.ssl.CApath;
if(cafile) {
CURLcode result = nss_load_cert(&conn->ssl[sockindex], cafile, PR_TRUE);
if(result)
return result;
}
if(capath) {
struct_stat st;
if(stat(capath, &st) == -1)
return CURLE_SSL_CACERT_BADFILE;
if(S_ISDIR(st.st_mode)) {
PRDirEntry *entry;
PRDir *dir = PR_OpenDir(capath);
if(!dir)
return CURLE_SSL_CACERT_BADFILE;
while((entry = PR_ReadDir(dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN))) {
char *fullpath = aprintf("%s/%s", capath, entry->name);
if(!fullpath) {
PR_CloseDir(dir);
return CURLE_OUT_OF_MEMORY;
}
if(CURLE_OK != nss_load_cert(&conn->ssl[sockindex], fullpath, PR_TRUE))
/* This is purposefully tolerant of errors so non-PEM files can
* be in the same directory */
infof(data, "failed to load '%s' from CURLOPT_CAPATH\n", fullpath);
free(fullpath);
}
PR_CloseDir(dir);
}
else
infof(data, "warning: CURLOPT_CAPATH not a directory (%s)\n", capath);
}
infof(data, " CAfile: %s\n CApath: %s\n",
cafile ? cafile : "none",
capath ? capath : "none");
return CURLE_OK;
}
static CURLcode nss_init_sslver(SSLVersionRange *sslver,
struct Curl_easy *data)
{
switch(data->set.ssl.version) {
default:
case CURL_SSLVERSION_DEFAULT:
case CURL_SSLVERSION_TLSv1:
sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
#ifdef SSL_LIBRARY_VERSION_TLS_1_2
sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
#elif defined SSL_LIBRARY_VERSION_TLS_1_1
sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
#else
sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
#endif
return CURLE_OK;
case CURL_SSLVERSION_SSLv2:
sslver->min = SSL_LIBRARY_VERSION_2;
sslver->max = SSL_LIBRARY_VERSION_2;
return CURLE_OK;
case CURL_SSLVERSION_SSLv3:
sslver->min = SSL_LIBRARY_VERSION_3_0;
sslver->max = SSL_LIBRARY_VERSION_3_0;
return CURLE_OK;
case CURL_SSLVERSION_TLSv1_0:
sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
return CURLE_OK;
case CURL_SSLVERSION_TLSv1_1:
#ifdef SSL_LIBRARY_VERSION_TLS_1_1
sslver->min = SSL_LIBRARY_VERSION_TLS_1_1;
sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
return CURLE_OK;
#endif
break;
case CURL_SSLVERSION_TLSv1_2:
#ifdef SSL_LIBRARY_VERSION_TLS_1_2
sslver->min = SSL_LIBRARY_VERSION_TLS_1_2;
sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
return CURLE_OK;
#endif
break;
}
failf(data, "TLS minor version cannot be set");
return CURLE_SSL_CONNECT_ERROR;
}
static CURLcode nss_fail_connect(struct ssl_connect_data *connssl,
struct Curl_easy *data,
CURLcode curlerr)
{
PRErrorCode err = 0;
if(is_nss_error(curlerr)) {
/* read NSPR error code */
err = PR_GetError();
if(is_cc_error(err))
curlerr = CURLE_SSL_CERTPROBLEM;
/* print the error number and error string */
infof(data, "NSS error %d (%s)\n", err, nss_error_to_name(err));
/* print a human-readable message describing the error if available */
nss_print_error_message(data, err);
}
/* cleanup on connection failure */
Curl_llist_destroy(connssl->obj_list, NULL);
connssl->obj_list = NULL;
return curlerr;
}
/* Switch the SSL socket into non-blocking mode. */
static CURLcode nss_set_nonblock(struct ssl_connect_data *connssl,
struct Curl_easy *data)
{
static PRSocketOptionData sock_opt;
sock_opt.option = PR_SockOpt_Nonblocking;
sock_opt.value.non_blocking = PR_TRUE;
if(PR_SetSocketOption(connssl->handle, &sock_opt) != PR_SUCCESS)
return nss_fail_connect(connssl, data, CURLE_SSL_CONNECT_ERROR);
return CURLE_OK;
}
static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex)
{
PRFileDesc *model = NULL;
PRFileDesc *nspr_io = NULL;
PRFileDesc *nspr_io_stub = NULL;
PRBool ssl_no_cache;
PRBool ssl_cbc_random_iv;
struct Curl_easy *data = conn->data;
curl_socket_t sockfd = conn->sock[sockindex];
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
CURLcode result;
SSLVersionRange sslver = {
SSL_LIBRARY_VERSION_TLS_1_0, /* min */
SSL_LIBRARY_VERSION_TLS_1_0 /* max */
};
connssl->data = data;
/* list of all NSS objects we need to destroy in Curl_nss_close() */
connssl->obj_list = Curl_llist_alloc(nss_destroy_object);
if(!connssl->obj_list)
return CURLE_OUT_OF_MEMORY;
/* FIXME. NSS doesn't support multiple databases open at the same time. */
PR_Lock(nss_initlock);
result = nss_init(conn->data);
if(result) {
PR_Unlock(nss_initlock);
goto error;
}
result = CURLE_SSL_CONNECT_ERROR;
if(!mod) {
char *configstring = aprintf("library=%s name=PEM", pem_library);
if(!configstring) {
PR_Unlock(nss_initlock);
goto error;
}
mod = SECMOD_LoadUserModule(configstring, NULL, PR_FALSE);
free(configstring);
if(!mod || !mod->loaded) {
if(mod) {
SECMOD_DestroyModule(mod);
mod = NULL;
}
infof(data, "WARNING: failed to load NSS PEM library %s. Using "
"OpenSSL PEM certificates will not work.\n", pem_library);
}
}
PK11_SetPasswordFunc(nss_get_password);
PR_Unlock(nss_initlock);
model = PR_NewTCPSocket();
if(!model)
goto error;
model = SSL_ImportFD(NULL, model);
if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess)
goto error;
if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess)
goto error;
if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess)
goto error;
/* do not use SSL cache if disabled or we are not going to verify peer */
ssl_no_cache = (conn->ssl_config.sessionid && data->set.ssl.verifypeer) ?
PR_FALSE : PR_TRUE;
if(SSL_OptionSet(model, SSL_NO_CACHE, ssl_no_cache) != SECSuccess)
goto error;
/* enable/disable the requested SSL version(s) */
if(nss_init_sslver(&sslver, data) != CURLE_OK)
goto error;
if(SSL_VersionRangeSet(model, &sslver) != SECSuccess)
goto error;
ssl_cbc_random_iv = !data->set.ssl_enable_beast;
#ifdef SSL_CBC_RANDOM_IV
/* unless the user explicitly asks to allow the protocol vulnerability, we
use the work-around */
if(SSL_OptionSet(model, SSL_CBC_RANDOM_IV, ssl_cbc_random_iv) != SECSuccess)
infof(data, "warning: failed to set SSL_CBC_RANDOM_IV = %d\n",
ssl_cbc_random_iv);
#else
if(ssl_cbc_random_iv)
infof(data, "warning: support for SSL_CBC_RANDOM_IV not compiled in\n");
#endif
if(data->set.ssl.cipher_list) {
if(set_ciphers(data, model, data->set.ssl.cipher_list) != SECSuccess) {
result = CURLE_SSL_CIPHER;
goto error;
}
}
if(!data->set.ssl.verifypeer && data->set.ssl.verifyhost)
infof(data, "warning: ignoring value of ssl.verifyhost\n");
/* bypass the default SSL_AuthCertificate() hook in case we do not want to
* verify peer */
if(SSL_AuthCertificateHook(model, nss_auth_cert_hook, conn) != SECSuccess)
goto error;
data->set.ssl.certverifyresult=0; /* not checked yet */
if(SSL_BadCertHook(model, BadCertHandler, conn) != SECSuccess)
goto error;
if(SSL_HandshakeCallback(model, HandshakeCallback, conn) != SECSuccess)
goto error;
if(data->set.ssl.verifypeer) {
const CURLcode rv = nss_load_ca_certificates(conn, sockindex);
if(rv) {
result = rv;
goto error;
}
}
if(data->set.ssl.CRLfile) {
const CURLcode rv = nss_load_crl(data->set.ssl.CRLfile);
if(rv) {
result = rv;
goto error;
}
infof(data, " CRLfile: %s\n", data->set.ssl.CRLfile);
}
if(data->set.str[STRING_CERT]) {
char *nickname = dup_nickname(data, STRING_CERT);
if(nickname) {
/* we are not going to use libnsspem.so to read the client cert */
connssl->obj_clicert = NULL;
}
else {
CURLcode rv = cert_stuff(conn, sockindex, data->set.str[STRING_CERT],
data->set.str[STRING_KEY]);
if(rv) {
/* failf() is already done in cert_stuff() */
result = rv;
goto error;
}
}
/* store the nickname for SelectClientCert() called during handshake */
connssl->client_nickname = nickname;
}
else
connssl->client_nickname = NULL;
if(SSL_GetClientAuthDataHook(model, SelectClientCert,
(void *)connssl) != SECSuccess) {
result = CURLE_SSL_CERTPROBLEM;
goto error;
}
/* wrap OS file descriptor by NSPR's file descriptor abstraction */
nspr_io = PR_ImportTCPSocket(sockfd);
if(!nspr_io)
goto error;
/* create our own NSPR I/O layer */
nspr_io_stub = PR_CreateIOLayerStub(nspr_io_identity, &nspr_io_methods);
if(!nspr_io_stub) {
PR_Close(nspr_io);
goto error;
}
/* make the per-connection data accessible from NSPR I/O callbacks */
nspr_io_stub->secret = (void *)connssl;
/* push our new layer to the NSPR I/O stack */
if(PR_PushIOLayer(nspr_io, PR_TOP_IO_LAYER, nspr_io_stub) != PR_SUCCESS) {
PR_Close(nspr_io);
PR_Close(nspr_io_stub);
goto error;
}
/* import our model socket onto the current I/O stack */
connssl->handle = SSL_ImportFD(model, nspr_io);
if(!connssl->handle) {
PR_Close(nspr_io);
goto error;
}
PR_Close(model); /* We don't need this any more */
model = NULL;
/* This is the password associated with the cert that we're using */
if(data->set.str[STRING_KEY_PASSWD]) {
SSL_SetPKCS11PinArg(connssl->handle, data->set.str[STRING_KEY_PASSWD]);
}
#ifdef SSL_ENABLE_OCSP_STAPLING
if(data->set.ssl.verifystatus) {
if(SSL_OptionSet(connssl->handle, SSL_ENABLE_OCSP_STAPLING, PR_TRUE)
!= SECSuccess)
goto error;
}
#endif
#ifdef SSL_ENABLE_NPN
if(SSL_OptionSet(connssl->handle, SSL_ENABLE_NPN, conn->bits.tls_enable_npn
? PR_TRUE : PR_FALSE) != SECSuccess)
goto error;
#endif
#ifdef SSL_ENABLE_ALPN
if(SSL_OptionSet(connssl->handle, SSL_ENABLE_ALPN, conn->bits.tls_enable_alpn
? PR_TRUE : PR_FALSE) != SECSuccess)
goto error;
#endif
#if NSSVERNUM >= 0x030f04 /* 3.15.4 */
if(data->set.ssl.falsestart) {
if(SSL_OptionSet(connssl->handle, SSL_ENABLE_FALSE_START, PR_TRUE)
!= SECSuccess)
goto error;
if(SSL_SetCanFalseStartCallback(connssl->handle, CanFalseStartCallback,
conn) != SECSuccess)
goto error;
}
#endif
#if defined(SSL_ENABLE_NPN) || defined(SSL_ENABLE_ALPN)
if(conn->bits.tls_enable_npn || conn->bits.tls_enable_alpn) {
int cur = 0;
unsigned char protocols[128];
#ifdef USE_NGHTTP2
if(data->set.httpversion >= CURL_HTTP_VERSION_2) {
protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
NGHTTP2_PROTO_VERSION_ID_LEN);
cur += NGHTTP2_PROTO_VERSION_ID_LEN;
}
#endif
protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
cur += ALPN_HTTP_1_1_LENGTH;
if(SSL_SetNextProtoNego(connssl->handle, protocols, cur) != SECSuccess)
goto error;
}
#endif
/* Force handshake on next I/O */
if(SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE)
!= SECSuccess)
goto error;
/* propagate hostname to the TLS layer */
if(SSL_SetURL(connssl->handle, conn->host.name) != SECSuccess)
goto error;
/* prevent NSS from re-using the session for a different hostname */
if(SSL_SetSockPeerID(connssl->handle, conn->host.name) != SECSuccess)
goto error;
return CURLE_OK;
error:
if(model)
PR_Close(model);
return nss_fail_connect(connssl, data, result);
}
static CURLcode nss_do_connect(struct connectdata *conn, int sockindex)
{
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
struct Curl_easy *data = conn->data;
CURLcode result = CURLE_SSL_CONNECT_ERROR;
PRUint32 timeout;
/* check timeout situation */
const long time_left = Curl_timeleft(data, NULL, TRUE);
if(time_left < 0L) {
failf(data, "timed out before SSL handshake");
result = CURLE_OPERATION_TIMEDOUT;
goto error;
}
/* Force the handshake now */
timeout = PR_MillisecondsToInterval((PRUint32) time_left);
if(SSL_ForceHandshakeWithTimeout(connssl->handle, timeout) != SECSuccess) {
if(PR_GetError() == PR_WOULD_BLOCK_ERROR)
/* blocking direction is updated by nss_update_connecting_state() */
return CURLE_AGAIN;
else if(conn->data->set.ssl.certverifyresult == SSL_ERROR_BAD_CERT_DOMAIN)
result = CURLE_PEER_FAILED_VERIFICATION;
else if(conn->data->set.ssl.certverifyresult!=0)
result = CURLE_SSL_CACERT;
goto error;
}
result = display_conn_info(conn, connssl->handle);
if(result)
goto error;
if(data->set.str[STRING_SSL_ISSUERCERT]) {
SECStatus ret = SECFailure;
char *nickname = dup_nickname(data, STRING_SSL_ISSUERCERT);
if(nickname) {
/* we support only nicknames in case of STRING_SSL_ISSUERCERT for now */
ret = check_issuer_cert(connssl->handle, nickname);
free(nickname);
}
if(SECFailure == ret) {
infof(data, "SSL certificate issuer check failed\n");
result = CURLE_SSL_ISSUER_ERROR;
goto error;
}
else {
infof(data, "SSL certificate issuer check ok\n");
}
}
result = cmp_peer_pubkey(connssl, data->set.str[STRING_SSL_PINNEDPUBLICKEY]);
if(result)
/* status already printed */
goto error;
return CURLE_OK;
error:
return nss_fail_connect(connssl, data, result);
}
static CURLcode nss_connect_common(struct connectdata *conn, int sockindex,
bool *done)
{
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
struct Curl_easy *data = conn->data;
const bool blocking = (done == NULL);
CURLcode result;
if(connssl->state == ssl_connection_complete)
return CURLE_OK;
if(connssl->connecting_state == ssl_connect_1) {
result = nss_setup_connect(conn, sockindex);
if(result)
/* we do not expect CURLE_AGAIN from nss_setup_connect() */
return result;
if(!blocking) {
/* in non-blocking mode, set NSS non-blocking mode before handshake */
result = nss_set_nonblock(connssl, data);
if(result)
return result;
}
connssl->connecting_state = ssl_connect_2;
}
result = nss_do_connect(conn, sockindex);
switch(result) {
case CURLE_OK:
break;
case CURLE_AGAIN:
if(!blocking)
/* CURLE_AGAIN in non-blocking mode is not an error */
return CURLE_OK;
/* fall through */
default:
return result;
}
if(blocking) {
/* in blocking mode, set NSS non-blocking mode _after_ SSL handshake */
result = nss_set_nonblock(connssl, data);
if(result)
return result;
}
else
/* signal completed SSL handshake */
*done = TRUE;
connssl->state = ssl_connection_complete;
conn->recv[sockindex] = nss_recv;
conn->send[sockindex] = nss_send;
/* ssl_connect_done is never used outside, go back to the initial state */
connssl->connecting_state = ssl_connect_1;
return CURLE_OK;
}
CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
{
return nss_connect_common(conn, sockindex, /* blocking */ NULL);
}
CURLcode Curl_nss_connect_nonblocking(struct connectdata *conn,
int sockindex, bool *done)
{
return nss_connect_common(conn, sockindex, done);
}
static ssize_t nss_send(struct connectdata *conn, /* connection data */
int sockindex, /* socketindex */
const void *mem, /* send this data */
size_t len, /* amount to write */
CURLcode *curlcode)
{
ssize_t rc = PR_Send(conn->ssl[sockindex].handle, mem, (int)len, 0,
PR_INTERVAL_NO_WAIT);
if(rc < 0) {
PRInt32 err = PR_GetError();
if(err == PR_WOULD_BLOCK_ERROR)
*curlcode = CURLE_AGAIN;
else {
/* print the error number and error string */
const char *err_name = nss_error_to_name(err);
infof(conn->data, "SSL write: error %d (%s)\n", err, err_name);
/* print a human-readable message describing the error if available */
nss_print_error_message(conn->data, err);
*curlcode = (is_cc_error(err))
? CURLE_SSL_CERTPROBLEM
: CURLE_SEND_ERROR;
}
return -1;
}
return rc; /* number of bytes */
}
static ssize_t nss_recv(struct connectdata * conn, /* connection data */
int num, /* socketindex */
char *buf, /* store read data here */
size_t buffersize, /* max amount to read */
CURLcode *curlcode)
{
ssize_t nread = PR_Recv(conn->ssl[num].handle, buf, (int)buffersize, 0,
PR_INTERVAL_NO_WAIT);
if(nread < 0) {
/* failed SSL read */
PRInt32 err = PR_GetError();
if(err == PR_WOULD_BLOCK_ERROR)
*curlcode = CURLE_AGAIN;
else {
/* print the error number and error string */
const char *err_name = nss_error_to_name(err);
infof(conn->data, "SSL read: errno %d (%s)\n", err, err_name);
/* print a human-readable message describing the error if available */
nss_print_error_message(conn->data, err);
*curlcode = (is_cc_error(err))
? CURLE_SSL_CERTPROBLEM
: CURLE_RECV_ERROR;
}
return -1;
}
return nread;
}
size_t Curl_nss_version(char *buffer, size_t size)
{
return snprintf(buffer, size, "NSS/%s", NSS_VERSION);
}
/* data might be NULL */
int Curl_nss_seed(struct Curl_easy *data)
{
/* make sure that NSS is initialized */
return !!Curl_nss_force_init(data);
}
/* data might be NULL */
int Curl_nss_random(struct Curl_easy *data,
unsigned char *entropy,
size_t length)
{
Curl_nss_seed(data); /* Initiate the seed if not already done */
if(SECSuccess != PK11_GenerateRandom(entropy, curlx_uztosi(length)))
/* signal a failure */
return -1;
return 0;
}
void Curl_nss_md5sum(unsigned char *tmp, /* input */
size_t tmplen,
unsigned char *md5sum, /* output */
size_t md5len)
{
PK11Context *MD5pw = PK11_CreateDigestContext(SEC_OID_MD5);
unsigned int MD5out;
PK11_DigestOp(MD5pw, tmp, curlx_uztoui(tmplen));
PK11_DigestFinal(MD5pw, md5sum, &MD5out, curlx_uztoui(md5len));
PK11_DestroyContext(MD5pw, PR_TRUE);
}
void Curl_nss_sha256sum(const unsigned char *tmp, /* input */
size_t tmplen,
unsigned char *sha256sum, /* output */
size_t sha256len)
{
PK11Context *SHA256pw = PK11_CreateDigestContext(SEC_OID_SHA256);
unsigned int SHA256out;
PK11_DigestOp(SHA256pw, tmp, curlx_uztoui(tmplen));
PK11_DigestFinal(SHA256pw, sha256sum, &SHA256out, curlx_uztoui(sha256len));
PK11_DestroyContext(SHA256pw, PR_TRUE);
}
bool Curl_nss_cert_status_request(void)
{
#ifdef SSL_ENABLE_OCSP_STAPLING
return TRUE;
#else
return FALSE;
#endif
}
bool Curl_nss_false_start(void) {
#if NSSVERNUM >= 0x030f04 /* 3.15.4 */
return TRUE;
#else
return FALSE;
#endif
}
#endif /* USE_NSS */
| ./CrossVul/dataset_final_sorted/CWE-287/c/good_5264_1 |
crossvul-cpp_data_bad_5267_0 | /*
* IRC - Internet Relay Chat, src/modules/m_sasl.c
* (C) 2012 The UnrealIRCd Team
*
* See file AUTHORS in IRC package for additional names of
* the programmers.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 1, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "unrealircd.h"
#define MSG_AUTHENTICATE "AUTHENTICATE"
#define MSG_SASL "SASL"
#define MSG_SVSLOGIN "SVSLOGIN"
/* returns a server identifier given agent_p */
#define AGENT_SID(agent_p) (agent_p->user != NULL ? agent_p->user->server : agent_p->name)
ModuleHeader MOD_HEADER(m_sasl)
= {
"m_sasl",
"4.0",
"SASL",
"3.2-b8-1",
NULL
};
/*
* This is a "lightweight" SASL implementation/stack which uses psuedo-identifiers
* to identify connecting clients. In Unreal 3.3, we should use real identifiers
* so that SASL sessions can be correlated.
*
* The following people were involved in making the current iteration of SASL over
* IRC which allowed psuedo-identifiers:
*
* danieldg, Daniel de Graff <danieldg@inspircd.org>
* jilles, Jilles Tjoelker <jilles@stack.nl>
* Jobe, Matthew Beeching <jobe@mdbnet.co.uk>
* gxti, Michael Tharp <gxti@partiallystapled.com>
* nenolod, William Pitcock <nenolod@dereferenced.org>
*
* Thanks also to all of the client authors which have implemented SASL in their
* clients. With the backwards-compatibility layer allowing "lightweight" SASL
* implementations, we now truly have a universal authentication mechanism for
* IRC.
*/
/*
* decode_puid
*
* Decode PUID sent from a SASL agent. If the servername in the PUID doesn't match
* ours, we reject the PUID (by returning NULL).
*/
static aClient *decode_puid(char *puid)
{
aClient *cptr;
char *it, *it2;
int cookie = 0;
if ((it = strrchr(puid, '!')) == NULL)
return NULL;
*it++ = '\0';
if ((it2 = strrchr(it, '.')) != NULL)
{
*it2++ = '\0';
cookie = atoi(it2);
}
if (stricmp(me.name, puid))
return NULL;
list_for_each_entry(cptr, &unknown_list, lclient_node)
if (cptr->local->sasl_cookie == cookie)
return cptr;
return NULL;
}
/*
* encode_puid
*
* Encode PUID based on aClient.
*/
static const char *encode_puid(aClient *client)
{
static char buf[HOSTLEN + 20];
/* create a cookie if necessary (and in case getrandom16 returns 0, then run again) */
while (!client->local->sasl_cookie)
client->local->sasl_cookie = getrandom16();
snprintf(buf, sizeof buf, "%s!0.%d", me.name, client->local->sasl_cookie);
return buf;
}
/*
* SVSLOGIN message
*
* parv[1]: propagation mask
* parv[2]: target PUID
* parv[3]: ESVID
*/
CMD_FUNC(m_svslogin)
{
if (!SASL_SERVER || MyClient(sptr) || (parc < 3) || !parv[3])
return 0;
if (!stricmp(parv[1], me.name))
{
aClient *target_p;
/* is the PUID valid? */
if ((target_p = decode_puid(parv[2])) == NULL)
return 0;
if (target_p->user == NULL)
make_user(target_p);
strlcpy(target_p->user->svid, parv[3], sizeof(target_p->user->svid));
sendto_one(target_p, err_str(RPL_LOGGEDIN), me.name,
BadPtr(target_p->name) ? "*" : target_p->name,
BadPtr(target_p->name) ? "*" : target_p->name,
BadPtr(target_p->user->username) ? "*" : target_p->user->username,
BadPtr(target_p->user->realhost) ? "*" : target_p->user->realhost,
target_p->user->svid, target_p->user->svid);
return 0;
}
/* not for us; propagate. */
sendto_server(cptr, 0, 0, ":%s SVSLOGIN %s %s %s",
sptr->name, parv[1], parv[2], parv[3]);
return 0;
}
/*
* SASL message
*
* parv[1]: distribution mask
* parv[2]: target PUID
* parv[3]: mode/state
* parv[4]: data
* parv[5]: out-of-bound data
*/
CMD_FUNC(m_sasl)
{
if (!SASL_SERVER || MyClient(sptr) || (parc < 4) || !parv[4])
return 0;
if (!stricmp(parv[1], me.name))
{
aClient *target_p;
/* is the PUID valid? */
if ((target_p = decode_puid(parv[2])) == NULL)
return 0;
if (target_p->user == NULL)
make_user(target_p);
/* reject if another SASL agent is answering */
if (*target_p->local->sasl_agent && stricmp(sptr->name, target_p->local->sasl_agent))
return 0;
else
strlcpy(target_p->local->sasl_agent, sptr->name, sizeof(target_p->local->sasl_agent));
if (*parv[3] == 'C')
sendto_one(target_p, "AUTHENTICATE %s", parv[4]);
else if (*parv[3] == 'D')
{
if (*parv[4] == 'F')
sendto_one(target_p, err_str(ERR_SASLFAIL), me.name, BadPtr(target_p->name) ? "*" : target_p->name);
else if (*parv[4] == 'S')
{
target_p->local->sasl_complete++;
sendto_one(target_p, err_str(RPL_SASLSUCCESS), me.name, BadPtr(target_p->name) ? "*" : target_p->name);
}
*target_p->local->sasl_agent = '\0';
}
else if (*parv[3] == 'M')
sendto_one(target_p, err_str(RPL_SASLMECHS), me.name, BadPtr(target_p->name) ? "*" : target_p->name, parv[4]);
return 0;
}
/* not for us; propagate. */
sendto_server(cptr, 0, 0, ":%s SASL %s %s %c %s %s",
sptr->name, parv[1], parv[2], *parv[3], parv[4], parc > 5 ? parv[5] : "");
return 0;
}
/*
* AUTHENTICATE message
*
* parv[1]: data
*/
CMD_FUNC(m_authenticate)
{
aClient *agent_p = NULL;
/* Failing to use CAP REQ for sasl is a protocol violation. */
if (!SASL_SERVER || !MyConnect(sptr) || BadPtr(parv[1]) || !CHECKPROTO(sptr, PROTO_SASL))
return 0;
if (sptr->local->sasl_complete)
{
sendto_one(sptr, err_str(ERR_SASLALREADY), me.name, BadPtr(sptr->name) ? "*" : sptr->name);
return 0;
}
if (strlen(parv[1]) > 400)
{
sendto_one(sptr, err_str(ERR_SASLTOOLONG), me.name, BadPtr(sptr->name) ? "*" : sptr->name);
return 0;
}
if (*sptr->local->sasl_agent)
agent_p = find_client(sptr->local->sasl_agent, NULL);
if (agent_p == NULL)
{
char *addr = BadPtr(sptr->ip) ? "0" : sptr->ip;
char *certfp = moddata_client_get(sptr, "certfp");
sendto_server(NULL, 0, 0, ":%s SASL %s %s H %s %s",
me.name, SASL_SERVER, encode_puid(sptr), addr, addr);
if (certfp)
sendto_server(NULL, 0, 0, ":%s SASL %s %s S %s %s",
me.name, SASL_SERVER, encode_puid(sptr), parv[1], certfp);
else
sendto_server(NULL, 0, 0, ":%s SASL %s %s S %s",
me.name, SASL_SERVER, encode_puid(sptr), parv[1]);
}
else
sendto_server(NULL, 0, 0, ":%s SASL %s %s C %s",
me.name, AGENT_SID(agent_p), encode_puid(sptr), parv[1]);
sptr->local->sasl_out++;
return 0;
}
static int abort_sasl(aClient *cptr)
{
if (cptr->local->sasl_out == 0 || cptr->local->sasl_complete)
return 0;
cptr->local->sasl_out = cptr->local->sasl_complete = 0;
sendto_one(cptr, err_str(ERR_SASLABORTED), me.name, BadPtr(cptr->name) ? "*" : cptr->name);
if (*cptr->local->sasl_agent)
{
aClient *agent_p = find_client(cptr->local->sasl_agent, NULL);
if (agent_p != NULL)
{
sendto_server(NULL, 0, 0, ":%s SASL %s %s D A",
me.name, AGENT_SID(agent_p), encode_puid(cptr));
return 0;
}
}
sendto_server(NULL, 0, 0, ":%s SASL * %s D A", me.name, encode_puid(cptr));
return 0;
}
int sasl_capability_visible(void)
{
if (!SASL_SERVER || !find_server(SASL_SERVER, NULL))
return 0;
return 1;
}
int sasl_connect(aClient *sptr)
{
return abort_sasl(sptr);
}
int sasl_quit(aClient *sptr, char *comment)
{
return abort_sasl(sptr);
}
MOD_INIT(m_sasl)
{
ClientCapability cap;
MARK_AS_OFFICIAL_MODULE(modinfo);
CommandAdd(modinfo->handle, MSG_SASL, m_sasl, MAXPARA, M_USER|M_SERVER);
CommandAdd(modinfo->handle, MSG_SVSLOGIN, m_svslogin, MAXPARA, M_USER|M_SERVER);
CommandAdd(modinfo->handle, MSG_AUTHENTICATE, m_authenticate, MAXPARA, M_UNREGISTERED);
HookAdd(modinfo->handle, HOOKTYPE_LOCAL_CONNECT, 0, sasl_connect);
HookAdd(modinfo->handle, HOOKTYPE_LOCAL_QUIT, 0, sasl_quit);
memset(&cap, 0, sizeof(cap));
cap.name = "sasl";
cap.cap = PROTO_SASL;
cap.visible = sasl_capability_visible;
ClientCapabilityAdd(modinfo->handle, &cap);
return MOD_SUCCESS;
}
MOD_LOAD(m_sasl)
{
return MOD_SUCCESS;
}
MOD_UNLOAD(m_sasl)
{
return MOD_SUCCESS;
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/bad_5267_0 |
crossvul-cpp_data_bad_3184_2 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/***************************************************************************
* Copyright (C) 2013-2017 Ping Identity Corporation
* All rights reserved.
*
* For further information please contact:
*
* Ping Identity Corporation
* 1099 18th St Suite 2950
* Denver, CO 80202
* 303.468.2900
* http://www.pingidentity.com
*
* DISCLAIMER OF WARRANTIES:
*
* THE SOFTWARE PROVIDED HEREUNDER IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
* ANY WARRANTIES OR REPRESENTATIONS EXPRESS, IMPLIED OR STATUTORY; INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF QUALITY, PERFORMANCE, NONINFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NOR ARE THERE ANY
* WARRANTIES CREATED BY A COURSE OR DEALING, COURSE OF PERFORMANCE OR TRADE
* USAGE. FURTHERMORE, THERE ARE NO WARRANTIES THAT THE SOFTWARE WILL MEET
* YOUR NEEDS OR BE FREE FROM ERRORS, OR THAT THE OPERATION OF THE SOFTWARE
* WILL BE UNINTERRUPTED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES 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.
*
* Initially based on mod_auth_cas.c:
* https://github.com/Jasig/mod_auth_cas
*
* Other code copied/borrowed/adapted:
* shared memory caching: mod_auth_mellon
*
* @Author: Hans Zandbelt - hans.zandbelt@zmartzone.eu
*
**************************************************************************/
#include "apr_hash.h"
#include "apr_strings.h"
#include "ap_config.h"
#include "ap_provider.h"
#include "apr_lib.h"
#include "apr_file_io.h"
#include "apr_sha1.h"
#include "apr_base64.h"
#include "httpd.h"
#include "http_core.h"
#include "http_config.h"
#include "http_log.h"
#include "http_protocol.h"
#include "http_request.h"
#include "mod_auth_openidc.h"
// TODO:
// - sort out oidc_cfg vs. oidc_dir_cfg stuff
// - rigid input checking on discovery responses
// - check self-issued support
// - README.quickstart
// - refresh metadata once-per too? (for non-signing key changes)
extern module AP_MODULE_DECLARE_DATA auth_openidc_module;
/*
* clean any suspicious headers in the HTTP request sent by the user agent
*/
static void oidc_scrub_request_headers(request_rec *r, const char *claim_prefix,
const char *authn_header) {
const int prefix_len = claim_prefix ? strlen(claim_prefix) : 0;
/* get an array representation of the incoming HTTP headers */
const apr_array_header_t * const h = apr_table_elts(r->headers_in);
/* table to keep the non-suspicious headers */
apr_table_t *clean_headers = apr_table_make(r->pool, h->nelts);
/* loop over the incoming HTTP headers */
const apr_table_entry_t * const e = (const apr_table_entry_t *) h->elts;
int i;
for (i = 0; i < h->nelts; i++) {
const char * const k = e[i].key;
/* is this header's name equivalent to the header that mod_auth_openidc would set for the authenticated user? */
const int authn_header_matches = (k != NULL) && authn_header
&& (oidc_strnenvcmp(k, authn_header, -1) == 0);
/*
* would this header be interpreted as a mod_auth_openidc attribute? Note
* that prefix_len will be zero if no attr_prefix is defined,
* so this will always be false. Also note that we do not
* scrub headers if the prefix is empty because every header
* would match.
*/
const int prefix_matches = (k != NULL) && prefix_len
&& (oidc_strnenvcmp(k, claim_prefix, prefix_len) == 0);
/* add to the clean_headers if non-suspicious, skip and report otherwise */
if (!prefix_matches && !authn_header_matches) {
apr_table_addn(clean_headers, k, e[i].val);
} else {
oidc_warn(r, "scrubbed suspicious request header (%s: %.32s)", k,
e[i].val);
}
}
/* overwrite the incoming headers with the cleaned result */
r->headers_in = clean_headers;
}
/*
* scrub all mod_auth_openidc related headers
*/
static void oidc_scrub_headers(request_rec *r) {
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
if (cfg->scrub_request_headers != 0) {
/* scrub all headers starting with OIDC_ first */
oidc_scrub_request_headers(r, OIDC_DEFAULT_HEADER_PREFIX,
oidc_cfg_dir_authn_header(r));
/*
* then see if the claim headers need to be removed on top of that
* (i.e. the prefix does not start with the default OIDC_)
*/
if ((strstr(cfg->claim_prefix, OIDC_DEFAULT_HEADER_PREFIX)
!= cfg->claim_prefix)) {
oidc_scrub_request_headers(r, cfg->claim_prefix, NULL);
}
}
}
/*
* strip the session cookie from the headers sent to the application/backend
*/
static void oidc_strip_cookies(request_rec *r) {
char *cookie, *ctx, *result = NULL;
const char *name = NULL;
int i;
apr_array_header_t *strip = oidc_dir_cfg_strip_cookies(r);
char *cookies = apr_pstrdup(r->pool,
(char *) apr_table_get(r->headers_in, "Cookie"));
if ((cookies != NULL) && (strip != NULL)) {
oidc_debug(r,
"looking for the following cookies to strip from cookie header: %s",
apr_array_pstrcat(r->pool, strip, ','));
cookie = apr_strtok(cookies, ";", &ctx);
do {
while (cookie != NULL && *cookie == ' ')
cookie++;
for (i = 0; i < strip->nelts; i++) {
name = ((const char**) strip->elts)[i];
if ((strncmp(cookie, name, strlen(name)) == 0)
&& (cookie[strlen(name)] == '=')) {
oidc_debug(r, "stripping: %s", name);
break;
}
}
if (i == strip->nelts) {
result =
result ?
apr_psprintf(r->pool, "%s;%s", result, cookie) :
cookie;
}
cookie = apr_strtok(NULL, ";", &ctx);
} while (cookie != NULL);
if (result != NULL) {
oidc_debug(r, "set cookie to backend to: %s",
result ?
apr_psprintf(r->pool, "\"%s\"", result) : "<null>");
apr_table_set(r->headers_in, "Cookie", result);
} else {
oidc_debug(r, "unsetting all cookies to backend");
apr_table_unset(r->headers_in, "Cookie");
}
}
}
#define OIDC_SHA1_LEN 20
/*
* calculates a hash value based on request fingerprint plus a provided nonce string.
*/
static char *oidc_get_browser_state_hash(request_rec *r, const char *nonce) {
oidc_debug(r, "enter");
/* helper to hold to header values */
const char *value = NULL;
/* the hash context */
apr_sha1_ctx_t sha1;
/* Initialize the hash context */
apr_sha1_init(&sha1);
/* get the X_FORWARDED_FOR header value */
value = (char *) apr_table_get(r->headers_in, "X_FORWARDED_FOR");
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, strlen(value));
/* get the USER_AGENT header value */
value = (char *) apr_table_get(r->headers_in, "USER_AGENT");
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, strlen(value));
/* get the remote client IP address or host name */
/*
int remotehost_is_ip;
value = ap_get_remote_host(r->connection, r->per_dir_config,
REMOTE_NOLOOKUP, &remotehost_is_ip);
apr_sha1_update(&sha1, value, strlen(value));
*/
/* concat the nonce parameter to the hash input */
apr_sha1_update(&sha1, nonce, strlen(nonce));
/* finalize the hash input and calculate the resulting hash output */
unsigned char hash[OIDC_SHA1_LEN];
apr_sha1_final(hash, &sha1);
/* base64url-encode the resulting hash and return it */
char *result = NULL;
oidc_base64url_encode(r, &result, (const char *) hash, OIDC_SHA1_LEN, TRUE);
return result;
}
/*
* return the name for the state cookie
*/
static char *oidc_get_state_cookie_name(request_rec *r, const char *state) {
return apr_psprintf(r->pool, "%s%s", OIDCStateCookiePrefix, state);
}
/*
* return the static provider configuration, i.e. from a metadata URL or configuration primitives
*/
static apr_byte_t oidc_provider_static_config(request_rec *r, oidc_cfg *c,
oidc_provider_t **provider) {
json_t *j_provider = NULL;
const char *s_json = NULL;
/* see if we should configure a static provider based on external (cached) metadata */
if ((c->metadata_dir != NULL) || (c->provider.metadata_url == NULL)) {
*provider = &c->provider;
return TRUE;
}
c->cache->get(r, OIDC_CACHE_SECTION_PROVIDER,
oidc_util_escape_string(r, c->provider.metadata_url), &s_json);
if (s_json == NULL) {
if (oidc_metadata_provider_retrieve(r, c, NULL,
c->provider.metadata_url, &j_provider, &s_json) == FALSE) {
oidc_error(r, "could not retrieve metadata from url: %s",
c->provider.metadata_url);
return FALSE;
}
c->cache->set(r, OIDC_CACHE_SECTION_PROVIDER,
oidc_util_escape_string(r, c->provider.metadata_url), s_json,
apr_time_now()
+ (c->provider_metadata_refresh_interval <= 0 ?
apr_time_from_sec(
OIDC_CACHE_PROVIDER_METADATA_EXPIRY_DEFAULT) :
c->provider_metadata_refresh_interval));
} else {
/* correct parsing and validation was already done when it was put in the cache */
j_provider = json_loads(s_json, 0, 0);
}
*provider = apr_pcalloc(r->pool, sizeof(oidc_provider_t));
memcpy(*provider, &c->provider, sizeof(oidc_provider_t));
if (oidc_metadata_provider_parse(r, c, j_provider, *provider) == FALSE) {
oidc_error(r, "could not parse metadata from url: %s",
c->provider.metadata_url);
if (j_provider)
json_decref(j_provider);
return FALSE;
}
json_decref(j_provider);
return TRUE;
}
/*
* return the oidc_provider_t struct for the specified issuer
*/
static oidc_provider_t *oidc_get_provider_for_issuer(request_rec *r,
oidc_cfg *c, const char *issuer, apr_byte_t allow_discovery) {
/* by default we'll assume that we're dealing with a single statically configured OP */
oidc_provider_t *provider = NULL;
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return NULL;
/* unless a metadata directory was configured, so we'll try and get the provider settings from there */
if (c->metadata_dir != NULL) {
/* try and get metadata from the metadata directory for the OP that sent this response */
if ((oidc_metadata_get(r, c, issuer, &provider, allow_discovery)
== FALSE) || (provider == NULL)) {
/* don't know nothing about this OP/issuer */
oidc_error(r, "no provider metadata found for issuer \"%s\"",
issuer);
return NULL;
}
}
return provider;
}
/*
* find out whether the request is a response from an IDP discovery page
*/
static apr_byte_t oidc_is_discovery_response(request_rec *r, oidc_cfg *cfg) {
/*
* prereq: this is a call to the configured redirect_uri, now see if:
* the OIDC_DISC_OP_PARAM is present
*/
return oidc_util_request_has_parameter(r, OIDC_DISC_OP_PARAM)
|| oidc_util_request_has_parameter(r, OIDC_DISC_USER_PARAM);
}
/*
* return the HTTP method being called: only for POST data persistence purposes
*/
static const char *oidc_original_request_method(request_rec *r, oidc_cfg *cfg,
apr_byte_t handle_discovery_response) {
const char *method = OIDC_METHOD_GET;
char *m = NULL;
if ((handle_discovery_response == TRUE)
&& (oidc_util_request_matches_url(r, cfg->redirect_uri))
&& (oidc_is_discovery_response(r, cfg))) {
oidc_util_get_request_parameter(r, OIDC_DISC_RM_PARAM, &m);
if (m != NULL)
method = apr_pstrdup(r->pool, m);
} else {
/*
* if POST preserve is not enabled for this location, there's no point in preserving
* the method either which would result in POSTing empty data on return;
* so we revert to legacy behavior
*/
if (oidc_cfg_dir_preserve_post(r) == 0)
return OIDC_METHOD_GET;
const char *content_type = apr_table_get(r->headers_in, "Content-Type");
if ((r->method_number == M_POST)
&& (apr_strnatcmp(content_type,
"application/x-www-form-urlencoded") == 0))
method = OIDC_METHOD_FORM_POST;
}
oidc_debug(r, "return: %s", method);
return method;
}
/*
* send an OpenID Connect authorization request to the specified provider preserving POST parameters using HTML5 storage
*/
apr_byte_t oidc_post_preserve_javascript(request_rec *r, const char *location,
char **javascript, char **javascript_method) {
if (oidc_cfg_dir_preserve_post(r) == 0)
return FALSE;
oidc_debug(r, "enter");
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
const char *method = oidc_original_request_method(r, cfg, FALSE);
if (apr_strnatcmp(method, OIDC_METHOD_FORM_POST) != 0)
return FALSE;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return FALSE;
}
const apr_array_header_t *arr = apr_table_elts(params);
const apr_table_entry_t *elts = (const apr_table_entry_t*) arr->elts;
int i;
char *json = "";
for (i = 0; i < arr->nelts; i++) {
json = apr_psprintf(r->pool, "%s'%s': '%s'%s", json,
oidc_util_escape_string(r, elts[i].key),
oidc_util_escape_string(r, elts[i].val),
i < arr->nelts - 1 ? "," : "");
}
json = apr_psprintf(r->pool, "{ %s }", json);
const char *jmethod = "preserveOnLoad";
const char *jscript =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function %s() {\n"
" localStorage.setItem('mod_auth_openidc_preserve_post_params', JSON.stringify(%s));\n"
" %s"
" }\n"
" </script>\n", jmethod, json,
location ?
apr_psprintf(r->pool, "window.location='%s';\n",
location) :
"");
if (location == NULL) {
if (javascript_method)
*javascript_method = apr_pstrdup(r->pool, jmethod);
if (javascript)
*javascript = apr_pstrdup(r->pool, jscript);
} else {
oidc_util_html_send(r, "Preserving...", jscript, jmethod,
"<p>Preserving...</p>", DONE);
}
return TRUE;
}
/*
* restore POST parameters on original_url from HTML5 local storage
*/
static int oidc_request_post_preserved_restore(request_rec *r,
const char *original_url) {
oidc_debug(r, "enter: original_url=%s", original_url);
const char *method = "postOnLoad";
const char *script =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function %s() {\n"
" var mod_auth_openidc_preserve_post_params = JSON.parse(localStorage.getItem('mod_auth_openidc_preserve_post_params'));\n"
" localStorage.removeItem('mod_auth_openidc_preserve_post_params');\n"
" for (var key in mod_auth_openidc_preserve_post_params) {\n"
" var input = document.createElement(\"input\");\n"
" input.name = decodeURIComponent(key);\n"
" input.value = decodeURIComponent(mod_auth_openidc_preserve_post_params[key]);\n"
" input.type = \"hidden\";\n"
" document.forms[0].appendChild(input);\n"
" }\n"
" document.forms[0].action = '%s';\n"
" document.forms[0].submit();\n"
" }\n"
" </script>\n", method, original_url);
const char *body = " <p>Restoring...</p>\n"
" <form method=\"post\"></form>\n";
return oidc_util_html_send(r, "Restoring...", script, method, body,
DONE);
}
/*
* parse state that was sent to us by the issuer
*/
static apr_byte_t oidc_unsolicited_proto_state(request_rec *r, oidc_cfg *c,
const char *state, json_t **proto_state) {
char *alg = NULL;
oidc_debug(r, "enter: state header=%s",
oidc_proto_peek_jwt_header(r, state, &alg));
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret,
oidc_alg2keysize(alg), "sha256",
TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwt_t *jwt = NULL;
if (oidc_jwt_parse(r->pool, state, &jwt,
oidc_util_merge_symmetric_key(r->pool, c->private_keys, jwk),
&err) == FALSE) {
oidc_error(r,
"could not parse JWT from state: invalid unsolicited response: %s",
oidc_jose_e2s(r->pool, err));
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully parsed JWT from state");
if (jwt->payload.iss == NULL) {
oidc_error(r, "no \"iss\" could be retrieved from JWT state, aborting");
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_provider_t *provider = oidc_get_provider_for_issuer(r, c,
jwt->payload.iss, FALSE);
if (provider == NULL) {
oidc_jwt_destroy(jwt);
return FALSE;
}
/* validate the state JWT, validating optional exp + iat */
if (oidc_proto_validate_jwt(r, jwt, provider->issuer, FALSE, FALSE,
provider->idtoken_iat_slack) == FALSE) {
oidc_jwt_destroy(jwt);
return FALSE;
}
char *rfp = NULL;
if (oidc_jose_get_string(r->pool, jwt->payload.value.json, "rfp", TRUE,
&rfp, &err) == FALSE) {
oidc_error(r,
"no \"rfp\" claim could be retrieved from JWT state, aborting: %s",
oidc_jose_e2s(r->pool, err));
oidc_jwt_destroy(jwt);
return FALSE;
}
if (apr_strnatcmp(rfp, "iss") != 0) {
oidc_error(r, "\"rfp\" (%s) does not match \"iss\", aborting", rfp);
oidc_jwt_destroy(jwt);
return FALSE;
}
char *target_link_uri = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json, "target_link_uri",
FALSE, &target_link_uri, NULL);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
oidc_error(r,
"no \"target_link_uri\" claim could be retrieved from JWT state and no OIDCDefaultURL is set, aborting");
oidc_jwt_destroy(jwt);
return FALSE;
}
target_link_uri = c->default_sso_url;
}
if (c->metadata_dir != NULL) {
if ((oidc_metadata_get(r, c, jwt->payload.iss, &provider, FALSE)
== FALSE) || (provider == NULL)) {
oidc_error(r, "no provider metadata found for provider \"%s\"",
jwt->payload.iss);
oidc_jwt_destroy(jwt);
return FALSE;
}
}
char *jti = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json, "jti", FALSE, &jti,
NULL);
if (jti == NULL) {
char *cser = oidc_jwt_serialize(r->pool, jwt, &err);
if (cser == NULL)
return FALSE;
if (oidc_util_hash_string_and_base64url_encode(r, "sha256", cser,
&jti) == FALSE) {
oidc_error(r,
"oidc_util_hash_string_and_base64url_encode returned an error");
return FALSE;
}
}
const char *replay = NULL;
c->cache->get(r, OIDC_CACHE_SECTION_JTI, jti, &replay);
if (replay != NULL) {
oidc_error(r,
"the jti value (%s) passed in the browser state was found in the cache already; possible replay attack!?",
jti);
oidc_jwt_destroy(jwt);
return FALSE;
}
/* jti cache duration is the configured replay prevention window for token issuance plus 10 seconds for safety */
apr_time_t jti_cache_duration = apr_time_from_sec(
provider->idtoken_iat_slack * 2 + 10);
/* store it in the cache for the calculated duration */
c->cache->set(r, OIDC_CACHE_SECTION_JTI, jti, jti,
apr_time_now() + jti_cache_duration);
oidc_debug(r,
"jti \"%s\" validated successfully and is now cached for %" APR_TIME_T_FMT " seconds",
jti, apr_time_sec(jti_cache_duration));
jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret, 0,
NULL, TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwks_uri_t jwks_uri = { provider->jwks_uri,
provider->jwks_refresh_interval, provider->ssl_validate_server };
if (oidc_proto_jwt_verify(r, c, jwt, &jwks_uri,
oidc_util_merge_symmetric_key(r->pool, NULL, jwk)) == FALSE) {
oidc_error(r, "state JWT could not be validated, aborting");
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully verified state JWT");
*proto_state = json_object();
json_object_set_new(*proto_state, "issuer", json_string(jwt->payload.iss));
json_object_set_new(*proto_state, "original_url",
json_string(target_link_uri));
json_object_set_new(*proto_state, "original_method", json_string("get"));
json_object_set_new(*proto_state, "response_mode",
json_string(provider->response_mode));
json_object_set_new(*proto_state, "response_type",
json_string(provider->response_type));
json_object_set_new(*proto_state, "timestamp",
json_integer(apr_time_sec(apr_time_now())));
oidc_jwt_destroy(jwt);
return TRUE;
}
/* obtain the state from the cookie value */
static json_t * oidc_get_state_from_cookie(request_rec *r, oidc_cfg *c,
const char *cookieValue) {
json_t *result = NULL;
oidc_util_jwt_verify(r, c->crypto_passphrase, cookieValue, &result);
return result;
}
static void oidc_clean_expired_state_cookies(request_rec *r, oidc_cfg *c) {
char *cookie, *tokenizerCtx;
char *cookies = apr_pstrdup(r->pool,
(char *) apr_table_get(r->headers_in, "Cookie"));
if (cookies != NULL) {
cookie = apr_strtok(cookies, ";", &tokenizerCtx);
do {
while (cookie != NULL && *cookie == ' ')
cookie++;
if (strstr(cookie, OIDCStateCookiePrefix) == cookie) {
char *cookieName = cookie;
while (cookie != NULL && *cookie != '=')
cookie++;
if (*cookie == '=') {
*cookie = '\0';
cookie++;
json_t *state = oidc_get_state_from_cookie(r, c, cookie);
if (state != NULL) {
json_t *v = json_object_get(state, "timestamp");
apr_time_t now = apr_time_sec(apr_time_now());
if (now > json_integer_value(v) + c->state_timeout) {
oidc_error(r, "state has expired");
oidc_util_set_cookie(r, cookieName, "", 0);
}
json_decref(state);
}
}
}
cookie = apr_strtok(NULL, ";", &tokenizerCtx);
} while (cookie != NULL);
}
}
/*
* restore the state that was maintained between authorization request and response in an encrypted cookie
*/
static apr_byte_t oidc_restore_proto_state(request_rec *r, oidc_cfg *c,
const char *state, json_t **proto_state) {
oidc_debug(r, "enter");
/* clean expired state cookies to avoid pollution */
oidc_clean_expired_state_cookies(r, c);
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* get the state cookie value first */
char *cookieValue = oidc_util_get_cookie(r, cookieName);
if (cookieValue == NULL) {
oidc_error(r, "no \"%s\" state cookie found", cookieName);
return oidc_unsolicited_proto_state(r, c, state, proto_state);
}
/* clear state cookie because we don't need it anymore */
oidc_util_set_cookie(r, cookieName, "", 0);
*proto_state = oidc_get_state_from_cookie(r, c, cookieValue);
if (*proto_state == NULL)
return FALSE;
json_t *v = json_object_get(*proto_state, "nonce");
/* calculate the hash of the browser fingerprint concatenated with the nonce */
char *calc = oidc_get_browser_state_hash(r, json_string_value(v));
/* compare the calculated hash with the value provided in the authorization response */
if (apr_strnatcmp(calc, state) != 0) {
oidc_error(r,
"calculated state from cookie does not match state parameter passed back in URL: \"%s\" != \"%s\"",
state, calc);
json_decref(*proto_state);
return FALSE;
}
v = json_object_get(*proto_state, "timestamp");
apr_time_t now = apr_time_sec(apr_time_now());
/* check that the timestamp is not beyond the valid interval */
if (now > json_integer_value(v) + c->state_timeout) {
oidc_error(r, "state has expired");
oidc_util_html_send_error(r, c->error_template,
"Invalid Authentication Response",
apr_psprintf(r->pool,
"This is due to a timeout; please restart your authentication session by re-entering the URL/bookmark you originally wanted to access: %s",
json_string_value(
json_object_get(*proto_state, "original_url"))),
DONE);
json_decref(*proto_state);
return FALSE;
}
/* add the state */
json_object_set_new(*proto_state, "state", json_string(state));
char *s_value = json_dumps(*proto_state, JSON_ENCODE_ANY);
oidc_debug(r, "restored state: %s", s_value);
free(s_value);
/* we've made it */
return TRUE;
}
/*
* set the state that is maintained between an authorization request and an authorization response
* in a cookie in the browser that is cryptographically bound to that state
*/
static apr_byte_t oidc_authorization_request_set_cookie(request_rec *r,
oidc_cfg *c, const char *state, json_t *proto_state) {
/*
* create a cookie consisting of 8 elements:
* random value, original URL, original method, issuer, response_type, response_mod, prompt and timestamp
* encoded as JSON
*/
/* encrypt the resulting JSON value */
char *cookieValue = NULL;
if (oidc_util_jwt_create(r, c->crypto_passphrase, proto_state,
&cookieValue) == FALSE)
return FALSE;
/* clean expired state cookies to avoid pollution */
oidc_clean_expired_state_cookies(r, c);
/* assemble the cookie name for the state cookie */
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* set it as a cookie */
oidc_util_set_cookie(r, cookieName, cookieValue, -1);
//free(s_value);
return TRUE;
}
/*
* get the mod_auth_openidc related context from the (userdata in the) request
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
static apr_table_t *oidc_request_state(request_rec *rr) {
/* our state is always stored in the main request */
request_rec *r = (rr->main != NULL) ? rr->main : rr;
/* our state is a table, get it */
apr_table_t *state = NULL;
apr_pool_userdata_get((void **) &state, OIDC_USERDATA_KEY, r->pool);
/* if it does not exist, we'll create a new table */
if (state == NULL) {
state = apr_table_make(r->pool, 5);
apr_pool_userdata_set(state, OIDC_USERDATA_KEY, NULL, r->pool);
}
/* return the resulting table, always non-null now */
return state;
}
/*
* set a name/value pair in the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
void oidc_request_state_set(request_rec *r, const char *key, const char *value) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* put the name/value pair in that table */
apr_table_setn(state, key, value);
}
/*
* get a name/value pair from the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
const char*oidc_request_state_get(request_rec *r, const char *key) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* return the value from the table */
return apr_table_get(state, key);
}
/*
* set the claims from a JSON object (c.q. id_token or user_info response) stored
* in the session in to HTTP headers passed on to the application
*/
static apr_byte_t oidc_set_app_claims(request_rec *r,
const oidc_cfg * const cfg, oidc_session_t *session,
const char *s_claims) {
json_t *j_claims = NULL;
/* decode the string-encoded attributes in to a JSON structure */
if (s_claims != NULL) {
json_error_t json_error;
j_claims = json_loads(s_claims, 0, &json_error);
if (j_claims == NULL) {
/* whoops, JSON has been corrupted */
oidc_error(r,
"unable to parse \"%s\" JSON stored in the session: %s",
s_claims, json_error.text);
return FALSE;
}
}
/* set the resolved claims a HTTP headers for the application */
if (j_claims != NULL) {
oidc_util_set_app_infos(r, j_claims, cfg->claim_prefix,
cfg->claim_delimiter, oidc_cfg_dir_pass_info_in_headers(r),
oidc_cfg_dir_pass_info_in_envvars(r));
/* release resources */
json_decref(j_claims);
}
return TRUE;
}
static int oidc_authenticate_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, const char *original_url,
const char *login_hint, const char *id_token_hint, const char *prompt,
const char *auth_request_params);
/*
* log message about max session duration
*/
static void oidc_log_session_expires(request_rec *r, const char *msg,
apr_time_t session_expires) {
char buf[APR_RFC822_DATE_LEN + 1];
apr_rfc822_date(buf, session_expires);
oidc_debug(r, "%s: %s (in %" APR_TIME_T_FMT " secs from now)", msg, buf,
apr_time_sec(session_expires - apr_time_now()));
}
/*
* find out which action we need to take when encountering an unauthenticated request
*/
static int oidc_handle_unauthenticated_user(request_rec *r, oidc_cfg *c) {
/* see if we've configured OIDCUnAuthAction for this path */
switch (oidc_dir_cfg_unauth_action(r)) {
case OIDC_UNAUTH_RETURN410:
return HTTP_GONE;
case OIDC_UNAUTH_RETURN401:
return HTTP_UNAUTHORIZED;
case OIDC_UNAUTH_PASS:
r->user = "";
/*
* we're not going to pass information about an authenticated user to the application,
* but we do need to scrub the headers that mod_auth_openidc would set for security reasons
*/
oidc_scrub_headers(r);
return OK;
case OIDC_UNAUTH_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if ((apr_table_get(r->headers_in, "X-Requested-With") != NULL) && (apr_strnatcasecmp(apr_table_get(r->headers_in, "X-Requested-With"), "XMLHttpRequest") == 0))
return HTTP_UNAUTHORIZED;
}
/*
* else: no session (regardless of whether it is main or sub-request),
* and we need to authenticate the user
*/
return oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, NULL);
}
/*
* check if maximum session duration was exceeded
*/
static int oidc_check_max_session_duration(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
const char *s_session_expires = NULL;
apr_time_t session_expires;
/* get the session expiry from the session data */
oidc_session_get(r, session, OIDC_SESSION_EXPIRES_SESSION_KEY,
&s_session_expires);
/* convert the string to a timestamp */
sscanf(s_session_expires, "%" APR_TIME_T_FMT, &session_expires);
/* check the expire timestamp against the current time */
if (apr_time_now() > session_expires) {
oidc_warn(r, "maximum session duration exceeded for user: %s",
session->remote_user);
oidc_session_kill(r, session);
return oidc_handle_unauthenticated_user(r, cfg);
}
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
return OK;
}
/*
* validate received session cookie against the domain it was issued for:
*
* this handles the case where the cache configured is a the same single memcache, Redis, or file
* backend for different (virtual) hosts, or a client-side cookie protected with the same secret
*
* it also handles the case that a cookie is unexpectedly shared across multiple hosts in
* name-based virtual hosting even though the OP(s) would be the same
*/
static apr_byte_t oidc_check_cookie_domain(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
const char *c_cookie_domain =
cfg->cookie_domain ?
cfg->cookie_domain : oidc_get_current_url_host(r);
const char *s_cookie_domain = NULL;
oidc_session_get(r, session, OIDC_COOKIE_DOMAIN_SESSION_KEY,
&s_cookie_domain);
if ((s_cookie_domain == NULL)
|| (apr_strnatcmp(c_cookie_domain, s_cookie_domain) != 0)) {
oidc_warn(r,
"aborting: detected attempt to play cookie against a different domain/host than issued for! (issued=%s, current=%s)",
s_cookie_domain, c_cookie_domain);
return FALSE;
}
return TRUE;
}
/*
* get a handle to the provider configuration via the "issuer" stored in the session
*/
apr_byte_t oidc_get_provider_from_session(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t **provider) {
oidc_debug(r, "enter");
/* get the issuer value from the session state */
const char *issuer = NULL;
oidc_session_get(r, session, OIDC_ISSUER_SESSION_KEY, &issuer);
if (issuer == NULL) {
oidc_error(r, "session corrupted: no issuer found in session");
return FALSE;
}
/* get the provider info associated with the issuer value */
oidc_provider_t *p = oidc_get_provider_for_issuer(r, c, issuer, FALSE);
if (p == NULL) {
oidc_error(r, "session corrupted: no provider found for issuer: %s",
issuer);
return FALSE;
}
*provider = p;
return TRUE;
}
/*
* store the access token expiry timestamp in the session, based on the expires_in
*/
static void oidc_store_access_token_expiry(request_rec *r,
oidc_session_t *session, int expires_in) {
if (expires_in != -1) {
oidc_session_set(r, session, OIDC_ACCESSTOKEN_EXPIRES_SESSION_KEY,
apr_psprintf(r->pool, "%" APR_TIME_T_FMT,
apr_time_sec(apr_time_now()) + expires_in));
}
}
/*
* store claims resolved from the userinfo endpoint in the session
*/
static void oidc_store_userinfo_claims(request_rec *r, oidc_session_t *session,
oidc_provider_t *provider, const char *claims) {
oidc_debug(r, "enter");
/* see if we've resolved any claims */
if (claims != NULL) {
/*
* Successfully decoded a set claims from the response so we can store them
* (well actually the stringified representation in the response)
* in the session context safely now
*/
oidc_session_set(r, session, OIDC_CLAIMS_SESSION_KEY, claims);
} else {
/*
* clear the existing claims because we could not refresh them
*/
oidc_session_set(r, session, OIDC_CLAIMS_SESSION_KEY, NULL);
}
/* store the last refresh time if we've configured a userinfo refresh interval */
if (provider->userinfo_refresh_interval > 0)
oidc_session_set(r, session, OIDC_USERINFO_LAST_REFRESH_SESSION_KEY,
apr_psprintf(r->pool, "%" APR_TIME_T_FMT, apr_time_now()));
}
/*
* execute refresh token grant to refresh the existing access token
*/
static apr_byte_t oidc_refresh_access_token(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider,
char **new_access_token) {
oidc_debug(r, "enter");
/* get the refresh token that was stored in the session */
const char *refresh_token = NULL;
oidc_session_get(r, session, OIDC_REFRESHTOKEN_SESSION_KEY, &refresh_token);
if (refresh_token == NULL) {
oidc_warn(r,
"refresh token routine called but no refresh_token found in the session");
return FALSE;
}
/* elements returned in the refresh response */
char *s_id_token = NULL;
int expires_in = -1;
char *s_token_type = NULL;
char *s_access_token = NULL;
char *s_refresh_token = NULL;
/* refresh the tokens by calling the token endpoint */
if (oidc_proto_refresh_request(r, c, provider, refresh_token, &s_id_token,
&s_access_token, &s_token_type, &expires_in,
&s_refresh_token) == FALSE) {
oidc_error(r, "access_token could not be refreshed");
return FALSE;
}
/* store the new access_token in the session and discard the old one */
oidc_session_set(r, session, OIDC_ACCESSTOKEN_SESSION_KEY, s_access_token);
oidc_store_access_token_expiry(r, session, expires_in);
/* see if we need to return it as a parameter */
if (new_access_token != NULL)
*new_access_token = s_access_token;
/* if we have a new refresh token (rolling refresh), store it in the session and overwrite the old one */
if (s_refresh_token != NULL)
oidc_session_set(r, session, OIDC_REFRESHTOKEN_SESSION_KEY,
s_refresh_token);
return TRUE;
}
/*
* retrieve claims from the userinfo endpoint and return the stringified response
*/
static const char *oidc_retrieve_claims_from_userinfo_endpoint(request_rec *r,
oidc_cfg *c, oidc_provider_t *provider, const char *access_token,
oidc_session_t *session, char *id_token_sub) {
oidc_debug(r, "enter");
/* see if a userinfo endpoint is set, otherwise there's nothing to do for us */
if (provider->userinfo_endpoint_url == NULL) {
oidc_debug(r,
"not retrieving userinfo claims because userinfo_endpoint is not set");
return NULL;
}
/* see if there's an access token, otherwise we can't call the userinfo endpoint at all */
if (access_token == NULL) {
oidc_debug(r,
"not retrieving userinfo claims because access_token is not provided");
return NULL;
}
if ((id_token_sub == NULL) && (session != NULL)) {
// when refreshing claims from the userinfo endpoint
const char *s_id_token_claims = NULL;
oidc_session_get(r, session, OIDC_IDTOKEN_CLAIMS_SESSION_KEY,
&s_id_token_claims);
if (s_id_token_claims == NULL) {
oidc_error(r, "no id_token claims provided");
return NULL;
}
json_error_t json_error;
json_t *id_token_claims = json_loads(s_id_token_claims, 0, &json_error);
if (id_token_claims == NULL) {
oidc_error(r, "JSON parsing (json_loads) failed: %s (%s)",
json_error.text, s_id_token_claims);
return NULL;
}
oidc_jose_get_string(r->pool, id_token_claims, "sub", FALSE, &id_token_sub, NULL);
}
// TODO: return code should indicate whether the token expired or some other error occurred
// TODO: long-term: session storage should be JSON (with explicit types and less conversion, using standard routines)
/* try to get claims from the userinfo endpoint using the provided access token */
const char *result = NULL;
if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub, access_token,
&result) == FALSE) {
/* see if we have an existing session and we are refreshing the user info claims */
if (session != NULL) {
/* first call to user info endpoint failed, but the access token may have just expired, so refresh it */
char *access_token = NULL;
if (oidc_refresh_access_token(r, c, session, provider,
&access_token) == TRUE) {
/* try again with the new access token */
if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub, access_token,
&result) == FALSE) {
oidc_error(r,
"resolving user info claims with the refreshed access token failed, nothing will be stored in the session");
result = NULL;
}
} else {
oidc_warn(r,
"refreshing access token failed, claims will not be retrieved/refreshed from the userinfo endpoint");
result = NULL;
}
} else {
oidc_error(r,
"resolving user info claims with the existing/provided access token failed, nothing will be stored in the session");
result = NULL;
}
}
return result;
}
/*
* get (new) claims from the userinfo endpoint
*/
static apr_byte_t oidc_refresh_claims_from_userinfo_endpoint(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session) {
oidc_provider_t *provider = NULL;
const char *claims = NULL;
char *access_token = NULL;
/* get the current provider info */
if (oidc_get_provider_from_session(r, cfg, session, &provider) == FALSE)
return FALSE;
/* see if we can do anything here, i.e. we have a userinfo endpoint and a refresh interval is configured */
apr_time_t interval = apr_time_from_sec(
provider->userinfo_refresh_interval);
oidc_debug(r, "userinfo_endpoint=%s, interval=%d",
provider->userinfo_endpoint_url,
provider->userinfo_refresh_interval);
if ((provider->userinfo_endpoint_url != NULL) && (interval > 0)) {
/* get the last refresh timestamp from the session info */
apr_time_t last_refresh = 0;
const char *s_last_refresh = NULL;
oidc_session_get(r, session, OIDC_USERINFO_LAST_REFRESH_SESSION_KEY,
&s_last_refresh);
if (s_last_refresh != NULL) {
sscanf(s_last_refresh, "%" APR_TIME_T_FMT, &last_refresh);
}
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(last_refresh + interval - apr_time_now()));
/* see if we need to refresh again */
if (last_refresh + interval < apr_time_now()) {
/* get the current access token */
oidc_session_get(r, session, OIDC_ACCESSTOKEN_SESSION_KEY,
(const char **) &access_token);
/* retrieve the current claims */
claims = oidc_retrieve_claims_from_userinfo_endpoint(r, cfg,
provider, access_token, session, NULL);
/* store claims resolved from userinfo endpoint */
oidc_store_userinfo_claims(r, session, provider, claims);
/* indicated something changed */
return TRUE;
}
}
return FALSE;
}
/*
* copy the claims and id_token from the session to the request state and optionally return them
*/
static void oidc_copy_tokens_to_request_state(request_rec *r,
oidc_session_t *session, const char **s_id_token, const char **s_claims) {
const char *id_token = NULL, *claims = NULL;
oidc_session_get(r, session, OIDC_IDTOKEN_CLAIMS_SESSION_KEY, &id_token);
oidc_session_get(r, session, OIDC_CLAIMS_SESSION_KEY, &claims);
oidc_debug(r, "id_token=%s claims=%s", id_token, claims);
if (id_token != NULL) {
oidc_request_state_set(r, OIDC_IDTOKEN_CLAIMS_SESSION_KEY, id_token);
if (s_id_token != NULL)
*s_id_token = id_token;
}
if (claims != NULL) {
oidc_request_state_set(r, OIDC_CLAIMS_SESSION_KEY, claims);
if (s_claims != NULL)
*s_claims = claims;
}
}
/*
* pass refresh_token, access_token and access_token_expires as headers/environment variables to the application
*/
static apr_byte_t oidc_session_pass_tokens_and_save(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session, apr_byte_t needs_save) {
int pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
int pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
/* set the refresh_token in the app headers/variables, if enabled for this location/directory */
const char *refresh_token = NULL;
oidc_session_get(r, session, OIDC_REFRESHTOKEN_SESSION_KEY, &refresh_token);
if ((oidc_cfg_dir_pass_refresh_token(r) != 0) && (refresh_token != NULL)) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, "refresh_token", refresh_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* set the access_token in the app headers/variables */
const char *access_token = NULL;
oidc_session_get(r, session, OIDC_ACCESSTOKEN_SESSION_KEY, &access_token);
if (access_token != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, "access_token", access_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* set the expiry timestamp in the app headers/variables */
const char *access_token_expires = NULL;
oidc_session_get(r, session, OIDC_ACCESSTOKEN_EXPIRES_SESSION_KEY,
&access_token_expires);
if (access_token_expires != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, "access_token_expires", access_token_expires,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/*
* reset the session inactivity timer
* but only do this once per 10% of the inactivity timeout interval (with a max to 60 seconds)
* for performance reasons
*
* now there's a small chance that the session ends 10% (or a minute) earlier than configured/expected
* cq. when there's a request after a recent save (so no update) and then no activity happens until
* a request comes in just before the session should expire
* ("recent" and "just before" refer to 10%-with-a-max-of-60-seconds of the inactivity interval after
* the start/last-update and before the expiry of the session respectively)
*
* this is be deemed acceptable here because of performance gain
*/
apr_time_t interval = apr_time_from_sec(cfg->session_inactivity_timeout);
apr_time_t now = apr_time_now();
apr_time_t slack = interval / 10;
if (slack > apr_time_from_sec(60))
slack = apr_time_from_sec(60);
if (session->expiry - now < interval - slack) {
session->expiry = now + interval;
needs_save = TRUE;
}
/* log message about session expiry */
oidc_log_session_expires(r, "session inactivity timeout", session->expiry);
/* check if something was updated in the session and we need to save it again */
if (needs_save)
if (oidc_session_save(r, session) == FALSE)
return FALSE;
return TRUE;
}
/*
* handle the case where we have identified an existing authentication session for a user
*/
static int oidc_handle_existing_session(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
oidc_debug(r, "enter");
/* get the header name in which the remote user name needs to be passed */
char *authn_header = oidc_cfg_dir_authn_header(r);
int pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
int pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
/* verify current cookie domain against issued cookie domain */
if (oidc_check_cookie_domain(r, cfg, session) == FALSE)
return HTTP_UNAUTHORIZED;
/* check if the maximum session duration was exceeded */
int rc = oidc_check_max_session_duration(r, cfg, session);
if (rc != OK)
return rc;
/* if needed, refresh claims from the user info endpoint */
apr_byte_t needs_save = oidc_refresh_claims_from_userinfo_endpoint(r, cfg,
session);
/*
* we're going to pass the information that we have to the application,
* but first we need to scrub the headers that we're going to use for security reasons
*/
oidc_scrub_headers(r);
/* set the user authentication HTTP header if set and required */
if ((r->user != NULL) && (authn_header != NULL))
oidc_util_set_header(r, authn_header, r->user);
const char *s_claims = NULL;
const char *s_id_token = NULL;
/* copy id_token and claims from session to request state and obtain their values */
oidc_copy_tokens_to_request_state(r, session, &s_id_token, &s_claims);
/* set the claims in the app headers */
if (oidc_set_app_claims(r, cfg, session, s_claims) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_CLAIMS)) {
/* set the id_token in the app headers */
if (oidc_set_app_claims(r, cfg, session, s_id_token) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_PAYLOAD)) {
/* pass the id_token JSON object to the app in a header or environment variable */
oidc_util_set_app_info(r, "id_token_payload", s_id_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_SERIALIZED)) {
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
const char *s_id_token = NULL;
/* get the compact serialized JWT from the session */
oidc_session_get(r, session, OIDC_IDTOKEN_SESSION_KEY, &s_id_token);
/* pass the compact serialized JWT to the app in a header or environment variable */
oidc_util_set_app_info(r, "id_token", s_id_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
} else {
oidc_error(r,
"session type \"client-cookie\" does not allow storing/passing the id_token; use \"OIDCSessionType server-cache\" for that");
}
}
/* pass the at, rt and at expiry to the application, possibly update the session expiry and save the session */
if (oidc_session_pass_tokens_and_save(r, cfg, session, needs_save) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* return "user authenticated" status */
return OK;
}
/*
* helper function for basic/implicit client flows upon receiving an authorization response:
* check that it matches the state stored in the browser and return the variables associated
* with the state, such as original_url and OP oidc_provider_t pointer.
*/
static apr_byte_t oidc_authorization_response_match_state(request_rec *r,
oidc_cfg *c, const char *state, struct oidc_provider_t **provider,
json_t **proto_state) {
oidc_debug(r, "enter (state=%s)", state);
if ((state == NULL) || (apr_strnatcmp(state, "") == 0)) {
oidc_error(r, "state parameter is not set");
return FALSE;
}
/* check the state parameter against what we stored in a cookie */
if (oidc_restore_proto_state(r, c, state, proto_state) == FALSE) {
oidc_error(r, "unable to restore state");
return FALSE;
}
*provider = oidc_get_provider_for_issuer(r, c,
json_string_value(json_object_get(*proto_state, "issuer")), FALSE);
return (*provider != NULL);
}
/*
* redirect the browser to the session logout endpoint
*/
static int oidc_session_redirect_parent_window_to_logout(request_rec *r,
oidc_cfg *c) {
oidc_debug(r, "enter");
char *java_script = apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" window.top.location.href = '%s?session=logout';\n"
" </script>\n", c->redirect_uri);
return oidc_util_html_send(r, "Redirecting...", java_script, NULL, NULL,
DONE);
}
/*
* handle an error returned by the OP
*/
static int oidc_authorization_response_error(request_rec *r, oidc_cfg *c,
json_t *proto_state, const char *error, const char *error_description) {
const char *prompt =
json_object_get(proto_state, "prompt") ?
apr_pstrdup(r->pool,
json_string_value(
json_object_get(proto_state, "prompt"))) :
NULL;
json_decref(proto_state);
if ((prompt != NULL) && (apr_strnatcmp(prompt, "none") == 0)) {
return oidc_session_redirect_parent_window_to_logout(r, c);
}
return oidc_util_html_send_error(r, c->error_template,
apr_psprintf(r->pool, "OpenID Connect Provider error: %s", error),
error_description, DONE);
}
/*
* set the unique user identifier that will be propagated in the Apache r->user and REMOTE_USER variables
*/
static apr_byte_t oidc_get_remote_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, oidc_jwt_t *jwt, char **user,
const char *s_claims) {
char *issuer = provider->issuer;
char *claim_name = apr_pstrdup(r->pool, c->remote_user_claim.claim_name);
int n = strlen(claim_name);
int post_fix_with_issuer = (claim_name[n - 1] == '@');
if (post_fix_with_issuer) {
claim_name[n - 1] = '\0';
issuer =
(strstr(issuer, "https://") == NULL) ?
apr_pstrdup(r->pool, issuer) :
apr_pstrdup(r->pool, issuer + strlen("https://"));
}
/* extract the username claim (default: "sub") from the id_token payload or user claims */
char *username = NULL;
json_error_t json_error;
json_t *claims = json_loads(s_claims, 0, &json_error);
if (claims == NULL) {
username = apr_pstrdup(r->pool,
json_string_value(
json_object_get(jwt->payload.value.json, claim_name)));
} else {
oidc_util_json_merge(jwt->payload.value.json, claims);
username = apr_pstrdup(r->pool,
json_string_value(json_object_get(claims, claim_name)));
json_decref(claims);
}
if (username == NULL) {
oidc_error(r,
"OIDCRemoteUserClaim is set to \"%s\", but the id_token JSON payload and user claims did not contain a \"%s\" string",
c->remote_user_claim.claim_name, claim_name);
*user = NULL;
return FALSE;
}
/* set the unique username in the session (will propagate to r->user/REMOTE_USER) */
*user = post_fix_with_issuer ?
apr_psprintf(r->pool, "%s@%s", username, issuer) : username;
if (c->remote_user_claim.reg_exp != NULL) {
char *error_str = NULL;
if (oidc_util_regexp_first_match(r->pool, *user,
c->remote_user_claim.reg_exp, user, &error_str) == FALSE) {
oidc_error(r, "oidc_util_regexp_first_match failed: %s", error_str);
*user = NULL;
return FALSE;
}
}
oidc_debug(r, "set user to \"%s\"", *user);
return TRUE;
}
/*
* store resolved information in the session
*/
static apr_byte_t oidc_save_in_session(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider,
const char *remoteUser, const char *id_token, oidc_jwt_t *id_token_jwt,
const char *claims, const char *access_token, const int expires_in,
const char *refresh_token, const char *session_state, const char *state,
const char *original_url) {
/* store the user in the session */
session->remote_user = remoteUser;
/* set the session expiry to the inactivity timeout */
session->expiry =
apr_time_now() + apr_time_from_sec(c->session_inactivity_timeout);
/* store the claims payload in the id_token for later reference */
oidc_session_set(r, session, OIDC_IDTOKEN_CLAIMS_SESSION_KEY,
id_token_jwt->payload.value.str);
if (c->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* store the compact serialized representation of the id_token for later reference */
oidc_session_set(r, session, OIDC_IDTOKEN_SESSION_KEY, id_token);
}
/* store the issuer in the session (at least needed for session mgmt and token refresh */
oidc_session_set(r, session, OIDC_ISSUER_SESSION_KEY, provider->issuer);
/* store the state and original URL in the session for handling browser-back more elegantly */
oidc_session_set(r, session, OIDC_REQUEST_STATE_SESSION_KEY, state);
oidc_session_set(r, session, OIDC_REQUEST_ORIGINAL_URL, original_url);
if ((session_state != NULL) && (provider->check_session_iframe != NULL)) {
/* store the session state and required parameters session management */
oidc_session_set(r, session, OIDC_SESSION_STATE_SESSION_KEY,
session_state);
oidc_session_set(r, session, OIDC_CHECK_IFRAME_SESSION_KEY,
provider->check_session_iframe);
oidc_session_set(r, session, OIDC_CLIENTID_SESSION_KEY,
provider->client_id);
oidc_debug(r,
"session management enabled: stored session_state (%s), check_session_iframe (%s) and client_id (%s) in the session",
session_state, provider->check_session_iframe,
provider->client_id);
} else if (provider->check_session_iframe == NULL) {
oidc_debug(r,
"session management disabled: \"check_session_iframe\" is not set in provider configuration");
} else {
oidc_warn(r,
"session management disabled: no \"session_state\" value is provided in the authentication response even though \"check_session_iframe\" (%s) is set in the provider configuration",
provider->check_session_iframe);
}
if (provider->end_session_endpoint != NULL)
oidc_session_set(r, session, OIDC_LOGOUT_ENDPOINT_SESSION_KEY,
provider->end_session_endpoint);
/* store claims resolved from userinfo endpoint */
oidc_store_userinfo_claims(r, session, provider, claims);
/* see if we have an access_token */
if (access_token != NULL) {
/* store the access_token in the session context */
oidc_session_set(r, session, OIDC_ACCESSTOKEN_SESSION_KEY,
access_token);
/* store the associated expires_in value */
oidc_store_access_token_expiry(r, session, expires_in);
}
/* see if we have a refresh_token */
if (refresh_token != NULL) {
/* store the refresh_token in the session context */
oidc_session_set(r, session, OIDC_REFRESHTOKEN_SESSION_KEY,
refresh_token);
}
/* store max session duration in the session as a hard cut-off expiry timestamp */
apr_time_t session_expires =
(provider->session_max_duration == 0) ?
apr_time_from_sec(id_token_jwt->payload.exp) :
(apr_time_now()
+ apr_time_from_sec(provider->session_max_duration));
oidc_session_set(r, session, OIDC_SESSION_EXPIRES_SESSION_KEY,
apr_psprintf(r->pool, "%" APR_TIME_T_FMT, session_expires));
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
/* store the domain for which this session is valid */
oidc_session_set(r, session, OIDC_COOKIE_DOMAIN_SESSION_KEY,
c->cookie_domain ? c->cookie_domain : oidc_get_current_url_host(r));
/* store the session */
return oidc_session_save(r, session);
}
/*
* parse the expiry for the access token
*/
static int oidc_parse_expires_in(request_rec *r, const char *expires_in) {
if (expires_in != NULL) {
char *ptr = NULL;
long number = strtol(expires_in, &ptr, 10);
if (number <= 0) {
oidc_warn(r,
"could not convert \"expires_in\" value (%s) to a number",
expires_in);
return -1;
}
return number;
}
return -1;
}
/*
* handle the different flows (hybrid, implicit, Authorization Code)
*/
static apr_byte_t oidc_handle_flows(request_rec *r, oidc_cfg *c,
json_t *proto_state, oidc_provider_t *provider, apr_table_t *params,
const char *response_mode, oidc_jwt_t **jwt) {
apr_byte_t rc = FALSE;
const char *requested_response_type = json_string_value(
json_object_get(proto_state, "response_type"));
/* handle the requested response type/mode */
if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
"code id_token token")) {
rc = oidc_proto_authorization_response_code_idtoken_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
"code id_token")) {
rc = oidc_proto_authorization_response_code_idtoken(r, c, proto_state,
provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
"code token")) {
rc = oidc_proto_handle_authorization_response_code_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
"code")) {
rc = oidc_proto_handle_authorization_response_code(r, c, proto_state,
provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
"id_token token")) {
rc = oidc_proto_handle_authorization_response_idtoken_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
"id_token")) {
rc = oidc_proto_handle_authorization_response_idtoken(r, c, proto_state,
provider, params, response_mode, jwt);
} else {
oidc_error(r, "unsupported response type: \"%s\"",
requested_response_type);
}
if ((rc == FALSE) && (*jwt != NULL)) {
oidc_jwt_destroy(*jwt);
*jwt = NULL;
}
return rc;
}
/* handle the browser back on an authorization response */
static apr_byte_t oidc_handle_browser_back(request_rec *r, const char *r_state,
oidc_session_t *session) {
/* see if we have an existing session and browser-back was used */
const char *s_state = NULL, *o_url = NULL;
if (session->remote_user != NULL) {
oidc_session_get(r, session, OIDC_REQUEST_STATE_SESSION_KEY, &s_state);
oidc_session_get(r, session, OIDC_REQUEST_ORIGINAL_URL, &o_url);
if ((r_state != NULL) && (s_state != NULL)
&& (apr_strnatcmp(r_state, s_state) == 0)) {
/* log the browser back event detection */
oidc_warn(r,
"browser back detected, redirecting to original URL: %s",
o_url);
/* go back to the URL that he originally tried to access */
apr_table_add(r->headers_out, "Location", o_url);
return TRUE;
}
}
return FALSE;
}
/*
* complete the handling of an authorization response by obtaining, parsing and verifying the
* id_token and storing the authenticated user state in the session
*/
static int oidc_handle_authorization_response(request_rec *r, oidc_cfg *c,
oidc_session_t *session, apr_table_t *params, const char *response_mode) {
oidc_debug(r, "enter, response_mode=%s", response_mode);
oidc_provider_t *provider = NULL;
json_t *proto_state = NULL;
oidc_jwt_t *jwt = NULL;
/* see if this response came from a browser-back event */
if (oidc_handle_browser_back(r, apr_table_get(params, "state"),
session) == TRUE)
return HTTP_MOVED_TEMPORARILY;
/* match the returned state parameter against the state stored in the browser */
if (oidc_authorization_response_match_state(r, c,
apr_table_get(params, "state"), &provider, &proto_state) == FALSE) {
if (c->default_sso_url != NULL) {
oidc_warn(r,
"invalid authorization response state; a default SSO URL is set, sending the user there: %s",
c->default_sso_url);
apr_table_add(r->headers_out, "Location", c->default_sso_url);
return HTTP_MOVED_TEMPORARILY;
}
oidc_error(r,
"invalid authorization response state and no default SSO URL is set, sending an error...");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if the response is an error response */
if (apr_table_get(params, "error") != NULL)
return oidc_authorization_response_error(r, c, proto_state,
apr_table_get(params, "error"),
apr_table_get(params, "error_description"));
/* handle the code, implicit or hybrid flow */
if (oidc_handle_flows(r, c, proto_state, provider, params, response_mode,
&jwt) == FALSE)
return oidc_authorization_response_error(r, c, proto_state,
"Error in handling response type.", NULL);
if (jwt == NULL) {
oidc_error(r, "no id_token was provided");
return oidc_authorization_response_error(r, c, proto_state,
"No id_token was provided.", NULL);
}
int expires_in = oidc_parse_expires_in(r,
apr_table_get(params, "expires_in"));
/*
* optionally resolve additional claims against the userinfo endpoint
* parsed claims are not actually used here but need to be parsed anyway for error checking purposes
*/
const char *claims = oidc_retrieve_claims_from_userinfo_endpoint(r, c,
provider, apr_table_get(params, "access_token"), NULL, jwt->payload.sub);
/* restore the original protected URL that the user was trying to access */
const char *original_url = apr_pstrdup(r->pool,
json_string_value(json_object_get(proto_state, "original_url")));
const char *original_method = apr_pstrdup(r->pool,
json_string_value(json_object_get(proto_state, "original_method")));
/* set the user */
if (oidc_get_remote_user(r, c, provider, jwt, &r->user, claims) == TRUE) {
/* session management: if the user in the new response is not equal to the old one, error out */
if ((json_object_get(proto_state, "prompt") != NULL)
&& (apr_strnatcmp(
json_string_value(
json_object_get(proto_state, "prompt")), "none")
== 0)) {
// TOOD: actually need to compare sub? (need to store it in the session separately then
//const char *sub = NULL;
//oidc_session_get(r, session, "sub", &sub);
//if (apr_strnatcmp(sub, jwt->payload.sub) != 0) {
if (apr_strnatcmp(session->remote_user, r->user) != 0) {
oidc_warn(r,
"user set from new id_token is different from current one");
oidc_jwt_destroy(jwt);
return oidc_authorization_response_error(r, c, proto_state,
"User changed!", NULL);
}
}
/* store resolved information in the session */
if (oidc_save_in_session(r, c, session, provider, r->user,
apr_table_get(params, "id_token"), jwt, claims,
apr_table_get(params, "access_token"), expires_in,
apr_table_get(params, "refresh_token"),
apr_table_get(params, "session_state"),
apr_table_get(params, "state"), original_url) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
} else {
oidc_error(r, "remote user could not be set");
return oidc_authorization_response_error(r, c, proto_state,
"Remote user could not be set: contact the website administrator",
NULL);
}
/* cleanup */
json_decref(proto_state);
oidc_jwt_destroy(jwt);
/* check that we've actually authenticated a user; functions as error handling for oidc_get_remote_user */
if (r->user == NULL)
return HTTP_UNAUTHORIZED;
/* log the successful response */
oidc_debug(r,
"session created and stored, returning to original URL: %s, original method: %s",
original_url, original_method);
/* check whether form post data was preserved; if so restore it */
if (apr_strnatcmp(original_method, OIDC_METHOD_FORM_POST) == 0) {
return oidc_request_post_preserved_restore(r, original_url);
}
/* now we've authenticated the user so go back to the URL that he originally tried to access */
apr_table_add(r->headers_out, "Location", original_url);
/* do the actual redirect to the original URL */
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle an OpenID Connect Authorization Response using the POST (+fragment->POST) response_mode
*/
static int oidc_handle_post_authorization_response(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
oidc_debug(r, "enter");
/* initialize local variables */
char *response_mode = NULL;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if we've got any POST-ed data at all */
if ((apr_table_elts(params)->nelts < 1)
|| ((apr_table_elts(params)->nelts == 1)
&& apr_table_get(params, "response_mode")
&& (apr_strnatcmp(apr_table_get(params, "response_mode"),
"fragment") == 0))) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"You've hit an OpenID Connect Redirect URI with no parameters, this is an invalid request; you should not open this URL in your browser directly, or have the server administrator use a different OIDCRedirectURI setting.",
HTTP_INTERNAL_SERVER_ERROR);
}
/* get the parameters */
response_mode = (char *) apr_table_get(params, "response_mode");
/* do the actual implicit work */
return oidc_handle_authorization_response(r, c, session, params,
response_mode ? response_mode : "form_post");
}
/*
* handle an OpenID Connect Authorization Response using the redirect response_mode
*/
static int oidc_handle_redirect_authorization_response(request_rec *r,
oidc_cfg *c, oidc_session_t *session) {
oidc_debug(r, "enter");
/* read the parameters from the query string */
apr_table_t *params = apr_table_make(r->pool, 8);
oidc_util_read_form_encoded_params(r, params, r->args);
/* do the actual work */
return oidc_handle_authorization_response(r, c, session, params, "query");
}
/*
* present the user with an OP selection screen
*/
static int oidc_discovery(request_rec *r, oidc_cfg *cfg) {
oidc_debug(r, "enter");
/* obtain the URL we're currently accessing, to be stored in the state/session */
char *current_url = oidc_get_current_url(r);
const char *method = oidc_original_request_method(r, cfg, FALSE);
/* generate CSRF token */
char *csrf = NULL;
if (oidc_proto_generate_nonce(r, &csrf, 8) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
char *discover_url = oidc_cfg_dir_discover_url(r);
/* see if there's an external discovery page configured */
if (discover_url != NULL) {
/* yes, assemble the parameters for external discovery */
char *url = apr_psprintf(r->pool, "%s%s%s=%s&%s=%s&%s=%s&%s=%s",
discover_url, strchr(discover_url, '?') != NULL ? "&" : "?",
OIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url),
OIDC_DISC_RM_PARAM, method,
OIDC_DISC_CB_PARAM,
oidc_util_escape_string(r, cfg->redirect_uri),
OIDC_CSRF_NAME, oidc_util_escape_string(r, csrf));
/* log what we're about to do */
oidc_debug(r, "redirecting to external discovery page: %s", url);
/* set CSRF cookie */
oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1);
/* see if we need to preserve POST parameters through Javascript/HTML5 storage */
if (oidc_post_preserve_javascript(r, url, NULL, NULL) == TRUE)
return DONE;
/* do the actual redirect to an external discovery page */
apr_table_add(r->headers_out, "Location", url);
return HTTP_MOVED_TEMPORARILY;
}
/* get a list of all providers configured in the metadata directory */
apr_array_header_t *arr = NULL;
if (oidc_metadata_list(r, cfg, &arr) == FALSE)
return oidc_util_html_send_error(r, cfg->error_template,
"Configuration Error",
"No configured providers found, contact your administrator",
HTTP_UNAUTHORIZED);
/* assemble a where-are-you-from IDP discovery HTML page */
const char *s = " <h3>Select your OpenID Connect Identity Provider</h3>\n";
/* list all configured providers in there */
int i;
for (i = 0; i < arr->nelts; i++) {
const char *issuer = ((const char**) arr->elts)[i];
// TODO: html escape (especially & character)
char *display =
(strstr(issuer, "https://") == NULL) ?
apr_pstrdup(r->pool, issuer) :
apr_pstrdup(r->pool, issuer + strlen("https://"));
/* strip port number */
//char *p = strstr(display, ":");
//if (p != NULL) *p = '\0';
/* point back to the redirect_uri, where the selection is handled, with an IDP selection and return_to URL */
s =
apr_psprintf(r->pool,
"%s<p><a href=\"%s?%s=%s&%s=%s&%s=%s&%s=%s\">%s</a></p>\n",
s, cfg->redirect_uri, OIDC_DISC_OP_PARAM,
oidc_util_escape_string(r, issuer),
OIDC_DISC_RT_PARAM,
oidc_util_escape_string(r, current_url),
OIDC_DISC_RM_PARAM, method,
OIDC_CSRF_NAME, csrf, display);
}
/* add an option to enter an account or issuer name for dynamic OP discovery */
s = apr_psprintf(r->pool, "%s<form method=\"get\" action=\"%s\">\n", s,
cfg->redirect_uri);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_RT_PARAM, current_url);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_RM_PARAM, method);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_CSRF_NAME, csrf);
s =
apr_psprintf(r->pool,
"%s<p>Or enter your account name (eg. "mike@seed.gluu.org", or an IDP identifier (eg. "mitreid.org"):</p>\n",
s);
s = apr_psprintf(r->pool,
"%s<p><input type=\"text\" name=\"%s\" value=\"%s\"></p>\n", s,
OIDC_DISC_OP_PARAM, "");
s = apr_psprintf(r->pool,
"%s<p><input type=\"submit\" value=\"Submit\"></p>\n", s);
s = apr_psprintf(r->pool, "%s</form>\n", s);
oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1);
char *javascript = NULL, *javascript_method = NULL;
char *html_head =
"<style type=\"text/css\">body {text-align: center}</style>";
if (oidc_post_preserve_javascript(r, NULL, &javascript,
&javascript_method) == TRUE)
html_head = apr_psprintf(r->pool, "%s%s", html_head, javascript);
/* now send the HTML contents to the user agent */
return oidc_util_html_send(r, "OpenID Connect Provider Discovery",
html_head, javascript_method, s, DONE);
}
/*
* authenticate the user to the selected OP, if the OP is not selected yet perform discovery first
*/
static int oidc_authenticate_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, const char *original_url,
const char *login_hint, const char *id_token_hint, const char *prompt,
const char *auth_request_params) {
oidc_debug(r, "enter");
if (provider == NULL) {
// TODO: should we use an explicit redirect to the discovery endpoint (maybe a "discovery" param to the redirect_uri)?
if (c->metadata_dir != NULL)
return oidc_discovery(r, c);
/* we're not using multiple OP's configured in a metadata directory, pick the statically configured OP */
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
/* generate the random nonce value that correlates requests and responses */
char *nonce = NULL;
if (oidc_proto_generate_nonce(r, &nonce, OIDC_PROTO_NONCE_LENGTH) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
char *code_verifier = NULL;
char *code_challenge = NULL;
if ((oidc_util_spaced_string_contains(r->pool, provider->response_type,
"code") == TRUE) && (provider->pkce_method != NULL)) {
/* generate the code verifier value that correlates authorization requests and code exchange requests */
if (oidc_proto_generate_code_verifier(r, &code_verifier,
OIDC_PROTO_CODE_VERIFIER_LENGTH) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* generate the PKCE code challenge */
if (oidc_proto_generate_code_challenge(r, code_verifier,
&code_challenge, provider->pkce_method) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
/* create the state between request/response */
json_t *proto_state = json_object();
json_object_set_new(proto_state, "original_url", json_string(original_url));
json_object_set_new(proto_state, "original_method",
json_string(oidc_original_request_method(r, c, TRUE)));
json_object_set_new(proto_state, "issuer", json_string(provider->issuer));
json_object_set_new(proto_state, "response_type",
json_string(provider->response_type));
json_object_set_new(proto_state, "nonce", json_string(nonce));
json_object_set_new(proto_state, "timestamp",
json_integer(apr_time_sec(apr_time_now())));
if (provider->response_mode)
json_object_set_new(proto_state, "response_mode",
json_string(provider->response_mode));
if (prompt)
json_object_set_new(proto_state, "prompt", json_string(prompt));
if (code_verifier)
json_object_set_new(proto_state, "code_verifier",
json_string(code_verifier));
/* get a hash value that fingerprints the browser concatenated with the random input */
char *state = oidc_get_browser_state_hash(r, nonce);
/* create state that restores the context when the authorization response comes in; cryptographically bind it to the browser */
if (oidc_authorization_request_set_cookie(r, c, state, proto_state) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/*
* printout errors if Cookie settings are not going to work
*/
apr_uri_t o_uri;
memset(&o_uri, 0, sizeof(apr_uri_t));
apr_uri_t r_uri;
memset(&r_uri, 0, sizeof(apr_uri_t));
apr_uri_parse(r->pool, original_url, &o_uri);
apr_uri_parse(r->pool, c->redirect_uri, &r_uri);
if ((apr_strnatcmp(o_uri.scheme, r_uri.scheme) != 0)
&& (apr_strnatcmp(r_uri.scheme, "https") == 0)) {
oidc_error(r,
"the URL scheme (%s) of the configured OIDCRedirectURI does not match the URL scheme of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!",
r_uri.scheme, o_uri.scheme);
return HTTP_INTERNAL_SERVER_ERROR;
}
if (c->cookie_domain == NULL) {
if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
char *p = strstr(o_uri.hostname, r_uri.hostname);
if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
oidc_error(r,
"the URL hostname (%s) of the configured OIDCRedirectURI does not match the URL hostname of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!",
r_uri.hostname, o_uri.hostname);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
} else {
if (!oidc_util_cookie_domain_valid(r_uri.hostname, c->cookie_domain)) {
oidc_error(r,
"the domain (%s) configured in OIDCCookieDomain does not match the URL hostname (%s) of the URL being accessed (%s): setting \"state\" and \"session\" cookies will not work!!",
c->cookie_domain, o_uri.hostname, original_url);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
/* send off to the OpenID Connect Provider */
// TODO: maybe show intermediate/progress screen "redirecting to"
return oidc_proto_authorization_request(r, provider, login_hint,
c->redirect_uri, state, proto_state, id_token_hint, code_challenge,
auth_request_params);
}
/*
* check if the target_link_uri matches to configuration settings to prevent an open redirect
*/
static int oidc_target_link_uri_matches_configuration(request_rec *r,
oidc_cfg *cfg, const char *target_link_uri) {
apr_uri_t o_uri;
apr_uri_parse(r->pool, target_link_uri, &o_uri);
if (o_uri.hostname == NULL) {
oidc_error(r,
"could not parse the \"target_link_uri\" (%s) in to a valid URL: aborting.",
target_link_uri);
return FALSE;
}
apr_uri_t r_uri;
apr_uri_parse(r->pool, cfg->redirect_uri, &r_uri);
if (cfg->cookie_domain == NULL) {
/* cookie_domain set: see if the target_link_uri matches the redirect_uri host (because the session cookie will be set host-wide) */
if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
char *p = strstr(o_uri.hostname, r_uri.hostname);
if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
oidc_error(r,
"the URL hostname (%s) of the configured OIDCRedirectURI does not match the URL hostname of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
r_uri.hostname, o_uri.hostname);
return FALSE;
}
}
} else {
/* cookie_domain set: see if the target_link_uri is within the cookie_domain */
char *p = strstr(o_uri.hostname, cfg->cookie_domain);
if ((p == NULL) || (apr_strnatcmp(cfg->cookie_domain, p) != 0)) {
oidc_error(r,
"the domain (%s) configured in OIDCCookieDomain does not match the URL hostname (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.hostname, target_link_uri);
return FALSE;
}
}
/* see if the cookie_path setting matches the target_link_uri path */
char *cookie_path = oidc_cfg_dir_cookie_path(r);
if (cookie_path != NULL) {
char *p = (o_uri.path != NULL) ? strstr(o_uri.path, cookie_path) : NULL;
if ((p == NULL) || (p != o_uri.path)) {
oidc_error(r,
"the path (%s) configured in OIDCCookiePath does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.path, target_link_uri);
return FALSE;
} else if (strlen(o_uri.path) > strlen(cookie_path)) {
int n = strlen(cookie_path);
if (cookie_path[n - 1] == '/')
n--;
if (o_uri.path[n] != '/') {
oidc_error(r,
"the path (%s) configured in OIDCCookiePath does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.path, target_link_uri);
return FALSE;
}
}
}
return TRUE;
}
/*
* handle a response from an IDP discovery page and/or handle 3rd-party initiated SSO
*/
static int oidc_handle_discovery_response(request_rec *r, oidc_cfg *c) {
/* variables to hold the values returned in the response */
char *issuer = NULL, *target_link_uri = NULL, *login_hint = NULL,
*auth_request_params = NULL, *csrf_cookie, *csrf_query = NULL,
*user = NULL;
oidc_provider_t *provider = NULL;
oidc_util_get_request_parameter(r, OIDC_DISC_OP_PARAM, &issuer);
oidc_util_get_request_parameter(r, OIDC_DISC_USER_PARAM, &user);
oidc_util_get_request_parameter(r, OIDC_DISC_RT_PARAM, &target_link_uri);
oidc_util_get_request_parameter(r, OIDC_DISC_LH_PARAM, &login_hint);
oidc_util_get_request_parameter(r, OIDC_DISC_AR_PARAM,
&auth_request_params);
oidc_util_get_request_parameter(r, OIDC_CSRF_NAME, &csrf_query);
csrf_cookie = oidc_util_get_cookie(r, OIDC_CSRF_NAME);
/* do CSRF protection if not 3rd party initiated SSO */
if (csrf_cookie) {
/* clean CSRF cookie */
oidc_util_set_cookie(r, OIDC_CSRF_NAME, "", 0);
/* compare CSRF cookie value with query parameter value */
if ((csrf_query == NULL)
|| apr_strnatcmp(csrf_query, csrf_cookie) != 0) {
oidc_warn(r,
"CSRF protection failed, no Discovery and dynamic client registration will be allowed");
csrf_cookie = NULL;
}
}
// TODO: trim issuer/accountname/domain input and do more input validation
oidc_debug(r,
"issuer=\"%s\", target_link_uri=\"%s\", login_hint=\"%s\", user=\"%s\"",
issuer, target_link_uri, login_hint, user);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"SSO to this module without specifying a \"target_link_uri\" parameter is not possible because OIDCDefaultURL is not set.",
HTTP_INTERNAL_SERVER_ERROR);
}
target_link_uri = c->default_sso_url;
}
/* do open redirect prevention */
if (oidc_target_link_uri_matches_configuration(r, c,
target_link_uri) == FALSE) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"\"target_link_uri\" parameter does not match configuration settings, aborting to prevent an open redirect.",
HTTP_UNAUTHORIZED);
}
/* find out if the user entered an account name or selected an OP manually */
if (user != NULL) {
if (login_hint == NULL)
login_hint = apr_pstrdup(r->pool, user);
/* normalize the user identifier */
if (strstr(user, "https://") != user)
user = apr_psprintf(r->pool, "https://%s", user);
/* got an user identifier as input, perform OP discovery with that */
if (oidc_proto_url_based_discovery(r, c, user, &issuer) == FALSE) {
/* something did not work out, show a user facing error */
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"Could not resolve the provided user identifier to an OpenID Connect provider; check your syntax.",
HTTP_NOT_FOUND);
}
/* issuer is set now, so let's continue as planned */
} else if (strstr(issuer, "@") != NULL) {
if (login_hint == NULL) {
login_hint = apr_pstrdup(r->pool, issuer);
//char *p = strstr(issuer, "@");
//*p = '\0';
}
/* got an account name as input, perform OP discovery with that */
if (oidc_proto_account_based_discovery(r, c, issuer, &issuer) == FALSE) {
/* something did not work out, show a user facing error */
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"Could not resolve the provided account name to an OpenID Connect provider; check your syntax.",
HTTP_NOT_FOUND);
}
/* issuer is set now, so let's continue as planned */
}
/* strip trailing '/' */
int n = strlen(issuer);
if (issuer[n - 1] == '/')
issuer[n - 1] = '\0';
/* try and get metadata from the metadata directories for the selected OP */
if ((oidc_metadata_get(r, c, issuer, &provider, csrf_cookie != NULL) == TRUE)
&& (provider != NULL)) {
/* now we've got a selected OP, send the user there to authenticate */
return oidc_authenticate_user(r, c, provider, target_link_uri,
login_hint, NULL, NULL, auth_request_params);
}
/* something went wrong */
return oidc_util_html_send_error(r, c->error_template, "Invalid Request",
"Could not find valid provider metadata for the selected OpenID Connect provider; contact the administrator",
HTTP_NOT_FOUND);
}
static apr_uint32_t oidc_transparent_pixel[17] = { 0x474e5089, 0x0a1a0a0d,
0x0d000000, 0x52444849, 0x01000000, 0x01000000, 0x00000408, 0x0c1cb500,
0x00000002, 0x4144490b, 0x639c7854, 0x0000cffa, 0x02010702, 0x71311c9a,
0x00000000, 0x444e4549, 0x826042ae };
static apr_byte_t oidc_is_front_channel_logout(const char *logout_param_value) {
return ((logout_param_value != NULL)
&& ((apr_strnatcmp(logout_param_value,
OIDC_GET_STYLE_LOGOUT_PARAM_VALUE) == 0)
|| (apr_strnatcmp(logout_param_value,
OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0)));
}
/*
* handle a local logout
*/
static int oidc_handle_logout_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *url) {
oidc_debug(r, "enter (url=%s)", url);
/* if there's no remote_user then there's no (stored) session to kill */
if (session->remote_user != NULL) {
/* remove session state (cq. cache entry and cookie) */
oidc_session_kill(r, session);
}
/* see if this is the OP calling us */
if (oidc_is_front_channel_logout(url)) {
/* set recommended cache control headers */
apr_table_add(r->err_headers_out, "Cache-Control",
"no-cache, no-store");
apr_table_add(r->err_headers_out, "Pragma", "no-cache");
apr_table_add(r->err_headers_out, "P3P", "CAO PSA OUR");
apr_table_add(r->err_headers_out, "Expires", "0");
apr_table_add(r->err_headers_out, "X-Frame-Options", "DENY");
/* see if this is PF-PA style logout in which case we return a transparent pixel */
const char *accept = apr_table_get(r->headers_in, "Accept");
if ((apr_strnatcmp(url, OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0)
|| ((accept) && strstr(accept, "image/png"))) {
return oidc_util_http_send(r,
(const char *) &oidc_transparent_pixel,
sizeof(oidc_transparent_pixel), "image/png", DONE);
}
/* standard HTTP based logout: should be called in an iframe from the OP */
return oidc_util_html_send(r, "Logged Out", NULL, NULL,
"<p>Logged Out</p>", DONE);
}
/* see if we don't need to go somewhere special after killing the session locally */
if (url == NULL)
return oidc_util_html_send(r, "Logged Out", NULL, NULL,
"<p>Logged Out</p>", DONE);
/* send the user to the specified where-to-go-after-logout URL */
apr_table_add(r->headers_out, "Location", url);
return HTTP_MOVED_TEMPORARILY;
}
/*
* perform (single) logout
*/
static int oidc_handle_logout(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
/* pickup the command or URL where the user wants to go after logout */
char *url = NULL;
oidc_util_get_request_parameter(r, "logout", &url);
oidc_debug(r, "enter (url=%s)", url);
if (oidc_is_front_channel_logout(url)) {
return oidc_handle_logout_request(r, c, session, url);
}
if ((url == NULL) || (apr_strnatcmp(url, "") == 0)) {
url = c->default_slo_url;
} else {
/* do input validation on the logout parameter value */
const char *error_description = NULL;
apr_uri_t uri;
if (apr_uri_parse(r->pool, url, &uri) != APR_SUCCESS) {
const char *error_description = apr_psprintf(r->pool,
"Logout URL malformed: %s", url);
oidc_error(r, "%s", error_description);
return oidc_util_html_send_error(r, c->error_template,
"Malformed URL", error_description,
HTTP_INTERNAL_SERVER_ERROR);
}
if ((strstr(r->hostname, uri.hostname) == NULL)
|| (strstr(uri.hostname, r->hostname) == NULL)) {
error_description =
apr_psprintf(r->pool,
"logout value \"%s\" does not match the hostname of the current request \"%s\"",
apr_uri_unparse(r->pool, &uri, 0), r->hostname);
oidc_error(r, "%s", error_description);
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request", error_description,
HTTP_INTERNAL_SERVER_ERROR);
}
/* validate the URL to prevent HTTP header splitting */
if (((strstr(url, "\n") != NULL) || strstr(url, "\r") != NULL)) {
error_description =
apr_psprintf(r->pool,
"logout value \"%s\" contains illegal \"\n\" or \"\r\" character(s)",
url);
oidc_error(r, "%s", error_description);
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request", error_description,
HTTP_INTERNAL_SERVER_ERROR);
}
}
const char *end_session_endpoint = NULL;
oidc_session_get(r, session, OIDC_LOGOUT_ENDPOINT_SESSION_KEY,
&end_session_endpoint);
if (end_session_endpoint != NULL) {
const char *id_token_hint = NULL;
oidc_session_get(r, session, OIDC_IDTOKEN_SESSION_KEY, &id_token_hint);
char *logout_request = apr_pstrdup(r->pool, end_session_endpoint);
if (id_token_hint != NULL) {
logout_request = apr_psprintf(r->pool, "%s%sid_token_hint=%s",
logout_request,
strchr(logout_request, '?') != NULL ? "&" : "?",
oidc_util_escape_string(r, id_token_hint));
}
if (url != NULL) {
logout_request = apr_psprintf(r->pool,
"%s%spost_logout_redirect_uri=%s", logout_request,
strchr(logout_request, '?') != NULL ? "&" : "?",
oidc_util_escape_string(r, url));
}
url = logout_request;
}
return oidc_handle_logout_request(r, c, session, url);
}
/*
* handle request for JWKs
*/
int oidc_handle_jwks(request_rec *r, oidc_cfg *c) {
/* pickup requested JWKs type */
// char *jwks_type = NULL;
// oidc_util_get_request_parameter(r, "jwks", &jwks_type);
char *jwks = apr_pstrdup(r->pool, "{ \"keys\" : [");
apr_hash_index_t *hi = NULL;
apr_byte_t first = TRUE;
oidc_jose_error_t err;
if (c->public_keys != NULL) {
/* loop over the RSA public keys */
for (hi = apr_hash_first(r->pool, c->public_keys); hi; hi =
apr_hash_next(hi)) {
const char *s_kid = NULL;
oidc_jwk_t *jwk = NULL;
char *s_json = NULL;
apr_hash_this(hi, (const void**) &s_kid, NULL, (void**) &jwk);
if (oidc_jwk_to_json(r->pool, jwk, &s_json, &err) == TRUE) {
jwks = apr_psprintf(r->pool, "%s%s %s ", jwks, first ? "" : ",",
s_json);
first = FALSE;
} else {
oidc_error(r,
"could not convert RSA JWK to JSON using oidc_jwk_to_json: %s",
oidc_jose_e2s(r->pool, err));
}
}
}
// TODO: send stuff if first == FALSE?
jwks = apr_psprintf(r->pool, "%s ] }", jwks);
return oidc_util_http_send(r, jwks, strlen(jwks), "application/json", DONE);
}
static int oidc_handle_session_management_iframe_op(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *check_session_iframe) {
oidc_debug(r, "enter");
apr_table_add(r->headers_out, "Location", check_session_iframe);
return HTTP_MOVED_TEMPORARILY;
}
static int oidc_handle_session_management_iframe_rp(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *client_id,
const char *check_session_iframe) {
oidc_debug(r, "enter");
const char *java_script =
" <script type=\"text/javascript\">\n"
" var targetOrigin = '%s';\n"
" var message = '%s' + ' ' + '%s';\n"
" var timerID;\n"
"\n"
" function checkSession() {\n"
" console.log('checkSession: posting ' + message + ' to ' + targetOrigin);\n"
" var win = window.parent.document.getElementById('%s').contentWindow;\n"
" win.postMessage( message, targetOrigin);\n"
" }\n"
"\n"
" function setTimer() {\n"
" checkSession();\n"
" timerID = setInterval('checkSession()', %s);\n"
" }\n"
"\n"
" function receiveMessage(e) {\n"
" console.log('receiveMessage: ' + e.data + ' from ' + e.origin);\n"
" if (e.origin !== targetOrigin ) {\n"
" console.log('receiveMessage: cross-site scripting attack?');\n"
" return;\n"
" }\n"
" if (e.data != 'unchanged') {\n"
" clearInterval(timerID);\n"
" if (e.data == 'changed') {\n"
" window.location.href = '%s?session=check';\n"
" } else {\n"
" window.location.href = '%s?session=logout';\n"
" }\n"
" }\n"
" }\n"
"\n"
" window.addEventListener('message', receiveMessage, false);\n"
"\n"
" </script>\n";
/* determine the origin for the check_session_iframe endpoint */
char *origin = apr_pstrdup(r->pool, check_session_iframe);
apr_uri_t uri;
apr_uri_parse(r->pool, check_session_iframe, &uri);
char *p = strstr(origin, uri.path);
*p = '\0';
/* the element identifier for the OP iframe */
const char *op_iframe_id = "openidc-op";
/* restore the OP session_state from the session */
const char *session_state = NULL;
oidc_session_get(r, session, OIDC_SESSION_STATE_SESSION_KEY,
&session_state);
if (session_state == NULL) {
oidc_warn(r,
"no session_state found in the session; the OP does probably not support session management!?");
return DONE;
}
char *s_poll_interval = NULL;
oidc_util_get_request_parameter(r, "poll", &s_poll_interval);
if (s_poll_interval == NULL)
s_poll_interval = "3000";
java_script = apr_psprintf(r->pool, java_script, origin, client_id,
session_state, op_iframe_id, s_poll_interval, c->redirect_uri,
c->redirect_uri);
return oidc_util_html_send(r, NULL, java_script, "setTimer", NULL, DONE);
}
/*
* handle session management request
*/
static int oidc_handle_session_management(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *cmd = NULL;
const char *id_token_hint = NULL, *client_id = NULL, *check_session_iframe =
NULL;
oidc_provider_t *provider = NULL;
/* get the command passed to the session management handler */
oidc_util_get_request_parameter(r, "session", &cmd);
if (cmd == NULL) {
oidc_error(r, "session management handler called with no command");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if this is a local logout during session management */
if (apr_strnatcmp("logout", cmd) == 0) {
oidc_debug(r,
"[session=logout] calling oidc_handle_logout_request because of session mgmt local logout call.");
return oidc_handle_logout_request(r, c, session, c->default_slo_url);
}
/* see if this is a request for the OP iframe */
if (apr_strnatcmp("iframe_op", cmd) == 0) {
oidc_session_get(r, session, OIDC_CHECK_IFRAME_SESSION_KEY,
&check_session_iframe);
if (check_session_iframe != NULL) {
return oidc_handle_session_management_iframe_op(r, c, session,
check_session_iframe);
}
return HTTP_NOT_FOUND;
}
/* see if this is a request for the RP iframe */
if (apr_strnatcmp("iframe_rp", cmd) == 0) {
oidc_session_get(r, session, OIDC_CLIENTID_SESSION_KEY, &client_id);
oidc_session_get(r, session, OIDC_CHECK_IFRAME_SESSION_KEY,
&check_session_iframe);
if ((client_id != NULL) && (check_session_iframe != NULL)) {
return oidc_handle_session_management_iframe_rp(r, c, session,
client_id, check_session_iframe);
}
oidc_debug(r,
"iframe_rp command issued but no client (%s) and/or no check_session_iframe (%s) set",
client_id, check_session_iframe);
return HTTP_NOT_FOUND;
}
/* see if this is a request check the login state with the OP */
if (apr_strnatcmp("check", cmd) == 0) {
oidc_session_get(r, session, OIDC_IDTOKEN_SESSION_KEY, &id_token_hint);
oidc_get_provider_from_session(r, c, session, &provider);
if ((session->remote_user != NULL) && (provider != NULL)) {
return oidc_authenticate_user(r, c, provider,
apr_psprintf(r->pool, "%s?session=iframe_rp",
c->redirect_uri), NULL, id_token_hint, "none", NULL);
}
oidc_debug(r,
"[session=check] calling oidc_handle_logout_request because no session found.");
return oidc_session_redirect_parent_window_to_logout(r, c);
}
/* handle failure in fallthrough */
oidc_error(r, "unknown command: %s", cmd);
return HTTP_INTERNAL_SERVER_ERROR;
}
/*
* handle refresh token request
*/
static int oidc_handle_refresh_token_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *return_to = NULL;
char *r_access_token = NULL;
char *error_code = NULL;
/* get the command passed to the session management handler */
oidc_util_get_request_parameter(r, "refresh", &return_to);
oidc_util_get_request_parameter(r, "access_token", &r_access_token);
/* check the input parameters */
if (return_to == NULL) {
oidc_error(r,
"refresh token request handler called with no URL to return to");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (r_access_token == NULL) {
oidc_error(r,
"refresh token request handler called with no access_token parameter");
error_code = "no_access_token";
goto end;
}
char *s_access_token = NULL;
oidc_session_get(r, session, OIDC_ACCESSTOKEN_SESSION_KEY,
(const char **) &s_access_token);
if (s_access_token == NULL) {
oidc_error(r,
"no existing access_token found in the session, nothing to refresh");
error_code = "no_access_token_exists";
goto end;
}
/* compare the access_token parameter used for XSRF protection */
if (apr_strnatcmp(s_access_token, r_access_token) != 0) {
oidc_error(r,
"access_token passed in refresh request does not match the one stored in the session");
error_code = "no_access_token_match";
goto end;
}
/* get a handle to the provider configuration */
oidc_provider_t *provider = NULL;
if (oidc_get_provider_from_session(r, c, session, &provider) == FALSE) {
error_code = "session_corruption";
goto end;
}
/* execute the actual refresh grant */
if (oidc_refresh_access_token(r, c, session, provider, NULL) == FALSE) {
oidc_error(r, "access_token could not be refreshed");
error_code = "refresh_failed";
goto end;
}
/* pass the tokens to the application and save the session, possibly updating the expiry */
if (oidc_session_pass_tokens_and_save(r, c, session, TRUE) == FALSE) {
error_code = "session_corruption";
goto end;
}
end:
/* pass optional error message to the return URL */
if (error_code != NULL)
return_to = apr_psprintf(r->pool, "%s%serror_code=%s", return_to,
strchr(return_to, '?') ? "&" : "?",
oidc_util_escape_string(r, error_code));
/* add the redirect location header */
apr_table_add(r->headers_out, "Location", return_to);
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle request object by reference request
*/
static int oidc_handle_request_uri(request_rec *r, oidc_cfg *c) {
char *request_ref = NULL;
oidc_util_get_request_parameter(r, "request_uri", &request_ref);
if (request_ref == NULL) {
oidc_error(r, "no \"request_uri\" parameter found");
return HTTP_BAD_REQUEST;
}
const char *jwt = NULL;
c->cache->get(r, OIDC_CACHE_SECTION_REQUEST_URI, request_ref, &jwt);
if (jwt == NULL) {
oidc_error(r, "no cached JWT found for request_uri reference: %s",
request_ref);
return HTTP_NOT_FOUND;
}
c->cache->set(r, OIDC_CACHE_SECTION_REQUEST_URI, request_ref, NULL, 0);
return oidc_util_http_send(r, jwt, strlen(jwt), " application/jwt", DONE);
}
/*
* handle a request to invalidate a cached access token introspection result
*/
static int oidc_handle_remove_at_cache(request_rec *r, oidc_cfg *c) {
char *access_token = NULL;
oidc_util_get_request_parameter(r, "remove_at_cache", &access_token);
const char *cache_entry = NULL;
c->cache->get(r, OIDC_CACHE_SECTION_ACCESS_TOKEN, access_token, &cache_entry);
if (cache_entry == NULL) {
oidc_error(r, "no cached access token found for value: %s", access_token);
return HTTP_NOT_FOUND;
}
c->cache->set(r, OIDC_CACHE_SECTION_ACCESS_TOKEN, access_token, NULL, 0);
return DONE;
}
/*
* handle all requests to the redirect_uri
*/
int oidc_handle_redirect_uri_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
if (oidc_proto_is_redirect_authorization_response(r, c)) {
/* this is an authorization response from the OP using the Basic Client profile or a Hybrid flow*/
return oidc_handle_redirect_authorization_response(r, c, session);
} else if (oidc_proto_is_post_authorization_response(r, c)) {
/* this is an authorization response using the fragment(+POST) response_mode with the Implicit Client profile */
return oidc_handle_post_authorization_response(r, c, session);
} else if (oidc_is_discovery_response(r, c)) {
/* this is response from the OP discovery page */
return oidc_handle_discovery_response(r, c);
} else if (oidc_util_request_has_parameter(r, "logout")) {
/* handle logout */
return oidc_handle_logout(r, c, session);
} else if (oidc_util_request_has_parameter(r, "jwks")) {
/* handle JWKs request */
return oidc_handle_jwks(r, c);
} else if (oidc_util_request_has_parameter(r, "session")) {
/* handle session management request */
return oidc_handle_session_management(r, c, session);
} else if (oidc_util_request_has_parameter(r, "refresh")) {
/* handle refresh token request */
return oidc_handle_refresh_token_request(r, c, session);
} else if (oidc_util_request_has_parameter(r, "request_uri")) {
/* handle request object by reference request */
return oidc_handle_request_uri(r, c);
} else if (oidc_util_request_has_parameter(r, "remove_at_cache")) {
/* handle request to invalidate access token cache */
return oidc_handle_remove_at_cache(r, c);
} else if ((r->args == NULL) || (apr_strnatcmp(r->args, "") == 0)) {
/* this is a "bare" request to the redirect URI, indicating implicit flow using the fragment response_mode */
return oidc_proto_javascript_implicit(r, c);
}
/* this is not an authorization response or logout request */
/* check for "error" response */
if (oidc_util_request_has_parameter(r, "error")) {
// char *error = NULL, *descr = NULL;
// oidc_util_get_request_parameter(r, "error", &error);
// oidc_util_get_request_parameter(r, "error_description", &descr);
//
// /* send user facing error to browser */
// return oidc_util_html_send_error(r, error, descr, DONE);
oidc_handle_redirect_authorization_response(r, c, session);
}
oidc_error(r,
"The OpenID Connect callback URL received an invalid request: %s; returning HTTP_INTERNAL_SERVER_ERROR",
r->args);
/* something went wrong */
return oidc_util_html_send_error(r, c->error_template, "Invalid Request",
apr_psprintf(r->pool,
"The OpenID Connect callback URL received an invalid request"),
HTTP_INTERNAL_SERVER_ERROR);
}
/*
* main routine: handle OpenID Connect authentication
*/
static int oidc_check_userid_openidc(request_rec *r, oidc_cfg *c) {
if (c->redirect_uri == NULL) {
oidc_error(r,
"configuration error: the authentication type is set to \"openid-connect\" but OIDCRedirectURI has not been set");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* check if this is a sub-request or an initial request */
if (ap_is_initial_req(r)) {
int rc = OK;
/* load the session from the request state; this will be a new "empty" session if no state exists */
oidc_session_t *session = NULL;
oidc_session_load(r, &session);
/* see if the initial request is to the redirect URI; this handles potential logout too */
if (oidc_util_request_matches_url(r, c->redirect_uri)) {
/* handle request to the redirect_uri */
rc = oidc_handle_redirect_uri_request(r, c, session);
/* free resources allocated for the session */
oidc_session_free(r, session);
return rc;
/* initial request to non-redirect URI, check if we have an existing session */
} else if (session->remote_user != NULL) {
/* set the user in the main request for further (incl. sub-request) processing */
r->user = (char *) session->remote_user;
/* this is initial request and we already have a session */
rc = oidc_handle_existing_session(r, c, session);
/* free resources allocated for the session */
oidc_session_free(r, session);
/* strip any cookies that we need to */
oidc_strip_cookies(r);
return rc;
}
/* free resources allocated for the session */
oidc_session_free(r, session);
/*
* else: initial request, we have no session and it is not an authorization or
* discovery response: just hit the default flow for unauthenticated users
*/
} else {
/* not an initial request, try to recycle what we've already established in the main request */
if (r->main != NULL)
r->user = r->main->user;
else if (r->prev != NULL)
r->user = r->prev->user;
if (r->user != NULL) {
/* this is a sub-request and we have a session (headers will have been scrubbed and set already) */
oidc_debug(r,
"recycling user '%s' from initial request for sub-request",
r->user);
/*
* apparently request state can get lost in sub-requests, so let's see
* if we need to restore id_token and/or claims from the session cache
*/
const char *s_id_token = oidc_request_state_get(r,
OIDC_IDTOKEN_CLAIMS_SESSION_KEY);
if (s_id_token == NULL) {
oidc_session_t *session = NULL;
oidc_session_load(r, &session);
oidc_copy_tokens_to_request_state(r, session, NULL, NULL);
/* free resources allocated for the session */
oidc_session_free(r, session);
}
/* strip any cookies that we need to */
oidc_strip_cookies(r);
return OK;
}
/*
* else: not initial request, but we could not find a session, so:
* just hit the default flow for unauthenticated users
*/
}
return oidc_handle_unauthenticated_user(r, c);
}
/*
* generic Apache authentication hook for this module: dispatches to OpenID Connect or OAuth 2.0 specific routines
*/
int oidc_check_user_id(request_rec *r) {
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
/* log some stuff about the incoming HTTP request */
oidc_debug(r, "incoming request: \"%s?%s\", ap_is_initial_req(r)=%d",
r->parsed_uri.path, r->args, ap_is_initial_req(r));
/* see if any authentication has been defined at all */
if (ap_auth_type(r) == NULL)
return DECLINED;
/* see if we've configured OpenID Connect user authentication for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r), "openid-connect")
== 0)
return oidc_check_userid_openidc(r, c);
/* see if we've configured OAuth 2.0 access control for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r), "oauth20") == 0)
return oidc_oauth_check_userid(r, c);
/* this is not for us but for some other handler */
return DECLINED;
}
/*
* get the claims and id_token from request state
*/
static void oidc_authz_get_claims_and_idtoken(request_rec *r, json_t **claims,
json_t **id_token) {
const char *s_claims = oidc_request_state_get(r, OIDC_CLAIMS_SESSION_KEY);
const char *s_id_token = oidc_request_state_get(r,
OIDC_IDTOKEN_CLAIMS_SESSION_KEY);
json_error_t json_error;
if (s_claims != NULL) {
*claims = json_loads(s_claims, 0, &json_error);
if (*claims == NULL) {
oidc_error(r, "could not restore claims from request state: %s",
json_error.text);
}
}
if (s_id_token != NULL) {
*id_token = json_loads(s_id_token, 0, &json_error);
if (*id_token == NULL) {
oidc_error(r, "could not restore id_token from request state: %s",
json_error.text);
}
}
}
#if MODULE_MAGIC_NUMBER_MAJOR >= 20100714
/*
* generic Apache >=2.4 authorization hook for this module
* handles both OpenID Connect or OAuth 2.0 in the same way, based on the claims stored in the session
*/
authz_status oidc_authz_checker(request_rec *r, const char *require_args, const void *parsed_require_args) {
/* check for anonymous access and PASS mode */
if (r->user != NULL && strlen(r->user) == 0) {
r->user = NULL;
if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS) return AUTHZ_GRANTED;
}
/* get the set of claims from the request state (they've been set in the authentication part earlier */
json_t *claims = NULL, *id_token = NULL;
oidc_authz_get_claims_and_idtoken(r, &claims, &id_token);
/* merge id_token claims (e.g. "iss") in to claims json object */
if (claims)
oidc_util_json_merge(id_token, claims);
/* dispatch to the >=2.4 specific authz routine */
authz_status rc = oidc_authz_worker24(r, claims ? claims : id_token, require_args);
/* cleanup */
if (claims) json_decref(claims);
if (id_token) json_decref(id_token);
if ((rc == AUTHZ_DENIED) && ap_auth_type(r)
&& (apr_strnatcasecmp((const char *) ap_auth_type(r), "oauth20")
== 0))
oidc_oauth_return_www_authenticate(r, "insufficient_scope", "Different scope(s) or other claims required");
return rc;
}
#else
/*
* generic Apache <2.4 authorization hook for this module
* handles both OpenID Connect and OAuth 2.0 in the same way, based on the claims stored in the request context
*/
int oidc_auth_checker(request_rec *r) {
/* check for anonymous access and PASS mode */
if (r->user != NULL && strlen(r->user) == 0) {
r->user = NULL;
if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS)
return OK;
}
/* get the set of claims from the request state (they've been set in the authentication part earlier */
json_t *claims = NULL, *id_token = NULL;
oidc_authz_get_claims_and_idtoken(r, &claims, &id_token);
/* get the Require statements */
const apr_array_header_t * const reqs_arr = ap_requires(r);
/* see if we have any */
const require_line * const reqs =
reqs_arr ? (require_line *) reqs_arr->elts : NULL;
if (!reqs_arr) {
oidc_debug(r,
"no require statements found, so declining to perform authorization.");
return DECLINED;
}
/* merge id_token claims (e.g. "iss") in to claims json object */
if (claims)
oidc_util_json_merge(id_token, claims);
/* dispatch to the <2.4 specific authz routine */
int rc = oidc_authz_worker(r, claims ? claims : id_token, reqs,
reqs_arr->nelts);
/* cleanup */
if (claims)
json_decref(claims);
if (id_token)
json_decref(id_token);
if ((rc == HTTP_UNAUTHORIZED) && ap_auth_type(r)
&& (apr_strnatcasecmp((const char *) ap_auth_type(r), "oauth20")
== 0))
oidc_oauth_return_www_authenticate(r, "insufficient_scope",
"Different scope(s) or other claims required");
return rc;
}
#endif
extern const command_rec oidc_config_cmds[];
module AP_MODULE_DECLARE_DATA auth_openidc_module = {
STANDARD20_MODULE_STUFF,
oidc_create_dir_config,
oidc_merge_dir_config,
oidc_create_server_config,
oidc_merge_server_config,
oidc_config_cmds,
oidc_register_hooks
};
| ./CrossVul/dataset_final_sorted/CWE-287/c/bad_3184_2 |
crossvul-cpp_data_bad_2556_0 | /*
* jabberd - Jabber Open Source Server
* Copyright (c) 2002 Jeremie Miller, Thomas Muldowney,
* Ryan Eatmon, Robert Norris
*
* 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, MA02111-1307USA
*/
#include "c2s.h"
#include <stringprep.h>
#include <string.h>
#include <ctype.h>
static sig_atomic_t c2s_shutdown = 0;
sig_atomic_t c2s_lost_router = 0;
static sig_atomic_t c2s_logrotate = 0;
static sig_atomic_t c2s_sighup = 0;
static void _c2s_signal(int signum)
{
c2s_shutdown = 1;
c2s_lost_router = 0;
}
static void _c2s_signal_hup(int signum)
{
c2s_logrotate = 1;
c2s_sighup = 1;
}
static void _c2s_signal_usr1(int signum)
{
set_debug_flag(0);
}
static void _c2s_signal_usr2(int signum)
{
set_debug_flag(1);
}
/** store the process id */
static void _c2s_pidfile(c2s_t c2s) {
const char *pidfile;
FILE *f;
pid_t pid;
pidfile = config_get_one(c2s->config, "pidfile", 0);
if(pidfile == NULL)
return;
pid = getpid();
if((f = fopen(pidfile, "w+")) == NULL) {
log_write(c2s->log, LOG_ERR, "couldn't open %s for writing: %s", pidfile, strerror(errno));
return;
}
if(fprintf(f, "%d", pid) < 0) {
log_write(c2s->log, LOG_ERR, "couldn't write to %s: %s", pidfile, strerror(errno));
fclose(f);
return;
}
fclose(f);
log_write(c2s->log, LOG_INFO, "process id is %d, written to %s", pid, pidfile);
}
/** pull values out of the config file */
static void _c2s_config_expand(c2s_t c2s)
{
const char *str, *ip, *mask;
char *req_domain, *to_address, *to_port;
config_elem_t elem;
int i;
stream_redirect_t sr;
set_debug_log_from_config(c2s->config);
c2s->id = config_get_one(c2s->config, "id", 0);
if(c2s->id == NULL)
c2s->id = "c2s";
c2s->router_ip = config_get_one(c2s->config, "router.ip", 0);
if(c2s->router_ip == NULL)
c2s->router_ip = "127.0.0.1";
c2s->router_port = j_atoi(config_get_one(c2s->config, "router.port", 0), 5347);
c2s->router_user = config_get_one(c2s->config, "router.user", 0);
if(c2s->router_user == NULL)
c2s->router_user = "jabberd";
c2s->router_pass = config_get_one(c2s->config, "router.pass", 0);
if(c2s->router_pass == NULL)
c2s->router_pass = "secret";
c2s->router_pemfile = config_get_one(c2s->config, "router.pemfile", 0);
c2s->router_cachain = config_get_one(c2s->config, "router.cachain", 0);
c2s->router_private_key_password = config_get_one(c2s->config, "router.private_key_password", 0);
c2s->router_ciphers = config_get_one(c2s->config, "router.ciphers", 0);
c2s->retry_init = j_atoi(config_get_one(c2s->config, "router.retry.init", 0), 3);
c2s->retry_lost = j_atoi(config_get_one(c2s->config, "router.retry.lost", 0), 3);
if((c2s->retry_sleep = j_atoi(config_get_one(c2s->config, "router.retry.sleep", 0), 2)) < 1)
c2s->retry_sleep = 1;
c2s->log_type = log_STDOUT;
if(config_get(c2s->config, "log") != NULL) {
if((str = config_get_attr(c2s->config, "log", 0, "type")) != NULL) {
if(strcmp(str, "file") == 0)
c2s->log_type = log_FILE;
else if(strcmp(str, "syslog") == 0)
c2s->log_type = log_SYSLOG;
}
}
if(c2s->log_type == log_SYSLOG) {
c2s->log_facility = config_get_one(c2s->config, "log.facility", 0);
c2s->log_ident = config_get_one(c2s->config, "log.ident", 0);
if(c2s->log_ident == NULL)
c2s->log_ident = "jabberd/c2s";
} else if(c2s->log_type == log_FILE)
c2s->log_ident = config_get_one(c2s->config, "log.file", 0);
c2s->packet_stats = config_get_one(c2s->config, "stats.packet", 0);
c2s->local_ip = config_get_one(c2s->config, "local.ip", 0);
if(c2s->local_ip == NULL)
c2s->local_ip = "0.0.0.0";
c2s->local_port = j_atoi(config_get_one(c2s->config, "local.port", 0), 0);
c2s->local_pemfile = config_get_one(c2s->config, "local.pemfile", 0);
c2s->local_cachain = config_get_one(c2s->config, "local.cachain", 0);
c2s->local_private_key_password = config_get_one(c2s->config, "local.private_key_password", 0);
c2s->local_verify_mode = j_atoi(config_get_one(c2s->config, "local.verify-mode", 0), 0);
c2s->local_ciphers = config_get_one(c2s->config, "local.ciphers", 0);
c2s->local_ssl_port = j_atoi(config_get_one(c2s->config, "local.ssl-port", 0), 0);
c2s->http_forward = config_get_one(c2s->config, "local.httpforward", 0);
c2s->websocket = (config_get(c2s->config, "io.websocket") != NULL);
c2s->io_max_fds = j_atoi(config_get_one(c2s->config, "io.max_fds", 0), 1024);
c2s->compression = (config_get(c2s->config, "io.compression") != NULL);
c2s->io_check_interval = j_atoi(config_get_one(c2s->config, "io.check.interval", 0), 0);
c2s->io_check_idle = j_atoi(config_get_one(c2s->config, "io.check.idle", 0), 0);
c2s->io_check_keepalive = j_atoi(config_get_one(c2s->config, "io.check.keepalive", 0), 0);
c2s->pbx_pipe = config_get_one(c2s->config, "pbx.pipe", 0);
elem = config_get(c2s->config, "stream_redirect.redirect");
if(elem != NULL)
{
for(i = 0; i < elem->nvalues; i++)
{
sr = (stream_redirect_t) pmalloco(xhash_pool(c2s->stream_redirects), sizeof(struct stream_redirect_st));
if(!sr) {
log_write(c2s->log, LOG_ERR, "cannot allocate memory for new stream redirection record, aborting");
exit(1);
}
req_domain = j_attr((const char **) elem->attrs[i], "requested_domain");
to_address = j_attr((const char **) elem->attrs[i], "to_address");
to_port = j_attr((const char **) elem->attrs[i], "to_port");
if(req_domain == NULL || to_address == NULL || to_port == NULL) {
log_write(c2s->log, LOG_ERR, "Error reading a stream_redirect.redirect element from file, skipping");
continue;
}
// Note that to_address should be RFC 3986 compliant
sr->to_address = to_address;
sr->to_port = to_port;
xhash_put(c2s->stream_redirects, pstrdup(xhash_pool(c2s->stream_redirects), req_domain), sr);
}
}
c2s->ar_module_name = config_get_one(c2s->config, "authreg.module", 0);
if(config_get(c2s->config, "authreg.mechanisms.traditional.plain") != NULL) c2s->ar_mechanisms |= AR_MECH_TRAD_PLAIN;
if(config_get(c2s->config, "authreg.mechanisms.traditional.digest") != NULL) c2s->ar_mechanisms |= AR_MECH_TRAD_DIGEST;
if(config_get(c2s->config, "authreg.mechanisms.traditional.cram-md5") != NULL) c2s->ar_mechanisms |= AR_MECH_TRAD_CRAMMD5;
if(config_get(c2s->config, "authreg.ssl-mechanisms.traditional.plain") != NULL) c2s->ar_ssl_mechanisms |= AR_MECH_TRAD_PLAIN;
if(config_get(c2s->config, "authreg.ssl-mechanisms.traditional.digest") != NULL) c2s->ar_ssl_mechanisms |= AR_MECH_TRAD_DIGEST;
if(config_get(c2s->config, "authreg.ssl-mechanisms.traditional.cram-md5") != NULL) c2s->ar_ssl_mechanisms |= AR_MECH_TRAD_CRAMMD5;
elem = config_get(c2s->config, "io.limits.bytes");
if(elem != NULL)
{
c2s->byte_rate_total = j_atoi(elem->values[0], 0);
if(c2s->byte_rate_total != 0)
{
c2s->byte_rate_seconds = j_atoi(j_attr((const char **) elem->attrs[0], "seconds"), 1);
c2s->byte_rate_wait = j_atoi(j_attr((const char **) elem->attrs[0], "throttle"), 5);
}
}
elem = config_get(c2s->config, "io.limits.stanzas");
if(elem != NULL)
{
c2s->stanza_rate_total = j_atoi(elem->values[0], 0);
if(c2s->stanza_rate_total != 0)
{
c2s->stanza_rate_seconds = j_atoi(j_attr((const char **) elem->attrs[0], "seconds"), 1);
c2s->stanza_rate_wait = j_atoi(j_attr((const char **) elem->attrs[0], "throttle"), 5);
}
}
elem = config_get(c2s->config, "io.limits.connects");
if(elem != NULL)
{
c2s->conn_rate_total = j_atoi(elem->values[0], 0);
if(c2s->conn_rate_total != 0)
{
c2s->conn_rate_seconds = j_atoi(j_attr((const char **) elem->attrs[0], "seconds"), 5);
c2s->conn_rate_wait = j_atoi(j_attr((const char **) elem->attrs[0], "throttle"), 5);
}
}
c2s->stanza_size_limit = j_atoi(config_get_one(c2s->config, "io.limits.stanzasize", 0), 0);
/* tweak timed checks with rate times */
if(c2s->io_check_interval == 0) {
if(c2s->byte_rate_total != 0)
c2s->io_check_interval = c2s->byte_rate_wait;
if(c2s->stanza_rate_total != 0 && c2s->io_check_interval > c2s->stanza_rate_wait)
c2s->io_check_interval = c2s->stanza_rate_wait;
}
str = config_get_one(c2s->config, "io.access.order", 0);
if(str == NULL || strcmp(str, "deny,allow") != 0)
c2s->access = access_new(0);
else
c2s->access = access_new(1);
elem = config_get(c2s->config, "io.access.allow");
if(elem != NULL)
{
for(i = 0; i < elem->nvalues; i++)
{
ip = j_attr((const char **) elem->attrs[i], "ip");
mask = j_attr((const char **) elem->attrs[i], "mask");
if(ip == NULL)
continue;
if(mask == NULL)
mask = "255.255.255.255";
access_allow(c2s->access, ip, mask);
}
}
elem = config_get(c2s->config, "io.access.deny");
if(elem != NULL)
{
for(i = 0; i < elem->nvalues; i++)
{
ip = j_attr((const char **) elem->attrs[i], "ip");
mask = j_attr((const char **) elem->attrs[i], "mask");
if(ip == NULL)
continue;
if(mask == NULL)
mask = "255.255.255.255";
access_deny(c2s->access, ip, mask);
}
}
}
static void _c2s_hosts_expand(c2s_t c2s)
{
char *realm;
config_elem_t elem;
char id[1024];
int i;
elem = config_get(c2s->config, "local.id");
if(!elem) {
log_write(c2s->log, LOG_NOTICE, "no local.id configured - skipping local domains configuration");
return;
}
for(i = 0; i < elem->nvalues; i++) {
host_t host = (host_t) pmalloco(xhash_pool(c2s->hosts), sizeof(struct host_st));
if(!host) {
log_write(c2s->log, LOG_ERR, "cannot allocate memory for new host, aborting");
exit(1);
}
realm = j_attr((const char **) elem->attrs[i], "realm");
/* stringprep ids (domain names) so that they are in canonical form */
strncpy(id, elem->values[i], 1024);
id[1023] = '\0';
if (stringprep_nameprep(id, 1024) != 0) {
log_write(c2s->log, LOG_ERR, "cannot stringprep id %s, aborting", id);
exit(1);
}
host->realm = (realm != NULL) ? realm : pstrdup(xhash_pool(c2s->hosts), id);
host->host_pemfile = j_attr((const char **) elem->attrs[i], "pemfile");
host->host_cachain = j_attr((const char **) elem->attrs[i], "cachain");
host->host_verify_mode = j_atoi(j_attr((const char **) elem->attrs[i], "verify-mode"), 0);
host->host_private_key_password = j_attr((const char **) elem->attrs[i], "private-key-password");
host->host_ciphers = j_attr((const char **) elem->attrs[i], "ciphers");
#ifdef HAVE_SSL
if(host->host_pemfile != NULL) {
if(c2s->sx_ssl == NULL) {
c2s->sx_ssl = sx_env_plugin(c2s->sx_env, sx_ssl_init, host->realm, host->host_pemfile, host->host_cachain, host->host_verify_mode, host->host_private_key_password, host->host_ciphers);
if(c2s->sx_ssl == NULL) {
log_write(c2s->log, LOG_ERR, "failed to load %s SSL pemfile", host->realm);
host->host_pemfile = NULL;
}
} else {
if(sx_ssl_server_addcert(c2s->sx_ssl, host->realm, host->host_pemfile, host->host_cachain, host->host_verify_mode, host->host_private_key_password, host->host_ciphers) != 0) {
log_write(c2s->log, LOG_ERR, "failed to load %s SSL pemfile", host->realm);
host->host_pemfile = NULL;
}
}
}
#endif
host->host_require_starttls = (j_attr((const char **) elem->attrs[i], "require-starttls") != NULL);
host->ar_module_name = j_attr((const char **) elem->attrs[i], "authreg-module");
if(host->ar_module_name) {
if((host->ar = authreg_init(c2s, host->ar_module_name)) == NULL) {
log_write(c2s->log, LOG_NOTICE, "failed to load %s authreg module - using default", host->realm);
host->ar = c2s->ar;
}
} else
host->ar = c2s->ar;
host->ar_register_enable = (j_attr((const char **) elem->attrs[i], "register-enable") != NULL);
host->ar_register_oob = j_attr((const char **) elem->attrs[i], "register-oob");
if(host->ar_register_enable || host->ar_register_oob) {
host->ar_register_instructions = j_attr((const char **) elem->attrs[i], "instructions");
if(host->ar_register_instructions == NULL) {
if(host->ar_register_oob)
host->ar_register_instructions = "Only web based registration is possible with this server.";
else
host->ar_register_instructions = "Enter a username and password to register with this server.";
}
} else
host->ar_register_password = (j_attr((const char **) elem->attrs[i], "password-change") != NULL);
/* check for empty <id/> CDATA - XXX this "1" is VERY config.c dependant !!! */
if(! strcmp(id, "1")) {
/* remove the realm even if set */
host->realm = NULL;
/* skip if vHost already configured */
if(! c2s->vhost)
c2s->vhost = host;
/* add meaningful log "id" */
strcpy(id, "default vHost");
} else {
/* insert into vHosts xhash */
xhash_put(c2s->hosts, pstrdup(xhash_pool(c2s->hosts), id), host);
}
log_write(c2s->log, LOG_NOTICE, "[%s] configured; realm=%s, authreg=%s, registration %s, using PEM:%s",
id, (host->realm != NULL ? host->realm : "no realm set"),
(host->ar_module_name ? host->ar_module_name : c2s->ar_module_name),
(host->ar_register_enable ? "enabled" : "disabled"),
(host->host_pemfile ? host->host_pemfile : "Default"));
}
}
static int _c2s_router_connect(c2s_t c2s) {
log_write(c2s->log, LOG_NOTICE, "attempting connection to router at %s, port=%d", c2s->router_ip, c2s->router_port);
c2s->fd = mio_connect(c2s->mio, c2s->router_port, c2s->router_ip, NULL, c2s_router_mio_callback, (void *) c2s);
if(c2s->fd == NULL) {
if(errno == ECONNREFUSED)
c2s_lost_router = 1;
log_write(c2s->log, LOG_NOTICE, "connection attempt to router failed: %s (%d)", MIO_STRERROR(MIO_ERROR), MIO_ERROR);
return 1;
}
c2s->router = sx_new(c2s->sx_env, c2s->fd->fd, c2s_router_sx_callback, (void *) c2s);
sx_client_init(c2s->router, 0, NULL, NULL, NULL, "1.0");
return 0;
}
static int _c2s_sx_sasl_callback(int cb, void *arg, void **res, sx_t s, void *cbarg) {
c2s_t c2s = (c2s_t) cbarg;
const char *my_realm, *mech;
sx_sasl_creds_t creds;
static char buf[3072];
char mechbuf[256];
struct jid_st jid;
jid_static_buf jid_buf;
int i, r;
sess_t sess;
char skey[44];
host_t host;
/* init static jid */
jid_static(&jid,&jid_buf);
/* retrieve our session */
assert(s != NULL);
sprintf(skey, "%d", s->tag);
/*
* Retrieve the session, note that depending on the operation,
* session may be null.
*/
sess = xhash_get(c2s->sessions, skey);
switch(cb) {
case sx_sasl_cb_GET_REALM:
if(s->req_to == NULL) /* this shouldn't happen */
my_realm = "";
else {
/* get host for request */
host = xhash_get(c2s->hosts, s->req_to);
if(host == NULL) {
log_write(c2s->log, LOG_ERR, "SASL callback for non-existing host: %s", s->req_to);
*res = (void *)NULL;
return sx_sasl_ret_FAIL;
}
my_realm = host->realm;
if(my_realm == NULL)
my_realm = s->req_to;
}
strncpy(buf, my_realm, 256);
*res = (void *)buf;
log_debug(ZONE, "sx sasl callback: get realm: realm is '%s'", buf);
return sx_sasl_ret_OK;
break;
case sx_sasl_cb_GET_PASS:
assert(sess != NULL);
creds = (sx_sasl_creds_t) arg;
log_debug(ZONE, "sx sasl callback: get pass (authnid=%s, realm=%s)", creds->authnid, creds->realm);
if(sess->host->ar->get_password && (sess->host->ar->get_password)(
sess->host->ar, sess, (char *)creds->authnid, (creds->realm != NULL) ? (char *)creds->realm: "", buf) == 0) {
*res = buf;
return sx_sasl_ret_OK;
}
return sx_sasl_ret_FAIL;
case sx_sasl_cb_CHECK_PASS:
assert(sess != NULL);
creds = (sx_sasl_creds_t) arg;
log_debug(ZONE, "sx sasl callback: check pass (authnid=%s, realm=%s)", creds->authnid, creds->realm);
if(sess->host->ar->check_password != NULL) {
if ((sess->host->ar->check_password)(
sess->host->ar, sess, (char *)creds->authnid, (creds->realm != NULL) ? (char *)creds->realm : "", (char *)creds->pass) == 0)
return sx_sasl_ret_OK;
else
return sx_sasl_ret_FAIL;
}
if(sess->host->ar->get_password != NULL) {
if ((sess->host->ar->get_password)(sess->host->ar, sess, (char *)creds->authnid, (creds->realm != NULL) ? (char *)creds->realm : "", buf) != 0)
return sx_sasl_ret_FAIL;
if (strcmp(creds->pass, buf)==0)
return sx_sasl_ret_OK;
}
return sx_sasl_ret_FAIL;
break;
case sx_sasl_cb_CHECK_AUTHZID:
assert(sess != NULL);
creds = (sx_sasl_creds_t) arg;
/* we need authzid to validate */
if(creds->authzid == NULL || creds->authzid[0] == '\0')
return sx_sasl_ret_FAIL;
/* authzid must be a valid jid */
if(jid_reset(&jid, creds->authzid, -1) == NULL)
return sx_sasl_ret_FAIL;
/* and have domain == stream to addr */
if(!s->req_to || (strcmp(jid.domain, s->req_to) != 0))
return sx_sasl_ret_FAIL;
/* and have no resource */
if(jid.resource[0] != '\0')
return sx_sasl_ret_FAIL;
/* and user has right to authorize as */
if (sess->host->ar->user_authz_allowed) {
if (sess->host->ar->user_authz_allowed(sess->host->ar, sess, (char *)creds->authnid, (char *)creds->realm, (char *)creds->authzid))
return sx_sasl_ret_OK;
} else {
if (strcmp(creds->authnid, jid.node) == 0 &&
(sess->host->ar->user_exists)(sess->host->ar, sess, jid.node, jid.domain))
return sx_sasl_ret_OK;
}
return sx_sasl_ret_FAIL;
case sx_sasl_cb_GEN_AUTHZID:
/* generate a jid for SASL ANONYMOUS */
jid_reset(&jid, s->req_to, -1);
/* make node a random string */
jid_random_part(&jid, jid_NODE);
strcpy(buf, jid.node);
*res = (void *)buf;
return sx_sasl_ret_OK;
break;
case sx_sasl_cb_CHECK_MECH:
mech = (char *)arg;
strncpy(mechbuf, mech, sizeof(mechbuf));
mechbuf[sizeof(mechbuf)-1]='\0';
for(i = 0; mechbuf[i]; i++) mechbuf[i] = tolower(mechbuf[i]);
/* get host for request */
host = xhash_get(c2s->hosts, s->req_to);
if(host == NULL) {
log_write(c2s->log, LOG_WARNING, "SASL callback for non-existing host: %s", s->req_to);
return sx_sasl_ret_FAIL;
}
/* Determine if our configuration will let us use this mechanism.
* We support different mechanisms for both SSL and normal use */
if (strcmp(mechbuf, "digest-md5") == 0) {
/* digest-md5 requires that our authreg support get_password */
if (host->ar->get_password == NULL)
return sx_sasl_ret_FAIL;
} else if (strcmp(mechbuf, "plain") == 0) {
/* plain requires either get_password or check_password */
if (host->ar->get_password == NULL && host->ar->check_password == NULL)
return sx_sasl_ret_FAIL;
}
/* Using SSF is potentially dangerous, as SASL can also set the
* SSF of the connection. However, SASL shouldn't do so until after
* we've finished mechanism establishment
*/
if (s->ssf>0) {
r = snprintf(buf, sizeof(buf), "authreg.ssl-mechanisms.sasl.%s",mechbuf);
if (r < -1 || r > sizeof(buf))
return sx_sasl_ret_FAIL;
if(config_get(c2s->config,buf) != NULL)
return sx_sasl_ret_OK;
}
r = snprintf(buf, sizeof(buf), "authreg.mechanisms.sasl.%s",mechbuf);
if (r < -1 || r > sizeof(buf))
return sx_sasl_ret_FAIL;
/* Work out if our configuration will let us use this mechanism */
if(config_get(c2s->config,buf) != NULL)
return sx_sasl_ret_OK;
else
return sx_sasl_ret_FAIL;
default:
break;
}
return sx_sasl_ret_FAIL;
}
static void _c2s_time_checks(c2s_t c2s) {
sess_t sess;
time_t now;
union xhashv xhv;
now = time(NULL);
if(xhash_iter_first(c2s->sessions))
do {
xhv.sess_val = &sess;
xhash_iter_get(c2s->sessions, NULL, NULL, xhv.val);
if(!sess->s) continue;
if(c2s->io_check_idle > 0 && now > sess->last_activity + c2s->io_check_idle) {
log_write(c2s->log, LOG_NOTICE, "[%d] [%s, port=%d] timed out", sess->fd->fd, sess->ip, sess->port);
sx_error(sess->s, stream_err_HOST_GONE, "connection timed out");
sx_close(sess->s);
continue;
}
if(c2s->io_check_keepalive > 0 && now > sess->last_activity + c2s->io_check_keepalive && sess->s->state >= state_STREAM) {
log_debug(ZONE, "sending keepalive for %d", sess->fd->fd);
sx_raw_write(sess->s, " ", 1);
}
if(sess->rate != NULL && sess->rate->bad != 0 && rate_check(sess->rate) != 0) {
/* read the pending bytes when rate limit is no longer in effect */
log_debug(ZONE, "reading throttled %d", sess->fd->fd);
sess->s->want_read = 1;
sx_can_read(sess->s);
}
} while(xhash_iter_next(c2s->sessions));
}
static void _c2s_ar_free(const char *module, int modulelen, void *val, void *arg) {
authreg_t ar = (authreg_t) val;
authreg_free(ar);
}
JABBER_MAIN("jabberd2c2s", "Jabber 2 C2S", "Jabber Open Source Server: Client to Server", "jabberd2router\0")
{
c2s_t c2s;
char *config_file;
int optchar;
int mio_timeout;
sess_t sess;
bres_t res;
union xhashv xhv;
time_t check_time = 0;
const char *cli_id = 0;
#ifdef HAVE_UMASK
umask((mode_t) 0027);
#endif
srand(time(NULL));
#ifdef HAVE_WINSOCK2_H
/* get winsock running */
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
/* !!! tell user that we couldn't find a usable winsock dll */
return 0;
}
}
#endif
jabber_signal(SIGINT, _c2s_signal);
jabber_signal(SIGTERM, _c2s_signal);
#ifdef SIGHUP
jabber_signal(SIGHUP, _c2s_signal_hup);
#endif
#ifdef SIGPIPE
jabber_signal(SIGPIPE, SIG_IGN);
#endif
jabber_signal(SIGUSR1, _c2s_signal_usr1);
jabber_signal(SIGUSR2, _c2s_signal_usr2);
c2s = (c2s_t) calloc(1, sizeof(struct c2s_st));
/* load our config */
c2s->config = config_new();
config_file = CONFIG_DIR "/c2s.xml";
/* cmdline parsing */
while((optchar = getopt(argc, argv, "Dc:hi:?")) >= 0)
{
switch(optchar)
{
case 'c':
config_file = optarg;
break;
case 'D':
#ifdef DEBUG
set_debug_flag(1);
#else
printf("WARN: Debugging not enabled. Ignoring -D.\n");
#endif
break;
case 'i':
cli_id = optarg;
break;
case 'h': case '?': default:
fputs(
"c2s - jabberd client-to-server connector (" VERSION ")\n"
"Usage: c2s <options>\n"
"Options are:\n"
" -c <config> config file to use [default: " CONFIG_DIR "/c2s.xml]\n"
" -i id Override <id> config element\n"
#ifdef DEBUG
" -D Show debug output\n"
#endif
,
stdout);
config_free(c2s->config);
free(c2s);
return 1;
}
}
if(config_load_with_id(c2s->config, config_file, cli_id) != 0)
{
fputs("c2s: couldn't load config, aborting\n", stderr);
config_free(c2s->config);
free(c2s);
return 2;
}
c2s->stream_redirects = xhash_new(11);
_c2s_config_expand(c2s);
c2s->log = log_new(c2s->log_type, c2s->log_ident, c2s->log_facility);
c2s->ar_modules = xhash_new(5);
if(c2s->ar_module_name == NULL) {
log_write(c2s->log, LOG_NOTICE, "no default authreg module specified in config file");
}
else if((c2s->ar = authreg_init(c2s, c2s->ar_module_name)) == NULL) {
access_free(c2s->access);
config_free(c2s->config);
log_free(c2s->log);
free(c2s);
exit(1);
}
log_write(c2s->log, LOG_NOTICE, "starting up");
_c2s_pidfile(c2s);
c2s->sessions = xhash_new(1023);
c2s->conn_rates = xhash_new(101);
c2s->dead = jqueue_new();
c2s->dead_sess = jqueue_new();
c2s->sx_env = sx_env_new();
#ifdef HAVE_SSL
/* get the ssl context up and running */
if(c2s->local_pemfile != NULL) {
c2s->sx_ssl = sx_env_plugin(c2s->sx_env, sx_ssl_init, NULL, c2s->local_pemfile, c2s->local_cachain, c2s->local_verify_mode, c2s->local_private_key_password, c2s->local_ciphers);
if(c2s->sx_ssl == NULL) {
log_write(c2s->log, LOG_ERR, "failed to load local SSL pemfile, SSL will not be available to clients");
c2s->local_pemfile = NULL;
}
}
/* try and get something online, so at least we can encrypt to the router */
if(c2s->sx_ssl == NULL && c2s->router_pemfile != NULL) {
c2s->sx_ssl = sx_env_plugin(c2s->sx_env, sx_ssl_init, NULL, c2s->router_pemfile, c2s->router_cachain, NULL, c2s->router_private_key_password, c2s->router_ciphers);
if(c2s->sx_ssl == NULL) {
log_write(c2s->log, LOG_ERR, "failed to load router SSL pemfile, channel to router will not be SSL encrypted");
c2s->router_pemfile = NULL;
}
}
#endif
#ifdef USE_WEBSOCKET
/* possibly wrap in websocket */
if(c2s->websocket) {
sx_env_plugin(c2s->sx_env, sx_websocket_init, c2s->http_forward);
}
#else
if(c2s->websocket) {
log_write(c2s->log, LOG_ERR, "websocket support not built-in - not enabling");
}
if(c2s->http_forward) {
log_write(c2s->log, LOG_ERR, "httpforward available only with websocket support built-in");
}
#endif
#ifdef HAVE_LIBZ
/* get compression up and running */
if(c2s->compression) {
sx_env_plugin(c2s->sx_env, sx_compress_init);
}
#endif
/* get stanza ack up */
sx_env_plugin(c2s->sx_env, sx_ack_init);
/* and user IP address plugin */
sx_env_plugin(c2s->sx_env, address_init);
/* get sasl online */
c2s->sx_sasl = sx_env_plugin(c2s->sx_env, sx_sasl_init, "xmpp", _c2s_sx_sasl_callback, (void *) c2s);
if(c2s->sx_sasl == NULL) {
log_write(c2s->log, LOG_ERR, "failed to initialise SASL context, aborting");
exit(1);
}
/* get bind up */
sx_env_plugin(c2s->sx_env, bind_init, c2s);
c2s->mio = mio_new(c2s->io_max_fds);
if(c2s->mio == NULL) {
log_write(c2s->log, LOG_ERR, "failed to create MIO, aborting");
exit(1);
}
/* hosts mapping */
c2s->hosts = xhash_new(1021);
_c2s_hosts_expand(c2s);
c2s->sm_avail = xhash_new(1021);
c2s->retry_left = c2s->retry_init;
_c2s_router_connect(c2s);
mio_timeout = ((c2s->io_check_interval != 0 && c2s->io_check_interval < 5) ?
c2s->io_check_interval : 5);
while(!c2s_shutdown) {
mio_run(c2s->mio, mio_timeout);
if(c2s_logrotate) {
set_debug_log_from_config(c2s->config);
log_write(c2s->log, LOG_NOTICE, "reopening log ...");
log_free(c2s->log);
c2s->log = log_new(c2s->log_type, c2s->log_ident, c2s->log_facility);
log_write(c2s->log, LOG_NOTICE, "log started");
c2s_logrotate = 0;
}
if(c2s_sighup) {
log_write(c2s->log, LOG_NOTICE, "reloading some configuration items ...");
config_t conf;
conf = config_new();
if (conf && config_load(conf, config_file) == 0) {
xhash_free(c2s->stream_redirects);
c2s->stream_redirects = xhash_new(11);
char *req_domain, *to_address, *to_port;
config_elem_t elem;
int i;
stream_redirect_t sr;
elem = config_get(conf, "stream_redirect.redirect");
if(elem != NULL)
{
for(i = 0; i < elem->nvalues; i++)
{
sr = (stream_redirect_t) pmalloco(xhash_pool(c2s->stream_redirects), sizeof(struct stream_redirect_st));
if(!sr) {
log_write(c2s->log, LOG_ERR, "cannot allocate memory for new stream redirection record, aborting");
exit(1);
}
req_domain = j_attr((const char **) elem->attrs[i], "requested_domain");
to_address = j_attr((const char **) elem->attrs[i], "to_address");
to_port = j_attr((const char **) elem->attrs[i], "to_port");
if(req_domain == NULL || to_address == NULL || to_port == NULL) {
log_write(c2s->log, LOG_ERR, "Error reading a stream_redirect.redirect element from file, skipping");
continue;
}
// Note that to_address should be RFC 3986 compliant
sr->to_address = to_address;
sr->to_port = to_port;
xhash_put(c2s->stream_redirects, pstrdup(xhash_pool(c2s->stream_redirects), req_domain), sr);
}
}
config_free(conf);
} else {
log_write(c2s->log, LOG_WARNING, "couldn't reload config (%s)", config_file);
if (conf) config_free(conf);
}
c2s_sighup = 0;
}
if(c2s_lost_router) {
if(c2s->retry_left < 0) {
log_write(c2s->log, LOG_NOTICE, "attempting reconnect");
sleep(c2s->retry_sleep);
c2s_lost_router = 0;
if (c2s->router) sx_free(c2s->router);
_c2s_router_connect(c2s);
}
else if(c2s->retry_left == 0) {
c2s_shutdown = 1;
}
else {
log_write(c2s->log, LOG_NOTICE, "attempting reconnect (%d left)", c2s->retry_left);
c2s->retry_left--;
sleep(c2s->retry_sleep);
c2s_lost_router = 0;
if (c2s->router) sx_free(c2s->router);
_c2s_router_connect(c2s);
}
}
/* cleanup dead sess (before sx_t as sess->result uses sx_t nad cache) */
while(jqueue_size(c2s->dead_sess) > 0) {
sess = (sess_t) jqueue_pull(c2s->dead_sess);
/* free sess data */
if(sess->ip != NULL) free((void*)sess->ip);
if(sess->smcomp != NULL) free((void*)sess->smcomp);
if(sess->result != NULL) nad_free(sess->result);
if(sess->resources != NULL)
for(res = sess->resources; res != NULL;) {
bres_t tmp = res->next;
jid_free(res->jid);
free(res);
res = tmp;
}
if(sess->rate != NULL) rate_free(sess->rate);
if(sess->stanza_rate != NULL) rate_free(sess->stanza_rate);
free(sess);
}
/* cleanup dead sx_ts */
while(jqueue_size(c2s->dead) > 0)
sx_free((sx_t) jqueue_pull(c2s->dead));
/* time checks */
if(c2s->io_check_interval > 0 && time(NULL) >= c2s->next_check) {
log_debug(ZONE, "running time checks");
_c2s_time_checks(c2s);
c2s->next_check = time(NULL) + c2s->io_check_interval;
log_debug(ZONE, "next time check at %d", c2s->next_check);
}
if(time(NULL) > check_time + 60) {
#ifdef POOL_DEBUG
pool_stat(1);
#endif
if(c2s->packet_stats != NULL) {
int fd = open(c2s->packet_stats, O_TRUNC | O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP);
if (fd >= 0) {
char buf[100];
int len = snprintf(buf, 100, "%lld\n", c2s->packet_count);
if (write(fd, buf, len) != len) {
close(fd);
fd = -1;
} else close(fd);
}
if (fd < 0) {
log_write(c2s->log, LOG_ERR, "failed to write packet statistics to: %s", c2s->packet_stats);
c2s_shutdown = 1;
}
}
check_time = time(NULL);
}
}
log_write(c2s->log, LOG_NOTICE, "shutting down");
if(xhash_iter_first(c2s->sessions))
do {
xhv.sess_val = &sess;
xhash_iter_get(c2s->sessions, NULL, NULL, xhv.val);
if(sess->active && sess->s)
sx_close(sess->s);
} while(xhash_iter_next(c2s->sessions));
/* cleanup dead sess */
while(jqueue_size(c2s->dead_sess) > 0) {
sess = (sess_t) jqueue_pull(c2s->dead_sess);
/* free sess data */
if(sess->ip != NULL) free((void*)sess->ip);
if(sess->result != NULL) nad_free(sess->result);
if(sess->resources != NULL)
for(res = sess->resources; res != NULL;) {
bres_t tmp = res->next;
jid_free(res->jid);
free(res);
res = tmp;
}
free(sess);
}
while(jqueue_size(c2s->dead) > 0)
sx_free((sx_t) jqueue_pull(c2s->dead));
if (c2s->fd != NULL) mio_close(c2s->mio, c2s->fd);
sx_free(c2s->router);
sx_env_free(c2s->sx_env);
mio_free(c2s->mio);
xhash_free(c2s->sessions);
xhash_walk(c2s->ar_modules, _c2s_ar_free, NULL);
xhash_free(c2s->ar_modules);
xhash_free(c2s->conn_rates);
xhash_free(c2s->stream_redirects);
xhash_free(c2s->sm_avail);
xhash_free(c2s->hosts);
jqueue_free(c2s->dead);
jqueue_free(c2s->dead_sess);
access_free(c2s->access);
log_free(c2s->log);
config_free(c2s->config);
free(c2s);
#ifdef POOL_DEBUG
pool_stat(1);
#endif
#ifdef HAVE_WINSOCK2_H
WSACleanup();
#endif
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/bad_2556_0 |
crossvul-cpp_data_bad_3281_1 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* COPYRIGHT (C) 2006,2007
* THE REGENTS OF THE UNIVERSITY OF MICHIGAN
* ALL RIGHTS RESERVED
*
* Permission is granted to use, copy, create derivative works
* and redistribute this software and such derivative works
* for any purpose, so long as the name of The University of
* Michigan is not used in any advertising or publicity
* pertaining to the use of distribution of this software
* without specific, written prior authorization. If the
* above copyright notice or any other identification of the
* University of Michigan is included in any copy of any
* portion of this software, then the disclaimer below must
* also be included.
*
* THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION
* FROM THE UNIVERSITY OF MICHIGAN AS TO ITS FITNESS FOR ANY
* PURPOSE, AND WITHOUT WARRANTY BY THE UNIVERSITY OF
* MICHIGAN OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
* REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE LIABLE
* FOR ANY DAMAGES, INCLUDING SPECIAL, INDIRECT, INCIDENTAL, OR
* CONSEQUENTIAL DAMAGES, WITH RESPECT TO ANY CLAIM ARISING
* OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, EVEN
* IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
*/
#include <k5-int.h>
#include "pkinit.h"
#include "krb5/certauth_plugin.h"
/* Aliases used by the built-in certauth modules */
struct certauth_req_opts {
krb5_kdcpreauth_callbacks cb;
krb5_kdcpreauth_rock rock;
pkinit_kdc_context plgctx;
pkinit_kdc_req_context reqctx;
};
typedef struct certauth_module_handle_st {
struct krb5_certauth_vtable_st vt;
krb5_certauth_moddata moddata;
} *certauth_handle;
struct krb5_kdcpreauth_moddata_st {
pkinit_kdc_context *realm_contexts;
certauth_handle *certauth_modules;
};
static krb5_error_code
pkinit_init_kdc_req_context(krb5_context, pkinit_kdc_req_context *blob);
static void
pkinit_fini_kdc_req_context(krb5_context context, void *blob);
static void
pkinit_server_plugin_fini_realm(krb5_context context,
pkinit_kdc_context plgctx);
static void
pkinit_server_plugin_fini(krb5_context context,
krb5_kdcpreauth_moddata moddata);
static pkinit_kdc_context
pkinit_find_realm_context(krb5_context context,
krb5_kdcpreauth_moddata moddata,
krb5_principal princ);
static void
free_realm_contexts(krb5_context context, pkinit_kdc_context *realm_contexts)
{
int i;
if (realm_contexts == NULL)
return;
for (i = 0; realm_contexts[i] != NULL; i++)
pkinit_server_plugin_fini_realm(context, realm_contexts[i]);
pkiDebug("%s: freeing context at %p\n", __FUNCTION__, realm_contexts);
free(realm_contexts);
}
static void
free_certauth_handles(krb5_context context, certauth_handle *list)
{
int i;
if (list == NULL)
return;
for (i = 0; list[i] != NULL; i++) {
if (list[i]->vt.fini != NULL)
list[i]->vt.fini(context, list[i]->moddata);
free(list[i]);
}
free(list);
}
static krb5_error_code
pkinit_create_edata(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
pkinit_plg_opts *opts,
krb5_error_code err_code,
krb5_pa_data ***e_data_out)
{
krb5_error_code retval = KRB5KRB_ERR_GENERIC;
pkiDebug("pkinit_create_edata: creating edata for error %d (%s)\n",
err_code, error_message(err_code));
switch(err_code) {
case KRB5KDC_ERR_CANT_VERIFY_CERTIFICATE:
retval = pkinit_create_td_trusted_certifiers(context,
plg_cryptoctx, req_cryptoctx, id_cryptoctx, e_data_out);
break;
case KRB5KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED:
retval = pkinit_create_td_dh_parameters(context, plg_cryptoctx,
req_cryptoctx, id_cryptoctx, opts, e_data_out);
break;
case KRB5KDC_ERR_INVALID_CERTIFICATE:
case KRB5KDC_ERR_REVOKED_CERTIFICATE:
retval = pkinit_create_td_invalid_certificate(context,
plg_cryptoctx, req_cryptoctx, id_cryptoctx, e_data_out);
break;
default:
pkiDebug("no edata needed for error %d (%s)\n",
err_code, error_message(err_code));
retval = 0;
goto cleanup;
}
cleanup:
return retval;
}
static void
pkinit_server_get_edata(krb5_context context,
krb5_kdc_req *request,
krb5_kdcpreauth_callbacks cb,
krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata,
krb5_preauthtype pa_type,
krb5_kdcpreauth_edata_respond_fn respond,
void *arg)
{
krb5_error_code retval = 0;
pkinit_kdc_context plgctx = NULL;
pkiDebug("pkinit_server_get_edata: entered!\n");
/*
* If we don't have a realm context for the given realm,
* don't tell the client that we support pkinit!
*/
plgctx = pkinit_find_realm_context(context, moddata, request->server);
if (plgctx == NULL)
retval = EINVAL;
(*respond)(arg, retval, NULL);
}
static krb5_error_code
verify_client_san(krb5_context context,
pkinit_kdc_context plgctx,
pkinit_kdc_req_context reqctx,
krb5_kdcpreauth_callbacks cb,
krb5_kdcpreauth_rock rock,
krb5_const_principal client,
int *valid_san)
{
krb5_error_code retval;
krb5_principal *princs = NULL;
krb5_principal *upns = NULL;
int i;
#ifdef DEBUG_SAN_INFO
char *client_string = NULL, *san_string;
#endif
*valid_san = 0;
retval = crypto_retrieve_cert_sans(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
&princs,
plgctx->opts->allow_upn ? &upns : NULL,
NULL);
if (retval == ENOENT) {
TRACE_PKINIT_SERVER_NO_SAN(context);
goto out;
} else if (retval) {
pkiDebug("%s: error from retrieve_certificate_sans()\n", __FUNCTION__);
retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
goto out;
}
/* XXX Verify this is consistent with client side XXX */
#if 0
retval = call_san_checking_plugins(context, plgctx, reqctx, princs,
upns, NULL, &plugin_decision, &ignore);
pkiDebug("%s: call_san_checking_plugins() returned retval %d\n",
__FUNCTION__);
if (retval) {
retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
goto cleanup;
}
pkiDebug("%s: call_san_checking_plugins() returned decision %d\n",
__FUNCTION__, plugin_decision);
if (plugin_decision != NO_DECISION) {
retval = plugin_decision;
goto out;
}
#endif
#ifdef DEBUG_SAN_INFO
krb5_unparse_name(context, client, &client_string);
#endif
pkiDebug("%s: Checking pkinit sans\n", __FUNCTION__);
for (i = 0; princs != NULL && princs[i] != NULL; i++) {
#ifdef DEBUG_SAN_INFO
krb5_unparse_name(context, princs[i], &san_string);
pkiDebug("%s: Comparing client '%s' to pkinit san value '%s'\n",
__FUNCTION__, client_string, san_string);
krb5_free_unparsed_name(context, san_string);
#endif
if (cb->match_client(context, rock, princs[i])) {
TRACE_PKINIT_SERVER_MATCHING_SAN_FOUND(context);
*valid_san = 1;
retval = 0;
goto out;
}
}
pkiDebug("%s: no pkinit san match found\n", __FUNCTION__);
/*
* XXX if cert has names but none match, should we
* be returning KRB5KDC_ERR_CLIENT_NAME_MISMATCH here?
*/
if (upns == NULL) {
pkiDebug("%s: no upn sans (or we wouldn't accept them anyway)\n",
__FUNCTION__);
retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
goto out;
}
pkiDebug("%s: Checking upn sans\n", __FUNCTION__);
for (i = 0; upns[i] != NULL; i++) {
#ifdef DEBUG_SAN_INFO
krb5_unparse_name(context, upns[i], &san_string);
pkiDebug("%s: Comparing client '%s' to upn san value '%s'\n",
__FUNCTION__, client_string, san_string);
krb5_free_unparsed_name(context, san_string);
#endif
if (cb->match_client(context, rock, upns[i])) {
TRACE_PKINIT_SERVER_MATCHING_UPN_FOUND(context);
*valid_san = 1;
retval = 0;
goto out;
}
}
pkiDebug("%s: no upn san match found\n", __FUNCTION__);
/* We found no match */
if (princs != NULL || upns != NULL) {
*valid_san = 0;
/* XXX ??? If there was one or more name in the cert, but
* none matched the client name, then return mismatch? */
retval = KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
}
retval = 0;
out:
if (princs != NULL) {
for (i = 0; princs[i] != NULL; i++)
krb5_free_principal(context, princs[i]);
free(princs);
}
if (upns != NULL) {
for (i = 0; upns[i] != NULL; i++)
krb5_free_principal(context, upns[i]);
free(upns);
}
#ifdef DEBUG_SAN_INFO
if (client_string != NULL)
krb5_free_unparsed_name(context, client_string);
#endif
pkiDebug("%s: returning retval %d, valid_san %d\n",
__FUNCTION__, retval, *valid_san);
return retval;
}
static krb5_error_code
verify_client_eku(krb5_context context,
pkinit_kdc_context plgctx,
pkinit_kdc_req_context reqctx,
int *eku_accepted)
{
krb5_error_code retval;
*eku_accepted = 0;
if (plgctx->opts->require_eku == 0) {
TRACE_PKINIT_SERVER_EKU_SKIP(context);
*eku_accepted = 1;
retval = 0;
goto out;
}
retval = crypto_check_cert_eku(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
0, /* kdc cert */
plgctx->opts->accept_secondary_eku,
eku_accepted);
if (retval) {
pkiDebug("%s: Error from crypto_check_cert_eku %d (%s)\n",
__FUNCTION__, retval, error_message(retval));
goto out;
}
out:
pkiDebug("%s: returning retval %d, eku_accepted %d\n",
__FUNCTION__, retval, *eku_accepted);
return retval;
}
/* Run the received, verified certificate through certauth modules, to verify
* that it is authorized to authenticate as client. */
static krb5_error_code
authorize_cert(krb5_context context, certauth_handle *certauth_modules,
pkinit_kdc_context plgctx, pkinit_kdc_req_context reqctx,
krb5_kdcpreauth_callbacks cb, krb5_kdcpreauth_rock rock,
krb5_principal client)
{
krb5_error_code ret;
certauth_handle h;
struct certauth_req_opts opts;
krb5_boolean accepted = FALSE;
uint8_t *cert;
size_t i, cert_len;
void *db_ent = NULL;
char **ais = NULL, **ai = NULL;
/* Re-encode the received certificate into DER, which is extra work, but
* avoids creating an X.509 library dependency in the interface. */
ret = crypto_encode_der_cert(context, reqctx->cryptoctx, &cert, &cert_len);
if (ret)
goto cleanup;
/* Set options for the builtin module. */
opts.plgctx = plgctx;
opts.reqctx = reqctx;
opts.cb = cb;
opts.rock = rock;
db_ent = cb->client_entry(context, rock);
/*
* Check the certificate against each certauth module. For the certificate
* to be authorized at least one module must return 0, and no module can an
* error code other than KRB5_PLUGIN_NO_HANDLE (pass). Add indicators from
* modules that return 0 or pass.
*/
ret = KRB5_PLUGIN_NO_HANDLE;
for (i = 0; certauth_modules != NULL && certauth_modules[i] != NULL; i++) {
h = certauth_modules[i];
TRACE_PKINIT_SERVER_CERT_AUTH(context, h->vt.name);
ret = h->vt.authorize(context, h->moddata, cert, cert_len, client,
&opts, db_ent, &ais);
if (ret == 0)
accepted = TRUE;
else if (ret != KRB5_PLUGIN_NO_HANDLE)
goto cleanup;
if (ais != NULL) {
/* Assert authentication indicators from the module. */
for (ai = ais; *ai != NULL; ai++) {
ret = cb->add_auth_indicator(context, rock, *ai);
if (ret)
goto cleanup;
}
h->vt.free_ind(context, h->moddata, ais);
ais = NULL;
}
}
ret = accepted ? 0 : KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
cleanup:
free(cert);
return ret;
}
static void
pkinit_server_verify_padata(krb5_context context,
krb5_data *req_pkt,
krb5_kdc_req * request,
krb5_enc_tkt_part * enc_tkt_reply,
krb5_pa_data * data,
krb5_kdcpreauth_callbacks cb,
krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata,
krb5_kdcpreauth_verify_respond_fn respond,
void *arg)
{
krb5_error_code retval = 0;
krb5_data authp_data = {0, 0, NULL}, krb5_authz = {0, 0, NULL};
krb5_pa_pk_as_req *reqp = NULL;
krb5_pa_pk_as_req_draft9 *reqp9 = NULL;
krb5_auth_pack *auth_pack = NULL;
krb5_auth_pack_draft9 *auth_pack9 = NULL;
pkinit_kdc_context plgctx = NULL;
pkinit_kdc_req_context reqctx = NULL;
krb5_checksum cksum = {0, 0, 0, NULL};
krb5_data *der_req = NULL;
krb5_data k5data;
int is_signed = 1;
krb5_pa_data **e_data = NULL;
krb5_kdcpreauth_modreq modreq = NULL;
char **sp;
pkiDebug("pkinit_verify_padata: entered!\n");
if (data == NULL || data->length <= 0 || data->contents == NULL) {
(*respond)(arg, EINVAL, NULL, NULL, NULL);
return;
}
if (moddata == NULL) {
(*respond)(arg, EINVAL, NULL, NULL, NULL);
return;
}
plgctx = pkinit_find_realm_context(context, moddata, request->server);
if (plgctx == NULL) {
(*respond)(arg, EINVAL, NULL, NULL, NULL);
return;
}
#ifdef DEBUG_ASN1
print_buffer_bin(data->contents, data->length, "/tmp/kdc_as_req");
#endif
/* create a per-request context */
retval = pkinit_init_kdc_req_context(context, &reqctx);
if (retval)
goto cleanup;
reqctx->pa_type = data->pa_type;
PADATA_TO_KRB5DATA(data, &k5data);
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
TRACE_PKINIT_SERVER_PADATA_VERIFY(context);
retval = k5int_decode_krb5_pa_pk_as_req(&k5data, &reqp);
if (retval) {
pkiDebug("decode_krb5_pa_pk_as_req failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin(reqp->signedAuthPack.data,
reqp->signedAuthPack.length,
"/tmp/kdc_signed_data");
#endif
retval = cms_signeddata_verify(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_CLIENT,
plgctx->opts->require_crl_checking,
(unsigned char *)
reqp->signedAuthPack.data, reqp->signedAuthPack.length,
(unsigned char **)&authp_data.data,
&authp_data.length,
(unsigned char **)&krb5_authz.data,
&krb5_authz.length, &is_signed);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
TRACE_PKINIT_SERVER_PADATA_VERIFY_OLD(context);
retval = k5int_decode_krb5_pa_pk_as_req_draft9(&k5data, &reqp9);
if (retval) {
pkiDebug("decode_krb5_pa_pk_as_req_draft9 failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin(reqp9->signedAuthPack.data,
reqp9->signedAuthPack.length,
"/tmp/kdc_signed_data_draft9");
#endif
retval = cms_signeddata_verify(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_DRAFT9,
plgctx->opts->require_crl_checking,
(unsigned char *)
reqp9->signedAuthPack.data, reqp9->signedAuthPack.length,
(unsigned char **)&authp_data.data,
&authp_data.length,
(unsigned char **)&krb5_authz.data,
&krb5_authz.length, NULL);
break;
default:
pkiDebug("unrecognized pa_type = %d\n", data->pa_type);
retval = EINVAL;
goto cleanup;
}
if (retval) {
TRACE_PKINIT_SERVER_PADATA_VERIFY_FAIL(context);
goto cleanup;
}
if (is_signed) {
retval = authorize_cert(context, moddata->certauth_modules, plgctx,
reqctx, cb, rock, request->client);
if (retval)
goto cleanup;
} else { /* !is_signed */
if (!krb5_principal_compare(context, request->client,
krb5_anonymous_principal())) {
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval,
_("Pkinit request not signed, but client "
"not anonymous."));
goto cleanup;
}
}
#ifdef DEBUG_ASN1
print_buffer_bin(authp_data.data, authp_data.length, "/tmp/kdc_auth_pack");
#endif
OCTETDATA_TO_KRB5DATA(&authp_data, &k5data);
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
retval = k5int_decode_krb5_auth_pack(&k5data, &auth_pack);
if (retval) {
pkiDebug("failed to decode krb5_auth_pack\n");
goto cleanup;
}
retval = krb5_check_clockskew(context,
auth_pack->pkAuthenticator.ctime);
if (retval)
goto cleanup;
/* check dh parameters */
if (auth_pack->clientPublicValue != NULL) {
retval = server_check_dh(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
&auth_pack->clientPublicValue->algorithm.parameters,
plgctx->opts->dh_min_bits);
if (retval) {
pkiDebug("bad dh parameters\n");
goto cleanup;
}
} else if (!is_signed) {
/*Anonymous pkinit requires DH*/
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval,
_("Anonymous pkinit without DH public "
"value not supported."));
goto cleanup;
}
der_req = cb->request_body(context, rock);
retval = krb5_c_make_checksum(context, CKSUMTYPE_NIST_SHA, NULL,
0, der_req, &cksum);
if (retval) {
pkiDebug("unable to calculate AS REQ checksum\n");
goto cleanup;
}
if (cksum.length != auth_pack->pkAuthenticator.paChecksum.length ||
k5_bcmp(cksum.contents,
auth_pack->pkAuthenticator.paChecksum.contents,
cksum.length) != 0) {
pkiDebug("failed to match the checksum\n");
#ifdef DEBUG_CKSUM
pkiDebug("calculating checksum on buf size (%d)\n",
req_pkt->length);
print_buffer(req_pkt->data, req_pkt->length);
pkiDebug("received checksum type=%d size=%d ",
auth_pack->pkAuthenticator.paChecksum.checksum_type,
auth_pack->pkAuthenticator.paChecksum.length);
print_buffer(auth_pack->pkAuthenticator.paChecksum.contents,
auth_pack->pkAuthenticator.paChecksum.length);
pkiDebug("expected checksum type=%d size=%d ",
cksum.checksum_type, cksum.length);
print_buffer(cksum.contents, cksum.length);
#endif
retval = KRB5KDC_ERR_PA_CHECKSUM_MUST_BE_INCLUDED;
goto cleanup;
}
/* check if kdcPkId present and match KDC's subjectIdentifier */
if (reqp->kdcPkId.data != NULL) {
int valid_kdcPkId = 0;
retval = pkinit_check_kdc_pkid(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
(unsigned char *)reqp->kdcPkId.data,
reqp->kdcPkId.length, &valid_kdcPkId);
if (retval)
goto cleanup;
if (!valid_kdcPkId)
pkiDebug("kdcPkId in AS_REQ does not match KDC's cert"
"RFC says to ignore and proceed\n");
}
/* remember the decoded auth_pack for verify_padata routine */
reqctx->rcv_auth_pack = auth_pack;
auth_pack = NULL;
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = k5int_decode_krb5_auth_pack_draft9(&k5data, &auth_pack9);
if (retval) {
pkiDebug("failed to decode krb5_auth_pack_draft9\n");
goto cleanup;
}
if (auth_pack9->clientPublicValue != NULL) {
retval = server_check_dh(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx,
&auth_pack9->clientPublicValue->algorithm.parameters,
plgctx->opts->dh_min_bits);
if (retval) {
pkiDebug("bad dh parameters\n");
goto cleanup;
}
}
/* remember the decoded auth_pack for verify_padata routine */
reqctx->rcv_auth_pack9 = auth_pack9;
auth_pack9 = NULL;
break;
}
if (is_signed && plgctx->auth_indicators != NULL) {
/* Assert configured authentication indicators. */
for (sp = plgctx->auth_indicators; *sp != NULL; sp++) {
retval = cb->add_auth_indicator(context, rock, *sp);
if (retval)
goto cleanup;
}
}
/* remember to set the PREAUTH flag in the reply */
enc_tkt_reply->flags |= TKT_FLG_PRE_AUTH;
modreq = (krb5_kdcpreauth_modreq)reqctx;
reqctx = NULL;
cleanup:
if (retval && data->pa_type == KRB5_PADATA_PK_AS_REQ) {
pkiDebug("pkinit_verify_padata failed: creating e-data\n");
if (pkinit_create_edata(context, plgctx->cryptoctx, reqctx->cryptoctx,
plgctx->idctx, plgctx->opts, retval, &e_data))
pkiDebug("pkinit_create_edata failed\n");
}
switch ((int)data->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
free_krb5_pa_pk_as_req(&reqp);
free(cksum.contents);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
free_krb5_pa_pk_as_req_draft9(&reqp9);
}
free(authp_data.data);
free(krb5_authz.data);
if (reqctx != NULL)
pkinit_fini_kdc_req_context(context, reqctx);
free_krb5_auth_pack(&auth_pack);
free_krb5_auth_pack_draft9(context, &auth_pack9);
(*respond)(arg, retval, modreq, e_data, NULL);
}
static krb5_error_code
return_pkinit_kx(krb5_context context, krb5_kdc_req *request,
krb5_kdc_rep *reply, krb5_keyblock *encrypting_key,
krb5_pa_data **out_padata)
{
krb5_error_code ret = 0;
krb5_keyblock *session = reply->ticket->enc_part2->session;
krb5_keyblock *new_session = NULL;
krb5_pa_data *pa = NULL;
krb5_enc_data enc;
krb5_data *scratch = NULL;
*out_padata = NULL;
enc.ciphertext.data = NULL;
if (!krb5_principal_compare(context, request->client,
krb5_anonymous_principal()))
return 0;
/*
* The KDC contribution key needs to be a fresh key of an enctype supported
* by the client and server. The existing session key meets these
* requirements so we use it.
*/
ret = krb5_c_fx_cf2_simple(context, session, "PKINIT",
encrypting_key, "KEYEXCHANGE",
&new_session);
if (ret)
goto cleanup;
ret = encode_krb5_encryption_key( session, &scratch);
if (ret)
goto cleanup;
ret = krb5_encrypt_helper(context, encrypting_key,
KRB5_KEYUSAGE_PA_PKINIT_KX, scratch, &enc);
if (ret)
goto cleanup;
memset(scratch->data, 0, scratch->length);
krb5_free_data(context, scratch);
scratch = NULL;
ret = encode_krb5_enc_data(&enc, &scratch);
if (ret)
goto cleanup;
pa = malloc(sizeof(krb5_pa_data));
if (pa == NULL) {
ret = ENOMEM;
goto cleanup;
}
pa->pa_type = KRB5_PADATA_PKINIT_KX;
pa->length = scratch->length;
pa->contents = (krb5_octet *) scratch->data;
*out_padata = pa;
scratch->data = NULL;
memset(session->contents, 0, session->length);
krb5_free_keyblock_contents(context, session);
*session = *new_session;
new_session->contents = NULL;
cleanup:
krb5_free_data_contents(context, &enc.ciphertext);
krb5_free_keyblock(context, new_session);
krb5_free_data(context, scratch);
return ret;
}
static krb5_error_code
pkinit_pick_kdf_alg(krb5_context context, krb5_data **kdf_list,
krb5_data **alg_oid)
{
krb5_error_code retval = 0;
krb5_data *req_oid = NULL;
const krb5_data *supp_oid = NULL;
krb5_data *tmp_oid = NULL;
int i, j = 0;
/* if we don't find a match, return NULL value */
*alg_oid = NULL;
/* for each of the OIDs that the server supports... */
for (i = 0; NULL != (supp_oid = supported_kdf_alg_ids[i]); i++) {
/* if the requested OID is in the client's list, use it. */
for (j = 0; NULL != (req_oid = kdf_list[j]); j++) {
if ((req_oid->length == supp_oid->length) &&
(0 == memcmp(req_oid->data, supp_oid->data, req_oid->length))) {
tmp_oid = k5alloc(sizeof(krb5_data), &retval);
if (retval)
goto cleanup;
tmp_oid->data = k5memdup(supp_oid->data, supp_oid->length,
&retval);
if (retval)
goto cleanup;
tmp_oid->length = supp_oid->length;
*alg_oid = tmp_oid;
/* don't free the OID in clean-up if we are returning it */
tmp_oid = NULL;
goto cleanup;
}
}
}
cleanup:
if (tmp_oid)
krb5_free_data(context, tmp_oid);
return retval;
}
static krb5_error_code
pkinit_server_return_padata(krb5_context context,
krb5_pa_data * padata,
krb5_data *req_pkt,
krb5_kdc_req * request,
krb5_kdc_rep * reply,
krb5_keyblock * encrypting_key,
krb5_pa_data ** send_pa,
krb5_kdcpreauth_callbacks cb,
krb5_kdcpreauth_rock rock,
krb5_kdcpreauth_moddata moddata,
krb5_kdcpreauth_modreq modreq)
{
krb5_error_code retval = 0;
krb5_data scratch = {0, 0, NULL};
krb5_pa_pk_as_req *reqp = NULL;
krb5_pa_pk_as_req_draft9 *reqp9 = NULL;
int i = 0;
unsigned char *subjectPublicKey = NULL;
unsigned char *dh_pubkey = NULL, *server_key = NULL;
unsigned int subjectPublicKey_len = 0;
unsigned int server_key_len = 0, dh_pubkey_len = 0;
krb5_kdc_dh_key_info dhkey_info;
krb5_data *encoded_dhkey_info = NULL;
krb5_pa_pk_as_rep *rep = NULL;
krb5_pa_pk_as_rep_draft9 *rep9 = NULL;
krb5_data *out_data = NULL;
krb5_data secret;
krb5_enctype enctype = -1;
krb5_reply_key_pack *key_pack = NULL;
krb5_reply_key_pack_draft9 *key_pack9 = NULL;
krb5_data *encoded_key_pack = NULL;
pkinit_kdc_context plgctx;
pkinit_kdc_req_context reqctx;
int fixed_keypack = 0;
*send_pa = NULL;
if (padata->pa_type == KRB5_PADATA_PKINIT_KX) {
return return_pkinit_kx(context, request, reply,
encrypting_key, send_pa);
}
if (padata->length <= 0 || padata->contents == NULL)
return 0;
if (modreq == NULL) {
pkiDebug("missing request context \n");
return EINVAL;
}
plgctx = pkinit_find_realm_context(context, moddata, request->server);
if (plgctx == NULL) {
pkiDebug("Unable to locate correct realm context\n");
return ENOENT;
}
TRACE_PKINIT_SERVER_RETURN_PADATA(context);
reqctx = (pkinit_kdc_req_context)modreq;
if (encrypting_key->contents) {
free(encrypting_key->contents);
encrypting_key->length = 0;
encrypting_key->contents = NULL;
}
for(i = 0; i < request->nktypes; i++) {
enctype = request->ktype[i];
if (!krb5_c_valid_enctype(enctype))
continue;
else {
pkiDebug("KDC picked etype = %d\n", enctype);
break;
}
}
if (i == request->nktypes) {
retval = KRB5KDC_ERR_ETYPE_NOSUPP;
goto cleanup;
}
switch((int)reqctx->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
init_krb5_pa_pk_as_rep(&rep);
if (rep == NULL) {
retval = ENOMEM;
goto cleanup;
}
/* let's assume it's RSA. we'll reset it to DH if needed */
rep->choice = choice_pa_pk_as_rep_encKeyPack;
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
init_krb5_pa_pk_as_rep_draft9(&rep9);
if (rep9 == NULL) {
retval = ENOMEM;
goto cleanup;
}
rep9->choice = choice_pa_pk_as_rep_draft9_encKeyPack;
break;
default:
retval = KRB5KDC_ERR_PREAUTH_FAILED;
goto cleanup;
}
if (reqctx->rcv_auth_pack != NULL &&
reqctx->rcv_auth_pack->clientPublicValue != NULL) {
subjectPublicKey = (unsigned char *)
reqctx->rcv_auth_pack->clientPublicValue->subjectPublicKey.data;
subjectPublicKey_len =
reqctx->rcv_auth_pack->clientPublicValue->subjectPublicKey.length;
rep->choice = choice_pa_pk_as_rep_dhInfo;
} else if (reqctx->rcv_auth_pack9 != NULL &&
reqctx->rcv_auth_pack9->clientPublicValue != NULL) {
subjectPublicKey = (unsigned char *)
reqctx->rcv_auth_pack9->clientPublicValue->subjectPublicKey.data;
subjectPublicKey_len =
reqctx->rcv_auth_pack9->clientPublicValue->subjectPublicKey.length;
rep9->choice = choice_pa_pk_as_rep_draft9_dhSignedData;
}
/* if this DH, then process finish computing DH key */
if (rep != NULL && (rep->choice == choice_pa_pk_as_rep_dhInfo ||
rep->choice == choice_pa_pk_as_rep_draft9_dhSignedData)) {
pkiDebug("received DH key delivery AS REQ\n");
retval = server_process_dh(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, subjectPublicKey,
subjectPublicKey_len, &dh_pubkey, &dh_pubkey_len,
&server_key, &server_key_len);
if (retval) {
pkiDebug("failed to process/create dh paramters\n");
goto cleanup;
}
}
if ((rep9 != NULL &&
rep9->choice == choice_pa_pk_as_rep_draft9_dhSignedData) ||
(rep != NULL && rep->choice == choice_pa_pk_as_rep_dhInfo)) {
/*
* This is DH, so don't generate the key until after we
* encode the reply, because the encoded reply is needed
* to generate the key in some cases.
*/
dhkey_info.subjectPublicKey.length = dh_pubkey_len;
dhkey_info.subjectPublicKey.data = (char *)dh_pubkey;
dhkey_info.nonce = request->nonce;
dhkey_info.dhKeyExpiration = 0;
retval = k5int_encode_krb5_kdc_dh_key_info(&dhkey_info,
&encoded_dhkey_info);
if (retval) {
pkiDebug("encode_krb5_kdc_dh_key_info failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)encoded_dhkey_info->data,
encoded_dhkey_info->length,
"/tmp/kdc_dh_key_info");
#endif
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
retval = cms_signeddata_create(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_SERVER, 1,
(unsigned char *)
encoded_dhkey_info->data,
encoded_dhkey_info->length,
(unsigned char **)
&rep->u.dh_Info.dhSignedData.data,
&rep->u.dh_Info.dhSignedData.length);
if (retval) {
pkiDebug("failed to create pkcs7 signed data\n");
goto cleanup;
}
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = cms_signeddata_create(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, CMS_SIGN_DRAFT9, 1,
(unsigned char *)
encoded_dhkey_info->data,
encoded_dhkey_info->length,
(unsigned char **)
&rep9->u.dhSignedData.data,
&rep9->u.dhSignedData.length);
if (retval) {
pkiDebug("failed to create pkcs7 signed data\n");
goto cleanup;
}
break;
}
} else {
pkiDebug("received RSA key delivery AS REQ\n");
retval = krb5_c_make_random_key(context, enctype, encrypting_key);
if (retval) {
pkiDebug("unable to make a session key\n");
goto cleanup;
}
/* check if PA_TYPE of KRB5_PADATA_AS_CHECKSUM (132) is present which
* means the client is requesting that a checksum is send back instead
* of the nonce.
*/
for (i = 0; request->padata[i] != NULL; i++) {
pkiDebug("%s: Checking pa_type 0x%08x\n",
__FUNCTION__, request->padata[i]->pa_type);
if (request->padata[i]->pa_type == KRB5_PADATA_AS_CHECKSUM)
fixed_keypack = 1;
}
pkiDebug("%s: return checksum instead of nonce = %d\n",
__FUNCTION__, fixed_keypack);
/* if this is an RFC reply or draft9 client requested a checksum
* in the reply instead of the nonce, create an RFC-style keypack
*/
if ((int)padata->pa_type == KRB5_PADATA_PK_AS_REQ || fixed_keypack) {
init_krb5_reply_key_pack(&key_pack);
if (key_pack == NULL) {
retval = ENOMEM;
goto cleanup;
}
retval = krb5_c_make_checksum(context, 0,
encrypting_key, KRB5_KEYUSAGE_TGS_REQ_AUTH_CKSUM,
req_pkt, &key_pack->asChecksum);
if (retval) {
pkiDebug("unable to calculate AS REQ checksum\n");
goto cleanup;
}
#ifdef DEBUG_CKSUM
pkiDebug("calculating checksum on buf size = %d\n", req_pkt->length);
print_buffer(req_pkt->data, req_pkt->length);
pkiDebug("checksum size = %d\n", key_pack->asChecksum.length);
print_buffer(key_pack->asChecksum.contents,
key_pack->asChecksum.length);
pkiDebug("encrypting key (%d)\n", encrypting_key->length);
print_buffer(encrypting_key->contents, encrypting_key->length);
#endif
krb5_copy_keyblock_contents(context, encrypting_key,
&key_pack->replyKey);
retval = k5int_encode_krb5_reply_key_pack(key_pack,
&encoded_key_pack);
if (retval) {
pkiDebug("failed to encode reply_key_pack\n");
goto cleanup;
}
}
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
rep->choice = choice_pa_pk_as_rep_encKeyPack;
retval = cms_envelopeddata_create(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, padata->pa_type, 1,
(unsigned char *)
encoded_key_pack->data,
encoded_key_pack->length,
(unsigned char **)
&rep->u.encKeyPack.data,
&rep->u.encKeyPack.length);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
/* if the request is from the broken draft9 client that
* expects back a nonce, create it now
*/
if (!fixed_keypack) {
init_krb5_reply_key_pack_draft9(&key_pack9);
if (key_pack9 == NULL) {
retval = ENOMEM;
goto cleanup;
}
key_pack9->nonce = reqctx->rcv_auth_pack9->pkAuthenticator.nonce;
krb5_copy_keyblock_contents(context, encrypting_key,
&key_pack9->replyKey);
retval = k5int_encode_krb5_reply_key_pack_draft9(key_pack9,
&encoded_key_pack);
if (retval) {
pkiDebug("failed to encode reply_key_pack\n");
goto cleanup;
}
}
rep9->choice = choice_pa_pk_as_rep_draft9_encKeyPack;
retval = cms_envelopeddata_create(context, plgctx->cryptoctx,
reqctx->cryptoctx, plgctx->idctx, padata->pa_type, 1,
(unsigned char *)
encoded_key_pack->data,
encoded_key_pack->length,
(unsigned char **)
&rep9->u.encKeyPack.data, &rep9->u.encKeyPack.length);
break;
}
if (retval) {
pkiDebug("failed to create pkcs7 enveloped data: %s\n",
error_message(retval));
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)encoded_key_pack->data,
encoded_key_pack->length,
"/tmp/kdc_key_pack");
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
print_buffer_bin(rep->u.encKeyPack.data,
rep->u.encKeyPack.length,
"/tmp/kdc_enc_key_pack");
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
print_buffer_bin(rep9->u.encKeyPack.data,
rep9->u.encKeyPack.length,
"/tmp/kdc_enc_key_pack");
break;
}
#endif
}
if ((rep != NULL && rep->choice == choice_pa_pk_as_rep_dhInfo) &&
((reqctx->rcv_auth_pack != NULL &&
reqctx->rcv_auth_pack->supportedKDFs != NULL))) {
/* If using the alg-agility KDF, put the algorithm in the reply
* before encoding it.
*/
if (reqctx->rcv_auth_pack != NULL &&
reqctx->rcv_auth_pack->supportedKDFs != NULL) {
retval = pkinit_pick_kdf_alg(context, reqctx->rcv_auth_pack->supportedKDFs,
&(rep->u.dh_Info.kdfID));
if (retval) {
pkiDebug("pkinit_pick_kdf_alg failed: %s\n",
error_message(retval));
goto cleanup;
}
}
}
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
retval = k5int_encode_krb5_pa_pk_as_rep(rep, &out_data);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = k5int_encode_krb5_pa_pk_as_rep_draft9(rep9, &out_data);
break;
}
if (retval) {
pkiDebug("failed to encode AS_REP\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
if (out_data != NULL)
print_buffer_bin((unsigned char *)out_data->data, out_data->length,
"/tmp/kdc_as_rep");
#endif
/* If this is DH, we haven't computed the key yet, so do it now. */
if ((rep9 != NULL &&
rep9->choice == choice_pa_pk_as_rep_draft9_dhSignedData) ||
(rep != NULL && rep->choice == choice_pa_pk_as_rep_dhInfo)) {
/* If we're not doing draft 9, and mutually supported KDFs were found,
* use the algorithm agility KDF. */
if (rep != NULL && rep->u.dh_Info.kdfID) {
secret.data = (char *)server_key;
secret.length = server_key_len;
retval = pkinit_alg_agility_kdf(context, &secret,
rep->u.dh_Info.kdfID,
request->client, request->server,
enctype, req_pkt, out_data,
encrypting_key);
if (retval) {
pkiDebug("pkinit_alg_agility_kdf failed: %s\n",
error_message(retval));
goto cleanup;
}
/* Otherwise, use the older octetstring2key() function */
} else {
retval = pkinit_octetstring2key(context, enctype, server_key,
server_key_len, encrypting_key);
if (retval) {
pkiDebug("pkinit_octetstring2key failed: %s\n",
error_message(retval));
goto cleanup;
}
}
}
*send_pa = malloc(sizeof(krb5_pa_data));
if (*send_pa == NULL) {
retval = ENOMEM;
free(out_data->data);
free(out_data);
out_data = NULL;
goto cleanup;
}
(*send_pa)->magic = KV5M_PA_DATA;
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
(*send_pa)->pa_type = KRB5_PADATA_PK_AS_REP;
break;
case KRB5_PADATA_PK_AS_REQ_OLD:
case KRB5_PADATA_PK_AS_REP_OLD:
(*send_pa)->pa_type = KRB5_PADATA_PK_AS_REP_OLD;
break;
}
(*send_pa)->length = out_data->length;
(*send_pa)->contents = (krb5_octet *) out_data->data;
cleanup:
pkinit_fini_kdc_req_context(context, reqctx);
free(scratch.data);
free(out_data);
if (encoded_dhkey_info != NULL)
krb5_free_data(context, encoded_dhkey_info);
if (encoded_key_pack != NULL)
krb5_free_data(context, encoded_key_pack);
free(dh_pubkey);
free(server_key);
switch ((int)padata->pa_type) {
case KRB5_PADATA_PK_AS_REQ:
free_krb5_pa_pk_as_req(&reqp);
free_krb5_pa_pk_as_rep(&rep);
free_krb5_reply_key_pack(&key_pack);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
free_krb5_pa_pk_as_req_draft9(&reqp9);
free_krb5_pa_pk_as_rep_draft9(&rep9);
if (!fixed_keypack)
free_krb5_reply_key_pack_draft9(&key_pack9);
else
free_krb5_reply_key_pack(&key_pack);
break;
}
if (retval)
pkiDebug("pkinit_verify_padata failure");
return retval;
}
static int
pkinit_server_get_flags(krb5_context kcontext, krb5_preauthtype patype)
{
if (patype == KRB5_PADATA_PKINIT_KX)
return PA_INFO;
return PA_SUFFICIENT | PA_REPLACES_KEY | PA_TYPED_E_DATA;
}
static krb5_preauthtype supported_server_pa_types[] = {
KRB5_PADATA_PK_AS_REQ,
KRB5_PADATA_PK_AS_REQ_OLD,
KRB5_PADATA_PK_AS_REP_OLD,
KRB5_PADATA_PKINIT_KX,
0
};
static void
pkinit_fini_kdc_profile(krb5_context context, pkinit_kdc_context plgctx)
{
/*
* There is nothing currently allocated by pkinit_init_kdc_profile()
* which needs to be freed here.
*/
}
static krb5_error_code
pkinit_init_kdc_profile(krb5_context context, pkinit_kdc_context plgctx)
{
krb5_error_code retval;
char *eku_string = NULL, *ocsp_check = NULL;
pkiDebug("%s: entered for realm %s\n", __FUNCTION__, plgctx->realmname);
retval = pkinit_kdcdefault_string(context, plgctx->realmname,
KRB5_CONF_PKINIT_IDENTITY,
&plgctx->idopts->identity);
if (retval != 0 || NULL == plgctx->idopts->identity) {
retval = EINVAL;
krb5_set_error_message(context, retval,
_("No pkinit_identity supplied for realm %s"),
plgctx->realmname);
goto errout;
}
retval = pkinit_kdcdefault_strings(context, plgctx->realmname,
KRB5_CONF_PKINIT_ANCHORS,
&plgctx->idopts->anchors);
if (retval != 0 || NULL == plgctx->idopts->anchors) {
retval = EINVAL;
krb5_set_error_message(context, retval,
_("No pkinit_anchors supplied for realm %s"),
plgctx->realmname);
goto errout;
}
pkinit_kdcdefault_strings(context, plgctx->realmname,
KRB5_CONF_PKINIT_POOL,
&plgctx->idopts->intermediates);
pkinit_kdcdefault_strings(context, plgctx->realmname,
KRB5_CONF_PKINIT_REVOKE,
&plgctx->idopts->crls);
pkinit_kdcdefault_string(context, plgctx->realmname,
KRB5_CONF_PKINIT_KDC_OCSP,
&ocsp_check);
if (ocsp_check != NULL) {
free(ocsp_check);
retval = ENOTSUP;
krb5_set_error_message(context, retval,
_("OCSP is not supported: (realm: %s)"),
plgctx->realmname);
goto errout;
}
pkinit_kdcdefault_integer(context, plgctx->realmname,
KRB5_CONF_PKINIT_DH_MIN_BITS,
PKINIT_DEFAULT_DH_MIN_BITS,
&plgctx->opts->dh_min_bits);
if (plgctx->opts->dh_min_bits < PKINIT_DH_MIN_CONFIG_BITS) {
pkiDebug("%s: invalid value (%d < %d) for pkinit_dh_min_bits, "
"using default value (%d) instead\n", __FUNCTION__,
plgctx->opts->dh_min_bits, PKINIT_DH_MIN_CONFIG_BITS,
PKINIT_DEFAULT_DH_MIN_BITS);
plgctx->opts->dh_min_bits = PKINIT_DEFAULT_DH_MIN_BITS;
}
pkinit_kdcdefault_boolean(context, plgctx->realmname,
KRB5_CONF_PKINIT_ALLOW_UPN,
0, &plgctx->opts->allow_upn);
pkinit_kdcdefault_boolean(context, plgctx->realmname,
KRB5_CONF_PKINIT_REQUIRE_CRL_CHECKING,
0, &plgctx->opts->require_crl_checking);
pkinit_kdcdefault_string(context, plgctx->realmname,
KRB5_CONF_PKINIT_EKU_CHECKING,
&eku_string);
if (eku_string != NULL) {
if (strcasecmp(eku_string, "kpClientAuth") == 0) {
plgctx->opts->require_eku = 1;
plgctx->opts->accept_secondary_eku = 0;
} else if (strcasecmp(eku_string, "scLogin") == 0) {
plgctx->opts->require_eku = 1;
plgctx->opts->accept_secondary_eku = 1;
} else if (strcasecmp(eku_string, "none") == 0) {
plgctx->opts->require_eku = 0;
plgctx->opts->accept_secondary_eku = 0;
} else {
pkiDebug("%s: Invalid value for pkinit_eku_checking: '%s'\n",
__FUNCTION__, eku_string);
}
free(eku_string);
}
pkinit_kdcdefault_strings(context, plgctx->realmname,
KRB5_CONF_PKINIT_INDICATOR,
&plgctx->auth_indicators);
return 0;
errout:
pkinit_fini_kdc_profile(context, plgctx);
return retval;
}
static pkinit_kdc_context
pkinit_find_realm_context(krb5_context context,
krb5_kdcpreauth_moddata moddata,
krb5_principal princ)
{
int i;
pkinit_kdc_context *realm_contexts;
if (moddata == NULL)
return NULL;
realm_contexts = moddata->realm_contexts;
if (realm_contexts == NULL)
return NULL;
for (i = 0; realm_contexts[i] != NULL; i++) {
pkinit_kdc_context p = realm_contexts[i];
if ((p->realmname_len == princ->realm.length) &&
(strncmp(p->realmname, princ->realm.data, p->realmname_len) == 0)) {
pkiDebug("%s: returning context at %p for realm '%s'\n",
__FUNCTION__, p, p->realmname);
return p;
}
}
pkiDebug("%s: unable to find realm context for realm '%.*s'\n",
__FUNCTION__, princ->realm.length, princ->realm.data);
return NULL;
}
static int
pkinit_server_plugin_init_realm(krb5_context context, const char *realmname,
pkinit_kdc_context *pplgctx)
{
krb5_error_code retval = ENOMEM;
pkinit_kdc_context plgctx = NULL;
*pplgctx = NULL;
plgctx = calloc(1, sizeof(*plgctx));
if (plgctx == NULL)
goto errout;
pkiDebug("%s: initializing context at %p for realm '%s'\n",
__FUNCTION__, plgctx, realmname);
memset(plgctx, 0, sizeof(*plgctx));
plgctx->magic = PKINIT_CTX_MAGIC;
plgctx->realmname = strdup(realmname);
if (plgctx->realmname == NULL)
goto errout;
plgctx->realmname_len = strlen(plgctx->realmname);
retval = pkinit_init_plg_crypto(&plgctx->cryptoctx);
if (retval)
goto errout;
retval = pkinit_init_plg_opts(&plgctx->opts);
if (retval)
goto errout;
retval = pkinit_init_identity_crypto(&plgctx->idctx);
if (retval)
goto errout;
retval = pkinit_init_identity_opts(&plgctx->idopts);
if (retval)
goto errout;
retval = pkinit_init_kdc_profile(context, plgctx);
if (retval)
goto errout;
retval = pkinit_identity_initialize(context, plgctx->cryptoctx, NULL,
plgctx->idopts, plgctx->idctx,
NULL, NULL, NULL);
if (retval)
goto errout;
retval = pkinit_identity_prompt(context, plgctx->cryptoctx, NULL,
plgctx->idopts, plgctx->idctx,
NULL, NULL, 0, NULL);
if (retval)
goto errout;
pkiDebug("%s: returning context at %p for realm '%s'\n",
__FUNCTION__, plgctx, realmname);
*pplgctx = plgctx;
retval = 0;
errout:
if (retval)
pkinit_server_plugin_fini_realm(context, plgctx);
return retval;
}
static krb5_error_code
pkinit_san_authorize(krb5_context context, krb5_certauth_moddata moddata,
const uint8_t *cert, size_t cert_len,
krb5_const_principal princ, const void *opts,
const struct _krb5_db_entry_new *db_entry,
char ***authinds_out)
{
krb5_error_code ret;
int valid_san;
const struct certauth_req_opts *req_opts = opts;
*authinds_out = NULL;
ret = verify_client_san(context, req_opts->plgctx, req_opts->reqctx,
req_opts->cb, req_opts->rock, princ, &valid_san);
if (ret == ENOENT)
return KRB5_PLUGIN_NO_HANDLE;
else if (ret)
return ret;
if (!valid_san) {
TRACE_PKINIT_SERVER_SAN_REJECT(context);
return KRB5KDC_ERR_CLIENT_NAME_MISMATCH;
}
return 0;
}
static krb5_error_code
pkinit_eku_authorize(krb5_context context, krb5_certauth_moddata moddata,
const uint8_t *cert, size_t cert_len,
krb5_const_principal princ, const void *opts,
const struct _krb5_db_entry_new *db_entry,
char ***authinds_out)
{
krb5_error_code ret;
int valid_eku;
const struct certauth_req_opts *req_opts = opts;
*authinds_out = NULL;
/* Verify the client EKU. */
ret = verify_client_eku(context, req_opts->plgctx, req_opts->reqctx,
&valid_eku);
if (ret)
return ret;
if (!valid_eku) {
TRACE_PKINIT_SERVER_EKU_REJECT(context);
return KRB5KDC_ERR_INCONSISTENT_KEY_PURPOSE;
}
return 0;
}
static krb5_error_code
certauth_pkinit_san_initvt(krb5_context context, int maj_ver, int min_ver,
krb5_plugin_vtable vtable)
{
krb5_certauth_vtable vt;
if (maj_ver != 1)
return KRB5_PLUGIN_VER_NOTSUPP;
vt = (krb5_certauth_vtable)vtable;
vt->name = "pkinit_san";
vt->authorize = pkinit_san_authorize;
return 0;
}
static krb5_error_code
certauth_pkinit_eku_initvt(krb5_context context, int maj_ver, int min_ver,
krb5_plugin_vtable vtable)
{
krb5_certauth_vtable vt;
if (maj_ver != 1)
return KRB5_PLUGIN_VER_NOTSUPP;
vt = (krb5_certauth_vtable)vtable;
vt->name = "pkinit_eku";
vt->authorize = pkinit_eku_authorize;
return 0;
}
/*
* Do certificate auth based on a match expression in the pkinit_cert_match
* attribute string. An expression should be in the same form as those used
* for the pkinit_cert_match configuration option.
*/
static krb5_error_code
dbmatch_authorize(krb5_context context, krb5_certauth_moddata moddata,
const uint8_t *cert, size_t cert_len,
krb5_const_principal princ, const void *opts,
const struct _krb5_db_entry_new *db_entry,
char ***authinds_out)
{
krb5_error_code ret;
const struct certauth_req_opts *req_opts = opts;
char *pattern;
krb5_boolean matched;
*authinds_out = NULL;
/* Fetch the matching pattern. Pass if it isn't specified. */
ret = req_opts->cb->get_string(context, req_opts->rock,
"pkinit_cert_match", &pattern);
if (ret)
return ret;
if (pattern == NULL)
return KRB5_PLUGIN_NO_HANDLE;
/* Check the certificate against the match expression. */
ret = pkinit_client_cert_match(context, req_opts->plgctx->cryptoctx,
req_opts->reqctx->cryptoctx, pattern,
&matched);
req_opts->cb->free_string(context, req_opts->rock, pattern);
if (ret)
return ret;
return matched ? 0 : KRB5KDC_ERR_CERTIFICATE_MISMATCH;
}
static krb5_error_code
certauth_dbmatch_initvt(krb5_context context, int maj_ver, int min_ver,
krb5_plugin_vtable vtable)
{
krb5_certauth_vtable vt;
if (maj_ver != 1)
return KRB5_PLUGIN_VER_NOTSUPP;
vt = (krb5_certauth_vtable)vtable;
vt->name = "dbmatch";
vt->authorize = dbmatch_authorize;
return 0;
}
static krb5_error_code
load_certauth_plugins(krb5_context context, certauth_handle **handle_out)
{
krb5_error_code ret;
krb5_plugin_initvt_fn *modules = NULL, *mod;
certauth_handle *list = NULL, h;
size_t count;
/* Register the builtin modules. */
ret = k5_plugin_register(context, PLUGIN_INTERFACE_CERTAUTH,
"pkinit_san", certauth_pkinit_san_initvt);
if (ret)
goto cleanup;
ret = k5_plugin_register(context, PLUGIN_INTERFACE_CERTAUTH,
"pkinit_eku", certauth_pkinit_eku_initvt);
if (ret)
goto cleanup;
ret = k5_plugin_register(context, PLUGIN_INTERFACE_CERTAUTH, "dbmatch",
certauth_dbmatch_initvt);
if (ret)
goto cleanup;
ret = k5_plugin_load_all(context, PLUGIN_INTERFACE_CERTAUTH, &modules);
if (ret)
goto cleanup;
/* Allocate handle list. */
for (count = 0; modules[count]; count++);
list = k5calloc(count + 1, sizeof(*list), &ret);
if (list == NULL)
goto cleanup;
/* Initialize each module, ignoring ones that fail. */
count = 0;
for (mod = modules; *mod != NULL; mod++) {
h = k5calloc(1, sizeof(*h), &ret);
if (h == NULL)
goto cleanup;
ret = (*mod)(context, 1, 1, (krb5_plugin_vtable)&h->vt);
if (ret) {
TRACE_CERTAUTH_VTINIT_FAIL(context, ret);
free(h);
continue;
}
h->moddata = NULL;
if (h->vt.init != NULL) {
ret = h->vt.init(context, &h->moddata);
if (ret) {
TRACE_CERTAUTH_INIT_FAIL(context, h->vt.name, ret);
free(h);
continue;
}
}
list[count++] = h;
list[count] = NULL;
}
list[count] = NULL;
ret = 0;
*handle_out = list;
list = NULL;
cleanup:
k5_plugin_free_modules(context, modules);
free_certauth_handles(context, list);
return ret;
}
static int
pkinit_server_plugin_init(krb5_context context,
krb5_kdcpreauth_moddata *moddata_out,
const char **realmnames)
{
krb5_error_code retval = ENOMEM;
pkinit_kdc_context plgctx, *realm_contexts = NULL;
certauth_handle *certauth_modules = NULL;
krb5_kdcpreauth_moddata moddata;
size_t i, j;
size_t numrealms;
retval = pkinit_accessor_init();
if (retval)
return retval;
/* Determine how many realms we may need to support */
for (i = 0; realmnames[i] != NULL; i++) {};
numrealms = i;
realm_contexts = calloc(numrealms+1, sizeof(pkinit_kdc_context));
if (realm_contexts == NULL)
return ENOMEM;
for (i = 0, j = 0; i < numrealms; i++) {
TRACE_PKINIT_SERVER_INIT_REALM(context, realmnames[i]);
retval = pkinit_server_plugin_init_realm(context, realmnames[i], &plgctx);
if (retval == 0 && plgctx != NULL)
realm_contexts[j++] = plgctx;
}
if (j == 0) {
retval = EINVAL;
krb5_set_error_message(context, retval,
_("No realms configured correctly for pkinit "
"support"));
goto errout;
}
retval = load_certauth_plugins(context, &certauth_modules);
if (retval)
goto errout;
moddata = k5calloc(1, sizeof(*moddata), &retval);
if (moddata == NULL)
goto errout;
moddata->realm_contexts = realm_contexts;
moddata->certauth_modules = certauth_modules;
*moddata_out = moddata;
pkiDebug("%s: returning context at %p\n", __FUNCTION__, moddata);
return 0;
errout:
free_realm_contexts(context, realm_contexts);
free_certauth_handles(context, certauth_modules);
return retval;
}
static void
pkinit_server_plugin_fini_realm(krb5_context context, pkinit_kdc_context plgctx)
{
char **sp;
if (plgctx == NULL)
return;
pkinit_fini_kdc_profile(context, plgctx);
pkinit_fini_identity_opts(plgctx->idopts);
pkinit_fini_identity_crypto(plgctx->idctx);
pkinit_fini_plg_crypto(plgctx->cryptoctx);
pkinit_fini_plg_opts(plgctx->opts);
for (sp = plgctx->auth_indicators; sp != NULL && *sp != NULL; sp++)
free(*sp);
free(plgctx->auth_indicators);
free(plgctx->realmname);
free(plgctx);
}
static void
pkinit_server_plugin_fini(krb5_context context,
krb5_kdcpreauth_moddata moddata)
{
if (moddata == NULL)
return;
free_realm_contexts(context, moddata->realm_contexts);
free_certauth_handles(context, moddata->certauth_modules);
free(moddata);
}
static krb5_error_code
pkinit_init_kdc_req_context(krb5_context context, pkinit_kdc_req_context *ctx)
{
krb5_error_code retval = ENOMEM;
pkinit_kdc_req_context reqctx = NULL;
reqctx = malloc(sizeof(*reqctx));
if (reqctx == NULL)
return retval;
memset(reqctx, 0, sizeof(*reqctx));
reqctx->magic = PKINIT_CTX_MAGIC;
retval = pkinit_init_req_crypto(&reqctx->cryptoctx);
if (retval)
goto cleanup;
reqctx->rcv_auth_pack = NULL;
reqctx->rcv_auth_pack9 = NULL;
pkiDebug("%s: returning reqctx at %p\n", __FUNCTION__, reqctx);
*ctx = reqctx;
retval = 0;
cleanup:
if (retval)
pkinit_fini_kdc_req_context(context, reqctx);
return retval;
}
static void
pkinit_fini_kdc_req_context(krb5_context context, void *ctx)
{
pkinit_kdc_req_context reqctx = (pkinit_kdc_req_context)ctx;
if (reqctx == NULL || reqctx->magic != PKINIT_CTX_MAGIC) {
pkiDebug("pkinit_fini_kdc_req_context: got bad reqctx (%p)!\n", reqctx);
return;
}
pkiDebug("%s: freeing reqctx at %p\n", __FUNCTION__, reqctx);
pkinit_fini_req_crypto(reqctx->cryptoctx);
if (reqctx->rcv_auth_pack != NULL)
free_krb5_auth_pack(&reqctx->rcv_auth_pack);
if (reqctx->rcv_auth_pack9 != NULL)
free_krb5_auth_pack_draft9(context, &reqctx->rcv_auth_pack9);
free(reqctx);
}
krb5_error_code
kdcpreauth_pkinit_initvt(krb5_context context, int maj_ver, int min_ver,
krb5_plugin_vtable vtable);
krb5_error_code
kdcpreauth_pkinit_initvt(krb5_context context, int maj_ver, int min_ver,
krb5_plugin_vtable vtable)
{
krb5_kdcpreauth_vtable vt;
if (maj_ver != 1)
return KRB5_PLUGIN_VER_NOTSUPP;
vt = (krb5_kdcpreauth_vtable)vtable;
vt->name = "pkinit";
vt->pa_type_list = supported_server_pa_types;
vt->init = pkinit_server_plugin_init;
vt->fini = pkinit_server_plugin_fini;
vt->flags = pkinit_server_get_flags;
vt->edata = pkinit_server_get_edata;
vt->verify = pkinit_server_verify_padata;
vt->return_padata = pkinit_server_return_padata;
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/bad_3281_1 |
crossvul-cpp_data_good_3184_4 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/***************************************************************************
* Copyright (C) 2013-2017 Ping Identity Corporation
* All rights reserved.
*
* For further information please contact:
*
* Ping Identity Corporation
* 1099 18th St Suite 2950
* Denver, CO 80202
* 303.468.2900
* http://www.pingidentity.com
*
* DISCLAIMER OF WARRANTIES:
*
* THE SOFTWARE PROVIDED HEREUNDER IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
* ANY WARRANTIES OR REPRESENTATIONS EXPRESS, IMPLIED OR STATUTORY; INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF QUALITY, PERFORMANCE, NONINFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NOR ARE THERE ANY
* WARRANTIES CREATED BY A COURSE OR DEALING, COURSE OF PERFORMANCE OR TRADE
* USAGE. FURTHERMORE, THERE ARE NO WARRANTIES THAT THE SOFTWARE WILL MEET
* YOUR NEEDS OR BE FREE FROM ERRORS, OR THAT THE OPERATION OF THE SOFTWARE
* WILL BE UNINTERRUPTED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES 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.
*
* @Author: Hans Zandbelt - hans.zandbelt@zmartzone.eu
*/
#include <apr_lib.h>
#include <httpd.h>
#include <http_config.h>
#include <http_log.h>
#include <http_request.h>
#include "mod_auth_openidc.h"
#include "parse.h"
/*
* validate an access token against the validation endpoint of the Authorization server and gets a response back
*/
static apr_byte_t oidc_oauth_validate_access_token(request_rec *r, oidc_cfg *c,
const char *token, const char **response) {
/* assemble parameters to call the token endpoint for validation */
apr_table_t *params = apr_table_make(r->pool, 4);
/* add any configured extra static parameters to the introspection endpoint */
oidc_util_table_add_query_encoded_params(r->pool, params,
c->oauth.introspection_endpoint_params);
/* add the access_token itself */
apr_table_addn(params, c->oauth.introspection_token_param_name, token);
/* see if we want to do basic auth or post-param-based auth */
const char *basic_auth = NULL;
if ((c->oauth.client_id != NULL) && (c->oauth.client_secret != NULL)) {
if ((c->oauth.introspection_endpoint_auth != NULL)
&& (apr_strnatcmp(c->oauth.introspection_endpoint_auth,
"client_secret_post") == 0)) {
apr_table_addn(params, "client_id", c->oauth.client_id);
apr_table_addn(params, "client_secret", c->oauth.client_secret);
} else {
basic_auth = apr_psprintf(r->pool, "%s:%s", c->oauth.client_id,
c->oauth.client_secret);
}
}
/* call the endpoint with the constructed parameter set and return the resulting response */
return apr_strnatcmp(c->oauth.introspection_endpoint_method, OIDC_INTROSPECTION_METHOD_GET) == 0 ?
oidc_util_http_get(r, c->oauth.introspection_endpoint_url, params,
basic_auth, NULL, c->oauth.ssl_validate_server, response,
c->http_timeout_long, c->outgoing_proxy,
oidc_dir_cfg_pass_cookies(r), c->oauth.introspection_endpoint_tls_client_cert, c->oauth.introspection_endpoint_tls_client_key):
oidc_util_http_post_form(r, c->oauth.introspection_endpoint_url,
params, basic_auth, NULL, c->oauth.ssl_validate_server,
response, c->http_timeout_long, c->outgoing_proxy,
oidc_dir_cfg_pass_cookies(r), c->oauth.introspection_endpoint_tls_client_cert, c->oauth.introspection_endpoint_tls_client_key);
}
/*
* get the authorization header that should contain a bearer token
*/
static apr_byte_t oidc_oauth_get_bearer_token(request_rec *r,
const char **access_token) {
/* get the directory specific setting on how the token can be passed in */
int accept_token_in = oidc_cfg_dir_accept_token_in(r);
const char *cookie_name = oidc_cfg_dir_accept_token_in_option(r,
OIDC_OAUTH_ACCEPT_TOKEN_IN_OPTION_COOKIE_NAME);
oidc_debug(r, "accept_token_in=%d", accept_token_in);
*access_token = NULL;
if ((accept_token_in & OIDC_OAUTH_ACCEPT_TOKEN_IN_HEADER)
|| (accept_token_in == OIDC_OAUTH_ACCEPT_TOKEN_IN_DEFAULT)) {
/* get the authorization header */
const char *auth_line;
auth_line = apr_table_get(r->headers_in, "Authorization");
if (auth_line) {
oidc_debug(r, "authorization header found");
/* look for the Bearer keyword */
if (apr_strnatcasecmp(ap_getword(r->pool, &auth_line, ' '),
"Bearer") == 0) {
/* skip any spaces after the Bearer keyword */
while (apr_isspace(*auth_line)) {
auth_line++;
}
/* copy the result in to the access_token */
*access_token = apr_pstrdup(r->pool, auth_line);
} else {
oidc_warn(r,
"client used unsupported authentication scheme: %s",
r->uri);
}
}
}
if ((*access_token == NULL) && (r->method_number == M_POST)
&& (accept_token_in & OIDC_OAUTH_ACCEPT_TOKEN_IN_POST)) {
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params) == TRUE) {
*access_token = apr_table_get(params, "access_token");
}
}
if ((*access_token == NULL)
&& (accept_token_in & OIDC_OAUTH_ACCEPT_TOKEN_IN_QUERY)) {
apr_table_t *params = apr_table_make(r->pool, 8);
oidc_util_read_form_encoded_params(r, params, r->args);
*access_token = apr_table_get(params, "access_token");
}
if ((*access_token == NULL)
&& (accept_token_in & OIDC_OAUTH_ACCEPT_TOKEN_IN_COOKIE)) {
const char *auth_line = oidc_util_get_cookie(r, cookie_name);
if (auth_line != NULL) {
/* copy the result in to the access_token */
*access_token = apr_pstrdup(r->pool, auth_line);
} else {
oidc_warn(r, "no cookie found with name: %s", cookie_name);
}
}
if (*access_token == NULL) {
oidc_debug(r, "no bearer token found in the allowed methods: %s",
oidc_accept_oauth_token_in2str(r->pool, accept_token_in));
return FALSE;
}
/* log some stuff */
oidc_debug(r, "bearer token: %s", *access_token);
return TRUE;
}
/*
* copy over space separated scope value but do it in an array for authorization purposes
*/
/*
static void oidc_oauth_spaced_string_to_array(request_rec *r, json_t *src,
const char *src_key, json_t *dst, const char *dst_key) {
apr_hash_t *ht = NULL;
apr_hash_index_t *hi = NULL;
json_t *arr = NULL;
json_t *src_val = json_object_get(src, src_key);
if (src_val != NULL)
ht = oidc_util_spaced_string_to_hashtable(r->pool,
json_string_value(src_val));
if (ht != NULL) {
arr = json_array();
for (hi = apr_hash_first(NULL, ht); hi; hi = apr_hash_next(hi)) {
const char *k;
const char *v;
apr_hash_this(hi, (const void**) &k, NULL, (void**) &v);
json_array_append_new(arr, json_string(v));
}
json_object_set_new(dst, dst_key, arr);
}
}
*/
/*
* parse (custom/configurable) token expiry claim in introspection result
*/
static apr_byte_t oidc_oauth_parse_and_cache_token_expiry(request_rec *r,
oidc_cfg *c, json_t *introspection_response,
const char *expiry_claim_name, int expiry_format_absolute,
int expiry_claim_is_mandatory, apr_time_t *cache_until) {
oidc_debug(r,
"expiry_claim_name=%s, expiry_format_absolute=%d, expiry_claim_is_mandatory=%d",
expiry_claim_name, expiry_format_absolute,
expiry_claim_is_mandatory);
json_t *expiry = json_object_get(introspection_response, expiry_claim_name);
if (expiry == NULL) {
if (expiry_claim_is_mandatory) {
oidc_error(r,
"introspection response JSON object did not contain an \"%s\" claim",
expiry_claim_name);
return FALSE;
}
return TRUE;
}
if (!json_is_integer(expiry)) {
if (expiry_claim_is_mandatory) {
oidc_error(r,
"introspection response JSON object contains a \"%s\" claim but it is not a JSON integer",
expiry_claim_name);
return FALSE;
}
oidc_warn(r,
"introspection response JSON object contains a \"%s\" claim that is not an (optional) JSON integer: the introspection result will NOT be cached",
expiry_claim_name);
return TRUE;
}
json_int_t value = json_integer_value(expiry);
if (value <= 0) {
oidc_warn(r,
"introspection response JSON object integer number value <= 0 (%ld); introspection result will not be cached",
(long )value);
return TRUE;
}
*cache_until = apr_time_from_sec(value);
if (expiry_format_absolute == FALSE)
(*cache_until) += apr_time_now();
return TRUE;
}
static apr_byte_t oidc_oauth_cache_access_token(request_rec *r, oidc_cfg *c,
apr_time_t cache_until, const char *access_token, json_t *json) {
oidc_debug(r, "caching introspection result");
json_t *cache_entry = json_object();
json_object_set(cache_entry, "response", json);
json_object_set_new(cache_entry, "timestamp",
json_integer(apr_time_sec(apr_time_now())));
char *cache_value = json_dumps(cache_entry, 0);
/* set it in the cache so subsequent request don't need to validate the access_token and get the claims anymore */
c->cache->set(r, OIDC_CACHE_SECTION_ACCESS_TOKEN, access_token, cache_value,
cache_until);
json_decref(cache_entry);
free(cache_value);
return TRUE;
}
static apr_byte_t oidc_oauth_get_cached_access_token(request_rec *r,
oidc_cfg *c, const char *access_token, json_t **json) {
json_t *cache_entry = NULL;
const char *s_cache_entry = NULL;
json_error_t json_error;
/* see if we've got the claims for this access_token cached already */
c->cache->get(r, OIDC_CACHE_SECTION_ACCESS_TOKEN, access_token,
&s_cache_entry);
if (s_cache_entry == NULL)
return FALSE;
/* json decode the cache entry */
cache_entry = json_loads(s_cache_entry, 0, &json_error);
if (cache_entry == NULL) {
oidc_error(r, "cached JSON was corrupted: %s", json_error.text);
*json = NULL;
return FALSE;
}
/* compare the timestamp against the freshness requirement */
json_t *v = json_object_get(cache_entry, "timestamp");
apr_time_t now = apr_time_sec(apr_time_now());
int token_introspection_interval = oidc_cfg_token_introspection_interval(r);
if ((token_introspection_interval > 0)
&& (now > json_integer_value(v) + token_introspection_interval)) {
/* printout info about the event */
char buf[APR_RFC822_DATE_LEN + 1];
apr_rfc822_date(buf, apr_time_from_sec(json_integer_value(v)));
oidc_debug(r,
"token that was validated/cached at: [%s], does not meet token freshness requirement: %d)",
buf, token_introspection_interval);
/* invalidate the cache entry */
*json = NULL;
json_decref(cache_entry);
return FALSE;
}
oidc_debug(r,
"returning cached introspection result that meets freshness requirements: %s",
s_cache_entry);
/* we've got a cached introspection result that is still valid for this path's requirements */
*json = json_deep_copy(json_object_get(cache_entry, "response"));
json_decref(cache_entry);
return TRUE;
}
/*
* resolve and validate an access_token against the configured Authorization Server
*/
static apr_byte_t oidc_oauth_resolve_access_token(request_rec *r, oidc_cfg *c,
const char *access_token, json_t **token, char **response) {
json_t *result = NULL;
/* see if we've got the claims for this access_token cached already */
oidc_oauth_get_cached_access_token(r, c, access_token, &result);
if (result == NULL) {
const char *s_json = NULL;
/* not cached, go out and validate the access_token against the Authorization server and get the JSON claims back */
if (oidc_oauth_validate_access_token(r, c, access_token,
&s_json) == FALSE) {
oidc_error(r,
"could not get a validation response from the Authorization server");
return FALSE;
}
/* decode and see if it is not an error response somehow */
if (oidc_util_decode_json_and_check_error(r, s_json, &result) == FALSE)
return FALSE;
json_t *active = json_object_get(result, "active");
apr_time_t cache_until;
if (active != NULL) {
if (json_is_boolean(active)) {
if (!json_is_true(active)) {
oidc_debug(r,
"\"active\" boolean object with value \"false\" found in response JSON object");
json_decref(result);
return FALSE;
}
} else if (json_is_string(active)) {
if (apr_strnatcasecmp(json_string_value(active), "true") != 0) {
oidc_debug(r,
"\"active\" string object with value that is not equal to \"true\" found in response JSON object: %s",
json_string_value(active));
json_decref(result);
return FALSE;
}
} else {
oidc_debug(r,
"no \"active\" boolean or string object found in response JSON object");
json_decref(result);
return FALSE;
}
if (oidc_oauth_parse_and_cache_token_expiry(r, c, result, "exp",
TRUE, FALSE, &cache_until) == FALSE) {
json_decref(result);
return FALSE;
}
/* set it in the cache so subsequent request don't need to validate the access_token and get the claims anymore */
oidc_oauth_cache_access_token(r, c, cache_until, access_token,
result);
} else {
if (oidc_oauth_parse_and_cache_token_expiry(r, c, result,
c->oauth.introspection_token_expiry_claim_name,
apr_strnatcmp(
c->oauth.introspection_token_expiry_claim_format,
"absolute") == 0,
c->oauth.introspection_token_expiry_claim_required,
&cache_until) == FALSE) {
json_decref(result);
return FALSE;
}
/* set it in the cache so subsequent request don't need to validate the access_token and get the claims anymore */
oidc_oauth_cache_access_token(r, c, cache_until, access_token,
result);
}
}
/* return the access_token JSON object */
json_t *tkn = json_object_get(result, "access_token");
if ((tkn != NULL) && (json_is_object(tkn))) {
/*
* assume PingFederate validation: copy over those claims from the access_token
* that are relevant for authorization purposes
*/
json_object_set(tkn, "client_id", json_object_get(result, "client_id"));
json_object_set(tkn, "scope", json_object_get(result, "scope"));
//oidc_oauth_spaced_string_to_array(r, result, "scope", tkn, "scopes");
/* return only the pimped access_token results */
*token = json_deep_copy(tkn);
json_decref(result);
} else {
//oidc_oauth_spaced_string_to_array(r, result, "scope", result, "scopes");
/* assume spec compliant introspection */
*token = result;
}
char *s_token = json_dumps(*token, 0);
*response = apr_pstrdup(r->pool, s_token);
free(s_token);
return TRUE;
}
/*
* set the unique user identifier that will be propagated in the Apache r->user and REMOTE_USER variables
*/
static apr_byte_t oidc_oauth_set_remote_user(request_rec *r, oidc_cfg *c,
json_t *token) {
/* get the configured claim name to populate REMOTE_USER with (defaults to "Username") */
char *claim_name = apr_pstrdup(r->pool,
c->oauth.remote_user_claim.claim_name);
/* get the claim value from the resolved token JSON response to use as the REMOTE_USER key */
json_t *username = json_object_get(token, claim_name);
if ((username == NULL) || (!json_is_string(username))) {
oidc_warn(r, "response JSON object did not contain a \"%s\" string",
claim_name);
return FALSE;
}
r->user = apr_pstrdup(r->pool, json_string_value(username));
if (c->oauth.remote_user_claim.reg_exp != NULL) {
char *error_str = NULL;
if (oidc_util_regexp_first_match(r->pool, r->user,
c->oauth.remote_user_claim.reg_exp, &r->user,
&error_str) == FALSE) {
oidc_error(r, "oidc_util_regexp_first_match failed: %s", error_str);
r->user = NULL;
return FALSE;
}
}
oidc_debug(r, "set REMOTE_USER to claim %s=%s", claim_name,
json_string_value(username));
return TRUE;
}
/*
* validate a JWT access token (locally)
*
* TODO: document that we're reusing the following settings from the OIDC config section:
* - JWKs URI refresh interval
* - encryption key material (OIDCPrivateKeyFiles)
* - iat slack (OIDCIDTokenIatSlack)
*
* OIDCOAuthRemoteUserClaim client_id
* # 32x 61 hex
* OIDCOAuthVerifySharedKeys aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
*/
static apr_byte_t oidc_oauth_validate_jwt_access_token(request_rec *r,
oidc_cfg *c, const char *access_token, json_t **token, char **response) {
oidc_debug(r, "enter: JWT access_token header=%s",
oidc_proto_peek_jwt_header(r, access_token, NULL));
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret, 0, NULL,
TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwt_t *jwt = NULL;
if (oidc_jwt_parse(r->pool, access_token, &jwt,
oidc_util_merge_symmetric_key(r->pool, c->private_keys, jwk),
&err) == FALSE) {
oidc_error(r, "could not parse JWT from access_token: %s",
oidc_jose_e2s(r->pool, err));
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully parsed JWT with header: %s",
jwt->header.value.str);
/* validate the access token JWT, validating optional exp + iat */
if (oidc_proto_validate_jwt(r, jwt, NULL, FALSE, FALSE,
c->provider.idtoken_iat_slack) == FALSE) {
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_debug(r,
"verify JWT against %d statically configured public keys and %d shared keys, with JWKs URI set to %s",
c->oauth.verify_public_keys ?
apr_hash_count(c->oauth.verify_public_keys) : 0,
c->oauth.verify_shared_keys ?
apr_hash_count(c->oauth.verify_shared_keys) : 0,
c->oauth.verify_jwks_uri);
oidc_jwks_uri_t jwks_uri = { c->oauth.verify_jwks_uri,
c->provider.jwks_refresh_interval, c->oauth.ssl_validate_server };
if (oidc_proto_jwt_verify(r, c, jwt, &jwks_uri,
oidc_util_merge_key_sets(r->pool, c->oauth.verify_public_keys,
c->oauth.verify_shared_keys)) == FALSE) {
oidc_error(r,
"JWT access token signature could not be validated, aborting");
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_debug(r, "successfully verified JWT access token: %s",
jwt->payload.value.str);
*token = jwt->payload.value.json;
*response = jwt->payload.value.str;
return TRUE;
}
/*
* set the WWW-Authenticate response header according to https://tools.ietf.org/html/rfc6750#section-3
*/
int oidc_oauth_return_www_authenticate(request_rec *r, const char *error,
const char *error_description) {
char *hdr = apr_psprintf(r->pool, "Bearer");
if (ap_auth_name(r) != NULL)
hdr = apr_psprintf(r->pool, "%s realm=\"%s\"", hdr, ap_auth_name(r));
if (error != NULL)
hdr = apr_psprintf(r->pool, "%s%s error=\"%s\"", hdr,
(ap_auth_name(r) ? "," : ""), error);
if (error_description != NULL)
hdr = apr_psprintf(r->pool, "%s, error_description=\"%s\"", hdr,
error_description);
apr_table_setn(r->err_headers_out, "WWW-Authenticate", hdr);
return HTTP_UNAUTHORIZED;
}
/*
* main routine: handle OAuth 2.0 authentication/authorization
*/
int oidc_oauth_check_userid(request_rec *r, oidc_cfg *c) {
/* check if this is a sub-request or an initial request */
if (!ap_is_initial_req(r)) {
if (r->main != NULL)
r->user = r->main->user;
else if (r->prev != NULL)
r->user = r->prev->user;
if (r->user != NULL) {
/* this is a sub-request and we have a session */
oidc_debug(r,
"recycling user '%s' from initial request for sub-request",
r->user);
return OK;
}
/* check if this is a request for the public (encryption) keys */
} else if ((c->redirect_uri != NULL)
&& (oidc_util_request_matches_url(r, c->redirect_uri))) {
if (oidc_util_request_has_parameter(r, "jwks")) {
return oidc_handle_jwks(r, c);
}
}
/* we don't have a session yet */
/* get the bearer access token from the Authorization header */
const char *access_token = NULL;
if (oidc_oauth_get_bearer_token(r, &access_token) == FALSE)
return oidc_oauth_return_www_authenticate(r, "invalid_request",
"No bearer token found in the request");
/* validate the obtained access token against the OAuth AS validation endpoint */
json_t *token = NULL;
char *s_token = NULL;
/* check if an introspection endpoint is set */
if (c->oauth.introspection_endpoint_url != NULL) {
/* we'll validate the token remotely */
if (oidc_oauth_resolve_access_token(r, c, access_token, &token,
&s_token) == FALSE)
return oidc_oauth_return_www_authenticate(r, "invalid_token",
"Reference token could not be introspected");
} else {
/* no introspection endpoint is set, assume the token is a JWT and validate it locally */
if (oidc_oauth_validate_jwt_access_token(r, c, access_token, &token,
&s_token) == FALSE)
return oidc_oauth_return_www_authenticate(r, "invalid_token",
"JWT token could not be validated");
}
/* check that we've got something back */
if (token == NULL) {
oidc_error(r, "could not resolve claims (token == NULL)");
return oidc_oauth_return_www_authenticate(r, "invalid_token",
"No claims could be parsed from the token");
}
/* store the parsed token (cq. the claims from the response) in the request state so it can be accessed by the authz routines */
oidc_request_state_set(r, OIDC_CLAIMS_SESSION_KEY, (const char *) s_token);
/* set the REMOTE_USER variable */
if (oidc_oauth_set_remote_user(r, c, token) == FALSE) {
oidc_error(r,
"remote user could not be set, aborting with HTTP_UNAUTHORIZED");
return oidc_oauth_return_www_authenticate(r, "invalid_token",
"Could not set remote user");
}
/*
* we're going to pass the information that we have to the application,
* but first we need to scrub the headers that we're going to use for security reasons
*/
oidc_scrub_headers(r);
/* set the user authentication HTTP header if set and required */
char *authn_header = oidc_cfg_dir_authn_header(r);
int pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
int pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
if ((r->user != NULL) && (authn_header != NULL)) {
oidc_debug(r, "setting authn header (%s) to: %s", authn_header,
r->user);
apr_table_set(r->headers_in, authn_header, r->user);
}
/* set the resolved claims in the HTTP headers for the target application */
oidc_util_set_app_infos(r, token, c->claim_prefix, c->claim_delimiter,
pass_headers, pass_envvars);
/* set the access_token in the app headers */
if (access_token != NULL) {
oidc_util_set_app_info(r, "access_token", access_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* free JSON resources */
json_decref(token);
return OK;
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/good_3184_4 |
crossvul-cpp_data_good_3281_0 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* COPYRIGHT (C) 2006,2007
* THE REGENTS OF THE UNIVERSITY OF MICHIGAN
* ALL RIGHTS RESERVED
*
* Permission is granted to use, copy, create derivative works
* and redistribute this software and such derivative works
* for any purpose, so long as the name of The University of
* Michigan is not used in any advertising or publicity
* pertaining to the use of distribution of this software
* without specific, written prior authorization. If the
* above copyright notice or any other identification of the
* University of Michigan is included in any copy of any
* portion of this software, then the disclaimer below must
* also be included.
*
* THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION
* FROM THE UNIVERSITY OF MICHIGAN AS TO ITS FITNESS FOR ANY
* PURPOSE, AND WITHOUT WARRANTY BY THE UNIVERSITY OF
* MICHIGAN OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
* REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE LIABLE
* FOR ANY DAMAGES, INCLUDING SPECIAL, INDIRECT, INCIDENTAL, OR
* CONSEQUENTIAL DAMAGES, WITH RESPECT TO ANY CLAIM ARISING
* OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, EVEN
* IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
*/
#include "pkinit_crypto_openssl.h"
#include "k5-buf.h"
#include <dlfcn.h>
#include <unistd.h>
#include <dirent.h>
#include <arpa/inet.h>
static krb5_error_code pkinit_init_pkinit_oids(pkinit_plg_crypto_context );
static void pkinit_fini_pkinit_oids(pkinit_plg_crypto_context );
static krb5_error_code pkinit_init_dh_params(pkinit_plg_crypto_context );
static void pkinit_fini_dh_params(pkinit_plg_crypto_context );
static krb5_error_code pkinit_init_certs(pkinit_identity_crypto_context ctx);
static void pkinit_fini_certs(pkinit_identity_crypto_context ctx);
static krb5_error_code pkinit_init_pkcs11(pkinit_identity_crypto_context ctx);
static void pkinit_fini_pkcs11(pkinit_identity_crypto_context ctx);
static krb5_error_code pkinit_encode_dh_params
(const BIGNUM *, const BIGNUM *, const BIGNUM *, uint8_t **, unsigned int *);
static DH *decode_dh_params(const uint8_t *, unsigned int );
static int pkinit_check_dh_params(DH *dh1, DH *dh2);
static krb5_error_code pkinit_sign_data
(krb5_context context, pkinit_identity_crypto_context cryptoctx,
unsigned char *data, unsigned int data_len,
unsigned char **sig, unsigned int *sig_len);
static krb5_error_code create_signature
(unsigned char **, unsigned int *, unsigned char *, unsigned int,
EVP_PKEY *pkey);
static krb5_error_code pkinit_decode_data
(krb5_context context, pkinit_identity_crypto_context cryptoctx,
const uint8_t *data, unsigned int data_len, uint8_t **decoded,
unsigned int *decoded_len);
#ifdef DEBUG_DH
static void print_dh(DH *, char *);
static void print_pubkey(BIGNUM *, char *);
#endif
static int prepare_enc_data
(const uint8_t *indata, int indata_len, uint8_t **outdata, int *outdata_len);
static int openssl_callback (int, X509_STORE_CTX *);
static int openssl_callback_ignore_crls (int, X509_STORE_CTX *);
static int pkcs7_decrypt
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
PKCS7 *p7, BIO *bio);
static BIO * pkcs7_dataDecode
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
PKCS7 *p7);
static ASN1_OBJECT * pkinit_pkcs7type2oid
(pkinit_plg_crypto_context plg_cryptoctx, int pkcs7_type);
static krb5_error_code pkinit_create_sequence_of_principal_identifiers
(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int type, krb5_pa_data ***e_data_out);
#ifndef WITHOUT_PKCS11
static krb5_error_code pkinit_find_private_key
(pkinit_identity_crypto_context, CK_ATTRIBUTE_TYPE usage,
CK_OBJECT_HANDLE *objp);
static krb5_error_code pkinit_login
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
CK_TOKEN_INFO *tip, const char *password);
static krb5_error_code pkinit_open_session
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx);
static void * pkinit_C_LoadModule(const char *modname, CK_FUNCTION_LIST_PTR_PTR p11p);
static CK_RV pkinit_C_UnloadModule(void *handle);
#ifdef SILLYDECRYPT
CK_RV pkinit_C_Decrypt
(pkinit_identity_crypto_context id_cryptoctx,
CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen,
CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen);
#endif
static krb5_error_code pkinit_sign_data_pkcs11
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data, unsigned int data_len,
unsigned char **sig, unsigned int *sig_len);
static krb5_error_code pkinit_decode_data_pkcs11
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
const uint8_t *data, unsigned int data_len, uint8_t **decoded_data,
unsigned int *decoded_data_len);
#endif /* WITHOUT_PKCS11 */
static krb5_error_code pkinit_sign_data_fs
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data, unsigned int data_len,
unsigned char **sig, unsigned int *sig_len);
static krb5_error_code pkinit_decode_data_fs
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
const uint8_t *data, unsigned int data_len, uint8_t **decoded_data,
unsigned int *decoded_data_len);
static krb5_error_code
create_krb5_invalidCertificates(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_external_principal_identifier *** ids);
static krb5_error_code
create_identifiers_from_stack(STACK_OF(X509) *sk,
krb5_external_principal_identifier *** ids);
static int
wrap_signeddata(unsigned char *data, unsigned int data_len,
unsigned char **out, unsigned int *out_len);
static char *
pkinit_pkcs11_code_to_text(int err);
#ifdef HAVE_OPENSSL_CMS
/* Use CMS support present in OpenSSL. */
#include <openssl/cms.h>
#define pkinit_CMS_get0_content_signed(_cms) CMS_get0_content(_cms)
#define pkinit_CMS_get0_content_data(_cms) CMS_get0_content(_cms)
#define pkinit_CMS_free1_crls(_sk_x509crl) \
sk_X509_CRL_pop_free((_sk_x509crl), X509_CRL_free)
#define pkinit_CMS_free1_certs(_sk_x509) \
sk_X509_pop_free((_sk_x509), X509_free)
#define pkinit_CMS_SignerInfo_get_cert(_cms,_si,_x509_pp) \
CMS_SignerInfo_get0_algs(_si,NULL,_x509_pp,NULL,NULL)
#else
/* Fake up CMS support using PKCS7. */
#define pkinit_CMS_free1_crls(_stack_of_x509crls) /* Don't free these */
#define pkinit_CMS_free1_certs(_stack_of_x509certs) /* Don't free these */
#define CMS_NO_SIGNER_CERT_VERIFY PKCS7_NOVERIFY
#define CMS_NOATTR PKCS7_NOATTR
#define CMS_ContentInfo PKCS7
#define CMS_SignerInfo PKCS7_SIGNER_INFO
#define d2i_CMS_ContentInfo d2i_PKCS7
#define CMS_get0_type(_p7) ((_p7)->type)
#define pkinit_CMS_get0_content_signed(_p7) (&((_p7)->d.sign->contents->d.other->value.octet_string))
#define pkinit_CMS_get0_content_data(_p7) (&((_p7)->d.other->value.octet_string))
#define CMS_set1_signers_certs(_p7,_stack_of_x509,_uint)
#define CMS_get0_SignerInfos PKCS7_get_signer_info
#define stack_st_CMS_SignerInfo stack_st_PKCS7_SIGNER_INFO
#undef sk_CMS_SignerInfo_value
#define sk_CMS_SignerInfo_value sk_PKCS7_SIGNER_INFO_value
#define CMS_get0_eContentType(_p7) (_p7->d.sign->contents->type)
#define CMS_verify PKCS7_verify
#define CMS_get1_crls(_p7) (_p7->d.sign->crl)
#define CMS_get1_certs(_p7) (_p7->d.sign->cert)
#define CMS_ContentInfo_free(_p7) PKCS7_free(_p7)
#define pkinit_CMS_SignerInfo_get_cert(_p7,_si,_x509_pp) \
(*_x509_pp) = PKCS7_cert_from_signer_info(_p7,_si)
#endif
#if OPENSSL_VERSION_NUMBER < 0x10100000L
/* 1.1 standardizes constructor and destructor names, renaming
* EVP_MD_CTX_{create,destroy} and deprecating ASN1_STRING_data. */
#define EVP_MD_CTX_new EVP_MD_CTX_create
#define EVP_MD_CTX_free EVP_MD_CTX_destroy
#define ASN1_STRING_get0_data ASN1_STRING_data
/* 1.1 makes many handle types opaque and adds accessors. Add compatibility
* versions of the new accessors we use for pre-1.1. */
#define OBJ_get0_data(o) ((o)->data)
#define OBJ_length(o) ((o)->length)
#define DH_set0_pqg compat_dh_set0_pqg
static int compat_dh_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g)
{
/* The real function frees the old values and does argument checking, but
* our code doesn't need that. */
dh->p = p;
dh->q = q;
dh->g = g;
return 1;
}
#define DH_get0_pqg compat_dh_get0_pqg
static void compat_dh_get0_pqg(const DH *dh, const BIGNUM **p,
const BIGNUM **q, const BIGNUM **g)
{
if (p != NULL)
*p = dh->p;
if (q != NULL)
*q = dh->q;
if (g != NULL)
*g = dh->g;
}
#define DH_get0_key compat_dh_get0_key
static void compat_dh_get0_key(const DH *dh, const BIGNUM **pub,
const BIGNUM **priv)
{
if (pub != NULL)
*pub = dh->pub_key;
if (priv != NULL)
*priv = dh->priv_key;
}
/* Return true if the cert c includes a key usage which doesn't include u.
* Define using direct member access for pre-1.1. */
#define ku_reject(c, u) \
(((c)->ex_flags & EXFLAG_KUSAGE) && !((c)->ex_kusage & (u)))
#else /* OPENSSL_VERSION_NUMBER >= 0x10100000L */
/* Return true if the cert x includes a key usage which doesn't include u. */
#define ku_reject(c, u) (!(X509_get_key_usage(c) & (u)))
#endif
static struct pkcs11_errstrings {
short code;
char *text;
} pkcs11_errstrings[] = {
{ 0x0, "ok" },
{ 0x1, "cancel" },
{ 0x2, "host memory" },
{ 0x3, "slot id invalid" },
{ 0x5, "general error" },
{ 0x6, "function failed" },
{ 0x7, "arguments bad" },
{ 0x8, "no event" },
{ 0x9, "need to create threads" },
{ 0xa, "cant lock" },
{ 0x10, "attribute read only" },
{ 0x11, "attribute sensitive" },
{ 0x12, "attribute type invalid" },
{ 0x13, "attribute value invalid" },
{ 0x20, "data invalid" },
{ 0x21, "data len range" },
{ 0x30, "device error" },
{ 0x31, "device memory" },
{ 0x32, "device removed" },
{ 0x40, "encrypted data invalid" },
{ 0x41, "encrypted data len range" },
{ 0x50, "function canceled" },
{ 0x51, "function not parallel" },
{ 0x54, "function not supported" },
{ 0x60, "key handle invalid" },
{ 0x62, "key size range" },
{ 0x63, "key type inconsistent" },
{ 0x64, "key not needed" },
{ 0x65, "key changed" },
{ 0x66, "key needed" },
{ 0x67, "key indigestible" },
{ 0x68, "key function not permitted" },
{ 0x69, "key not wrappable" },
{ 0x6a, "key unextractable" },
{ 0x70, "mechanism invalid" },
{ 0x71, "mechanism param invalid" },
{ 0x82, "object handle invalid" },
{ 0x90, "operation active" },
{ 0x91, "operation not initialized" },
{ 0xa0, "pin incorrect" },
{ 0xa1, "pin invalid" },
{ 0xa2, "pin len range" },
{ 0xa3, "pin expired" },
{ 0xa4, "pin locked" },
{ 0xb0, "session closed" },
{ 0xb1, "session count" },
{ 0xb3, "session handle invalid" },
{ 0xb4, "session parallel not supported" },
{ 0xb5, "session read only" },
{ 0xb6, "session exists" },
{ 0xb7, "session read only exists" },
{ 0xb8, "session read write so exists" },
{ 0xc0, "signature invalid" },
{ 0xc1, "signature len range" },
{ 0xd0, "template incomplete" },
{ 0xd1, "template inconsistent" },
{ 0xe0, "token not present" },
{ 0xe1, "token not recognized" },
{ 0xe2, "token write protected" },
{ 0xf0, "unwrapping key handle invalid" },
{ 0xf1, "unwrapping key size range" },
{ 0xf2, "unwrapping key type inconsistent" },
{ 0x100, "user already logged in" },
{ 0x101, "user not logged in" },
{ 0x102, "user pin not initialized" },
{ 0x103, "user type invalid" },
{ 0x104, "user another already logged in" },
{ 0x105, "user too many types" },
{ 0x110, "wrapped key invalid" },
{ 0x112, "wrapped key len range" },
{ 0x113, "wrapping key handle invalid" },
{ 0x114, "wrapping key size range" },
{ 0x115, "wrapping key type inconsistent" },
{ 0x120, "random seed not supported" },
{ 0x121, "random no rng" },
{ 0x130, "domain params invalid" },
{ 0x150, "buffer too small" },
{ 0x160, "saved state invalid" },
{ 0x170, "information sensitive" },
{ 0x180, "state unsaveable" },
{ 0x190, "cryptoki not initialized" },
{ 0x191, "cryptoki already initialized" },
{ 0x1a0, "mutex bad" },
{ 0x1a1, "mutex not locked" },
{ 0x200, "function rejected" },
{ -1, NULL }
};
/* DH parameters */
static uint8_t oakley_1024[128] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1,
0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22,
0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B,
0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45,
0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B,
0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5,
0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE6, 0x53, 0x81,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t oakley_2048[2048/8] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1,
0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22,
0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B,
0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45,
0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B,
0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5,
0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D,
0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,
0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A,
0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,
0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96,
0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,
0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D,
0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,
0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C,
0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B,
0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03,
0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F,
0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9,
0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18,
0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5,
0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10,
0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAC, 0xAA, 0x68,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t oakley_4096[4096/8] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1,
0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22,
0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B,
0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45,
0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B,
0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5,
0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D,
0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,
0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A,
0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,
0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96,
0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,
0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D,
0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,
0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C,
0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B,
0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03,
0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F,
0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9,
0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18,
0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5,
0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10,
0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D,
0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33,
0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64,
0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A,
0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D,
0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7,
0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7,
0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D,
0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B,
0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64,
0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64,
0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C,
0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C,
0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2,
0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31,
0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E,
0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x21, 0x08, 0x01,
0x1A, 0x72, 0x3C, 0x12, 0xA7, 0x87, 0xE6, 0xD7,
0x88, 0x71, 0x9A, 0x10, 0xBD, 0xBA, 0x5B, 0x26,
0x99, 0xC3, 0x27, 0x18, 0x6A, 0xF4, 0xE2, 0x3C,
0x1A, 0x94, 0x68, 0x34, 0xB6, 0x15, 0x0B, 0xDA,
0x25, 0x83, 0xE9, 0xCA, 0x2A, 0xD4, 0x4C, 0xE8,
0xDB, 0xBB, 0xC2, 0xDB, 0x04, 0xDE, 0x8E, 0xF9,
0x2E, 0x8E, 0xFC, 0x14, 0x1F, 0xBE, 0xCA, 0xA6,
0x28, 0x7C, 0x59, 0x47, 0x4E, 0x6B, 0xC0, 0x5D,
0x99, 0xB2, 0x96, 0x4F, 0xA0, 0x90, 0xC3, 0xA2,
0x23, 0x3B, 0xA1, 0x86, 0x51, 0x5B, 0xE7, 0xED,
0x1F, 0x61, 0x29, 0x70, 0xCE, 0xE2, 0xD7, 0xAF,
0xB8, 0x1B, 0xDD, 0x76, 0x21, 0x70, 0x48, 0x1C,
0xD0, 0x06, 0x91, 0x27, 0xD5, 0xB0, 0x5A, 0xA9,
0x93, 0xB4, 0xEA, 0x98, 0x8D, 0x8F, 0xDD, 0xC1,
0x86, 0xFF, 0xB7, 0xDC, 0x90, 0xA6, 0xC0, 0x8F,
0x4D, 0xF4, 0x35, 0xC9, 0x34, 0x06, 0x31, 0x99,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
MAKE_INIT_FUNCTION(pkinit_openssl_init);
static krb5_error_code oerr(krb5_context context, krb5_error_code code,
const char *fmt, ...)
#if !defined(__cplusplus) && (__GNUC__ > 2)
__attribute__((__format__(__printf__, 3, 4)))
#endif
;
/*
* Set an error string containing the formatted arguments and the first pending
* OpenSSL error. Write the formatted arguments and all pending OpenSSL error
* messages to the trace log. Return code, or KRB5KDC_ERR_PREAUTH_FAILED if
* code is 0.
*/
static krb5_error_code
oerr(krb5_context context, krb5_error_code code, const char *fmt, ...)
{
unsigned long err;
va_list ap;
char *str, buf[128];
int r;
if (!code)
code = KRB5KDC_ERR_PREAUTH_FAILED;
va_start(ap, fmt);
r = vasprintf(&str, fmt, ap);
va_end(ap);
if (r < 0)
return code;
err = ERR_peek_error();
if (err) {
krb5_set_error_message(context, code, _("%s: %s"), str,
ERR_reason_error_string(err));
} else {
krb5_set_error_message(context, code, "%s", str);
}
TRACE_PKINIT_OPENSSL_ERROR(context, str);
while ((err = ERR_get_error()) != 0) {
ERR_error_string_n(err, buf, sizeof(buf));
TRACE_PKINIT_OPENSSL_ERROR(context, buf);
}
free(str);
return code;
}
/*
* Set an appropriate error string containing msg for a certificate
* verification failure from certctx. Write the message and all pending
* OpenSSL error messages to the trace log. Return code, or
* KRB5KDC_ERR_PREAUTH_FAILED if code is 0.
*/
static krb5_error_code
oerr_cert(krb5_context context, krb5_error_code code, X509_STORE_CTX *certctx,
const char *msg)
{
int depth = X509_STORE_CTX_get_error_depth(certctx);
int err = X509_STORE_CTX_get_error(certctx);
const char *errstr = X509_verify_cert_error_string(err);
return oerr(context, code, _("%s (depth %d): %s"), msg, depth, errstr);
}
krb5_error_code
pkinit_init_plg_crypto(pkinit_plg_crypto_context *cryptoctx)
{
krb5_error_code retval = ENOMEM;
pkinit_plg_crypto_context ctx = NULL;
(void)CALL_INIT_FUNCTION(pkinit_openssl_init);
ctx = malloc(sizeof(*ctx));
if (ctx == NULL)
goto out;
memset(ctx, 0, sizeof(*ctx));
pkiDebug("%s: initializing openssl crypto context at %p\n",
__FUNCTION__, ctx);
retval = pkinit_init_pkinit_oids(ctx);
if (retval)
goto out;
retval = pkinit_init_dh_params(ctx);
if (retval)
goto out;
*cryptoctx = ctx;
out:
if (retval && ctx != NULL)
pkinit_fini_plg_crypto(ctx);
return retval;
}
void
pkinit_fini_plg_crypto(pkinit_plg_crypto_context cryptoctx)
{
pkiDebug("%s: freeing context at %p\n", __FUNCTION__, cryptoctx);
if (cryptoctx == NULL)
return;
pkinit_fini_pkinit_oids(cryptoctx);
pkinit_fini_dh_params(cryptoctx);
free(cryptoctx);
}
krb5_error_code
pkinit_init_identity_crypto(pkinit_identity_crypto_context *idctx)
{
krb5_error_code retval = ENOMEM;
pkinit_identity_crypto_context ctx = NULL;
ctx = malloc(sizeof(*ctx));
if (ctx == NULL)
goto out;
memset(ctx, 0, sizeof(*ctx));
ctx->identity = NULL;
retval = pkinit_init_certs(ctx);
if (retval)
goto out;
retval = pkinit_init_pkcs11(ctx);
if (retval)
goto out;
pkiDebug("%s: returning ctx at %p\n", __FUNCTION__, ctx);
*idctx = ctx;
out:
if (retval) {
if (ctx)
pkinit_fini_identity_crypto(ctx);
}
return retval;
}
void
pkinit_fini_identity_crypto(pkinit_identity_crypto_context idctx)
{
if (idctx == NULL)
return;
pkiDebug("%s: freeing ctx at %p\n", __FUNCTION__, idctx);
if (idctx->deferred_ids != NULL)
pkinit_free_deferred_ids(idctx->deferred_ids);
free(idctx->identity);
pkinit_fini_certs(idctx);
pkinit_fini_pkcs11(idctx);
free(idctx);
}
krb5_error_code
pkinit_init_req_crypto(pkinit_req_crypto_context *cryptoctx)
{
krb5_error_code retval = ENOMEM;
pkinit_req_crypto_context ctx = NULL;
ctx = malloc(sizeof(*ctx));
if (ctx == NULL)
goto out;
memset(ctx, 0, sizeof(*ctx));
ctx->dh = NULL;
ctx->received_cert = NULL;
*cryptoctx = ctx;
pkiDebug("%s: returning ctx at %p\n", __FUNCTION__, ctx);
retval = 0;
out:
if (retval)
free(ctx);
return retval;
}
void
pkinit_fini_req_crypto(pkinit_req_crypto_context req_cryptoctx)
{
if (req_cryptoctx == NULL)
return;
pkiDebug("%s: freeing ctx at %p\n", __FUNCTION__, req_cryptoctx);
if (req_cryptoctx->dh != NULL)
DH_free(req_cryptoctx->dh);
if (req_cryptoctx->received_cert != NULL)
X509_free(req_cryptoctx->received_cert);
free(req_cryptoctx);
}
static krb5_error_code
pkinit_init_pkinit_oids(pkinit_plg_crypto_context ctx)
{
ctx->id_pkinit_san = OBJ_txt2obj("1.3.6.1.5.2.2", 1);
if (ctx->id_pkinit_san == NULL)
return ENOMEM;
ctx->id_pkinit_authData = OBJ_txt2obj("1.3.6.1.5.2.3.1", 1);
if (ctx->id_pkinit_authData == NULL)
return ENOMEM;
ctx->id_pkinit_DHKeyData = OBJ_txt2obj("1.3.6.1.5.2.3.2", 1);
if (ctx->id_pkinit_DHKeyData == NULL)
return ENOMEM;
ctx->id_pkinit_rkeyData = OBJ_txt2obj("1.3.6.1.5.2.3.3", 1);
if (ctx->id_pkinit_rkeyData == NULL)
return ENOMEM;
ctx->id_pkinit_KPClientAuth = OBJ_txt2obj("1.3.6.1.5.2.3.4", 1);
if (ctx->id_pkinit_KPClientAuth == NULL)
return ENOMEM;
ctx->id_pkinit_KPKdc = OBJ_txt2obj("1.3.6.1.5.2.3.5", 1);
if (ctx->id_pkinit_KPKdc == NULL)
return ENOMEM;
ctx->id_ms_kp_sc_logon = OBJ_txt2obj("1.3.6.1.4.1.311.20.2.2", 1);
if (ctx->id_ms_kp_sc_logon == NULL)
return ENOMEM;
ctx->id_ms_san_upn = OBJ_txt2obj("1.3.6.1.4.1.311.20.2.3", 1);
if (ctx->id_ms_san_upn == NULL)
return ENOMEM;
ctx->id_kp_serverAuth = OBJ_txt2obj("1.3.6.1.5.5.7.3.1", 1);
if (ctx->id_kp_serverAuth == NULL)
return ENOMEM;
return 0;
}
static krb5_error_code
get_cert(char *filename, X509 **retcert)
{
X509 *cert = NULL;
BIO *tmp = NULL;
int code;
krb5_error_code retval;
if (filename == NULL || retcert == NULL)
return EINVAL;
*retcert = NULL;
tmp = BIO_new(BIO_s_file());
if (tmp == NULL)
return ENOMEM;
code = BIO_read_filename(tmp, filename);
if (code == 0) {
retval = errno;
goto cleanup;
}
cert = (X509 *) PEM_read_bio_X509(tmp, NULL, NULL, NULL);
if (cert == NULL) {
retval = EIO;
pkiDebug("failed to read certificate from %s\n", filename);
goto cleanup;
}
*retcert = cert;
retval = 0;
cleanup:
if (tmp != NULL)
BIO_free(tmp);
return retval;
}
struct get_key_cb_data {
krb5_context context;
pkinit_identity_crypto_context id_cryptoctx;
const char *fsname;
char *filename;
const char *password;
};
static int
get_key_cb(char *buf, int size, int rwflag, void *userdata)
{
struct get_key_cb_data *data = userdata;
pkinit_identity_crypto_context id_cryptoctx;
krb5_data rdat;
krb5_prompt kprompt;
krb5_prompt_type prompt_type;
krb5_error_code retval;
char *prompt;
if (data->id_cryptoctx->defer_id_prompt) {
/* Supply the identity name to be passed to a responder callback. */
pkinit_set_deferred_id(&data->id_cryptoctx->deferred_ids,
data->fsname, 0, NULL);
return -1;
}
if (data->password == NULL) {
/* We don't already have a password to use, so prompt for one. */
if (data->id_cryptoctx->prompter == NULL)
return -1;
if (asprintf(&prompt, "%s %s", _("Pass phrase for"),
data->filename) < 0)
return -1;
rdat.data = buf;
rdat.length = size;
kprompt.prompt = prompt;
kprompt.hidden = 1;
kprompt.reply = &rdat;
prompt_type = KRB5_PROMPT_TYPE_PREAUTH;
/* PROMPTER_INVOCATION */
k5int_set_prompt_types(data->context, &prompt_type);
id_cryptoctx = data->id_cryptoctx;
retval = (data->id_cryptoctx->prompter)(data->context,
id_cryptoctx->prompter_data,
NULL, NULL, 1, &kprompt);
k5int_set_prompt_types(data->context, 0);
free(prompt);
if (retval != 0)
return -1;
} else {
/* Just use the already-supplied password. */
rdat.length = strlen(data->password);
if ((int)rdat.length >= size)
return -1;
snprintf(buf, size, "%s", data->password);
}
return (int)rdat.length;
}
static krb5_error_code
get_key(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
char *filename, const char *fsname, EVP_PKEY **retkey,
const char *password)
{
EVP_PKEY *pkey = NULL;
BIO *tmp = NULL;
struct get_key_cb_data cb_data;
int code;
krb5_error_code retval;
if (filename == NULL || retkey == NULL)
return EINVAL;
tmp = BIO_new(BIO_s_file());
if (tmp == NULL)
return ENOMEM;
code = BIO_read_filename(tmp, filename);
if (code == 0) {
retval = errno;
goto cleanup;
}
cb_data.context = context;
cb_data.id_cryptoctx = id_cryptoctx;
cb_data.filename = filename;
cb_data.fsname = fsname;
cb_data.password = password;
pkey = PEM_read_bio_PrivateKey(tmp, NULL, get_key_cb, &cb_data);
if (pkey == NULL && !id_cryptoctx->defer_id_prompt) {
retval = EIO;
pkiDebug("failed to read private key from %s\n", filename);
goto cleanup;
}
*retkey = pkey;
retval = 0;
cleanup:
if (tmp != NULL)
BIO_free(tmp);
return retval;
}
static void
pkinit_fini_pkinit_oids(pkinit_plg_crypto_context ctx)
{
if (ctx == NULL)
return;
ASN1_OBJECT_free(ctx->id_pkinit_san);
ASN1_OBJECT_free(ctx->id_pkinit_authData);
ASN1_OBJECT_free(ctx->id_pkinit_DHKeyData);
ASN1_OBJECT_free(ctx->id_pkinit_rkeyData);
ASN1_OBJECT_free(ctx->id_pkinit_KPClientAuth);
ASN1_OBJECT_free(ctx->id_pkinit_KPKdc);
ASN1_OBJECT_free(ctx->id_ms_kp_sc_logon);
ASN1_OBJECT_free(ctx->id_ms_san_upn);
ASN1_OBJECT_free(ctx->id_kp_serverAuth);
}
/* Construct an OpenSSL DH object for an Oakley group. */
static DH *
make_oakley_dh(uint8_t *prime, size_t len)
{
DH *dh = NULL;
BIGNUM *p = NULL, *q = NULL, *g = NULL;
p = BN_bin2bn(prime, len, NULL);
if (p == NULL)
goto cleanup;
q = BN_new();
if (q == NULL)
goto cleanup;
if (!BN_rshift1(q, p))
goto cleanup;
g = BN_new();
if (g == NULL)
goto cleanup;
if (!BN_set_word(g, DH_GENERATOR_2))
goto cleanup;
dh = DH_new();
if (dh == NULL)
goto cleanup;
DH_set0_pqg(dh, p, q, g);
p = g = q = NULL;
cleanup:
BN_free(p);
BN_free(q);
BN_free(g);
return dh;
}
static krb5_error_code
pkinit_init_dh_params(pkinit_plg_crypto_context plgctx)
{
krb5_error_code retval = ENOMEM;
plgctx->dh_1024 = make_oakley_dh(oakley_1024, sizeof(oakley_1024));
if (plgctx->dh_1024 == NULL)
goto cleanup;
plgctx->dh_2048 = make_oakley_dh(oakley_2048, sizeof(oakley_2048));
if (plgctx->dh_2048 == NULL)
goto cleanup;
plgctx->dh_4096 = make_oakley_dh(oakley_4096, sizeof(oakley_4096));
if (plgctx->dh_4096 == NULL)
goto cleanup;
retval = 0;
cleanup:
if (retval)
pkinit_fini_dh_params(plgctx);
return retval;
}
static void
pkinit_fini_dh_params(pkinit_plg_crypto_context plgctx)
{
if (plgctx->dh_1024 != NULL)
DH_free(plgctx->dh_1024);
if (plgctx->dh_2048 != NULL)
DH_free(plgctx->dh_2048);
if (plgctx->dh_4096 != NULL)
DH_free(plgctx->dh_4096);
plgctx->dh_1024 = plgctx->dh_2048 = plgctx->dh_4096 = NULL;
}
static krb5_error_code
pkinit_init_certs(pkinit_identity_crypto_context ctx)
{
krb5_error_code retval = ENOMEM;
int i;
for (i = 0; i < MAX_CREDS_ALLOWED; i++)
ctx->creds[i] = NULL;
ctx->my_certs = NULL;
ctx->cert_index = 0;
ctx->my_key = NULL;
ctx->trustedCAs = NULL;
ctx->intermediateCAs = NULL;
ctx->revoked = NULL;
retval = 0;
return retval;
}
static void
pkinit_fini_certs(pkinit_identity_crypto_context ctx)
{
if (ctx == NULL)
return;
if (ctx->my_certs != NULL)
sk_X509_pop_free(ctx->my_certs, X509_free);
if (ctx->my_key != NULL)
EVP_PKEY_free(ctx->my_key);
if (ctx->trustedCAs != NULL)
sk_X509_pop_free(ctx->trustedCAs, X509_free);
if (ctx->intermediateCAs != NULL)
sk_X509_pop_free(ctx->intermediateCAs, X509_free);
if (ctx->revoked != NULL)
sk_X509_CRL_pop_free(ctx->revoked, X509_CRL_free);
}
static krb5_error_code
pkinit_init_pkcs11(pkinit_identity_crypto_context ctx)
{
krb5_error_code retval = ENOMEM;
#ifndef WITHOUT_PKCS11
ctx->p11_module_name = strdup(PKCS11_MODNAME);
if (ctx->p11_module_name == NULL)
return retval;
ctx->p11_module = NULL;
ctx->slotid = PK_NOSLOT;
ctx->token_label = NULL;
ctx->cert_label = NULL;
ctx->session = CK_INVALID_HANDLE;
ctx->p11 = NULL;
#endif
ctx->pkcs11_method = 0;
retval = 0;
return retval;
}
static void
pkinit_fini_pkcs11(pkinit_identity_crypto_context ctx)
{
#ifndef WITHOUT_PKCS11
if (ctx == NULL)
return;
if (ctx->p11 != NULL) {
if (ctx->session != CK_INVALID_HANDLE) {
ctx->p11->C_CloseSession(ctx->session);
ctx->session = CK_INVALID_HANDLE;
}
ctx->p11->C_Finalize(NULL_PTR);
ctx->p11 = NULL;
}
if (ctx->p11_module != NULL) {
pkinit_C_UnloadModule(ctx->p11_module);
ctx->p11_module = NULL;
}
free(ctx->p11_module_name);
free(ctx->token_label);
free(ctx->cert_id);
free(ctx->cert_label);
#endif
}
krb5_error_code
pkinit_identity_set_prompter(pkinit_identity_crypto_context id_cryptoctx,
krb5_prompter_fct prompter,
void *prompter_data)
{
id_cryptoctx->prompter = prompter;
id_cryptoctx->prompter_data = prompter_data;
return 0;
}
/* Create a CMS ContentInfo of type oid containing the octet string in data. */
static krb5_error_code
create_contentinfo(krb5_context context, ASN1_OBJECT *oid,
unsigned char *data, size_t data_len, PKCS7 **p7_out)
{
PKCS7 *p7 = NULL;
ASN1_OCTET_STRING *ostr = NULL;
*p7_out = NULL;
ostr = ASN1_OCTET_STRING_new();
if (ostr == NULL)
goto oom;
if (!ASN1_OCTET_STRING_set(ostr, (unsigned char *)data, data_len))
goto oom;
p7 = PKCS7_new();
if (p7 == NULL)
goto oom;
p7->type = OBJ_dup(oid);
if (p7->type == NULL)
goto oom;
if (OBJ_obj2nid(oid) == NID_pkcs7_data) {
/* Draft 9 uses id-pkcs7-data for signed data. For this type OpenSSL
* expects an octet string in d.data. */
p7->d.data = ostr;
} else {
p7->d.other = ASN1_TYPE_new();
if (p7->d.other == NULL)
goto oom;
p7->d.other->type = V_ASN1_OCTET_STRING;
p7->d.other->value.octet_string = ostr;
}
*p7_out = p7;
return 0;
oom:
if (ostr != NULL)
ASN1_OCTET_STRING_free(ostr);
if (p7 != NULL)
PKCS7_free(p7);
return ENOMEM;
}
krb5_error_code
cms_contentinfo_create(krb5_context context, /* IN */
pkinit_plg_crypto_context plg_cryptoctx, /* IN */
pkinit_req_crypto_context req_cryptoctx, /* IN */
pkinit_identity_crypto_context id_cryptoctx, /* IN */
int cms_msg_type,
unsigned char *data, unsigned int data_len,
unsigned char **out_data, unsigned int *out_data_len)
{
krb5_error_code retval = ENOMEM;
ASN1_OBJECT *oid;
PKCS7 *p7 = NULL;
unsigned char *p;
/* Pick the correct oid for the eContentInfo. */
oid = pkinit_pkcs7type2oid(plg_cryptoctx, cms_msg_type);
if (oid == NULL)
goto cleanup;
retval = create_contentinfo(context, oid, data, data_len, &p7);
if (retval != 0)
goto cleanup;
*out_data_len = i2d_PKCS7(p7, NULL);
if (!(*out_data_len)) {
retval = oerr(context, 0, _("Failed to DER encode PKCS7"));
goto cleanup;
}
retval = ENOMEM;
if ((p = *out_data = malloc(*out_data_len)) == NULL)
goto cleanup;
/* DER encode PKCS7 data */
retval = i2d_PKCS7(p7, &p);
if (!retval) {
retval = oerr(context, 0, _("Failed to DER encode PKCS7"));
goto cleanup;
}
retval = 0;
cleanup:
if (p7)
PKCS7_free(p7);
return retval;
}
krb5_error_code
cms_signeddata_create(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int cms_msg_type,
int include_certchain,
unsigned char *data,
unsigned int data_len,
unsigned char **signed_data,
unsigned int *signed_data_len)
{
krb5_error_code retval = ENOMEM;
PKCS7 *p7 = NULL, *inner_p7 = NULL;
PKCS7_SIGNED *p7s = NULL;
PKCS7_SIGNER_INFO *p7si = NULL;
unsigned char *p;
STACK_OF(X509) * cert_stack = NULL;
ASN1_OCTET_STRING *digest_attr = NULL;
EVP_MD_CTX *ctx;
const EVP_MD *md_tmp = NULL;
unsigned char md_data[EVP_MAX_MD_SIZE], md_data2[EVP_MAX_MD_SIZE];
unsigned char *digestInfo_buf = NULL, *abuf = NULL;
unsigned int md_len, md_len2, alen, digestInfo_len;
STACK_OF(X509_ATTRIBUTE) * sk;
unsigned char *sig = NULL;
unsigned int sig_len = 0;
X509_ALGOR *alg = NULL;
ASN1_OCTET_STRING *digest = NULL;
unsigned int alg_len = 0, digest_len = 0;
unsigned char *y = NULL;
X509 *cert = NULL;
ASN1_OBJECT *oid = NULL, *oid_copy;
/* Start creating PKCS7 data. */
if ((p7 = PKCS7_new()) == NULL)
goto cleanup;
p7->type = OBJ_nid2obj(NID_pkcs7_signed);
if ((p7s = PKCS7_SIGNED_new()) == NULL)
goto cleanup;
p7->d.sign = p7s;
if (!ASN1_INTEGER_set(p7s->version, 3))
goto cleanup;
/* pick the correct oid for the eContentInfo */
oid = pkinit_pkcs7type2oid(plg_cryptoctx, cms_msg_type);
if (oid == NULL)
goto cleanup;
if (id_cryptoctx->my_certs != NULL) {
/* create a cert chain that has at least the signer's certificate */
if ((cert_stack = sk_X509_new_null()) == NULL)
goto cleanup;
cert = sk_X509_value(id_cryptoctx->my_certs, id_cryptoctx->cert_index);
if (!include_certchain) {
pkiDebug("only including signer's certificate\n");
sk_X509_push(cert_stack, X509_dup(cert));
} else {
/* create a cert chain */
X509_STORE *certstore = NULL;
X509_STORE_CTX *certctx;
STACK_OF(X509) *certstack = NULL;
char buf[DN_BUF_LEN];
unsigned int i = 0, size = 0;
if ((certstore = X509_STORE_new()) == NULL)
goto cleanup;
pkiDebug("building certificate chain\n");
X509_STORE_set_verify_cb(certstore, openssl_callback);
certctx = X509_STORE_CTX_new();
if (certctx == NULL)
goto cleanup;
X509_STORE_CTX_init(certctx, certstore, cert,
id_cryptoctx->intermediateCAs);
X509_STORE_CTX_trusted_stack(certctx, id_cryptoctx->trustedCAs);
if (!X509_verify_cert(certctx)) {
retval = oerr_cert(context, 0, certctx,
_("Failed to verify own certificate"));
goto cleanup;
}
certstack = X509_STORE_CTX_get1_chain(certctx);
size = sk_X509_num(certstack);
pkiDebug("size of certificate chain = %d\n", size);
for(i = 0; i < size - 1; i++) {
X509 *x = sk_X509_value(certstack, i);
X509_NAME_oneline(X509_get_subject_name(x), buf, sizeof(buf));
pkiDebug("cert #%d: %s\n", i, buf);
sk_X509_push(cert_stack, X509_dup(x));
}
X509_STORE_CTX_free(certctx);
X509_STORE_free(certstore);
sk_X509_pop_free(certstack, X509_free);
}
p7s->cert = cert_stack;
/* fill-in PKCS7_SIGNER_INFO */
if ((p7si = PKCS7_SIGNER_INFO_new()) == NULL)
goto cleanup;
if (!ASN1_INTEGER_set(p7si->version, 1))
goto cleanup;
if (!X509_NAME_set(&p7si->issuer_and_serial->issuer,
X509_get_issuer_name(cert)))
goto cleanup;
/* because ASN1_INTEGER_set is used to set a 'long' we will do
* things the ugly way. */
ASN1_INTEGER_free(p7si->issuer_and_serial->serial);
if (!(p7si->issuer_and_serial->serial =
ASN1_INTEGER_dup(X509_get_serialNumber(cert))))
goto cleanup;
/* will not fill-out EVP_PKEY because it's on the smartcard */
/* Set digest algs */
p7si->digest_alg->algorithm = OBJ_nid2obj(NID_sha1);
if (p7si->digest_alg->parameter != NULL)
ASN1_TYPE_free(p7si->digest_alg->parameter);
if ((p7si->digest_alg->parameter = ASN1_TYPE_new()) == NULL)
goto cleanup;
p7si->digest_alg->parameter->type = V_ASN1_NULL;
/* Set sig algs */
if (p7si->digest_enc_alg->parameter != NULL)
ASN1_TYPE_free(p7si->digest_enc_alg->parameter);
p7si->digest_enc_alg->algorithm = OBJ_nid2obj(NID_sha1WithRSAEncryption);
if (!(p7si->digest_enc_alg->parameter = ASN1_TYPE_new()))
goto cleanup;
p7si->digest_enc_alg->parameter->type = V_ASN1_NULL;
if (cms_msg_type == CMS_SIGN_DRAFT9){
/* don't include signed attributes for pa-type 15 request */
abuf = data;
alen = data_len;
} else {
/* add signed attributes */
/* compute sha1 digest over the EncapsulatedContentInfo */
ctx = EVP_MD_CTX_new();
if (ctx == NULL)
goto cleanup;
EVP_DigestInit_ex(ctx, EVP_sha1(), NULL);
EVP_DigestUpdate(ctx, data, data_len);
md_tmp = EVP_MD_CTX_md(ctx);
EVP_DigestFinal_ex(ctx, md_data, &md_len);
EVP_MD_CTX_free(ctx);
/* create a message digest attr */
digest_attr = ASN1_OCTET_STRING_new();
ASN1_OCTET_STRING_set(digest_attr, md_data, (int)md_len);
PKCS7_add_signed_attribute(p7si, NID_pkcs9_messageDigest,
V_ASN1_OCTET_STRING, (char *) digest_attr);
/* create a content-type attr */
oid_copy = OBJ_dup(oid);
if (oid_copy == NULL)
goto cleanup2;
PKCS7_add_signed_attribute(p7si, NID_pkcs9_contentType,
V_ASN1_OBJECT, oid_copy);
/* create the signature over signed attributes. get DER encoded value */
/* This is the place where smartcard signature needs to be calculated */
sk = p7si->auth_attr;
alen = ASN1_item_i2d((ASN1_VALUE *) sk, &abuf,
ASN1_ITEM_rptr(PKCS7_ATTR_SIGN));
if (abuf == NULL)
goto cleanup2;
} /* signed attributes */
#ifndef WITHOUT_PKCS11
/* Some tokens can only do RSAEncryption without sha1 hash */
/* to compute sha1WithRSAEncryption, encode the algorithm ID for the hash
* function and the hash value into an ASN.1 value of type DigestInfo
* DigestInfo::=SEQUENCE {
* digestAlgorithm AlgorithmIdentifier,
* digest OCTET STRING }
*/
if (id_cryptoctx->pkcs11_method == 1 &&
id_cryptoctx->mech == CKM_RSA_PKCS) {
pkiDebug("mech = CKM_RSA_PKCS\n");
ctx = EVP_MD_CTX_new();
if (ctx == NULL)
goto cleanup;
/* if this is not draft9 request, include digest signed attribute */
if (cms_msg_type != CMS_SIGN_DRAFT9)
EVP_DigestInit_ex(ctx, md_tmp, NULL);
else
EVP_DigestInit_ex(ctx, EVP_sha1(), NULL);
EVP_DigestUpdate(ctx, abuf, alen);
EVP_DigestFinal_ex(ctx, md_data2, &md_len2);
EVP_MD_CTX_free(ctx);
alg = X509_ALGOR_new();
if (alg == NULL)
goto cleanup2;
X509_ALGOR_set0(alg, OBJ_nid2obj(NID_sha1), V_ASN1_NULL, NULL);
alg_len = i2d_X509_ALGOR(alg, NULL);
digest = ASN1_OCTET_STRING_new();
if (digest == NULL)
goto cleanup2;
ASN1_OCTET_STRING_set(digest, md_data2, (int)md_len2);
digest_len = i2d_ASN1_OCTET_STRING(digest, NULL);
digestInfo_len = ASN1_object_size(1, (int)(alg_len + digest_len),
V_ASN1_SEQUENCE);
y = digestInfo_buf = malloc(digestInfo_len);
if (digestInfo_buf == NULL)
goto cleanup2;
ASN1_put_object(&y, 1, (int)(alg_len + digest_len), V_ASN1_SEQUENCE,
V_ASN1_UNIVERSAL);
i2d_X509_ALGOR(alg, &y);
i2d_ASN1_OCTET_STRING(digest, &y);
#ifdef DEBUG_SIG
pkiDebug("signing buffer\n");
print_buffer(digestInfo_buf, digestInfo_len);
print_buffer_bin(digestInfo_buf, digestInfo_len, "/tmp/pkcs7_tosign");
#endif
retval = pkinit_sign_data(context, id_cryptoctx, digestInfo_buf,
digestInfo_len, &sig, &sig_len);
} else
#endif
{
pkiDebug("mech = %s\n",
id_cryptoctx->pkcs11_method == 1 ? "CKM_SHA1_RSA_PKCS" : "FS");
retval = pkinit_sign_data(context, id_cryptoctx, abuf, alen,
&sig, &sig_len);
}
#ifdef DEBUG_SIG
print_buffer(sig, sig_len);
#endif
if (cms_msg_type != CMS_SIGN_DRAFT9 )
free(abuf);
if (retval)
goto cleanup2;
/* Add signature */
if (!ASN1_STRING_set(p7si->enc_digest, (unsigned char *) sig,
(int)sig_len)) {
retval = oerr(context, 0, _("Failed to add digest attribute"));
goto cleanup2;
}
/* adder signer_info to pkcs7 signed */
if (!PKCS7_add_signer(p7, p7si))
goto cleanup2;
} /* we have a certificate */
/* start on adding data to the pkcs7 signed */
retval = create_contentinfo(context, oid, data, data_len, &inner_p7);
if (p7s->contents != NULL)
PKCS7_free(p7s->contents);
p7s->contents = inner_p7;
*signed_data_len = i2d_PKCS7(p7, NULL);
if (!(*signed_data_len)) {
retval = oerr(context, 0, _("Failed to DER encode PKCS7"));
goto cleanup2;
}
retval = ENOMEM;
if ((p = *signed_data = malloc(*signed_data_len)) == NULL)
goto cleanup2;
/* DER encode PKCS7 data */
retval = i2d_PKCS7(p7, &p);
if (!retval) {
retval = oerr(context, 0, _("Failed to DER encode PKCS7"));
goto cleanup2;
}
retval = 0;
#ifdef DEBUG_ASN1
if (cms_msg_type == CMS_SIGN_CLIENT) {
print_buffer_bin(*signed_data, *signed_data_len,
"/tmp/client_pkcs7_signeddata");
} else {
if (cms_msg_type == CMS_SIGN_SERVER) {
print_buffer_bin(*signed_data, *signed_data_len,
"/tmp/kdc_pkcs7_signeddata");
} else {
print_buffer_bin(*signed_data, *signed_data_len,
"/tmp/draft9_pkcs7_signeddata");
}
}
#endif
cleanup2:
if (p7si) {
if (cms_msg_type != CMS_SIGN_DRAFT9)
#ifndef WITHOUT_PKCS11
if (id_cryptoctx->pkcs11_method == 1 &&
id_cryptoctx->mech == CKM_RSA_PKCS) {
free(digestInfo_buf);
if (digest != NULL)
ASN1_OCTET_STRING_free(digest);
}
#endif
if (alg != NULL)
X509_ALGOR_free(alg);
}
cleanup:
if (p7 != NULL)
PKCS7_free(p7);
free(sig);
return retval;
}
krb5_error_code
cms_signeddata_verify(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
pkinit_identity_crypto_context idctx,
int cms_msg_type,
int require_crl_checking,
unsigned char *signed_data,
unsigned int signed_data_len,
unsigned char **data,
unsigned int *data_len,
unsigned char **authz_data,
unsigned int *authz_data_len,
int *is_signed)
{
/*
* Warning: Since most openssl functions do not set retval, large chunks of
* this function assume that retval is always a failure and may go to
* cleanup without setting retval explicitly. Make sure retval is not set
* to 0 or errors such as signature verification failure may be converted
* to success with significant security consequences.
*/
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
CMS_ContentInfo *cms = NULL;
BIO *out = NULL;
int flags = CMS_NO_SIGNER_CERT_VERIFY;
int valid_oid = 0;
unsigned int i = 0;
unsigned int vflags = 0, size = 0;
const unsigned char *p = signed_data;
STACK_OF(CMS_SignerInfo) *si_sk = NULL;
CMS_SignerInfo *si = NULL;
X509 *x = NULL;
X509_STORE *store = NULL;
X509_STORE_CTX *cert_ctx;
STACK_OF(X509) *signerCerts = NULL;
STACK_OF(X509) *intermediateCAs = NULL;
STACK_OF(X509_CRL) *signerRevoked = NULL;
STACK_OF(X509_CRL) *revoked = NULL;
STACK_OF(X509) *verified_chain = NULL;
ASN1_OBJECT *oid = NULL;
const ASN1_OBJECT *type = NULL, *etype = NULL;
ASN1_OCTET_STRING **octets;
krb5_external_principal_identifier **krb5_verified_chain = NULL;
krb5_data *authz = NULL;
char buf[DN_BUF_LEN];
#ifdef DEBUG_ASN1
print_buffer_bin(signed_data, signed_data_len,
"/tmp/client_received_pkcs7_signeddata");
#endif
if (is_signed)
*is_signed = 1;
oid = pkinit_pkcs7type2oid(plgctx, cms_msg_type);
if (oid == NULL)
goto cleanup;
/* decode received CMS message */
if ((cms = d2i_CMS_ContentInfo(NULL, &p, (int)signed_data_len)) == NULL) {
retval = oerr(context, 0, _("Failed to decode CMS message"));
goto cleanup;
}
etype = CMS_get0_eContentType(cms);
/*
* Prior to 1.10 the MIT client incorrectly emitted the pkinit structure
* directly in a CMS ContentInfo rather than using SignedData with no
* signers. Handle that case.
*/
type = CMS_get0_type(cms);
if (is_signed && !OBJ_cmp(type, oid)) {
unsigned char *d;
*is_signed = 0;
octets = pkinit_CMS_get0_content_data(cms);
if (!octets || ((*octets)->type != V_ASN1_OCTET_STRING)) {
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval,
_("Invalid pkinit packet: octet string "
"expected"));
goto cleanup;
}
*data_len = ASN1_STRING_length(*octets);
d = malloc(*data_len);
if (d == NULL) {
retval = ENOMEM;
goto cleanup;
}
memcpy(d, ASN1_STRING_get0_data(*octets), *data_len);
*data = d;
goto out;
} else {
/* Verify that the received message is CMS SignedData message. */
if (OBJ_obj2nid(type) != NID_pkcs7_signed) {
pkiDebug("Expected id-signedData CMS msg (received type = %d)\n",
OBJ_obj2nid(type));
krb5_set_error_message(context, retval, _("wrong oid\n"));
goto cleanup;
}
}
/* setup to verify X509 certificate used to sign CMS message */
if (!(store = X509_STORE_new()))
goto cleanup;
/* check if we are inforcing CRL checking */
vflags = X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL;
if (require_crl_checking)
X509_STORE_set_verify_cb(store, openssl_callback);
else
X509_STORE_set_verify_cb(store, openssl_callback_ignore_crls);
X509_STORE_set_flags(store, vflags);
/*
* Get the signer's information from the CMS message. Match signer ID
* against anchors and intermediate CAs in case no certs are present in the
* SignedData. If we start sending kdcPkId values in requests, we'll need
* to match against the source of that information too.
*/
CMS_set1_signers_certs(cms, NULL, 0);
CMS_set1_signers_certs(cms, idctx->trustedCAs, CMS_NOINTERN);
CMS_set1_signers_certs(cms, idctx->intermediateCAs, CMS_NOINTERN);
if (((si_sk = CMS_get0_SignerInfos(cms)) == NULL) ||
((si = sk_CMS_SignerInfo_value(si_sk, 0)) == NULL)) {
/* Not actually signed; anonymous case */
if (!is_signed)
goto cleanup;
*is_signed = 0;
/* We cannot use CMS_dataInit because there may be no digest */
octets = pkinit_CMS_get0_content_signed(cms);
if (octets)
out = BIO_new_mem_buf((*octets)->data, (*octets)->length);
if (out == NULL)
goto cleanup;
} else {
pkinit_CMS_SignerInfo_get_cert(cms, si, &x);
if (x == NULL)
goto cleanup;
/* create available CRL information (get local CRLs and include CRLs
* received in the CMS message
*/
signerRevoked = CMS_get1_crls(cms);
if (idctx->revoked == NULL)
revoked = signerRevoked;
else if (signerRevoked == NULL)
revoked = idctx->revoked;
else {
size = sk_X509_CRL_num(idctx->revoked);
revoked = sk_X509_CRL_new_null();
for (i = 0; i < size; i++)
sk_X509_CRL_push(revoked, sk_X509_CRL_value(idctx->revoked, i));
size = sk_X509_CRL_num(signerRevoked);
for (i = 0; i < size; i++)
sk_X509_CRL_push(revoked, sk_X509_CRL_value(signerRevoked, i));
}
/* create available intermediate CAs chains (get local intermediateCAs and
* include the CA chain received in the CMS message
*/
signerCerts = CMS_get1_certs(cms);
if (idctx->intermediateCAs == NULL)
intermediateCAs = signerCerts;
else if (signerCerts == NULL)
intermediateCAs = idctx->intermediateCAs;
else {
size = sk_X509_num(idctx->intermediateCAs);
intermediateCAs = sk_X509_new_null();
for (i = 0; i < size; i++) {
sk_X509_push(intermediateCAs,
sk_X509_value(idctx->intermediateCAs, i));
}
size = sk_X509_num(signerCerts);
for (i = 0; i < size; i++) {
sk_X509_push(intermediateCAs, sk_X509_value(signerCerts, i));
}
}
/* initialize x509 context with the received certificate and
* trusted and intermediate CA chains and CRLs
*/
cert_ctx = X509_STORE_CTX_new();
if (cert_ctx == NULL)
goto cleanup;
if (!X509_STORE_CTX_init(cert_ctx, store, x, intermediateCAs))
goto cleanup;
X509_STORE_CTX_set0_crls(cert_ctx, revoked);
/* add trusted CAs certificates for cert verification */
if (idctx->trustedCAs != NULL)
X509_STORE_CTX_trusted_stack(cert_ctx, idctx->trustedCAs);
else {
pkiDebug("unable to find any trusted CAs\n");
goto cleanup;
}
#ifdef DEBUG_CERTCHAIN
if (intermediateCAs != NULL) {
size = sk_X509_num(intermediateCAs);
pkiDebug("untrusted cert chain of size %d\n", size);
for (i = 0; i < size; i++) {
X509_NAME_oneline(X509_get_subject_name(
sk_X509_value(intermediateCAs, i)), buf, sizeof(buf));
pkiDebug("cert #%d: %s\n", i, buf);
}
}
if (idctx->trustedCAs != NULL) {
size = sk_X509_num(idctx->trustedCAs);
pkiDebug("trusted cert chain of size %d\n", size);
for (i = 0; i < size; i++) {
X509_NAME_oneline(X509_get_subject_name(
sk_X509_value(idctx->trustedCAs, i)), buf, sizeof(buf));
pkiDebug("cert #%d: %s\n", i, buf);
}
}
if (revoked != NULL) {
size = sk_X509_CRL_num(revoked);
pkiDebug("CRL chain of size %d\n", size);
for (i = 0; i < size; i++) {
X509_CRL *crl = sk_X509_CRL_value(revoked, i);
X509_NAME_oneline(X509_CRL_get_issuer(crl), buf, sizeof(buf));
pkiDebug("crls by CA #%d: %s\n", i , buf);
}
}
#endif
i = X509_verify_cert(cert_ctx);
if (i <= 0) {
int j = X509_STORE_CTX_get_error(cert_ctx);
X509 *cert;
cert = X509_STORE_CTX_get_current_cert(cert_ctx);
reqctx->received_cert = X509_dup(cert);
switch(j) {
case X509_V_ERR_CERT_REVOKED:
retval = KRB5KDC_ERR_REVOKED_CERTIFICATE;
break;
case X509_V_ERR_UNABLE_TO_GET_CRL:
retval = KRB5KDC_ERR_REVOCATION_STATUS_UNKNOWN;
break;
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
retval = KRB5KDC_ERR_CANT_VERIFY_CERTIFICATE;
break;
default:
retval = KRB5KDC_ERR_INVALID_CERTIFICATE;
}
(void)oerr_cert(context, retval, cert_ctx,
_("Failed to verify received certificate"));
if (reqctx->received_cert == NULL)
strlcpy(buf, "(none)", sizeof(buf));
else
X509_NAME_oneline(X509_get_subject_name(reqctx->received_cert),
buf, sizeof(buf));
pkiDebug("problem with cert DN = %s (error=%d) %s\n", buf, j,
X509_verify_cert_error_string(j));
#ifdef DEBUG_CERTCHAIN
size = sk_X509_num(signerCerts);
pkiDebug("received cert chain of size %d\n", size);
for (j = 0; j < size; j++) {
X509 *tmp_cert = sk_X509_value(signerCerts, j);
X509_NAME_oneline(X509_get_subject_name(tmp_cert), buf, sizeof(buf));
pkiDebug("cert #%d: %s\n", j, buf);
}
#endif
} else {
/* retrieve verified certificate chain */
if (cms_msg_type == CMS_SIGN_CLIENT || cms_msg_type == CMS_SIGN_DRAFT9)
verified_chain = X509_STORE_CTX_get1_chain(cert_ctx);
}
X509_STORE_CTX_free(cert_ctx);
if (i <= 0)
goto cleanup;
out = BIO_new(BIO_s_mem());
if (cms_msg_type == CMS_SIGN_DRAFT9)
flags |= CMS_NOATTR;
if (CMS_verify(cms, NULL, store, NULL, out, flags) == 0) {
unsigned long err = ERR_peek_error();
switch(ERR_GET_REASON(err)) {
case PKCS7_R_DIGEST_FAILURE:
retval = KRB5KDC_ERR_DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED;
break;
case PKCS7_R_SIGNATURE_FAILURE:
default:
retval = KRB5KDC_ERR_INVALID_SIG;
}
(void)oerr(context, retval, _("Failed to verify CMS message"));
goto cleanup;
}
} /* message was signed */
if (!OBJ_cmp(etype, oid))
valid_oid = 1;
else if (cms_msg_type == CMS_SIGN_DRAFT9) {
/*
* Various implementations of the pa-type 15 request use
* different OIDS. We check that the returned object
* has any of the acceptable OIDs
*/
ASN1_OBJECT *client_oid = NULL, *server_oid = NULL, *rsa_oid = NULL;
client_oid = pkinit_pkcs7type2oid(plgctx, CMS_SIGN_CLIENT);
server_oid = pkinit_pkcs7type2oid(plgctx, CMS_SIGN_SERVER);
rsa_oid = pkinit_pkcs7type2oid(plgctx, CMS_ENVEL_SERVER);
if (!OBJ_cmp(etype, client_oid) ||
!OBJ_cmp(etype, server_oid) ||
!OBJ_cmp(etype, rsa_oid))
valid_oid = 1;
}
if (valid_oid)
pkiDebug("CMS Verification successful\n");
else {
pkiDebug("wrong oid in eContentType\n");
print_buffer(OBJ_get0_data(etype), OBJ_length(etype));
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval, "wrong oid\n");
goto cleanup;
}
/* transfer the data from CMS message into return buffer */
for (size = 0;;) {
int remain;
retval = ENOMEM;
if ((*data = realloc(*data, size + 1024 * 10)) == NULL)
goto cleanup;
remain = BIO_read(out, &((*data)[size]), 1024 * 10);
if (remain <= 0)
break;
else
size += remain;
}
*data_len = size;
if (x) {
reqctx->received_cert = X509_dup(x);
/* generate authorization data */
if (cms_msg_type == CMS_SIGN_CLIENT || cms_msg_type == CMS_SIGN_DRAFT9) {
if (authz_data == NULL || authz_data_len == NULL)
goto out;
*authz_data = NULL;
retval = create_identifiers_from_stack(verified_chain,
&krb5_verified_chain);
if (retval) {
pkiDebug("create_identifiers_from_stack failed\n");
goto cleanup;
}
retval = k5int_encode_krb5_td_trusted_certifiers((krb5_external_principal_identifier *const *)krb5_verified_chain, &authz);
if (retval) {
pkiDebug("encode_krb5_td_trusted_certifiers failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)authz->data, authz->length,
"/tmp/kdc_ad_initial_verified_cas");
#endif
*authz_data = malloc(authz->length);
if (*authz_data == NULL) {
retval = ENOMEM;
goto cleanup;
}
memcpy(*authz_data, authz->data, authz->length);
*authz_data_len = authz->length;
}
}
out:
retval = 0;
cleanup:
if (out != NULL)
BIO_free(out);
if (store != NULL)
X509_STORE_free(store);
if (cms != NULL) {
if (signerCerts != NULL)
pkinit_CMS_free1_certs(signerCerts);
if (idctx->intermediateCAs != NULL && signerCerts)
sk_X509_free(intermediateCAs);
if (signerRevoked != NULL)
pkinit_CMS_free1_crls(signerRevoked);
if (idctx->revoked != NULL && signerRevoked)
sk_X509_CRL_free(revoked);
CMS_ContentInfo_free(cms);
}
if (verified_chain != NULL)
sk_X509_pop_free(verified_chain, X509_free);
if (krb5_verified_chain != NULL)
free_krb5_external_principal_identifier(&krb5_verified_chain);
if (authz != NULL)
krb5_free_data(context, authz);
return retval;
}
krb5_error_code
cms_envelopeddata_create(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
pkinit_identity_crypto_context idctx,
krb5_preauthtype pa_type,
int include_certchain,
unsigned char *key_pack,
unsigned int key_pack_len,
unsigned char **out,
unsigned int *out_len)
{
krb5_error_code retval = ENOMEM;
PKCS7 *p7 = NULL;
BIO *in = NULL;
unsigned char *p = NULL, *signed_data = NULL, *enc_data = NULL;
int signed_data_len = 0, enc_data_len = 0, flags = PKCS7_BINARY;
STACK_OF(X509) *encerts = NULL;
const EVP_CIPHER *cipher = NULL;
int cms_msg_type;
/* create the PKCS7 SignedData portion of the PKCS7 EnvelopedData */
switch ((int)pa_type) {
case KRB5_PADATA_PK_AS_REQ_OLD:
case KRB5_PADATA_PK_AS_REP_OLD:
cms_msg_type = CMS_SIGN_DRAFT9;
break;
case KRB5_PADATA_PK_AS_REQ:
cms_msg_type = CMS_ENVEL_SERVER;
break;
default:
goto cleanup;
}
retval = cms_signeddata_create(context, plgctx, reqctx, idctx,
cms_msg_type, include_certchain, key_pack, key_pack_len,
&signed_data, (unsigned int *)&signed_data_len);
if (retval) {
pkiDebug("failed to create pkcs7 signed data\n");
goto cleanup;
}
/* check we have client's certificate */
if (reqctx->received_cert == NULL) {
retval = KRB5KDC_ERR_PREAUTH_FAILED;
goto cleanup;
}
encerts = sk_X509_new_null();
sk_X509_push(encerts, reqctx->received_cert);
cipher = EVP_des_ede3_cbc();
in = BIO_new(BIO_s_mem());
switch (pa_type) {
case KRB5_PADATA_PK_AS_REQ:
prepare_enc_data(signed_data, signed_data_len, &enc_data,
&enc_data_len);
retval = BIO_write(in, enc_data, enc_data_len);
if (retval != enc_data_len) {
pkiDebug("BIO_write only wrote %d\n", retval);
goto cleanup;
}
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = BIO_write(in, signed_data, signed_data_len);
if (retval != signed_data_len) {
pkiDebug("BIO_write only wrote %d\n", retval);
goto cleanup;
}
break;
default:
retval = -1;
goto cleanup;
}
p7 = PKCS7_encrypt(encerts, in, cipher, flags);
if (p7 == NULL) {
retval = oerr(context, 0, _("Failed to encrypt PKCS7 object"));
goto cleanup;
}
switch (pa_type) {
case KRB5_PADATA_PK_AS_REQ:
p7->d.enveloped->enc_data->content_type =
OBJ_nid2obj(NID_pkcs7_signed);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
p7->d.enveloped->enc_data->content_type =
OBJ_nid2obj(NID_pkcs7_data);
break;
break;
break;
break;
}
*out_len = i2d_PKCS7(p7, NULL);
if (!*out_len || (p = *out = malloc(*out_len)) == NULL) {
retval = ENOMEM;
goto cleanup;
}
retval = i2d_PKCS7(p7, &p);
if (!retval) {
retval = oerr(context, 0, _("Failed to DER encode PKCS7"));
goto cleanup;
}
retval = 0;
#ifdef DEBUG_ASN1
print_buffer_bin(*out, *out_len, "/tmp/kdc_enveloped_data");
#endif
cleanup:
if (p7 != NULL)
PKCS7_free(p7);
if (in != NULL)
BIO_free(in);
free(signed_data);
free(enc_data);
if (encerts != NULL)
sk_X509_free(encerts);
return retval;
}
krb5_error_code
cms_envelopeddata_verify(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_preauthtype pa_type,
int require_crl_checking,
unsigned char *enveloped_data,
unsigned int enveloped_data_len,
unsigned char **data,
unsigned int *data_len)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
PKCS7 *p7 = NULL;
BIO *out = NULL;
int i = 0;
unsigned int size = 0;
const unsigned char *p = enveloped_data;
unsigned int tmp_buf_len = 0, tmp_buf2_len = 0, vfy_buf_len = 0;
unsigned char *tmp_buf = NULL, *tmp_buf2 = NULL, *vfy_buf = NULL;
int msg_type = 0;
#ifdef DEBUG_ASN1
print_buffer_bin(enveloped_data, enveloped_data_len,
"/tmp/client_envelopeddata");
#endif
/* decode received PKCS7 message */
if ((p7 = d2i_PKCS7(NULL, &p, (int)enveloped_data_len)) == NULL) {
retval = oerr(context, 0, _("Failed to decode PKCS7"));
goto cleanup;
}
/* verify that the received message is PKCS7 EnvelopedData message */
if (OBJ_obj2nid(p7->type) != NID_pkcs7_enveloped) {
pkiDebug("Expected id-enveloped PKCS7 msg (received type = %d)\n",
OBJ_obj2nid(p7->type));
krb5_set_error_message(context, retval, "wrong oid\n");
goto cleanup;
}
/* decrypt received PKCS7 message */
out = BIO_new(BIO_s_mem());
if (pkcs7_decrypt(context, id_cryptoctx, p7, out)) {
pkiDebug("PKCS7 decryption successful\n");
} else {
retval = oerr(context, 0, _("Failed to decrypt PKCS7 message"));
goto cleanup;
}
/* transfer the decoded PKCS7 SignedData message into a separate buffer */
for (;;) {
if ((tmp_buf = realloc(tmp_buf, size + 1024 * 10)) == NULL)
goto cleanup;
i = BIO_read(out, &(tmp_buf[size]), 1024 * 10);
if (i <= 0)
break;
else
size += i;
}
tmp_buf_len = size;
#ifdef DEBUG_ASN1
print_buffer_bin(tmp_buf, tmp_buf_len, "/tmp/client_enc_keypack");
#endif
/* verify PKCS7 SignedData message */
switch (pa_type) {
case KRB5_PADATA_PK_AS_REP:
msg_type = CMS_ENVEL_SERVER;
break;
case KRB5_PADATA_PK_AS_REP_OLD:
msg_type = CMS_SIGN_DRAFT9;
break;
default:
pkiDebug("%s: unrecognized pa_type = %d\n", __FUNCTION__, pa_type);
retval = KRB5KDC_ERR_PREAUTH_FAILED;
goto cleanup;
}
/*
* If this is the RFC style, wrap the signed data to make
* decoding easier in the verify routine.
* For draft9-compatible, we don't do anything because it
* is already wrapped.
*/
if (msg_type == CMS_ENVEL_SERVER) {
retval = wrap_signeddata(tmp_buf, tmp_buf_len,
&tmp_buf2, &tmp_buf2_len);
if (retval) {
pkiDebug("failed to encode signeddata\n");
goto cleanup;
}
vfy_buf = tmp_buf2;
vfy_buf_len = tmp_buf2_len;
} else {
vfy_buf = tmp_buf;
vfy_buf_len = tmp_buf_len;
}
#ifdef DEBUG_ASN1
print_buffer_bin(vfy_buf, vfy_buf_len, "/tmp/client_enc_keypack2");
#endif
retval = cms_signeddata_verify(context, plg_cryptoctx, req_cryptoctx,
id_cryptoctx, msg_type,
require_crl_checking,
vfy_buf, vfy_buf_len,
data, data_len, NULL, NULL, NULL);
if (!retval)
pkiDebug("PKCS7 Verification Success\n");
else {
pkiDebug("PKCS7 Verification Failure\n");
goto cleanup;
}
retval = 0;
cleanup:
if (p7 != NULL)
PKCS7_free(p7);
if (out != NULL)
BIO_free(out);
free(tmp_buf);
free(tmp_buf2);
return retval;
}
static krb5_error_code
crypto_retrieve_X509_sans(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
X509 *cert,
krb5_principal **princs_ret,
krb5_principal **upn_ret,
unsigned char ***dns_ret)
{
krb5_error_code retval = EINVAL;
char buf[DN_BUF_LEN];
int p = 0, u = 0, d = 0, ret = 0, l;
krb5_principal *princs = NULL;
krb5_principal *upns = NULL;
unsigned char **dnss = NULL;
unsigned int i, num_found = 0, num_sans = 0;
X509_EXTENSION *ext = NULL;
GENERAL_NAMES *ialt = NULL;
GENERAL_NAME *gen = NULL;
if (princs_ret != NULL)
*princs_ret = NULL;
if (upn_ret != NULL)
*upn_ret = NULL;
if (dns_ret != NULL)
*dns_ret = NULL;
if (princs_ret == NULL && upn_ret == NULL && dns_ret == NULL) {
pkiDebug("%s: nowhere to return any values!\n", __FUNCTION__);
return retval;
}
if (cert == NULL) {
pkiDebug("%s: no certificate!\n", __FUNCTION__);
return retval;
}
X509_NAME_oneline(X509_get_subject_name(cert),
buf, sizeof(buf));
pkiDebug("%s: looking for SANs in cert = %s\n", __FUNCTION__, buf);
l = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
if (l < 0)
return 0;
if (!(ext = X509_get_ext(cert, l)) || !(ialt = X509V3_EXT_d2i(ext))) {
pkiDebug("%s: found no subject alt name extensions\n", __FUNCTION__);
goto cleanup;
}
num_sans = sk_GENERAL_NAME_num(ialt);
pkiDebug("%s: found %d subject alt name extension(s)\n", __FUNCTION__,
num_sans);
/* OK, we're likely returning something. Allocate return values */
if (princs_ret != NULL) {
princs = calloc(num_sans + 1, sizeof(krb5_principal));
if (princs == NULL) {
retval = ENOMEM;
goto cleanup;
}
}
if (upn_ret != NULL) {
upns = calloc(num_sans + 1, sizeof(krb5_principal));
if (upns == NULL) {
retval = ENOMEM;
goto cleanup;
}
}
if (dns_ret != NULL) {
dnss = calloc(num_sans + 1, sizeof(*dnss));
if (dnss == NULL) {
retval = ENOMEM;
goto cleanup;
}
}
for (i = 0; i < num_sans; i++) {
krb5_data name = { 0, 0, NULL };
gen = sk_GENERAL_NAME_value(ialt, i);
switch (gen->type) {
case GEN_OTHERNAME:
name.length = gen->d.otherName->value->value.sequence->length;
name.data = (char *)gen->d.otherName->value->value.sequence->data;
if (princs != NULL &&
OBJ_cmp(plgctx->id_pkinit_san,
gen->d.otherName->type_id) == 0) {
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)name.data, name.length,
"/tmp/pkinit_san");
#endif
ret = k5int_decode_krb5_principal_name(&name, &princs[p]);
if (ret) {
pkiDebug("%s: failed decoding pkinit san value\n",
__FUNCTION__);
} else {
p++;
num_found++;
}
} else if (upns != NULL &&
OBJ_cmp(plgctx->id_ms_san_upn,
gen->d.otherName->type_id) == 0) {
/* Prevent abuse of embedded null characters. */
if (memchr(name.data, '\0', name.length))
break;
ret = krb5_parse_name_flags(context, name.data,
KRB5_PRINCIPAL_PARSE_ENTERPRISE,
&upns[u]);
if (ret) {
pkiDebug("%s: failed parsing ms-upn san value\n",
__FUNCTION__);
} else {
u++;
num_found++;
}
} else {
pkiDebug("%s: unrecognized othername oid in SAN\n",
__FUNCTION__);
continue;
}
break;
case GEN_DNS:
if (dnss != NULL) {
/* Prevent abuse of embedded null characters. */
if (memchr(gen->d.dNSName->data, '\0', gen->d.dNSName->length))
break;
pkiDebug("%s: found dns name = %s\n", __FUNCTION__,
gen->d.dNSName->data);
dnss[d] = (unsigned char *)
strdup((char *)gen->d.dNSName->data);
if (dnss[d] == NULL) {
pkiDebug("%s: failed to duplicate dns name\n",
__FUNCTION__);
} else {
d++;
num_found++;
}
}
break;
default:
pkiDebug("%s: SAN type = %d expecting %d\n", __FUNCTION__,
gen->type, GEN_OTHERNAME);
}
}
sk_GENERAL_NAME_pop_free(ialt, GENERAL_NAME_free);
retval = 0;
if (princs != NULL && *princs != NULL) {
*princs_ret = princs;
princs = NULL;
}
if (upns != NULL && *upns != NULL) {
*upn_ret = upns;
upns = NULL;
}
if (dnss != NULL && *dnss != NULL) {
*dns_ret = dnss;
dnss = NULL;
}
cleanup:
for (i = 0; princs != NULL && princs[i] != NULL; i++)
krb5_free_principal(context, princs[i]);
free(princs);
for (i = 0; upns != NULL && upns[i] != NULL; i++)
krb5_free_principal(context, upns[i]);
free(upns);
for (i = 0; dnss != NULL && dnss[i] != NULL; i++)
free(dnss[i]);
free(dnss);
return retval;
}
krb5_error_code
crypto_retrieve_signer_identity(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
const char **identity)
{
*identity = id_cryptoctx->identity;
if (*identity == NULL)
return ENOENT;
return 0;
}
krb5_error_code
crypto_retrieve_cert_sans(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
pkinit_identity_crypto_context idctx,
krb5_principal **princs_ret,
krb5_principal **upn_ret,
unsigned char ***dns_ret)
{
krb5_error_code retval = EINVAL;
if (reqctx->received_cert == NULL) {
pkiDebug("%s: No certificate!\n", __FUNCTION__);
return retval;
}
return crypto_retrieve_X509_sans(context, plgctx, reqctx,
reqctx->received_cert, princs_ret,
upn_ret, dns_ret);
}
krb5_error_code
crypto_check_cert_eku(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
pkinit_identity_crypto_context idctx,
int checking_kdc_cert,
int allow_secondary_usage,
int *valid_eku)
{
char buf[DN_BUF_LEN];
int found_eku = 0;
krb5_error_code retval = EINVAL;
int i;
*valid_eku = 0;
if (reqctx->received_cert == NULL)
goto cleanup;
X509_NAME_oneline(X509_get_subject_name(reqctx->received_cert),
buf, sizeof(buf));
if ((i = X509_get_ext_by_NID(reqctx->received_cert,
NID_ext_key_usage, -1)) >= 0) {
EXTENDED_KEY_USAGE *extusage;
extusage = X509_get_ext_d2i(reqctx->received_cert, NID_ext_key_usage,
NULL, NULL);
if (extusage) {
pkiDebug("%s: found eku info in the cert\n", __FUNCTION__);
for (i = 0; found_eku == 0 && i < sk_ASN1_OBJECT_num(extusage); i++) {
ASN1_OBJECT *tmp_oid;
tmp_oid = sk_ASN1_OBJECT_value(extusage, i);
pkiDebug("%s: checking eku %d of %d, allow_secondary = %d\n",
__FUNCTION__, i+1, sk_ASN1_OBJECT_num(extusage),
allow_secondary_usage);
if (checking_kdc_cert) {
if ((OBJ_cmp(tmp_oid, plgctx->id_pkinit_KPKdc) == 0)
|| (allow_secondary_usage
&& OBJ_cmp(tmp_oid, plgctx->id_kp_serverAuth) == 0))
found_eku = 1;
} else {
if ((OBJ_cmp(tmp_oid, plgctx->id_pkinit_KPClientAuth) == 0)
|| (allow_secondary_usage
&& OBJ_cmp(tmp_oid, plgctx->id_ms_kp_sc_logon) == 0))
found_eku = 1;
}
}
}
EXTENDED_KEY_USAGE_free(extusage);
if (found_eku) {
ASN1_BIT_STRING *usage = NULL;
/* check that digitalSignature KeyUsage is present */
X509_check_ca(reqctx->received_cert);
if ((usage = X509_get_ext_d2i(reqctx->received_cert,
NID_key_usage, NULL, NULL))) {
if (!ku_reject(reqctx->received_cert,
X509v3_KU_DIGITAL_SIGNATURE)) {
TRACE_PKINIT_EKU(context);
*valid_eku = 1;
} else
TRACE_PKINIT_EKU_NO_KU(context);
}
ASN1_BIT_STRING_free(usage);
}
}
retval = 0;
cleanup:
pkiDebug("%s: returning retval %d, valid_eku %d\n",
__FUNCTION__, retval, *valid_eku);
return retval;
}
krb5_error_code
pkinit_octetstring2key(krb5_context context,
krb5_enctype etype,
unsigned char *key,
unsigned int dh_key_len,
krb5_keyblock *key_block)
{
krb5_error_code retval;
unsigned char *buf = NULL;
unsigned char md[SHA_DIGEST_LENGTH];
unsigned char counter;
size_t keybytes, keylength, offset;
krb5_data random_data;
if ((buf = malloc(dh_key_len)) == NULL) {
retval = ENOMEM;
goto cleanup;
}
memset(buf, 0, dh_key_len);
counter = 0;
offset = 0;
do {
SHA_CTX c;
SHA1_Init(&c);
SHA1_Update(&c, &counter, 1);
SHA1_Update(&c, key, dh_key_len);
SHA1_Final(md, &c);
if (dh_key_len - offset < sizeof(md))
memcpy(buf + offset, md, dh_key_len - offset);
else
memcpy(buf + offset, md, sizeof(md));
offset += sizeof(md);
counter++;
} while (offset < dh_key_len);
key_block->magic = 0;
key_block->enctype = etype;
retval = krb5_c_keylengths(context, etype, &keybytes, &keylength);
if (retval)
goto cleanup;
key_block->length = keylength;
key_block->contents = malloc(keylength);
if (key_block->contents == NULL) {
retval = ENOMEM;
goto cleanup;
}
random_data.length = keybytes;
random_data.data = (char *)buf;
retval = krb5_c_random_to_key(context, etype, &random_data, key_block);
cleanup:
free(buf);
/* If this is an error return, free the allocated keyblock, if any */
if (retval) {
krb5_free_keyblock_contents(context, key_block);
}
return retval;
}
/**
* Given an algorithm_identifier, this function returns the hash length
* and EVP function associated with that algorithm.
*/
static krb5_error_code
pkinit_alg_values(krb5_context context,
const krb5_data *alg_id,
size_t *hash_bytes,
const EVP_MD *(**func)(void))
{
*hash_bytes = 0;
*func = NULL;
if ((alg_id->length == krb5_pkinit_sha1_oid_len) &&
(0 == memcmp(alg_id->data, &krb5_pkinit_sha1_oid,
krb5_pkinit_sha1_oid_len))) {
*hash_bytes = 20;
*func = &EVP_sha1;
return 0;
} else if ((alg_id->length == krb5_pkinit_sha256_oid_len) &&
(0 == memcmp(alg_id->data, krb5_pkinit_sha256_oid,
krb5_pkinit_sha256_oid_len))) {
*hash_bytes = 32;
*func = &EVP_sha256;
return 0;
} else if ((alg_id->length == krb5_pkinit_sha512_oid_len) &&
(0 == memcmp(alg_id->data, krb5_pkinit_sha512_oid,
krb5_pkinit_sha512_oid_len))) {
*hash_bytes = 64;
*func = &EVP_sha512;
return 0;
} else {
krb5_set_error_message(context, KRB5_ERR_BAD_S2K_PARAMS,
"Bad algorithm ID passed to PK-INIT KDF.");
return KRB5_ERR_BAD_S2K_PARAMS;
}
} /* pkinit_alg_values() */
/* pkinit_alg_agility_kdf() --
* This function generates a key using the KDF described in
* draft_ietf_krb_wg_pkinit_alg_agility-04.txt. The algorithm is
* described as follows:
*
* 1. reps = keydatalen (K) / hash length (H)
*
* 2. Initialize a 32-bit, big-endian bit string counter as 1.
*
* 3. For i = 1 to reps by 1, do the following:
*
* - Compute Hashi = H(counter || Z || OtherInfo).
*
* - Increment counter (modulo 2^32)
*
* 4. Set key = Hash1 || Hash2 || ... so that length of key is K bytes.
*/
krb5_error_code
pkinit_alg_agility_kdf(krb5_context context,
krb5_data *secret,
krb5_data *alg_oid,
krb5_const_principal party_u_info,
krb5_const_principal party_v_info,
krb5_enctype enctype,
krb5_data *as_req,
krb5_data *pk_as_rep,
krb5_keyblock *key_block)
{
krb5_error_code retval = 0;
unsigned int reps = 0;
uint32_t counter = 1; /* Does this type work on Windows? */
size_t offset = 0;
size_t hash_len = 0;
size_t rand_len = 0;
size_t key_len = 0;
krb5_data random_data;
krb5_sp80056a_other_info other_info_fields;
krb5_pkinit_supp_pub_info supp_pub_info_fields;
krb5_data *other_info = NULL;
krb5_data *supp_pub_info = NULL;
krb5_algorithm_identifier alg_id;
EVP_MD_CTX *ctx = NULL;
const EVP_MD *(*EVP_func)(void);
/* initialize random_data here to make clean-up safe */
random_data.length = 0;
random_data.data = NULL;
/* allocate and initialize the key block */
key_block->magic = 0;
key_block->enctype = enctype;
if (0 != (retval = krb5_c_keylengths(context, enctype, &rand_len,
&key_len)))
goto cleanup;
random_data.length = rand_len;
key_block->length = key_len;
if (NULL == (key_block->contents = malloc(key_block->length))) {
retval = ENOMEM;
goto cleanup;
}
memset (key_block->contents, 0, key_block->length);
/* If this is anonymous pkinit, use the anonymous principle for party_u_info */
if (party_u_info && krb5_principal_compare_any_realm(context, party_u_info,
krb5_anonymous_principal()))
party_u_info = (krb5_principal)krb5_anonymous_principal();
if (0 != (retval = pkinit_alg_values(context, alg_oid, &hash_len, &EVP_func)))
goto cleanup;
/* 1. reps = keydatalen (K) / hash length (H) */
reps = key_block->length/hash_len;
/* ... and round up, if necessary */
if (key_block->length > (reps * hash_len))
reps++;
/* Allocate enough space in the random data buffer to hash directly into
* it, even if the last hash will make it bigger than the key length. */
if (NULL == (random_data.data = malloc(reps * hash_len))) {
retval = ENOMEM;
goto cleanup;
}
/* Encode the ASN.1 octet string for "SuppPubInfo" */
supp_pub_info_fields.enctype = enctype;
supp_pub_info_fields.as_req = *as_req;
supp_pub_info_fields.pk_as_rep = *pk_as_rep;
if (0 != ((retval = encode_krb5_pkinit_supp_pub_info(&supp_pub_info_fields,
&supp_pub_info))))
goto cleanup;
/* Now encode the ASN.1 octet string for "OtherInfo" */
memset(&alg_id, 0, sizeof alg_id);
alg_id.algorithm = *alg_oid; /*alias*/
other_info_fields.algorithm_identifier = alg_id;
other_info_fields.party_u_info = (krb5_principal) party_u_info;
other_info_fields.party_v_info = (krb5_principal) party_v_info;
other_info_fields.supp_pub_info = *supp_pub_info;
if (0 != (retval = encode_krb5_sp80056a_other_info(&other_info_fields, &other_info)))
goto cleanup;
/* 2. Initialize a 32-bit, big-endian bit string counter as 1.
* 3. For i = 1 to reps by 1, do the following:
* - Compute Hashi = H(counter || Z || OtherInfo).
* - Increment counter (modulo 2^32)
*/
for (counter = 1; counter <= reps; counter++) {
uint s = 0;
uint32_t be_counter = htonl(counter);
ctx = EVP_MD_CTX_new();
if (ctx == NULL) {
retval = KRB5_CRYPTO_INTERNAL;
goto cleanup;
}
/* - Compute Hashi = H(counter || Z || OtherInfo). */
if (!EVP_DigestInit(ctx, EVP_func())) {
krb5_set_error_message(context, KRB5_CRYPTO_INTERNAL,
"Call to OpenSSL EVP_DigestInit() returned an error.");
retval = KRB5_CRYPTO_INTERNAL;
goto cleanup;
}
if (!EVP_DigestUpdate(ctx, &be_counter, 4) ||
!EVP_DigestUpdate(ctx, secret->data, secret->length) ||
!EVP_DigestUpdate(ctx, other_info->data, other_info->length)) {
krb5_set_error_message(context, KRB5_CRYPTO_INTERNAL,
"Call to OpenSSL EVP_DigestUpdate() returned an error.");
retval = KRB5_CRYPTO_INTERNAL;
goto cleanup;
}
/* 4. Set key = Hash1 || Hash2 || ... so that length of key is K bytes. */
if (!EVP_DigestFinal(ctx, (uint8_t *)random_data.data + offset, &s)) {
krb5_set_error_message(context, KRB5_CRYPTO_INTERNAL,
"Call to OpenSSL EVP_DigestUpdate() returned an error.");
retval = KRB5_CRYPTO_INTERNAL;
goto cleanup;
}
offset += s;
assert(s == hash_len);
EVP_MD_CTX_free(ctx);
ctx = NULL;
}
retval = krb5_c_random_to_key(context, enctype, &random_data,
key_block);
cleanup:
EVP_MD_CTX_free(ctx);
/* If this has been an error, free the allocated key_block, if any */
if (retval) {
krb5_free_keyblock_contents(context, key_block);
}
/* free other allocated resources, either way */
if (random_data.data)
free(random_data.data);
krb5_free_data(context, other_info);
krb5_free_data(context, supp_pub_info);
return retval;
} /*pkinit_alg_agility_kdf() */
/* Call DH_compute_key() and ensure that we left-pad short results instead of
* leaving junk bytes at the end of the buffer. */
static void
compute_dh(unsigned char *buf, int size, BIGNUM *server_pub_key, DH *dh)
{
int len, pad;
len = DH_compute_key(buf, server_pub_key, dh);
assert(len >= 0 && len <= size);
if (len < size) {
pad = size - len;
memmove(buf + pad, buf, len);
memset(buf, 0, pad);
}
}
krb5_error_code
client_create_dh(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int dh_size,
unsigned char **dh_params,
unsigned int *dh_params_len,
unsigned char **dh_pubkey,
unsigned int *dh_pubkey_len)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
unsigned char *buf = NULL;
int dh_err = 0;
ASN1_INTEGER *pub_key = NULL;
const BIGNUM *pubkey_bn, *p, *q, *g;
if (cryptoctx->dh == NULL) {
if (dh_size == 1024)
cryptoctx->dh = make_oakley_dh(oakley_1024, sizeof(oakley_1024));
else if (dh_size == 2048)
cryptoctx->dh = make_oakley_dh(oakley_2048, sizeof(oakley_2048));
else if (dh_size == 4096)
cryptoctx->dh = make_oakley_dh(oakley_4096, sizeof(oakley_4096));
if (cryptoctx->dh == NULL)
goto cleanup;
}
DH_generate_key(cryptoctx->dh);
DH_get0_key(cryptoctx->dh, &pubkey_bn, NULL);
DH_check(cryptoctx->dh, &dh_err);
if (dh_err != 0) {
pkiDebug("Warning: dh_check failed with %d\n", dh_err);
if (dh_err & DH_CHECK_P_NOT_PRIME)
pkiDebug("p value is not prime\n");
if (dh_err & DH_CHECK_P_NOT_SAFE_PRIME)
pkiDebug("p value is not a safe prime\n");
if (dh_err & DH_UNABLE_TO_CHECK_GENERATOR)
pkiDebug("unable to check the generator value\n");
if (dh_err & DH_NOT_SUITABLE_GENERATOR)
pkiDebug("the g value is not a generator\n");
}
#ifdef DEBUG_DH
print_dh(cryptoctx->dh, "client's DH params\n");
print_pubkey(cryptoctx->dh->pub_key, "client's pub_key=");
#endif
DH_check_pub_key(cryptoctx->dh, pubkey_bn, &dh_err);
if (dh_err != 0) {
pkiDebug("dh_check_pub_key failed with %d\n", dh_err);
goto cleanup;
}
/* pack DHparams */
/* aglo: usually we could just call i2d_DHparams to encode DH params
* however, PKINIT requires RFC3279 encoding and openssl does pkcs#3.
*/
DH_get0_pqg(cryptoctx->dh, &p, &q, &g);
retval = pkinit_encode_dh_params(p, g, q, dh_params, dh_params_len);
if (retval)
goto cleanup;
/* pack DH public key */
/* Diffie-Hellman public key must be ASN1 encoded as an INTEGER; this
* encoding shall be used as the contents (the value) of the
* subjectPublicKey component (a BIT STRING) of the SubjectPublicKeyInfo
* data element
*/
pub_key = BN_to_ASN1_INTEGER(pubkey_bn, NULL);
if (pub_key == NULL) {
retval = ENOMEM;
goto cleanup;
}
*dh_pubkey_len = i2d_ASN1_INTEGER(pub_key, NULL);
if ((buf = *dh_pubkey = malloc(*dh_pubkey_len)) == NULL) {
retval = ENOMEM;
goto cleanup;
}
i2d_ASN1_INTEGER(pub_key, &buf);
if (pub_key != NULL)
ASN1_INTEGER_free(pub_key);
retval = 0;
return retval;
cleanup:
if (cryptoctx->dh != NULL)
DH_free(cryptoctx->dh);
cryptoctx->dh = NULL;
free(*dh_params);
*dh_params = NULL;
free(*dh_pubkey);
*dh_pubkey = NULL;
if (pub_key != NULL)
ASN1_INTEGER_free(pub_key);
return retval;
}
krb5_error_code
client_process_dh(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *subjectPublicKey_data,
unsigned int subjectPublicKey_length,
unsigned char **client_key,
unsigned int *client_key_len)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
BIGNUM *server_pub_key = NULL;
ASN1_INTEGER *pub_key = NULL;
const unsigned char *p = NULL;
*client_key_len = DH_size(cryptoctx->dh);
if ((*client_key = malloc(*client_key_len)) == NULL) {
retval = ENOMEM;
goto cleanup;
}
p = subjectPublicKey_data;
pub_key = d2i_ASN1_INTEGER(NULL, &p, (long)subjectPublicKey_length);
if (pub_key == NULL)
goto cleanup;
if ((server_pub_key = ASN1_INTEGER_to_BN(pub_key, NULL)) == NULL)
goto cleanup;
compute_dh(*client_key, *client_key_len, server_pub_key, cryptoctx->dh);
#ifdef DEBUG_DH
print_pubkey(server_pub_key, "server's pub_key=");
pkiDebug("client computed key (%d)= ", *client_key_len);
print_buffer(*client_key, *client_key_len);
#endif
retval = 0;
if (server_pub_key != NULL)
BN_free(server_pub_key);
if (pub_key != NULL)
ASN1_INTEGER_free(pub_key);
return retval;
cleanup:
free(*client_key);
*client_key = NULL;
if (pub_key != NULL)
ASN1_INTEGER_free(pub_key);
return retval;
}
/* Return 1 if dh is a permitted well-known group, otherwise return 0. */
static int
check_dh_wellknown(pkinit_plg_crypto_context cryptoctx, DH *dh, int nbits)
{
switch (nbits) {
case 1024:
/* Oakley MODP group 2 */
if (pkinit_check_dh_params(cryptoctx->dh_1024, dh) == 0)
return 1;
break;
case 2048:
/* Oakley MODP group 14 */
if (pkinit_check_dh_params(cryptoctx->dh_2048, dh) == 0)
return 1;
break;
case 4096:
/* Oakley MODP group 16 */
if (pkinit_check_dh_params(cryptoctx->dh_4096, dh) == 0)
return 1;
break;
default:
break;
}
return 0;
}
krb5_error_code
server_check_dh(krb5_context context,
pkinit_plg_crypto_context cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_data *dh_params,
int minbits)
{
DH *dh = NULL;
const BIGNUM *p;
int dh_prime_bits;
krb5_error_code retval = KRB5KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
dh = decode_dh_params((uint8_t *)dh_params->data, dh_params->length);
if (dh == NULL) {
pkiDebug("failed to decode dhparams\n");
goto cleanup;
}
/* KDC SHOULD check to see if the key parameters satisfy its policy */
DH_get0_pqg(dh, &p, NULL, NULL);
dh_prime_bits = BN_num_bits(p);
if (minbits && dh_prime_bits < minbits) {
pkiDebug("client sent dh params with %d bits, we require %d\n",
dh_prime_bits, minbits);
goto cleanup;
}
if (check_dh_wellknown(cryptoctx, dh, dh_prime_bits))
retval = 0;
cleanup:
if (retval == 0)
req_cryptoctx->dh = dh;
else
DH_free(dh);
return retval;
}
/* Duplicate a DH handle (parameters only, not public or private key). */
static DH *
dup_dh_params(const DH *src)
{
const BIGNUM *oldp, *oldq, *oldg;
BIGNUM *p = NULL, *q = NULL, *g = NULL;
DH *dh;
DH_get0_pqg(src, &oldp, &oldq, &oldg);
p = BN_dup(oldp);
q = BN_dup(oldq);
g = BN_dup(oldg);
dh = DH_new();
if (p == NULL || q == NULL || g == NULL || dh == NULL) {
BN_free(p);
BN_free(q);
BN_free(g);
DH_free(dh);
return NULL;
}
DH_set0_pqg(dh, p, q, g);
return dh;
}
/* kdc's dh function */
krb5_error_code
server_process_dh(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data,
unsigned int data_len,
unsigned char **dh_pubkey,
unsigned int *dh_pubkey_len,
unsigned char **server_key,
unsigned int *server_key_len)
{
krb5_error_code retval = ENOMEM;
DH *dh = NULL, *dh_server = NULL;
unsigned char *p = NULL;
ASN1_INTEGER *pub_key = NULL;
BIGNUM *client_pubkey = NULL;
const BIGNUM *server_pubkey;
*dh_pubkey = *server_key = NULL;
*dh_pubkey_len = *server_key_len = 0;
/* get client's received DH parameters that we saved in server_check_dh */
dh = cryptoctx->dh;
dh_server = dup_dh_params(dh);
if (dh_server == NULL)
goto cleanup;
/* decode client's public key */
p = data;
pub_key = d2i_ASN1_INTEGER(NULL, (const unsigned char **)&p, (int)data_len);
if (pub_key == NULL)
goto cleanup;
client_pubkey = ASN1_INTEGER_to_BN(pub_key, NULL);
if (client_pubkey == NULL)
goto cleanup;
ASN1_INTEGER_free(pub_key);
if (!DH_generate_key(dh_server))
goto cleanup;
DH_get0_key(dh_server, &server_pubkey, NULL);
/* generate DH session key */
*server_key_len = DH_size(dh_server);
if ((*server_key = malloc(*server_key_len)) == NULL)
goto cleanup;
compute_dh(*server_key, *server_key_len, client_pubkey, dh_server);
#ifdef DEBUG_DH
print_dh(dh_server, "client&server's DH params\n");
print_pubkey(client_pubkey, "client's pub_key=");
print_pubkey(server_pubkey, "server's pub_key=");
pkiDebug("server computed key=");
print_buffer(*server_key, *server_key_len);
#endif
/* KDC reply */
/* pack DH public key */
/* Diffie-Hellman public key must be ASN1 encoded as an INTEGER; this
* encoding shall be used as the contents (the value) of the
* subjectPublicKey component (a BIT STRING) of the SubjectPublicKeyInfo
* data element
*/
pub_key = BN_to_ASN1_INTEGER(server_pubkey, NULL);
if (pub_key == NULL)
goto cleanup;
*dh_pubkey_len = i2d_ASN1_INTEGER(pub_key, NULL);
if ((p = *dh_pubkey = malloc(*dh_pubkey_len)) == NULL)
goto cleanup;
i2d_ASN1_INTEGER(pub_key, &p);
if (pub_key != NULL)
ASN1_INTEGER_free(pub_key);
retval = 0;
if (dh_server != NULL)
DH_free(dh_server);
return retval;
cleanup:
BN_free(client_pubkey);
DH_free(dh_server);
free(*dh_pubkey);
free(*server_key);
return retval;
}
int
pkinit_openssl_init()
{
/* Initialize OpenSSL. */
ERR_load_crypto_strings();
OpenSSL_add_all_algorithms();
return 0;
}
static krb5_error_code
pkinit_encode_dh_params(const BIGNUM *p, const BIGNUM *g, const BIGNUM *q,
uint8_t **buf, unsigned int *buf_len)
{
krb5_error_code retval = ENOMEM;
int bufsize = 0, r = 0;
unsigned char *tmp = NULL;
ASN1_INTEGER *ap = NULL, *ag = NULL, *aq = NULL;
if ((ap = BN_to_ASN1_INTEGER(p, NULL)) == NULL)
goto cleanup;
if ((ag = BN_to_ASN1_INTEGER(g, NULL)) == NULL)
goto cleanup;
if ((aq = BN_to_ASN1_INTEGER(q, NULL)) == NULL)
goto cleanup;
bufsize = i2d_ASN1_INTEGER(ap, NULL);
bufsize += i2d_ASN1_INTEGER(ag, NULL);
bufsize += i2d_ASN1_INTEGER(aq, NULL);
r = ASN1_object_size(1, bufsize, V_ASN1_SEQUENCE);
tmp = *buf = malloc((size_t) r);
if (tmp == NULL)
goto cleanup;
ASN1_put_object(&tmp, 1, bufsize, V_ASN1_SEQUENCE, V_ASN1_UNIVERSAL);
i2d_ASN1_INTEGER(ap, &tmp);
i2d_ASN1_INTEGER(ag, &tmp);
i2d_ASN1_INTEGER(aq, &tmp);
*buf_len = r;
retval = 0;
cleanup:
if (ap != NULL)
ASN1_INTEGER_free(ap);
if (ag != NULL)
ASN1_INTEGER_free(ag);
if (aq != NULL)
ASN1_INTEGER_free(aq);
return retval;
}
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
/*
* We need to decode DomainParameters from RFC 3279 section 2.3.3. We would
* like to just call d2i_DHxparams(), but Microsoft's implementation may omit
* the q value in violation of the RFC. Instead we must copy the internal
* structures and sequence declarations from dh_asn1.c, modified to make the q
* field optional.
*/
typedef struct {
ASN1_BIT_STRING *seed;
BIGNUM *counter;
} int_dhvparams;
typedef struct {
BIGNUM *p;
BIGNUM *q;
BIGNUM *g;
BIGNUM *j;
int_dhvparams *vparams;
} int_dhx942_dh;
ASN1_SEQUENCE(DHvparams) = {
ASN1_SIMPLE(int_dhvparams, seed, ASN1_BIT_STRING),
ASN1_SIMPLE(int_dhvparams, counter, BIGNUM)
} static_ASN1_SEQUENCE_END_name(int_dhvparams, DHvparams)
ASN1_SEQUENCE(DHxparams) = {
ASN1_SIMPLE(int_dhx942_dh, p, BIGNUM),
ASN1_SIMPLE(int_dhx942_dh, g, BIGNUM),
ASN1_OPT(int_dhx942_dh, q, BIGNUM),
ASN1_OPT(int_dhx942_dh, j, BIGNUM),
ASN1_OPT(int_dhx942_dh, vparams, DHvparams),
} static_ASN1_SEQUENCE_END_name(int_dhx942_dh, DHxparams)
static DH *
decode_dh_params(const uint8_t *p, unsigned int len)
{
int_dhx942_dh *params;
DH *dh;
dh = DH_new();
if (dh == NULL)
return NULL;
params = (int_dhx942_dh *)ASN1_item_d2i(NULL, &p, len,
ASN1_ITEM_rptr(DHxparams));
if (params == NULL) {
DH_free(dh);
return NULL;
}
/* Steal the p, q, and g values from dhparams for dh. Ignore j and
* vparams. */
DH_set0_pqg(dh, params->p, params->q, params->g);
params->p = params->q = params->g = NULL;
ASN1_item_free((ASN1_VALUE *)params, ASN1_ITEM_rptr(DHxparams));
return dh;
}
#else /* OPENSSL_VERSION_NUMBER < 0x10100000L */
/*
* Do the same decoding (except without decoding j and vparams or checking the
* sequence length) using the pre-OpenSSL-1.1 asn1_mac.h. Define an internal
* function in the form demanded by the macros, then wrap it for caller
* convenience.
*/
static DH *
decode_dh_params_int(DH ** a, uint8_t **pp, unsigned int len)
{
ASN1_INTEGER ai, *aip = NULL;
long length = (long) len;
M_ASN1_D2I_vars(a, DH *, DH_new);
M_ASN1_D2I_Init();
M_ASN1_D2I_start_sequence();
aip = &ai;
ai.data = NULL;
ai.length = 0;
M_ASN1_D2I_get_x(ASN1_INTEGER, aip, d2i_ASN1_INTEGER);
if (aip == NULL)
return NULL;
else {
ret->p = ASN1_INTEGER_to_BN(aip, NULL);
if (ret->p == NULL)
return NULL;
if (ai.data != NULL) {
OPENSSL_free(ai.data);
ai.data = NULL;
ai.length = 0;
}
}
M_ASN1_D2I_get_x(ASN1_INTEGER, aip, d2i_ASN1_INTEGER);
if (aip == NULL)
return NULL;
else {
ret->g = ASN1_INTEGER_to_BN(aip, NULL);
if (ret->g == NULL)
return NULL;
if (ai.data != NULL) {
OPENSSL_free(ai.data);
ai.data = NULL;
ai.length = 0;
}
}
M_ASN1_D2I_get_opt(aip, d2i_ASN1_INTEGER, V_ASN1_INTEGER);
if (aip == NULL || ai.data == NULL)
ret->q = NULL;
else {
ret->q = ASN1_INTEGER_to_BN(aip, NULL);
if (ret->q == NULL)
return NULL;
if (ai.data != NULL) {
OPENSSL_free(ai.data);
ai.data = NULL;
ai.length = 0;
}
}
M_ASN1_D2I_end_sequence();
M_ASN1_D2I_Finish(a, DH_free, 0);
}
static DH *
decode_dh_params(const uint8_t *p, unsigned int len)
{
uint8_t *ptr = (uint8_t *)p;
return decode_dh_params_int(NULL, &ptr, len);
}
#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
static krb5_error_code
pkinit_create_sequence_of_principal_identifiers(
krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int type,
krb5_pa_data ***e_data_out)
{
krb5_error_code retval = KRB5KRB_ERR_GENERIC;
krb5_external_principal_identifier **krb5_trusted_certifiers = NULL;
krb5_data *td_certifiers = NULL;
krb5_pa_data **pa_data = NULL;
switch(type) {
case TD_TRUSTED_CERTIFIERS:
retval = create_krb5_trustedCertifiers(context, plg_cryptoctx,
req_cryptoctx, id_cryptoctx, &krb5_trusted_certifiers);
if (retval) {
pkiDebug("create_krb5_trustedCertifiers failed\n");
goto cleanup;
}
break;
case TD_INVALID_CERTIFICATES:
retval = create_krb5_invalidCertificates(context, plg_cryptoctx,
req_cryptoctx, id_cryptoctx, &krb5_trusted_certifiers);
if (retval) {
pkiDebug("create_krb5_invalidCertificates failed\n");
goto cleanup;
}
break;
default:
retval = -1;
goto cleanup;
}
retval = k5int_encode_krb5_td_trusted_certifiers((krb5_external_principal_identifier *const *)krb5_trusted_certifiers, &td_certifiers);
if (retval) {
pkiDebug("encode_krb5_td_trusted_certifiers failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)td_certifiers->data,
td_certifiers->length, "/tmp/kdc_td_certifiers");
#endif
pa_data = malloc(2 * sizeof(krb5_pa_data *));
if (pa_data == NULL) {
retval = ENOMEM;
goto cleanup;
}
pa_data[1] = NULL;
pa_data[0] = malloc(sizeof(krb5_pa_data));
if (pa_data[0] == NULL) {
free(pa_data);
retval = ENOMEM;
goto cleanup;
}
pa_data[0]->pa_type = type;
pa_data[0]->length = td_certifiers->length;
pa_data[0]->contents = (krb5_octet *)td_certifiers->data;
*e_data_out = pa_data;
retval = 0;
cleanup:
if (krb5_trusted_certifiers != NULL)
free_krb5_external_principal_identifier(&krb5_trusted_certifiers);
free(td_certifiers);
return retval;
}
krb5_error_code
pkinit_create_td_trusted_certifiers(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_pa_data ***e_data_out)
{
krb5_error_code retval = KRB5KRB_ERR_GENERIC;
retval = pkinit_create_sequence_of_principal_identifiers(context,
plg_cryptoctx, req_cryptoctx, id_cryptoctx,
TD_TRUSTED_CERTIFIERS, e_data_out);
return retval;
}
krb5_error_code
pkinit_create_td_invalid_certificate(
krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_pa_data ***e_data_out)
{
krb5_error_code retval = KRB5KRB_ERR_GENERIC;
retval = pkinit_create_sequence_of_principal_identifiers(context,
plg_cryptoctx, req_cryptoctx, id_cryptoctx,
TD_INVALID_CERTIFICATES, e_data_out);
return retval;
}
krb5_error_code
pkinit_create_td_dh_parameters(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
pkinit_plg_opts *opts,
krb5_pa_data ***e_data_out)
{
krb5_error_code retval = ENOMEM;
unsigned int buf1_len = 0, buf2_len = 0, buf3_len = 0, i = 0;
unsigned char *buf1 = NULL, *buf2 = NULL, *buf3 = NULL;
krb5_pa_data **pa_data = NULL;
krb5_data *encoded_algId = NULL;
krb5_algorithm_identifier **algId = NULL;
const BIGNUM *p, *q, *g;
if (opts->dh_min_bits > 4096)
goto cleanup;
if (opts->dh_min_bits <= 1024) {
DH_get0_pqg(plg_cryptoctx->dh_1024, &p, &q, &g);
retval = pkinit_encode_dh_params(p, g, q, &buf1, &buf1_len);
if (retval)
goto cleanup;
}
if (opts->dh_min_bits <= 2048) {
DH_get0_pqg(plg_cryptoctx->dh_2048, &p, &q, &g);
retval = pkinit_encode_dh_params(p, g, q, &buf2, &buf2_len);
if (retval)
goto cleanup;
}
DH_get0_pqg(plg_cryptoctx->dh_4096, &p, &q, &g);
retval = pkinit_encode_dh_params(p, g, q, &buf3, &buf3_len);
if (retval)
goto cleanup;
if (opts->dh_min_bits <= 1024) {
algId = malloc(4 * sizeof(krb5_algorithm_identifier *));
if (algId == NULL)
goto cleanup;
algId[3] = NULL;
algId[0] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[0] == NULL)
goto cleanup;
algId[0]->parameters.data = malloc(buf2_len);
if (algId[0]->parameters.data == NULL)
goto cleanup;
memcpy(algId[0]->parameters.data, buf2, buf2_len);
algId[0]->parameters.length = buf2_len;
algId[0]->algorithm = dh_oid;
algId[1] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[1] == NULL)
goto cleanup;
algId[1]->parameters.data = malloc(buf3_len);
if (algId[1]->parameters.data == NULL)
goto cleanup;
memcpy(algId[1]->parameters.data, buf3, buf3_len);
algId[1]->parameters.length = buf3_len;
algId[1]->algorithm = dh_oid;
algId[2] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[2] == NULL)
goto cleanup;
algId[2]->parameters.data = malloc(buf1_len);
if (algId[2]->parameters.data == NULL)
goto cleanup;
memcpy(algId[2]->parameters.data, buf1, buf1_len);
algId[2]->parameters.length = buf1_len;
algId[2]->algorithm = dh_oid;
} else if (opts->dh_min_bits <= 2048) {
algId = malloc(3 * sizeof(krb5_algorithm_identifier *));
if (algId == NULL)
goto cleanup;
algId[2] = NULL;
algId[0] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[0] == NULL)
goto cleanup;
algId[0]->parameters.data = malloc(buf2_len);
if (algId[0]->parameters.data == NULL)
goto cleanup;
memcpy(algId[0]->parameters.data, buf2, buf2_len);
algId[0]->parameters.length = buf2_len;
algId[0]->algorithm = dh_oid;
algId[1] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[1] == NULL)
goto cleanup;
algId[1]->parameters.data = malloc(buf3_len);
if (algId[1]->parameters.data == NULL)
goto cleanup;
memcpy(algId[1]->parameters.data, buf3, buf3_len);
algId[1]->parameters.length = buf3_len;
algId[1]->algorithm = dh_oid;
} else if (opts->dh_min_bits <= 4096) {
algId = malloc(2 * sizeof(krb5_algorithm_identifier *));
if (algId == NULL)
goto cleanup;
algId[1] = NULL;
algId[0] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[0] == NULL)
goto cleanup;
algId[0]->parameters.data = malloc(buf3_len);
if (algId[0]->parameters.data == NULL)
goto cleanup;
memcpy(algId[0]->parameters.data, buf3, buf3_len);
algId[0]->parameters.length = buf3_len;
algId[0]->algorithm = dh_oid;
}
retval = k5int_encode_krb5_td_dh_parameters((krb5_algorithm_identifier *const *)algId, &encoded_algId);
if (retval)
goto cleanup;
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)encoded_algId->data,
encoded_algId->length, "/tmp/kdc_td_dh_params");
#endif
pa_data = malloc(2 * sizeof(krb5_pa_data *));
if (pa_data == NULL) {
retval = ENOMEM;
goto cleanup;
}
pa_data[1] = NULL;
pa_data[0] = malloc(sizeof(krb5_pa_data));
if (pa_data[0] == NULL) {
free(pa_data);
retval = ENOMEM;
goto cleanup;
}
pa_data[0]->pa_type = TD_DH_PARAMETERS;
pa_data[0]->length = encoded_algId->length;
pa_data[0]->contents = (krb5_octet *)encoded_algId->data;
*e_data_out = pa_data;
retval = 0;
cleanup:
free(buf1);
free(buf2);
free(buf3);
free(encoded_algId);
if (algId != NULL) {
while(algId[i] != NULL) {
free(algId[i]->parameters.data);
free(algId[i]);
i++;
}
free(algId);
}
return retval;
}
krb5_error_code
pkinit_check_kdc_pkid(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *pdid_buf,
unsigned int pkid_len,
int *valid_kdcPkId)
{
PKCS7_ISSUER_AND_SERIAL *is = NULL;
const unsigned char *p = pdid_buf;
int status = 1;
X509 *kdc_cert = sk_X509_value(id_cryptoctx->my_certs, id_cryptoctx->cert_index);
*valid_kdcPkId = 0;
pkiDebug("found kdcPkId in AS REQ\n");
is = d2i_PKCS7_ISSUER_AND_SERIAL(NULL, &p, (int)pkid_len);
if (is == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
status = X509_NAME_cmp(X509_get_issuer_name(kdc_cert), is->issuer);
if (!status) {
status = ASN1_INTEGER_cmp(X509_get_serialNumber(kdc_cert), is->serial);
if (!status)
*valid_kdcPkId = 1;
}
X509_NAME_free(is->issuer);
ASN1_INTEGER_free(is->serial);
free(is);
return 0;
}
/* Check parameters against a well-known DH group. */
static int
pkinit_check_dh_params(DH *dh1, DH *dh2)
{
const BIGNUM *p1, *p2, *g1, *g2;
DH_get0_pqg(dh1, &p1, NULL, &g1);
DH_get0_pqg(dh2, &p2, NULL, &g2);
if (BN_cmp(p1, p2) != 0) {
pkiDebug("p is not well-known group dhparameter\n");
return -1;
}
if (BN_cmp(g1, g2) != 0) {
pkiDebug("bad g dhparameter\n");
return -1;
}
pkiDebug("good %d dhparams\n", BN_num_bits(p1));
return 0;
}
krb5_error_code
pkinit_process_td_dh_params(krb5_context context,
pkinit_plg_crypto_context cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_algorithm_identifier **algId,
int *new_dh_size)
{
krb5_error_code retval = KRB5KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
int i = 0, use_sent_dh = 0, ok = 0;
pkiDebug("dh parameters\n");
while (algId[i] != NULL) {
DH *dh = NULL;
const BIGNUM *p;
int dh_prime_bits = 0;
if (algId[i]->algorithm.length != dh_oid.length ||
memcmp(algId[i]->algorithm.data, dh_oid.data, dh_oid.length))
goto cleanup;
dh = decode_dh_params((uint8_t *)algId[i]->parameters.data,
algId[i]->parameters.length);
if (dh == NULL)
goto cleanup;
DH_get0_pqg(dh, &p, NULL, NULL);
dh_prime_bits = BN_num_bits(p);
pkiDebug("client sent %d DH bits server prefers %d DH bits\n",
*new_dh_size, dh_prime_bits);
ok = check_dh_wellknown(cryptoctx, dh, dh_prime_bits);
if (ok) {
*new_dh_size = dh_prime_bits;
}
if (!ok) {
DH_check(dh, &retval);
if (retval != 0) {
pkiDebug("DH parameters provided by server are unacceptable\n");
retval = KRB5KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
}
else {
use_sent_dh = 1;
ok = 1;
}
}
if (!use_sent_dh)
DH_free(dh);
if (ok) {
if (req_cryptoctx->dh != NULL) {
DH_free(req_cryptoctx->dh);
req_cryptoctx->dh = NULL;
}
if (use_sent_dh)
req_cryptoctx->dh = dh;
break;
}
i++;
}
if (ok)
retval = 0;
cleanup:
return retval;
}
static int
openssl_callback(int ok, X509_STORE_CTX * ctx)
{
#ifdef DEBUG
if (!ok) {
X509 *cert = X509_STORE_CTX_get_current_cert(ctx);
int err = X509_STORE_CTX_get_error(ctx);
const char *errmsg = X509_verify_cert_error_string(err);
char buf[DN_BUF_LEN];
X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
pkiDebug("cert = %s\n", buf);
pkiDebug("callback function: %d (%s)\n", err, errmsg);
}
#endif
return ok;
}
static int
openssl_callback_ignore_crls(int ok, X509_STORE_CTX * ctx)
{
if (ok)
return ok;
return X509_STORE_CTX_get_error(ctx) == X509_V_ERR_UNABLE_TO_GET_CRL;
}
static ASN1_OBJECT *
pkinit_pkcs7type2oid(pkinit_plg_crypto_context cryptoctx, int pkcs7_type)
{
switch (pkcs7_type) {
case CMS_SIGN_CLIENT:
return cryptoctx->id_pkinit_authData;
case CMS_SIGN_DRAFT9:
return OBJ_nid2obj(NID_pkcs7_data);
case CMS_SIGN_SERVER:
return cryptoctx->id_pkinit_DHKeyData;
case CMS_ENVEL_SERVER:
return cryptoctx->id_pkinit_rkeyData;
default:
return NULL;
}
}
static int
wrap_signeddata(unsigned char *data, unsigned int data_len,
unsigned char **out, unsigned int *out_len)
{
unsigned int orig_len = 0, oid_len = 0, tot_len = 0;
ASN1_OBJECT *oid = NULL;
unsigned char *p = NULL;
/* Get length to wrap the original data with SEQUENCE tag */
tot_len = orig_len = ASN1_object_size(1, (int)data_len, V_ASN1_SEQUENCE);
/* Add the signedData OID and adjust lengths */
oid = OBJ_nid2obj(NID_pkcs7_signed);
oid_len = i2d_ASN1_OBJECT(oid, NULL);
tot_len = ASN1_object_size(1, (int)(orig_len+oid_len), V_ASN1_SEQUENCE);
p = *out = malloc(tot_len);
if (p == NULL) return -1;
ASN1_put_object(&p, 1, (int)(orig_len+oid_len),
V_ASN1_SEQUENCE, V_ASN1_UNIVERSAL);
i2d_ASN1_OBJECT(oid, &p);
ASN1_put_object(&p, 1, (int)data_len, 0, V_ASN1_CONTEXT_SPECIFIC);
memcpy(p, data, data_len);
*out_len = tot_len;
return 0;
}
static int
prepare_enc_data(const uint8_t *indata, int indata_len, uint8_t **outdata,
int *outdata_len)
{
int tag, class;
long tlen, slen;
const uint8_t *p = indata, *oldp;
if (ASN1_get_object(&p, &slen, &tag, &class, indata_len) & 0x80)
return EINVAL;
if (tag != V_ASN1_SEQUENCE)
return EINVAL;
oldp = p;
if (ASN1_get_object(&p, &tlen, &tag, &class, slen) & 0x80)
return EINVAL;
p += tlen;
slen -= (p - oldp);
if (ASN1_get_object(&p, &tlen, &tag, &class, slen) & 0x80)
return EINVAL;
*outdata = malloc(tlen);
if (*outdata == NULL)
return ENOMEM;
memcpy(*outdata, p, tlen);
*outdata_len = tlen;
return 0;
}
#ifndef WITHOUT_PKCS11
static void *
pkinit_C_LoadModule(const char *modname, CK_FUNCTION_LIST_PTR_PTR p11p)
{
void *handle;
CK_RV (*getflist)(CK_FUNCTION_LIST_PTR_PTR);
pkiDebug("loading module \"%s\"... ", modname);
handle = dlopen(modname, RTLD_NOW);
if (handle == NULL) {
pkiDebug("not found\n");
return NULL;
}
getflist = (CK_RV (*)(CK_FUNCTION_LIST_PTR_PTR)) dlsym(handle, "C_GetFunctionList");
if (getflist == NULL || (*getflist)(p11p) != CKR_OK) {
dlclose(handle);
pkiDebug("failed\n");
return NULL;
}
pkiDebug("ok\n");
return handle;
}
static CK_RV
pkinit_C_UnloadModule(void *handle)
{
dlclose(handle);
return CKR_OK;
}
static krb5_error_code
pkinit_login(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
CK_TOKEN_INFO *tip, const char *password)
{
krb5_data rdat;
char *prompt;
const char *warning;
krb5_prompt kprompt;
krb5_prompt_type prompt_type;
int r = 0;
if (tip->flags & CKF_PROTECTED_AUTHENTICATION_PATH) {
rdat.data = NULL;
rdat.length = 0;
} else if (password != NULL) {
rdat.data = strdup(password);
rdat.length = strlen(password);
} else if (id_cryptoctx->prompter == NULL) {
r = KRB5_LIBOS_CANTREADPWD;
rdat.data = NULL;
} else {
if (tip->flags & CKF_USER_PIN_LOCKED)
warning = " (Warning: PIN locked)";
else if (tip->flags & CKF_USER_PIN_FINAL_TRY)
warning = " (Warning: PIN final try)";
else if (tip->flags & CKF_USER_PIN_COUNT_LOW)
warning = " (Warning: PIN count low)";
else
warning = "";
if (asprintf(&prompt, "%.*s PIN%s", (int) sizeof (tip->label),
tip->label, warning) < 0)
return ENOMEM;
rdat.data = malloc(tip->ulMaxPinLen + 2);
rdat.length = tip->ulMaxPinLen + 1;
kprompt.prompt = prompt;
kprompt.hidden = 1;
kprompt.reply = &rdat;
prompt_type = KRB5_PROMPT_TYPE_PREAUTH;
/* PROMPTER_INVOCATION */
k5int_set_prompt_types(context, &prompt_type);
r = (*id_cryptoctx->prompter)(context, id_cryptoctx->prompter_data,
NULL, NULL, 1, &kprompt);
k5int_set_prompt_types(context, 0);
free(prompt);
}
if (r == 0) {
r = id_cryptoctx->p11->C_Login(id_cryptoctx->session, CKU_USER,
(u_char *) rdat.data, rdat.length);
if (r != CKR_OK) {
pkiDebug("C_Login: %s\n", pkinit_pkcs11_code_to_text(r));
r = KRB5KDC_ERR_PREAUTH_FAILED;
}
}
free(rdat.data);
return r;
}
static krb5_error_code
pkinit_open_session(krb5_context context,
pkinit_identity_crypto_context cctx)
{
CK_ULONG i, r;
unsigned char *cp;
size_t label_len;
CK_ULONG count = 0;
CK_SLOT_ID_PTR slotlist;
CK_TOKEN_INFO tinfo;
char *p11name;
const char *password;
if (cctx->p11_module != NULL)
return 0; /* session already open */
/* Load module */
cctx->p11_module =
pkinit_C_LoadModule(cctx->p11_module_name, &cctx->p11);
if (cctx->p11_module == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
/* Init */
if ((r = cctx->p11->C_Initialize(NULL)) != CKR_OK) {
pkiDebug("C_Initialize: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
/* Get the list of available slots */
if (cctx->p11->C_GetSlotList(TRUE, NULL, &count) != CKR_OK)
return KRB5KDC_ERR_PREAUTH_FAILED;
if (count == 0)
return KRB5KDC_ERR_PREAUTH_FAILED;
slotlist = calloc(count, sizeof(CK_SLOT_ID));
if (slotlist == NULL)
return ENOMEM;
if (cctx->p11->C_GetSlotList(TRUE, slotlist, &count) != CKR_OK)
return KRB5KDC_ERR_PREAUTH_FAILED;
/* Look for the given token label, or if none given take the first one */
for (i = 0; i < count; i++) {
/* Skip slots that don't match the specified slotid, if given. */
if (cctx->slotid != PK_NOSLOT && cctx->slotid != slotlist[i])
continue;
/* Open session */
if ((r = cctx->p11->C_OpenSession(slotlist[i], CKF_SERIAL_SESSION,
NULL, NULL, &cctx->session)) != CKR_OK) {
pkiDebug("C_OpenSession: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
/* Get token info */
if ((r = cctx->p11->C_GetTokenInfo(slotlist[i], &tinfo)) != CKR_OK) {
pkiDebug("C_GetTokenInfo: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
/* tinfo.label is zero-filled but not necessarily zero-terminated.
* Find the length, ignoring any trailing spaces. */
for (cp = tinfo.label + sizeof(tinfo.label); cp > tinfo.label; cp--) {
if (cp[-1] != '\0' && cp[-1] != ' ')
break;
}
label_len = cp - tinfo.label;
pkiDebug("open_session: slotid %d token \"%.*s\"\n",
(int)slotlist[i], (int)label_len, tinfo.label);
if (cctx->token_label == NULL ||
(strlen(cctx->token_label) == label_len &&
memcmp(cctx->token_label, tinfo.label, label_len) == 0))
break;
cctx->p11->C_CloseSession(cctx->session);
}
if (i >= count) {
free(slotlist);
pkiDebug("open_session: no matching token found\n");
return KRB5KDC_ERR_PREAUTH_FAILED;
}
cctx->slotid = slotlist[i];
free(slotlist);
pkiDebug("open_session: slotid %d (%lu of %d)\n", (int)cctx->slotid,
i + 1, (int) count);
/* Login if needed */
if (tinfo.flags & CKF_LOGIN_REQUIRED) {
if (cctx->p11_module_name != NULL) {
if (cctx->slotid != PK_NOSLOT) {
if (asprintf(&p11name,
"PKCS11:module_name=%s:slotid=%ld:token=%.*s",
cctx->p11_module_name, (long)cctx->slotid,
(int)label_len, tinfo.label) < 0)
p11name = NULL;
} else {
if (asprintf(&p11name,
"PKCS11:module_name=%s,token=%.*s",
cctx->p11_module_name,
(int)label_len, tinfo.label) < 0)
p11name = NULL;
}
} else {
p11name = NULL;
}
if (cctx->defer_id_prompt) {
/* Supply the identity name to be passed to the responder. */
pkinit_set_deferred_id(&cctx->deferred_ids,
p11name, tinfo.flags, NULL);
free(p11name);
return KRB5KRB_ERR_GENERIC;
}
/* Look up a responder-supplied password for the token. */
password = pkinit_find_deferred_id(cctx->deferred_ids, p11name);
free(p11name);
r = pkinit_login(context, cctx, &tinfo, password);
}
return r;
}
/*
* Look for a key that's:
* 1. private
* 2. capable of the specified operation (usually signing or decrypting)
* 3. RSA (this may be wrong but it's all we can do for now)
* 4. matches the id of the cert we chose
*
* You must call pkinit_get_certs before calling pkinit_find_private_key
* (that's because we need the ID of the private key)
*
* pkcs11 says the id of the key doesn't have to match that of the cert, but
* I can't figure out any other way to decide which key to use.
*
* We should only find one key that fits all the requirements.
* If there are more than one, we just take the first one.
*/
krb5_error_code
pkinit_find_private_key(pkinit_identity_crypto_context id_cryptoctx,
CK_ATTRIBUTE_TYPE usage,
CK_OBJECT_HANDLE *objp)
{
CK_OBJECT_CLASS cls;
CK_ATTRIBUTE attrs[4];
CK_ULONG count;
CK_KEY_TYPE keytype;
unsigned int nattrs = 0;
int r;
#ifdef PKINIT_USE_KEY_USAGE
CK_BBOOL true_false;
#endif
cls = CKO_PRIVATE_KEY;
attrs[nattrs].type = CKA_CLASS;
attrs[nattrs].pValue = &cls;
attrs[nattrs].ulValueLen = sizeof cls;
nattrs++;
#ifdef PKINIT_USE_KEY_USAGE
/*
* Some cards get confused if you try to specify a key usage,
* so don't, and hope for the best. This will fail if you have
* several keys with the same id and different usages but I have
* not seen this on real cards.
*/
true_false = TRUE;
attrs[nattrs].type = usage;
attrs[nattrs].pValue = &true_false;
attrs[nattrs].ulValueLen = sizeof true_false;
nattrs++;
#endif
keytype = CKK_RSA;
attrs[nattrs].type = CKA_KEY_TYPE;
attrs[nattrs].pValue = &keytype;
attrs[nattrs].ulValueLen = sizeof keytype;
nattrs++;
attrs[nattrs].type = CKA_ID;
attrs[nattrs].pValue = id_cryptoctx->cert_id;
attrs[nattrs].ulValueLen = id_cryptoctx->cert_id_len;
nattrs++;
r = id_cryptoctx->p11->C_FindObjectsInit(id_cryptoctx->session, attrs, nattrs);
if (r != CKR_OK) {
pkiDebug("krb5_pkinit_sign_data: C_FindObjectsInit: %s\n",
pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
r = id_cryptoctx->p11->C_FindObjects(id_cryptoctx->session, objp, 1, &count);
id_cryptoctx->p11->C_FindObjectsFinal(id_cryptoctx->session);
pkiDebug("found %d private keys (%s)\n", (int) count, pkinit_pkcs11_code_to_text(r));
if (r != CKR_OK || count < 1)
return KRB5KDC_ERR_PREAUTH_FAILED;
return 0;
}
#endif
static krb5_error_code
pkinit_decode_data_fs(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
const uint8_t *data, unsigned int data_len,
uint8_t **decoded_data, unsigned int *decoded_data_len)
{
X509 *cert = sk_X509_value(id_cryptoctx->my_certs,
id_cryptoctx->cert_index);
EVP_PKEY *pkey = id_cryptoctx->my_key;
uint8_t *buf;
int buf_len, decrypt_len;
*decoded_data = NULL;
*decoded_data_len = 0;
if (cert != NULL && !X509_check_private_key(cert, pkey)) {
pkiDebug("private key does not match certificate\n");
return KRB5KDC_ERR_PREAUTH_FAILED;
}
buf_len = EVP_PKEY_size(pkey);
buf = malloc(buf_len + 10);
if (buf == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
decrypt_len = EVP_PKEY_decrypt_old(buf, data, data_len, pkey);
if (decrypt_len <= 0) {
pkiDebug("unable to decrypt received data (len=%d)\n", data_len);
free(buf);
return KRB5KDC_ERR_PREAUTH_FAILED;
}
*decoded_data = buf;
*decoded_data_len = decrypt_len;
return 0;
}
#ifndef WITHOUT_PKCS11
/*
* When using the ActivCard Linux pkcs11 library (v2.0.1), the decrypt function
* fails. By inserting an extra function call, which serves nothing but to
* change the stack, we were able to work around the issue. If the ActivCard
* library is fixed in the future, this function can be inlined back into the
* caller.
*/
static CK_RV
pkinit_C_Decrypt(pkinit_identity_crypto_context id_cryptoctx,
CK_BYTE_PTR pEncryptedData,
CK_ULONG ulEncryptedDataLen,
CK_BYTE_PTR pData,
CK_ULONG_PTR pulDataLen)
{
CK_RV rv = CKR_OK;
rv = id_cryptoctx->p11->C_Decrypt(id_cryptoctx->session, pEncryptedData,
ulEncryptedDataLen, pData, pulDataLen);
if (rv == CKR_OK) {
pkiDebug("pData %p *pulDataLen %d\n", (void *) pData,
(int) *pulDataLen);
}
return rv;
}
static krb5_error_code
pkinit_decode_data_pkcs11(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
const uint8_t *data, unsigned int data_len,
uint8_t **decoded_data,
unsigned int *decoded_data_len)
{
CK_OBJECT_HANDLE obj;
CK_ULONG len;
CK_MECHANISM mech;
uint8_t *cp;
int r;
*decoded_data = NULL;
*decoded_data_len = 0;
if (pkinit_open_session(context, id_cryptoctx)) {
pkiDebug("can't open pkcs11 session\n");
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkinit_find_private_key(id_cryptoctx, CKA_DECRYPT, &obj);
mech.mechanism = CKM_RSA_PKCS;
mech.pParameter = NULL;
mech.ulParameterLen = 0;
if ((r = id_cryptoctx->p11->C_DecryptInit(id_cryptoctx->session, &mech,
obj)) != CKR_OK) {
pkiDebug("C_DecryptInit: 0x%x\n", (int) r);
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkiDebug("data_len = %d\n", data_len);
cp = malloc((size_t) data_len);
if (cp == NULL)
return ENOMEM;
len = data_len;
pkiDebug("session %p edata %p edata_len %d data %p datalen @%p %d\n",
(void *) id_cryptoctx->session, (void *) data, (int) data_len,
(void *) cp, (void *) &len, (int) len);
r = pkinit_C_Decrypt(id_cryptoctx, (CK_BYTE_PTR) data, (CK_ULONG) data_len,
cp, &len);
if (r != CKR_OK) {
pkiDebug("C_Decrypt: %s\n", pkinit_pkcs11_code_to_text(r));
if (r == CKR_BUFFER_TOO_SMALL)
pkiDebug("decrypt %d needs %d\n", (int) data_len, (int) len);
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkiDebug("decrypt %d -> %d\n", (int) data_len, (int) len);
*decoded_data_len = len;
*decoded_data = cp;
return 0;
}
#endif
krb5_error_code
pkinit_decode_data(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
const uint8_t *data, unsigned int data_len,
uint8_t **decoded_data, unsigned int *decoded_data_len)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
*decoded_data = NULL;
*decoded_data_len = 0;
if (id_cryptoctx->pkcs11_method != 1)
retval = pkinit_decode_data_fs(context, id_cryptoctx, data, data_len,
decoded_data, decoded_data_len);
#ifndef WITHOUT_PKCS11
else
retval = pkinit_decode_data_pkcs11(context, id_cryptoctx, data,
data_len, decoded_data, decoded_data_len);
#endif
return retval;
}
static krb5_error_code
pkinit_sign_data_fs(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data,
unsigned int data_len,
unsigned char **sig,
unsigned int *sig_len)
{
if (create_signature(sig, sig_len, data, data_len,
id_cryptoctx->my_key) != 0) {
pkiDebug("failed to create the signature\n");
return KRB5KDC_ERR_PREAUTH_FAILED;
}
return 0;
}
#ifndef WITHOUT_PKCS11
static krb5_error_code
pkinit_sign_data_pkcs11(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data,
unsigned int data_len,
unsigned char **sig,
unsigned int *sig_len)
{
CK_OBJECT_HANDLE obj;
CK_ULONG len;
CK_MECHANISM mech;
unsigned char *cp;
int r;
if (pkinit_open_session(context, id_cryptoctx)) {
pkiDebug("can't open pkcs11 session\n");
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkinit_find_private_key(id_cryptoctx, CKA_SIGN, &obj);
mech.mechanism = id_cryptoctx->mech;
mech.pParameter = NULL;
mech.ulParameterLen = 0;
if ((r = id_cryptoctx->p11->C_SignInit(id_cryptoctx->session, &mech,
obj)) != CKR_OK) {
pkiDebug("C_SignInit: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
/*
* Key len would give an upper bound on sig size, but there's no way to
* get that. So guess, and if it's too small, re-malloc.
*/
len = PK_SIGLEN_GUESS;
cp = malloc((size_t) len);
if (cp == NULL)
return ENOMEM;
r = id_cryptoctx->p11->C_Sign(id_cryptoctx->session, data,
(CK_ULONG) data_len, cp, &len);
if (r == CKR_BUFFER_TOO_SMALL || (r == CKR_OK && len >= PK_SIGLEN_GUESS)) {
free(cp);
pkiDebug("C_Sign realloc %d\n", (int) len);
cp = malloc((size_t) len);
r = id_cryptoctx->p11->C_Sign(id_cryptoctx->session, data,
(CK_ULONG) data_len, cp, &len);
}
if (r != CKR_OK) {
pkiDebug("C_Sign: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkiDebug("sign %d -> %d\n", (int) data_len, (int) len);
*sig_len = len;
*sig = cp;
return 0;
}
#endif
krb5_error_code
pkinit_sign_data(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data,
unsigned int data_len,
unsigned char **sig,
unsigned int *sig_len)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
if (id_cryptoctx == NULL || id_cryptoctx->pkcs11_method != 1)
retval = pkinit_sign_data_fs(context, id_cryptoctx, data, data_len,
sig, sig_len);
#ifndef WITHOUT_PKCS11
else
retval = pkinit_sign_data_pkcs11(context, id_cryptoctx, data, data_len,
sig, sig_len);
#endif
return retval;
}
static krb5_error_code
create_signature(unsigned char **sig, unsigned int *sig_len,
unsigned char *data, unsigned int data_len, EVP_PKEY *pkey)
{
krb5_error_code retval = ENOMEM;
EVP_MD_CTX *ctx;
if (pkey == NULL)
return retval;
ctx = EVP_MD_CTX_new();
if (ctx == NULL)
return ENOMEM;
EVP_SignInit(ctx, EVP_sha1());
EVP_SignUpdate(ctx, data, data_len);
*sig_len = EVP_PKEY_size(pkey);
if ((*sig = malloc(*sig_len)) == NULL)
goto cleanup;
EVP_SignFinal(ctx, *sig, sig_len, pkey);
retval = 0;
cleanup:
EVP_MD_CTX_free(ctx);
return retval;
}
/*
* Note:
* This is not the routine the KDC uses to get its certificate.
* This routine is intended to be called by the client
* to obtain the KDC's certificate from some local storage
* to be sent as a hint in its request to the KDC.
*/
krb5_error_code
pkinit_get_kdc_cert(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
req_cryptoctx->received_cert = NULL;
retval = 0;
return retval;
}
static char *
reassemble_pkcs12_name(const char *filename)
{
char *ret;
if (asprintf(&ret, "PKCS12:%s", filename) < 0)
return NULL;
return ret;
}
static krb5_error_code
pkinit_get_certs_pkcs12(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
char *prompt_string = NULL;
X509 *x = NULL;
PKCS12 *p12 = NULL;
int ret;
FILE *fp;
EVP_PKEY *y = NULL;
if (idopts->cert_filename == NULL) {
pkiDebug("%s: failed to get user's cert location\n", __FUNCTION__);
goto cleanup;
}
if (idopts->key_filename == NULL) {
pkiDebug("%s: failed to get user's private key location\n", __FUNCTION__);
goto cleanup;
}
fp = fopen(idopts->cert_filename, "rb");
if (fp == NULL) {
TRACE_PKINIT_PKCS_OPEN_FAIL(context, idopts->cert_filename, errno);
goto cleanup;
}
set_cloexec_file(fp);
p12 = d2i_PKCS12_fp(fp, NULL);
fclose(fp);
if (p12 == NULL) {
TRACE_PKINIT_PKCS_DECODE_FAIL(context, idopts->cert_filename);
goto cleanup;
}
/*
* Try parsing with no pass phrase first. If that fails,
* prompt for the pass phrase and try again.
*/
ret = PKCS12_parse(p12, NULL, &y, &x, NULL);
if (ret == 0) {
krb5_data rdat;
krb5_prompt kprompt;
krb5_prompt_type prompt_type;
krb5_error_code r;
char prompt_reply[128];
char *prompt_prefix = _("Pass phrase for");
char *p12name = reassemble_pkcs12_name(idopts->cert_filename);
const char *tmp;
TRACE_PKINIT_PKCS_PARSE_FAIL_FIRST(context);
if (id_cryptoctx->defer_id_prompt) {
/* Supply the identity name to be passed to the responder. */
pkinit_set_deferred_id(&id_cryptoctx->deferred_ids, p12name, 0,
NULL);
free(p12name);
retval = 0;
goto cleanup;
}
/* Try to read a responder-supplied password. */
tmp = pkinit_find_deferred_id(id_cryptoctx->deferred_ids, p12name);
free(p12name);
if (tmp != NULL) {
/* Try using the responder-supplied password. */
rdat.data = (char *)tmp;
rdat.length = strlen(tmp);
} else if (id_cryptoctx->prompter == NULL) {
/* We can't use a prompter. */
goto cleanup;
} else {
/* Ask using a prompter. */
memset(prompt_reply, '\0', sizeof(prompt_reply));
rdat.data = prompt_reply;
rdat.length = sizeof(prompt_reply);
if (asprintf(&prompt_string, "%s %s", prompt_prefix,
idopts->cert_filename) < 0) {
prompt_string = NULL;
goto cleanup;
}
kprompt.prompt = prompt_string;
kprompt.hidden = 1;
kprompt.reply = &rdat;
prompt_type = KRB5_PROMPT_TYPE_PREAUTH;
/* PROMPTER_INVOCATION */
k5int_set_prompt_types(context, &prompt_type);
r = (*id_cryptoctx->prompter)(context, id_cryptoctx->prompter_data,
NULL, NULL, 1, &kprompt);
k5int_set_prompt_types(context, 0);
if (r) {
TRACE_PKINIT_PKCS_PROMPT_FAIL(context);
goto cleanup;
}
}
ret = PKCS12_parse(p12, rdat.data, &y, &x, NULL);
if (ret == 0) {
TRACE_PKINIT_PKCS_PARSE_FAIL_SECOND(context);
goto cleanup;
}
}
id_cryptoctx->creds[0] = malloc(sizeof(struct _pkinit_cred_info));
if (id_cryptoctx->creds[0] == NULL)
goto cleanup;
id_cryptoctx->creds[0]->name =
reassemble_pkcs12_name(idopts->cert_filename);
id_cryptoctx->creds[0]->cert = x;
#ifndef WITHOUT_PKCS11
id_cryptoctx->creds[0]->cert_id = NULL;
id_cryptoctx->creds[0]->cert_id_len = 0;
#endif
id_cryptoctx->creds[0]->key = y;
id_cryptoctx->creds[1] = NULL;
retval = 0;
cleanup:
free(prompt_string);
if (p12)
PKCS12_free(p12);
if (retval) {
if (x != NULL)
X509_free(x);
if (y != NULL)
EVP_PKEY_free(y);
}
return retval;
}
static char *
reassemble_files_name(const char *certfile, const char *keyfile)
{
char *ret;
if (keyfile != NULL) {
if (asprintf(&ret, "FILE:%s,%s", certfile, keyfile) < 0)
return NULL;
} else {
if (asprintf(&ret, "FILE:%s", certfile) < 0)
return NULL;
}
return ret;
}
static krb5_error_code
pkinit_load_fs_cert_and_key(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
char *certname,
char *keyname,
int cindex)
{
krb5_error_code retval;
X509 *x = NULL;
EVP_PKEY *y = NULL;
char *fsname = NULL;
const char *password;
fsname = reassemble_files_name(certname, keyname);
/* Try to read a responder-supplied password. */
password = pkinit_find_deferred_id(id_cryptoctx->deferred_ids, fsname);
/* Load the certificate. */
retval = get_cert(certname, &x);
if (retval != 0 || x == NULL) {
retval = oerr(context, 0, _("Cannot read certificate file '%s'"),
certname);
goto cleanup;
}
/* Load the key. */
retval = get_key(context, id_cryptoctx, keyname, fsname, &y, password);
if (retval != 0 || y == NULL) {
retval = oerr(context, 0, _("Cannot read key file '%s'"), fsname);
goto cleanup;
}
id_cryptoctx->creds[cindex] = malloc(sizeof(struct _pkinit_cred_info));
if (id_cryptoctx->creds[cindex] == NULL) {
retval = ENOMEM;
goto cleanup;
}
id_cryptoctx->creds[cindex]->name = reassemble_files_name(certname,
keyname);
id_cryptoctx->creds[cindex]->cert = x;
#ifndef WITHOUT_PKCS11
id_cryptoctx->creds[cindex]->cert_id = NULL;
id_cryptoctx->creds[cindex]->cert_id_len = 0;
#endif
id_cryptoctx->creds[cindex]->key = y;
id_cryptoctx->creds[cindex+1] = NULL;
retval = 0;
cleanup:
free(fsname);
if (retval != 0 || y == NULL) {
if (x != NULL)
X509_free(x);
if (y != NULL)
EVP_PKEY_free(y);
}
return retval;
}
static krb5_error_code
pkinit_get_certs_fs(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
if (idopts->cert_filename == NULL) {
pkiDebug("%s: failed to get user's cert location\n", __FUNCTION__);
goto cleanup;
}
if (idopts->key_filename == NULL) {
TRACE_PKINIT_NO_PRIVKEY(context);
goto cleanup;
}
retval = pkinit_load_fs_cert_and_key(context, id_cryptoctx,
idopts->cert_filename,
idopts->key_filename, 0);
cleanup:
return retval;
}
static krb5_error_code
pkinit_get_certs_dir(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ)
{
krb5_error_code retval = ENOMEM;
DIR *d = NULL;
struct dirent *dentry = NULL;
char certname[1024];
char keyname[1024];
int i = 0, len;
char *dirname, *suf;
if (idopts->cert_filename == NULL) {
TRACE_PKINIT_NO_CERT(context);
return ENOENT;
}
dirname = idopts->cert_filename;
d = opendir(dirname);
if (d == NULL)
return errno;
/*
* We'll assume that certs are named XXX.crt and the corresponding
* key is named XXX.key
*/
while ((i < MAX_CREDS_ALLOWED) && (dentry = readdir(d)) != NULL) {
/* Ignore subdirectories and anything starting with a dot */
#ifdef DT_DIR
if (dentry->d_type == DT_DIR)
continue;
#endif
if (dentry->d_name[0] == '.')
continue;
len = strlen(dentry->d_name);
if (len < 5)
continue;
suf = dentry->d_name + (len - 4);
if (strncmp(suf, ".crt", 4) != 0)
continue;
/* Checked length */
if (strlen(dirname) + strlen(dentry->d_name) + 2 > sizeof(certname)) {
pkiDebug("%s: Path too long -- directory '%s' and file '%s'\n",
__FUNCTION__, dirname, dentry->d_name);
continue;
}
snprintf(certname, sizeof(certname), "%s/%s", dirname, dentry->d_name);
snprintf(keyname, sizeof(keyname), "%s/%s", dirname, dentry->d_name);
len = strlen(keyname);
keyname[len - 3] = 'k';
keyname[len - 2] = 'e';
keyname[len - 1] = 'y';
retval = pkinit_load_fs_cert_and_key(context, id_cryptoctx,
certname, keyname, i);
if (retval == 0) {
TRACE_PKINIT_LOADED_CERT(context, dentry->d_name);
i++;
}
else
continue;
}
if (!id_cryptoctx->defer_id_prompt && i == 0) {
TRACE_PKINIT_NO_CERT_AND_KEY(context, idopts->cert_filename);
retval = ENOENT;
goto cleanup;
}
retval = 0;
cleanup:
if (d)
closedir(d);
return retval;
}
#ifndef WITHOUT_PKCS11
static char *
reassemble_pkcs11_name(pkinit_identity_opts *idopts)
{
struct k5buf buf;
int n = 0;
char *ret;
k5_buf_init_dynamic(&buf);
k5_buf_add(&buf, "PKCS11:");
n = 0;
if (idopts->p11_module_name != NULL) {
k5_buf_add_fmt(&buf, "%smodule_name=%s", n++ ? ":" : "",
idopts->p11_module_name);
}
if (idopts->token_label != NULL) {
k5_buf_add_fmt(&buf, "%stoken=%s", n++ ? ":" : "",
idopts->token_label);
}
if (idopts->cert_label != NULL) {
k5_buf_add_fmt(&buf, "%scertlabel=%s", n++ ? ":" : "",
idopts->cert_label);
}
if (idopts->cert_id_string != NULL) {
k5_buf_add_fmt(&buf, "%scertid=%s", n++ ? ":" : "",
idopts->cert_id_string);
}
if (idopts->slotid != PK_NOSLOT) {
k5_buf_add_fmt(&buf, "%sslotid=%ld", n++ ? ":" : "",
(long)idopts->slotid);
}
if (k5_buf_status(&buf) == 0)
ret = strdup(buf.data);
else
ret = NULL;
k5_buf_free(&buf);
return ret;
}
static krb5_error_code
pkinit_get_certs_pkcs11(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ)
{
#ifdef PKINIT_USE_MECH_LIST
CK_MECHANISM_TYPE_PTR mechp;
CK_MECHANISM_INFO info;
#endif
CK_OBJECT_CLASS cls;
CK_OBJECT_HANDLE obj;
CK_ATTRIBUTE attrs[4];
CK_ULONG count;
CK_CERTIFICATE_TYPE certtype;
CK_BYTE_PTR cert = NULL, cert_id;
const unsigned char *cp;
int i, r;
unsigned int nattrs;
X509 *x = NULL;
/* Copy stuff from idopts -> id_cryptoctx */
if (idopts->p11_module_name != NULL) {
free(id_cryptoctx->p11_module_name);
id_cryptoctx->p11_module_name = strdup(idopts->p11_module_name);
if (id_cryptoctx->p11_module_name == NULL)
return ENOMEM;
}
if (idopts->token_label != NULL) {
id_cryptoctx->token_label = strdup(idopts->token_label);
if (id_cryptoctx->token_label == NULL)
return ENOMEM;
}
if (idopts->cert_label != NULL) {
id_cryptoctx->cert_label = strdup(idopts->cert_label);
if (id_cryptoctx->cert_label == NULL)
return ENOMEM;
}
/* Convert the ascii cert_id string into a binary blob */
if (idopts->cert_id_string != NULL) {
BIGNUM *bn = NULL;
BN_hex2bn(&bn, idopts->cert_id_string);
if (bn == NULL)
return ENOMEM;
id_cryptoctx->cert_id_len = BN_num_bytes(bn);
id_cryptoctx->cert_id = malloc((size_t) id_cryptoctx->cert_id_len);
if (id_cryptoctx->cert_id == NULL) {
BN_free(bn);
return ENOMEM;
}
BN_bn2bin(bn, id_cryptoctx->cert_id);
BN_free(bn);
}
id_cryptoctx->slotid = idopts->slotid;
id_cryptoctx->pkcs11_method = 1;
if (pkinit_open_session(context, id_cryptoctx)) {
pkiDebug("can't open pkcs11 session\n");
if (!id_cryptoctx->defer_id_prompt)
return KRB5KDC_ERR_PREAUTH_FAILED;
}
if (id_cryptoctx->defer_id_prompt) {
/*
* We need to reset all of the PKCS#11 state, so that the next time we
* poke at it, it'll be in as close to the state it was in after we
* loaded it the first time as we can make it.
*/
pkinit_fini_pkcs11(id_cryptoctx);
pkinit_init_pkcs11(id_cryptoctx);
return 0;
}
#ifndef PKINIT_USE_MECH_LIST
/*
* We'd like to use CKM_SHA1_RSA_PKCS for signing if it's available, but
* many cards seems to be confused about whether they are capable of
* this or not. The safe thing seems to be to ignore the mechanism list,
* always use CKM_RSA_PKCS and calculate the sha1 digest ourselves.
*/
id_cryptoctx->mech = CKM_RSA_PKCS;
#else
if ((r = id_cryptoctx->p11->C_GetMechanismList(id_cryptoctx->slotid, NULL,
&count)) != CKR_OK || count <= 0) {
pkiDebug("C_GetMechanismList: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
mechp = malloc(count * sizeof (CK_MECHANISM_TYPE));
if (mechp == NULL)
return ENOMEM;
if ((r = id_cryptoctx->p11->C_GetMechanismList(id_cryptoctx->slotid,
mechp, &count)) != CKR_OK)
return KRB5KDC_ERR_PREAUTH_FAILED;
for (i = 0; i < count; i++) {
if ((r = id_cryptoctx->p11->C_GetMechanismInfo(id_cryptoctx->slotid,
mechp[i], &info)) != CKR_OK)
return KRB5KDC_ERR_PREAUTH_FAILED;
#ifdef DEBUG_MECHINFO
pkiDebug("mech %x flags %x\n", (int) mechp[i], (int) info.flags);
if ((info.flags & (CKF_SIGN|CKF_DECRYPT)) == (CKF_SIGN|CKF_DECRYPT))
pkiDebug(" this mech is good for sign & decrypt\n");
#endif
if (mechp[i] == CKM_RSA_PKCS) {
/* This seems backwards... */
id_cryptoctx->mech =
(info.flags & CKF_SIGN) ? CKM_SHA1_RSA_PKCS : CKM_RSA_PKCS;
}
}
free(mechp);
pkiDebug("got %d mechs from card\n", (int) count);
#endif
cls = CKO_CERTIFICATE;
attrs[0].type = CKA_CLASS;
attrs[0].pValue = &cls;
attrs[0].ulValueLen = sizeof cls;
certtype = CKC_X_509;
attrs[1].type = CKA_CERTIFICATE_TYPE;
attrs[1].pValue = &certtype;
attrs[1].ulValueLen = sizeof certtype;
nattrs = 2;
/* If a cert id and/or label were given, use them too */
if (id_cryptoctx->cert_id_len > 0) {
attrs[nattrs].type = CKA_ID;
attrs[nattrs].pValue = id_cryptoctx->cert_id;
attrs[nattrs].ulValueLen = id_cryptoctx->cert_id_len;
nattrs++;
}
if (id_cryptoctx->cert_label != NULL) {
attrs[nattrs].type = CKA_LABEL;
attrs[nattrs].pValue = id_cryptoctx->cert_label;
attrs[nattrs].ulValueLen = strlen(id_cryptoctx->cert_label);
nattrs++;
}
r = id_cryptoctx->p11->C_FindObjectsInit(id_cryptoctx->session, attrs, nattrs);
if (r != CKR_OK) {
pkiDebug("C_FindObjectsInit: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
for (i = 0; ; i++) {
if (i >= MAX_CREDS_ALLOWED)
return KRB5KDC_ERR_PREAUTH_FAILED;
/* Look for x.509 cert */
if ((r = id_cryptoctx->p11->C_FindObjects(id_cryptoctx->session,
&obj, 1, &count)) != CKR_OK || count <= 0) {
id_cryptoctx->creds[i] = NULL;
break;
}
/* Get cert and id len */
attrs[0].type = CKA_VALUE;
attrs[0].pValue = NULL;
attrs[0].ulValueLen = 0;
attrs[1].type = CKA_ID;
attrs[1].pValue = NULL;
attrs[1].ulValueLen = 0;
if ((r = id_cryptoctx->p11->C_GetAttributeValue(id_cryptoctx->session,
obj, attrs, 2)) != CKR_OK && r != CKR_BUFFER_TOO_SMALL) {
pkiDebug("C_GetAttributeValue: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
cert = (CK_BYTE_PTR) malloc((size_t) attrs[0].ulValueLen + 1);
cert_id = (CK_BYTE_PTR) malloc((size_t) attrs[1].ulValueLen + 1);
if (cert == NULL || cert_id == NULL)
return ENOMEM;
/* Read the cert and id off the card */
attrs[0].type = CKA_VALUE;
attrs[0].pValue = cert;
attrs[1].type = CKA_ID;
attrs[1].pValue = cert_id;
if ((r = id_cryptoctx->p11->C_GetAttributeValue(id_cryptoctx->session,
obj, attrs, 2)) != CKR_OK) {
pkiDebug("C_GetAttributeValue: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkiDebug("cert %d size %d id %d idlen %d\n", i,
(int) attrs[0].ulValueLen, (int) cert_id[0],
(int) attrs[1].ulValueLen);
cp = (unsigned char *) cert;
x = d2i_X509(NULL, &cp, (int) attrs[0].ulValueLen);
if (x == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
id_cryptoctx->creds[i] = malloc(sizeof(struct _pkinit_cred_info));
if (id_cryptoctx->creds[i] == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
id_cryptoctx->creds[i]->name = reassemble_pkcs11_name(idopts);
id_cryptoctx->creds[i]->cert = x;
id_cryptoctx->creds[i]->key = NULL;
id_cryptoctx->creds[i]->cert_id = cert_id;
id_cryptoctx->creds[i]->cert_id_len = attrs[1].ulValueLen;
free(cert);
}
id_cryptoctx->p11->C_FindObjectsFinal(id_cryptoctx->session);
if (cert == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
return 0;
}
#endif
static void
free_cred_info(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
struct _pkinit_cred_info *cred)
{
if (cred != NULL) {
if (cred->cert != NULL)
X509_free(cred->cert);
if (cred->key != NULL)
EVP_PKEY_free(cred->key);
#ifndef WITHOUT_PKCS11
free(cred->cert_id);
#endif
free(cred->name);
free(cred);
}
}
krb5_error_code
crypto_free_cert_info(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx)
{
int i;
if (id_cryptoctx == NULL)
return EINVAL;
for (i = 0; i < MAX_CREDS_ALLOWED; i++) {
if (id_cryptoctx->creds[i] != NULL) {
free_cred_info(context, id_cryptoctx, id_cryptoctx->creds[i]);
id_cryptoctx->creds[i] = NULL;
}
}
return 0;
}
krb5_error_code
crypto_load_certs(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ,
krb5_boolean defer_id_prompts)
{
krb5_error_code retval;
id_cryptoctx->defer_id_prompt = defer_id_prompts;
switch(idopts->idtype) {
case IDTYPE_FILE:
retval = pkinit_get_certs_fs(context, plg_cryptoctx,
req_cryptoctx, idopts,
id_cryptoctx, princ);
break;
case IDTYPE_DIR:
retval = pkinit_get_certs_dir(context, plg_cryptoctx,
req_cryptoctx, idopts,
id_cryptoctx, princ);
break;
#ifndef WITHOUT_PKCS11
case IDTYPE_PKCS11:
retval = pkinit_get_certs_pkcs11(context, plg_cryptoctx,
req_cryptoctx, idopts,
id_cryptoctx, princ);
break;
#endif
case IDTYPE_PKCS12:
retval = pkinit_get_certs_pkcs12(context, plg_cryptoctx,
req_cryptoctx, idopts,
id_cryptoctx, princ);
break;
default:
retval = EINVAL;
}
if (retval)
goto cleanup;
cleanup:
return retval;
}
/*
* Get certificate Key Usage and Extended Key Usage
*/
static krb5_error_code
crypto_retrieve_X509_key_usage(krb5_context context,
pkinit_plg_crypto_context plgcctx,
pkinit_req_crypto_context reqcctx,
X509 *x,
unsigned int *ret_ku_bits,
unsigned int *ret_eku_bits)
{
krb5_error_code retval = 0;
int i;
unsigned int eku_bits = 0, ku_bits = 0;
ASN1_BIT_STRING *usage = NULL;
if (ret_ku_bits == NULL && ret_eku_bits == NULL)
return EINVAL;
if (ret_eku_bits)
*ret_eku_bits = 0;
else {
pkiDebug("%s: EKUs not requested, not checking\n", __FUNCTION__);
goto check_kus;
}
/* Start with Extended Key usage */
i = X509_get_ext_by_NID(x, NID_ext_key_usage, -1);
if (i >= 0) {
EXTENDED_KEY_USAGE *eku;
eku = X509_get_ext_d2i(x, NID_ext_key_usage, NULL, NULL);
if (eku) {
for (i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
ASN1_OBJECT *certoid;
certoid = sk_ASN1_OBJECT_value(eku, i);
if ((OBJ_cmp(certoid, plgcctx->id_pkinit_KPClientAuth)) == 0)
eku_bits |= PKINIT_EKU_PKINIT;
else if ((OBJ_cmp(certoid, OBJ_nid2obj(NID_ms_smartcard_login))) == 0)
eku_bits |= PKINIT_EKU_MSSCLOGIN;
else if ((OBJ_cmp(certoid, OBJ_nid2obj(NID_client_auth))) == 0)
eku_bits |= PKINIT_EKU_CLIENTAUTH;
else if ((OBJ_cmp(certoid, OBJ_nid2obj(NID_email_protect))) == 0)
eku_bits |= PKINIT_EKU_EMAILPROTECTION;
}
EXTENDED_KEY_USAGE_free(eku);
}
}
pkiDebug("%s: returning eku 0x%08x\n", __FUNCTION__, eku_bits);
*ret_eku_bits = eku_bits;
check_kus:
/* Now the Key Usage bits */
if (ret_ku_bits)
*ret_ku_bits = 0;
else {
pkiDebug("%s: KUs not requested, not checking\n", __FUNCTION__);
goto out;
}
/* Make sure usage exists before checking bits */
X509_check_ca(x);
usage = X509_get_ext_d2i(x, NID_key_usage, NULL, NULL);
if (usage) {
if (!ku_reject(x, X509v3_KU_DIGITAL_SIGNATURE))
ku_bits |= PKINIT_KU_DIGITALSIGNATURE;
if (!ku_reject(x, X509v3_KU_KEY_ENCIPHERMENT))
ku_bits |= PKINIT_KU_KEYENCIPHERMENT;
ASN1_BIT_STRING_free(usage);
}
pkiDebug("%s: returning ku 0x%08x\n", __FUNCTION__, ku_bits);
*ret_ku_bits = ku_bits;
retval = 0;
out:
return retval;
}
/*
* Return a string format of an X509_NAME in buf where
* size is an in/out parameter. On input it is the size
* of the buffer, and on output it is the actual length
* of the name.
* If buf is NULL, returns the length req'd to hold name
*/
static char *
X509_NAME_oneline_ex(X509_NAME * a,
char *buf,
unsigned int *size,
unsigned long flag)
{
BIO *out = NULL;
out = BIO_new(BIO_s_mem ());
if (X509_NAME_print_ex(out, a, 0, flag) > 0) {
if (buf != NULL && (*size) > (unsigned int) BIO_number_written(out)) {
memset(buf, 0, *size);
BIO_read(out, buf, (int) BIO_number_written(out));
}
else {
*size = BIO_number_written(out);
}
}
BIO_free(out);
return (buf);
}
/*
* Get number of certificates available after crypto_load_certs()
*/
static krb5_error_code
crypto_cert_get_count(pkinit_identity_crypto_context id_cryptoctx,
int *cert_count)
{
int count;
*cert_count = 0;
if (id_cryptoctx == NULL || id_cryptoctx->creds[0] == NULL)
return EINVAL;
for (count = 0;
count <= MAX_CREDS_ALLOWED && id_cryptoctx->creds[count] != NULL;
count++);
*cert_count = count;
return 0;
}
void
crypto_cert_free_matching_data(krb5_context context,
pkinit_cert_matching_data *md)
{
int i;
if (md == NULL)
return;
free(md->subject_dn);
free(md->issuer_dn);
for (i = 0; md->sans != NULL && md->sans[i] != NULL; i++)
krb5_free_principal(context, md->sans[i]);
free(md->sans);
free(md);
}
/*
* Free certificate matching data.
*/
void
crypto_cert_free_matching_data_list(krb5_context context,
pkinit_cert_matching_data **list)
{
int i;
for (i = 0; list != NULL && list[i] != NULL; i++)
crypto_cert_free_matching_data(context, list[i]);
free(list);
}
/*
* Get certificate matching data for cert.
*/
static krb5_error_code
get_matching_data(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx, X509 *cert,
pkinit_cert_matching_data **md_out)
{
krb5_error_code ret = ENOMEM;
pkinit_cert_matching_data *md = NULL;
krb5_principal *pkinit_sans = NULL, *upn_sans = NULL;
size_t i, j;
char buf[DN_BUF_LEN];
unsigned int bufsize = sizeof(buf);
*md_out = NULL;
md = calloc(1, sizeof(*md));
if (md == NULL)
goto cleanup;
/* Get the subject name (in rfc2253 format). */
X509_NAME_oneline_ex(X509_get_subject_name(cert), buf, &bufsize,
XN_FLAG_SEP_COMMA_PLUS);
md->subject_dn = strdup(buf);
if (md->subject_dn == NULL) {
ret = ENOMEM;
goto cleanup;
}
/* Get the issuer name (in rfc2253 format). */
X509_NAME_oneline_ex(X509_get_issuer_name(cert), buf, &bufsize,
XN_FLAG_SEP_COMMA_PLUS);
md->issuer_dn = strdup(buf);
if (md->issuer_dn == NULL) {
ret = ENOMEM;
goto cleanup;
}
/* Get the SAN data. */
ret = crypto_retrieve_X509_sans(context, plg_cryptoctx, req_cryptoctx,
cert, &pkinit_sans, &upn_sans, NULL);
if (ret)
goto cleanup;
j = 0;
if (pkinit_sans != NULL) {
for (i = 0; pkinit_sans[i] != NULL; i++)
j++;
}
if (upn_sans != NULL) {
for (i = 0; upn_sans[i] != NULL; i++)
j++;
}
if (j != 0) {
md->sans = calloc((size_t)j+1, sizeof(*md->sans));
if (md->sans == NULL) {
ret = ENOMEM;
goto cleanup;
}
j = 0;
if (pkinit_sans != NULL) {
for (i = 0; pkinit_sans[i] != NULL; i++)
md->sans[j++] = pkinit_sans[i];
free(pkinit_sans);
}
if (upn_sans != NULL) {
for (i = 0; upn_sans[i] != NULL; i++)
md->sans[j++] = upn_sans[i];
free(upn_sans);
}
md->sans[j] = NULL;
} else
md->sans = NULL;
/* Get the KU and EKU data. */
ret = crypto_retrieve_X509_key_usage(context, plg_cryptoctx,
req_cryptoctx, cert, &md->ku_bits,
&md->eku_bits);
if (ret)
goto cleanup;
*md_out = md;
md = NULL;
cleanup:
crypto_cert_free_matching_data(context, md);
return ret;
}
krb5_error_code
crypto_cert_get_matching_data(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
pkinit_cert_matching_data ***md_out)
{
krb5_error_code ret;
pkinit_cert_matching_data **md_list = NULL;
int count, i;
ret = crypto_cert_get_count(id_cryptoctx, &count);
if (ret)
goto cleanup;
md_list = calloc(count + 1, sizeof(*md_list));
if (md_list == NULL) {
ret = ENOMEM;
goto cleanup;
}
for (i = 0; i < count; i++) {
ret = get_matching_data(context, plg_cryptoctx, req_cryptoctx,
id_cryptoctx->creds[i]->cert, &md_list[i]);
if (ret) {
pkiDebug("%s: crypto_cert_get_matching_data error %d, %s\n",
__FUNCTION__, ret, error_message(ret));
goto cleanup;
}
}
*md_out = md_list;
md_list = NULL;
cleanup:
crypto_cert_free_matching_data_list(context, md_list);
return ret;
}
/*
* Set the certificate in idctx->creds[cred_index] as the selected certificate.
*/
krb5_error_code
crypto_cert_select(krb5_context context, pkinit_identity_crypto_context idctx,
size_t cred_index)
{
pkinit_cred_info ci = NULL;
if (cred_index >= MAX_CREDS_ALLOWED || idctx->creds[cred_index] == NULL)
return ENOENT;
ci = idctx->creds[cred_index];
/* copy the selected cert into our id_cryptoctx */
if (idctx->my_certs != NULL)
sk_X509_pop_free(idctx->my_certs, X509_free);
idctx->my_certs = sk_X509_new_null();
sk_X509_push(idctx->my_certs, ci->cert);
free(idctx->identity);
/* hang on to the selected credential name */
if (ci->name != NULL)
idctx->identity = strdup(ci->name);
else
idctx->identity = NULL;
ci->cert = NULL; /* Don't free it twice */
idctx->cert_index = 0;
if (idctx->pkcs11_method != 1) {
idctx->my_key = ci->key;
ci->key = NULL; /* Don't free it twice */
}
#ifndef WITHOUT_PKCS11
else {
idctx->cert_id = ci->cert_id;
ci->cert_id = NULL; /* Don't free it twice */
idctx->cert_id_len = ci->cert_id_len;
}
#endif
return 0;
}
/*
* Choose the default certificate as "the chosen one"
*/
krb5_error_code
crypto_cert_select_default(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx)
{
krb5_error_code retval;
int cert_count;
retval = crypto_cert_get_count(id_cryptoctx, &cert_count);
if (retval)
goto errout;
if (cert_count != 1) {
TRACE_PKINIT_NO_DEFAULT_CERT(context, cert_count);
retval = EINVAL;
goto errout;
}
/* copy the selected cert into our id_cryptoctx */
if (id_cryptoctx->my_certs != NULL) {
sk_X509_pop_free(id_cryptoctx->my_certs, X509_free);
}
id_cryptoctx->my_certs = sk_X509_new_null();
sk_X509_push(id_cryptoctx->my_certs, id_cryptoctx->creds[0]->cert);
id_cryptoctx->creds[0]->cert = NULL; /* Don't free it twice */
id_cryptoctx->cert_index = 0;
/* hang on to the selected credential name */
if (id_cryptoctx->creds[0]->name != NULL)
id_cryptoctx->identity = strdup(id_cryptoctx->creds[0]->name);
else
id_cryptoctx->identity = NULL;
if (id_cryptoctx->pkcs11_method != 1) {
id_cryptoctx->my_key = id_cryptoctx->creds[0]->key;
id_cryptoctx->creds[0]->key = NULL; /* Don't free it twice */
}
#ifndef WITHOUT_PKCS11
else {
id_cryptoctx->cert_id = id_cryptoctx->creds[0]->cert_id;
id_cryptoctx->creds[0]->cert_id = NULL; /* Don't free it twice */
id_cryptoctx->cert_id_len = id_cryptoctx->creds[0]->cert_id_len;
}
#endif
retval = 0;
errout:
return retval;
}
static krb5_error_code
load_cas_and_crls(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int catype,
char *filename)
{
STACK_OF(X509_INFO) *sk = NULL;
STACK_OF(X509) *ca_certs = NULL;
STACK_OF(X509_CRL) *ca_crls = NULL;
BIO *in = NULL;
krb5_error_code retval = ENOMEM;
int i = 0;
/* If there isn't already a stack in the context,
* create a temporary one now */
switch(catype) {
case CATYPE_ANCHORS:
if (id_cryptoctx->trustedCAs != NULL)
ca_certs = id_cryptoctx->trustedCAs;
else {
ca_certs = sk_X509_new_null();
if (ca_certs == NULL)
return ENOMEM;
}
break;
case CATYPE_INTERMEDIATES:
if (id_cryptoctx->intermediateCAs != NULL)
ca_certs = id_cryptoctx->intermediateCAs;
else {
ca_certs = sk_X509_new_null();
if (ca_certs == NULL)
return ENOMEM;
}
break;
case CATYPE_CRLS:
if (id_cryptoctx->revoked != NULL)
ca_crls = id_cryptoctx->revoked;
else {
ca_crls = sk_X509_CRL_new_null();
if (ca_crls == NULL)
return ENOMEM;
}
break;
default:
return ENOTSUP;
}
if (!(in = BIO_new_file(filename, "r"))) {
retval = oerr(context, 0, _("Cannot open file '%s'"), filename);
goto cleanup;
}
/* This loads from a file, a stack of x509/crl/pkey sets */
if ((sk = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL)) == NULL) {
pkiDebug("%s: error reading file '%s'\n", __FUNCTION__, filename);
retval = oerr(context, 0, _("Cannot read file '%s'"), filename);
goto cleanup;
}
/* scan over the stack created from loading the file contents,
* weed out duplicates, and push new ones onto the return stack
*/
for (i = 0; i < sk_X509_INFO_num(sk); i++) {
X509_INFO *xi = sk_X509_INFO_value(sk, i);
if (xi != NULL && xi->x509 != NULL && catype != CATYPE_CRLS) {
int j = 0, size = sk_X509_num(ca_certs), flag = 0;
if (!size) {
sk_X509_push(ca_certs, xi->x509);
xi->x509 = NULL;
continue;
}
for (j = 0; j < size; j++) {
X509 *x = sk_X509_value(ca_certs, j);
flag = X509_cmp(x, xi->x509);
if (flag == 0)
break;
else
continue;
}
if (flag != 0) {
sk_X509_push(ca_certs, X509_dup(xi->x509));
}
} else if (xi != NULL && xi->crl != NULL && catype == CATYPE_CRLS) {
int j = 0, size = sk_X509_CRL_num(ca_crls), flag = 0;
if (!size) {
sk_X509_CRL_push(ca_crls, xi->crl);
xi->crl = NULL;
continue;
}
for (j = 0; j < size; j++) {
X509_CRL *x = sk_X509_CRL_value(ca_crls, j);
flag = X509_CRL_cmp(x, xi->crl);
if (flag == 0)
break;
else
continue;
}
if (flag != 0) {
sk_X509_CRL_push(ca_crls, X509_CRL_dup(xi->crl));
}
}
}
/* If we added something and there wasn't a stack in the
* context before, add the temporary stack to the context.
*/
switch(catype) {
case CATYPE_ANCHORS:
if (sk_X509_num(ca_certs) == 0) {
TRACE_PKINIT_NO_CA_ANCHOR(context, filename);
if (id_cryptoctx->trustedCAs == NULL)
sk_X509_free(ca_certs);
} else {
if (id_cryptoctx->trustedCAs == NULL)
id_cryptoctx->trustedCAs = ca_certs;
}
break;
case CATYPE_INTERMEDIATES:
if (sk_X509_num(ca_certs) == 0) {
TRACE_PKINIT_NO_CA_INTERMEDIATE(context, filename);
if (id_cryptoctx->intermediateCAs == NULL)
sk_X509_free(ca_certs);
} else {
if (id_cryptoctx->intermediateCAs == NULL)
id_cryptoctx->intermediateCAs = ca_certs;
}
break;
case CATYPE_CRLS:
if (sk_X509_CRL_num(ca_crls) == 0) {
TRACE_PKINIT_NO_CRL(context, filename);
if (id_cryptoctx->revoked == NULL)
sk_X509_CRL_free(ca_crls);
} else {
if (id_cryptoctx->revoked == NULL)
id_cryptoctx->revoked = ca_crls;
}
break;
default:
/* Should have been caught above! */
retval = EINVAL;
goto cleanup;
break;
}
retval = 0;
cleanup:
if (in != NULL)
BIO_free(in);
if (sk != NULL)
sk_X509_INFO_pop_free(sk, X509_INFO_free);
return retval;
}
static krb5_error_code
load_cas_and_crls_dir(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int catype,
char *dirname)
{
krb5_error_code retval = EINVAL;
DIR *d = NULL;
struct dirent *dentry = NULL;
char filename[1024];
if (dirname == NULL)
return EINVAL;
d = opendir(dirname);
if (d == NULL)
return ENOENT;
while ((dentry = readdir(d))) {
if (strlen(dirname) + strlen(dentry->d_name) + 2 > sizeof(filename)) {
pkiDebug("%s: Path too long -- directory '%s' and file '%s'\n",
__FUNCTION__, dirname, dentry->d_name);
goto cleanup;
}
/* Ignore subdirectories and anything starting with a dot */
#ifdef DT_DIR
if (dentry->d_type == DT_DIR)
continue;
#endif
if (dentry->d_name[0] == '.')
continue;
snprintf(filename, sizeof(filename), "%s/%s", dirname, dentry->d_name);
retval = load_cas_and_crls(context, plg_cryptoctx, req_cryptoctx,
id_cryptoctx, catype, filename);
if (retval)
goto cleanup;
}
retval = 0;
cleanup:
if (d != NULL)
closedir(d);
return retval;
}
krb5_error_code
crypto_load_cas_and_crls(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
int idtype,
int catype,
char *id)
{
switch (idtype) {
case IDTYPE_FILE:
TRACE_PKINIT_LOAD_FROM_FILE(context);
return load_cas_and_crls(context, plg_cryptoctx, req_cryptoctx,
id_cryptoctx, catype, id);
break;
case IDTYPE_DIR:
TRACE_PKINIT_LOAD_FROM_DIR(context);
return load_cas_and_crls_dir(context, plg_cryptoctx, req_cryptoctx,
id_cryptoctx, catype, id);
break;
default:
return ENOTSUP;
break;
}
}
static krb5_error_code
create_identifiers_from_stack(STACK_OF(X509) *sk,
krb5_external_principal_identifier *** ids)
{
int i = 0, sk_size = sk_X509_num(sk);
krb5_external_principal_identifier **krb5_cas = NULL;
X509 *x = NULL;
X509_NAME *xn = NULL;
unsigned char *p = NULL;
int len = 0;
PKCS7_ISSUER_AND_SERIAL *is = NULL;
char buf[DN_BUF_LEN];
*ids = NULL;
krb5_cas = calloc(sk_size + 1, sizeof(*krb5_cas));
if (krb5_cas == NULL)
return ENOMEM;
for (i = 0; i < sk_size; i++) {
krb5_cas[i] = malloc(sizeof(krb5_external_principal_identifier));
x = sk_X509_value(sk, i);
X509_NAME_oneline(X509_get_subject_name(x), buf, sizeof(buf));
pkiDebug("#%d cert= %s\n", i, buf);
/* fill-in subjectName */
krb5_cas[i]->subjectName.magic = 0;
krb5_cas[i]->subjectName.length = 0;
krb5_cas[i]->subjectName.data = NULL;
xn = X509_get_subject_name(x);
len = i2d_X509_NAME(xn, NULL);
if ((p = malloc((size_t) len)) == NULL)
goto oom;
krb5_cas[i]->subjectName.data = (char *)p;
i2d_X509_NAME(xn, &p);
krb5_cas[i]->subjectName.length = len;
/* fill-in issuerAndSerialNumber */
krb5_cas[i]->issuerAndSerialNumber.length = 0;
krb5_cas[i]->issuerAndSerialNumber.magic = 0;
krb5_cas[i]->issuerAndSerialNumber.data = NULL;
is = PKCS7_ISSUER_AND_SERIAL_new();
if (is == NULL)
goto oom;
X509_NAME_set(&is->issuer, X509_get_issuer_name(x));
ASN1_INTEGER_free(is->serial);
is->serial = ASN1_INTEGER_dup(X509_get_serialNumber(x));
if (is->serial == NULL)
goto oom;
len = i2d_PKCS7_ISSUER_AND_SERIAL(is, NULL);
p = malloc(len);
if (p == NULL)
goto oom;
krb5_cas[i]->issuerAndSerialNumber.data = (char *)p;
i2d_PKCS7_ISSUER_AND_SERIAL(is, &p);
krb5_cas[i]->issuerAndSerialNumber.length = len;
/* fill-in subjectKeyIdentifier */
krb5_cas[i]->subjectKeyIdentifier.length = 0;
krb5_cas[i]->subjectKeyIdentifier.magic = 0;
krb5_cas[i]->subjectKeyIdentifier.data = NULL;
if (X509_get_ext_by_NID(x, NID_subject_key_identifier, -1) >= 0) {
ASN1_OCTET_STRING *ikeyid;
ikeyid = X509_get_ext_d2i(x, NID_subject_key_identifier, NULL,
NULL);
if (ikeyid != NULL) {
len = i2d_ASN1_OCTET_STRING(ikeyid, NULL);
p = malloc(len);
if (p == NULL)
goto oom;
krb5_cas[i]->subjectKeyIdentifier.data = (char *)p;
i2d_ASN1_OCTET_STRING(ikeyid, &p);
krb5_cas[i]->subjectKeyIdentifier.length = len;
ASN1_OCTET_STRING_free(ikeyid);
}
}
PKCS7_ISSUER_AND_SERIAL_free(is);
is = NULL;
}
*ids = krb5_cas;
return 0;
oom:
free_krb5_external_principal_identifier(&krb5_cas);
PKCS7_ISSUER_AND_SERIAL_free(is);
return ENOMEM;
}
static krb5_error_code
create_krb5_invalidCertificates(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_external_principal_identifier *** ids)
{
krb5_error_code retval = ENOMEM;
STACK_OF(X509) *sk = NULL;
*ids = NULL;
if (req_cryptoctx->received_cert == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
sk = sk_X509_new_null();
if (sk == NULL)
goto cleanup;
sk_X509_push(sk, req_cryptoctx->received_cert);
retval = create_identifiers_from_stack(sk, ids);
sk_X509_free(sk);
cleanup:
return retval;
}
krb5_error_code
create_krb5_supportedCMSTypes(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_algorithm_identifier ***oids)
{
krb5_error_code retval = ENOMEM;
krb5_algorithm_identifier **loids = NULL;
krb5_data des3oid = {0, 8, "\x2A\x86\x48\x86\xF7\x0D\x03\x07" };
*oids = NULL;
loids = malloc(2 * sizeof(krb5_algorithm_identifier *));
if (loids == NULL)
goto cleanup;
loids[1] = NULL;
loids[0] = malloc(sizeof(krb5_algorithm_identifier));
if (loids[0] == NULL) {
free(loids);
goto cleanup;
}
retval = pkinit_copy_krb5_data(&loids[0]->algorithm, &des3oid);
if (retval) {
free(loids[0]);
free(loids);
goto cleanup;
}
loids[0]->parameters.length = 0;
loids[0]->parameters.data = NULL;
*oids = loids;
retval = 0;
cleanup:
return retval;
}
krb5_error_code
create_krb5_trustedCertifiers(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_external_principal_identifier *** ids)
{
krb5_error_code retval = ENOMEM;
STACK_OF(X509) *sk = id_cryptoctx->trustedCAs;
*ids = NULL;
if (id_cryptoctx->trustedCAs == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
retval = create_identifiers_from_stack(sk, ids);
return retval;
}
krb5_error_code
create_issuerAndSerial(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char **out,
unsigned int *out_len)
{
unsigned char *p = NULL;
PKCS7_ISSUER_AND_SERIAL *is = NULL;
int len = 0;
krb5_error_code retval = ENOMEM;
X509 *cert = req_cryptoctx->received_cert;
*out = NULL;
*out_len = 0;
if (req_cryptoctx->received_cert == NULL)
return 0;
is = PKCS7_ISSUER_AND_SERIAL_new();
X509_NAME_set(&is->issuer, X509_get_issuer_name(cert));
ASN1_INTEGER_free(is->serial);
is->serial = ASN1_INTEGER_dup(X509_get_serialNumber(cert));
len = i2d_PKCS7_ISSUER_AND_SERIAL(is, NULL);
if ((p = *out = malloc((size_t) len)) == NULL)
goto cleanup;
i2d_PKCS7_ISSUER_AND_SERIAL(is, &p);
*out_len = len;
retval = 0;
cleanup:
X509_NAME_free(is->issuer);
ASN1_INTEGER_free(is->serial);
free(is);
return retval;
}
static int
pkcs7_decrypt(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
PKCS7 *p7,
BIO *data)
{
BIO *tmpmem = NULL;
int retval = 0, i = 0;
char buf[4096];
if(p7 == NULL)
return 0;
if(!PKCS7_type_is_enveloped(p7)) {
pkiDebug("wrong pkcs7 content type\n");
return 0;
}
if(!(tmpmem = pkcs7_dataDecode(context, id_cryptoctx, p7))) {
pkiDebug("unable to decrypt pkcs7 object\n");
return 0;
}
for(;;) {
i = BIO_read(tmpmem, buf, sizeof(buf));
if (i <= 0) break;
BIO_write(data, buf, i);
BIO_free_all(tmpmem);
return 1;
}
return retval;
}
krb5_error_code
pkinit_process_td_trusted_certifiers(
krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_external_principal_identifier **krb5_trusted_certifiers,
int td_type)
{
krb5_error_code retval = ENOMEM;
STACK_OF(X509_NAME) *sk_xn = NULL;
X509_NAME *xn = NULL;
PKCS7_ISSUER_AND_SERIAL *is = NULL;
ASN1_OCTET_STRING *id = NULL;
const unsigned char *p = NULL;
char buf[DN_BUF_LEN];
int i = 0;
if (td_type == TD_TRUSTED_CERTIFIERS)
pkiDebug("received trusted certifiers\n");
else
pkiDebug("received invalid certificate\n");
sk_xn = sk_X509_NAME_new_null();
while(krb5_trusted_certifiers[i] != NULL) {
if (krb5_trusted_certifiers[i]->subjectName.data != NULL) {
p = (unsigned char *)krb5_trusted_certifiers[i]->subjectName.data;
xn = d2i_X509_NAME(NULL, &p,
(int)krb5_trusted_certifiers[i]->subjectName.length);
if (xn == NULL)
goto cleanup;
X509_NAME_oneline(xn, buf, sizeof(buf));
if (td_type == TD_TRUSTED_CERTIFIERS)
pkiDebug("#%d cert = %s is trusted by kdc\n", i, buf);
else
pkiDebug("#%d cert = %s is invalid\n", i, buf);
sk_X509_NAME_push(sk_xn, xn);
}
if (krb5_trusted_certifiers[i]->issuerAndSerialNumber.data != NULL) {
p = (unsigned char *)
krb5_trusted_certifiers[i]->issuerAndSerialNumber.data;
is = d2i_PKCS7_ISSUER_AND_SERIAL(NULL, &p,
(int)krb5_trusted_certifiers[i]->issuerAndSerialNumber.length);
if (is == NULL)
goto cleanup;
X509_NAME_oneline(is->issuer, buf, sizeof(buf));
if (td_type == TD_TRUSTED_CERTIFIERS)
pkiDebug("#%d issuer = %s serial = %ld is trusted bu kdc\n", i,
buf, ASN1_INTEGER_get(is->serial));
else
pkiDebug("#%d issuer = %s serial = %ld is invalid\n", i, buf,
ASN1_INTEGER_get(is->serial));
PKCS7_ISSUER_AND_SERIAL_free(is);
}
if (krb5_trusted_certifiers[i]->subjectKeyIdentifier.data != NULL) {
p = (unsigned char *)
krb5_trusted_certifiers[i]->subjectKeyIdentifier.data;
id = d2i_ASN1_OCTET_STRING(NULL, &p,
(int)krb5_trusted_certifiers[i]->subjectKeyIdentifier.length);
if (id == NULL)
goto cleanup;
/* XXX */
ASN1_OCTET_STRING_free(id);
}
i++;
}
/* XXX Since we not doing anything with received trusted certifiers
* return an error. this is the place where we can pick a different
* client certificate based on the information in td_trusted_certifiers
*/
retval = KRB5KDC_ERR_PREAUTH_FAILED;
cleanup:
if (sk_xn != NULL)
sk_X509_NAME_pop_free(sk_xn, X509_NAME_free);
return retval;
}
static BIO *
pkcs7_dataDecode(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
PKCS7 *p7)
{
unsigned int eklen=0, tkeylen=0;
BIO *out=NULL,*etmp=NULL,*bio=NULL;
unsigned char *ek=NULL, *tkey=NULL;
ASN1_OCTET_STRING *data_body=NULL;
const EVP_CIPHER *evp_cipher=NULL;
EVP_CIPHER_CTX *evp_ctx=NULL;
X509_ALGOR *enc_alg=NULL;
STACK_OF(PKCS7_RECIP_INFO) *rsk=NULL;
PKCS7_RECIP_INFO *ri=NULL;
p7->state=PKCS7_S_HEADER;
rsk=p7->d.enveloped->recipientinfo;
enc_alg=p7->d.enveloped->enc_data->algorithm;
data_body=p7->d.enveloped->enc_data->enc_data;
evp_cipher=EVP_get_cipherbyobj(enc_alg->algorithm);
if (evp_cipher == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
goto cleanup;
}
if ((etmp=BIO_new(BIO_f_cipher())) == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,ERR_R_BIO_LIB);
goto cleanup;
}
/* It was encrypted, we need to decrypt the secret key
* with the private key */
/* RFC 4556 section 3.2.3.2 requires that there be exactly one
* recipientInfo. */
if (sk_PKCS7_RECIP_INFO_num(rsk) != 1) {
pkiDebug("invalid number of EnvelopedData RecipientInfos\n");
goto cleanup;
}
ri = sk_PKCS7_RECIP_INFO_value(rsk, 0);
(void)pkinit_decode_data(context, id_cryptoctx,
ASN1_STRING_get0_data(ri->enc_key),
ASN1_STRING_length(ri->enc_key), &ek, &eklen);
evp_ctx=NULL;
BIO_get_cipher_ctx(etmp,&evp_ctx);
if (EVP_CipherInit_ex(evp_ctx,evp_cipher,NULL,NULL,NULL,0) <= 0)
goto cleanup;
if (EVP_CIPHER_asn1_to_param(evp_ctx,enc_alg->parameter) < 0)
goto cleanup;
/* Generate a random symmetric key to avoid exposing timing data if RSA
* decryption fails the padding check. */
tkeylen = EVP_CIPHER_CTX_key_length(evp_ctx);
tkey = OPENSSL_malloc(tkeylen);
if (tkey == NULL)
goto cleanup;
if (EVP_CIPHER_CTX_rand_key(evp_ctx, tkey) <= 0)
goto cleanup;
if (ek == NULL) {
ek = tkey;
eklen = tkeylen;
tkey = NULL;
}
if (eklen != (unsigned)EVP_CIPHER_CTX_key_length(evp_ctx)) {
/* Some S/MIME clients don't use the same key
* and effective key length. The key length is
* determined by the size of the decrypted RSA key.
*/
if (!EVP_CIPHER_CTX_set_key_length(evp_ctx, (int)eklen)) {
ek = tkey;
eklen = tkeylen;
tkey = NULL;
}
}
if (EVP_CipherInit_ex(evp_ctx,NULL,NULL,ek,NULL,0) <= 0)
goto cleanup;
if (out == NULL)
out=etmp;
else
BIO_push(out,etmp);
etmp=NULL;
if (data_body->length > 0)
bio = BIO_new_mem_buf(data_body->data, data_body->length);
else {
bio=BIO_new(BIO_s_mem());
BIO_set_mem_eof_return(bio,0);
}
BIO_push(out,bio);
bio=NULL;
if (0) {
cleanup:
if (out != NULL) BIO_free_all(out);
if (etmp != NULL) BIO_free_all(etmp);
if (bio != NULL) BIO_free_all(bio);
out=NULL;
}
if (ek != NULL) {
OPENSSL_cleanse(ek, eklen);
OPENSSL_free(ek);
}
if (tkey != NULL) {
OPENSSL_cleanse(tkey, tkeylen);
OPENSSL_free(tkey);
}
return(out);
}
#ifdef DEBUG_DH
static void
print_dh(DH * dh, char *msg)
{
BIO *bio_err = NULL;
bio_err = BIO_new(BIO_s_file());
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
if (msg)
BIO_puts(bio_err, (const char *)msg);
if (dh)
DHparams_print(bio_err, dh);
BIO_puts(bio_err, "private key: ");
BN_print(bio_err, dh->priv_key);
BIO_puts(bio_err, (const char *)"\n");
BIO_free(bio_err);
}
static void
print_pubkey(BIGNUM * key, char *msg)
{
BIO *bio_err = NULL;
bio_err = BIO_new(BIO_s_file());
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
if (msg)
BIO_puts(bio_err, (const char *)msg);
if (key)
BN_print(bio_err, key);
BIO_puts(bio_err, "\n");
BIO_free(bio_err);
}
#endif
static char *
pkinit_pkcs11_code_to_text(int err)
{
int i;
static char uc[32];
for (i = 0; pkcs11_errstrings[i].text != NULL; i++)
if (pkcs11_errstrings[i].code == err)
break;
if (pkcs11_errstrings[i].text != NULL)
return (pkcs11_errstrings[i].text);
snprintf(uc, sizeof(uc), _("unknown code 0x%x"), err);
return (uc);
}
/*
* Add an item to the pkinit_identity_crypto_context's list of deferred
* identities.
*/
krb5_error_code
crypto_set_deferred_id(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
const char *identity, const char *password)
{
unsigned long ck_flags;
ck_flags = pkinit_get_deferred_id_flags(id_cryptoctx->deferred_ids,
identity);
return pkinit_set_deferred_id(&id_cryptoctx->deferred_ids,
identity, ck_flags, password);
}
/*
* Retrieve a read-only copy of the pkinit_identity_crypto_context's list of
* deferred identities, sure to be valid only until the next time someone calls
* either pkinit_set_deferred_id() or crypto_set_deferred_id().
*/
const pkinit_deferred_id *
crypto_get_deferred_ids(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx)
{
pkinit_deferred_id *deferred;
const pkinit_deferred_id *ret;
deferred = id_cryptoctx->deferred_ids;
ret = (const pkinit_deferred_id *)deferred;
return ret;
}
/* Return the received certificate as DER-encoded data. */
krb5_error_code
crypto_encode_der_cert(krb5_context context, pkinit_req_crypto_context reqctx,
uint8_t **der_out, size_t *der_len)
{
int len;
unsigned char *der, *p;
*der_out = NULL;
*der_len = 0;
if (reqctx->received_cert == NULL)
return EINVAL;
p = NULL;
len = i2d_X509(reqctx->received_cert, NULL);
if (len <= 0)
return EINVAL;
p = der = malloc(len);
if (der == NULL)
return ENOMEM;
if (i2d_X509(reqctx->received_cert, &p) <= 0) {
free(der);
return EINVAL;
}
*der_out = der;
*der_len = len;
return 0;
}
/*
* Get the certificate matching data from the request certificate.
*/
krb5_error_code
crypto_req_cert_matching_data(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
pkinit_cert_matching_data **md_out)
{
*md_out = NULL;
if (reqctx == NULL || reqctx->received_cert == NULL)
return ENOENT;
return get_matching_data(context, plgctx, reqctx, reqctx->received_cert,
md_out);
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/good_3281_0 |
crossvul-cpp_data_bad_1723_0 | /*
* PgBouncer - Lightweight connection pooler for PostgreSQL.
*
* Copyright (c) 2007-2009 Marko Kreen, Skype Technologies OÜ
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Client connection handling
*/
#include "bouncer.h"
#include <usual/pgutil.h>
static const char *hdr2hex(const struct MBuf *data, char *buf, unsigned buflen)
{
const uint8_t *bin = data->data + data->read_pos;
unsigned int dlen;
dlen = mbuf_avail_for_read(data);
return bin2hex(bin, dlen, buf, buflen);
}
static bool check_client_passwd(PgSocket *client, const char *passwd)
{
char md5[MD5_PASSWD_LEN + 1];
PgUser *user = client->auth_user;
int auth_type = client->client_auth_type;
/* disallow empty passwords */
if (!*passwd || !*user->passwd)
return false;
switch (auth_type) {
case AUTH_PLAIN:
return strcmp(user->passwd, passwd) == 0;
case AUTH_MD5:
if (strlen(passwd) != MD5_PASSWD_LEN)
return false;
if (!isMD5(user->passwd))
pg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd);
pg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5);
return strcmp(md5, passwd) == 0;
}
return false;
}
static bool send_client_authreq(PgSocket *client)
{
uint8_t saltlen = 0;
int res;
int auth_type = client->client_auth_type;
if (auth_type == AUTH_MD5) {
saltlen = 4;
get_random_bytes((void*)client->tmp_login_salt, saltlen);
} else if (auth_type == AUTH_PLAIN) {
/* nothing to do */
} else {
return false;
}
SEND_generic(res, client, 'R', "ib", auth_type, client->tmp_login_salt, saltlen);
if (!res)
disconnect_client(client, false, "failed to send auth req");
return res;
}
static void start_auth_request(PgSocket *client, const char *username)
{
int res;
PktBuf *buf;
client->auth_user = client->db->auth_user;
/* have to fetch user info from db */
client->pool = get_pool(client->db, client->db->auth_user);
if (!find_server(client)) {
client->wait_for_user_conn = true;
return;
}
slog_noise(client, "Doing auth_conn query");
client->wait_for_user_conn = false;
client->wait_for_user = true;
if (!sbuf_pause(&client->sbuf)) {
release_server(client->link);
disconnect_client(client, true, "pause failed");
return;
}
client->link->ready = 0;
res = 0;
buf = pktbuf_dynamic(512);
if (buf) {
pktbuf_write_ExtQuery(buf, cf_auth_query, 1, username);
res = pktbuf_send_immediate(buf, client->link);
pktbuf_free(buf);
/*
* Should do instead:
* res = pktbuf_send_queued(buf, client->link);
* but that needs better integration with SBuf.
*/
}
if (!res)
disconnect_server(client->link, false, "unable to send login query");
}
static bool login_via_cert(PgSocket *client)
{
struct tls *tls = client->sbuf.tls;
struct tls_cert *cert;
struct tls_cert_dname *subj;
if (!tls) {
disconnect_client(client, true, "TLS connection required");
return false;
}
if (tls_get_peer_cert(client->sbuf.tls, &cert, NULL) < 0 || !cert) {
disconnect_client(client, true, "TLS client certificate required");
return false;
}
subj = &cert->subject;
log_debug("TLS cert login: CN=%s/C=%s/L=%s/ST=%s/O=%s/OU=%s",
subj->common_name ? subj->common_name : "(null)",
subj->country_name ? subj->country_name : "(null)",
subj->locality_name ? subj->locality_name : "(null)",
subj->state_or_province_name ? subj->state_or_province_name : "(null)",
subj->organization_name ? subj->organization_name : "(null)",
subj->organizational_unit_name ? subj->organizational_unit_name : "(null)");
if (!subj->common_name) {
disconnect_client(client, true, "Invalid TLS certificate");
goto fail;
}
if (strcmp(subj->common_name, client->auth_user->name) != 0) {
disconnect_client(client, true, "TLS certificate name mismatch");
goto fail;
}
tls_cert_free(cert);
/* login successful */
return finish_client_login(client);
fail:
tls_cert_free(cert);
return false;
}
static bool login_as_unix_peer(PgSocket *client)
{
if (!pga_is_unix(&client->remote_addr))
goto fail;
if (!check_unix_peer_name(sbuf_socket(&client->sbuf), client->auth_user->name))
goto fail;
return finish_client_login(client);
fail:
disconnect_client(client, true, "unix socket login rejected");
return false;
}
static bool finish_set_pool(PgSocket *client, bool takeover)
{
PgUser *user = client->auth_user;
bool ok = false;
int auth;
/* pool user may be forced */
if (client->db->forced_user) {
user = client->db->forced_user;
}
client->pool = get_pool(client->db, user);
if (!client->pool) {
disconnect_client(client, true, "no memory for pool");
return false;
}
if (cf_log_connections) {
if (client->sbuf.tls) {
char infobuf[96] = "";
tls_get_connection_info(client->sbuf.tls, infobuf, sizeof infobuf);
slog_info(client, "login attempt: db=%s user=%s tls=%s",
client->db->name, client->auth_user->name, infobuf);
} else {
slog_info(client, "login attempt: db=%s user=%s tls=no",
client->db->name, client->auth_user->name);
}
}
if (!check_fast_fail(client))
return false;
if (takeover)
return true;
if (client->pool->db->admin) {
if (!admin_post_login(client))
return false;
}
if (client->own_user)
return finish_client_login(client);
auth = cf_auth_type;
if (auth == AUTH_HBA) {
auth = hba_eval(parsed_hba, &client->remote_addr, !!client->sbuf.tls,
client->db->name, client->auth_user->name);
}
/* remember method */
client->client_auth_type = auth;
switch (auth) {
case AUTH_ANY:
case AUTH_TRUST:
ok = finish_client_login(client);
break;
case AUTH_PLAIN:
case AUTH_MD5:
ok = send_client_authreq(client);
break;
case AUTH_CERT:
ok = login_via_cert(client);
break;
case AUTH_PEER:
ok = login_as_unix_peer(client);
break;
default:
disconnect_client(client, true, "login rejected");
ok = false;
}
return ok;
}
bool set_pool(PgSocket *client, const char *dbname, const char *username, const char *password, bool takeover)
{
/* find database */
client->db = find_database(dbname);
if (!client->db) {
client->db = register_auto_database(dbname);
if (!client->db) {
disconnect_client(client, true, "No such database: %s", dbname);
if (cf_log_connections)
slog_info(client, "login failed: db=%s user=%s", dbname, username);
return false;
} else {
slog_info(client, "registered new auto-database: db = %s", dbname );
}
}
/* are new connections allowed? */
if (client->db->db_disabled) {
disconnect_client(client, true, "database does not allow connections: %s", dbname);
return false;
}
if (client->db->admin) {
if (admin_pre_login(client, username))
return finish_set_pool(client, takeover);
}
/* find user */
if (cf_auth_type == AUTH_ANY) {
/* ignore requested user */
if (client->db->forced_user == NULL) {
slog_error(client, "auth_type=any requires forced user");
disconnect_client(client, true, "bouncer config error");
return false;
}
client->auth_user = client->db->forced_user;
} else {
/* the user clients wants to log in as */
client->auth_user = find_user(username);
if (!client->auth_user && client->db->auth_user) {
if (takeover) {
client->auth_user = add_db_user(client->db, username, password);
return finish_set_pool(client, takeover);
}
start_auth_request(client, username);
return false;
}
if (!client->auth_user) {
disconnect_client(client, true, "No such user: %s", username);
if (cf_log_connections)
slog_info(client, "login failed: db=%s user=%s", dbname, username);
return false;
}
}
return finish_set_pool(client, takeover);
}
bool handle_auth_response(PgSocket *client, PktHdr *pkt) {
uint16_t columns;
uint32_t length;
const char *username, *password;
PgUser user;
PgSocket *server = client->link;
switch(pkt->type) {
case 'T': /* RowDescription */
if (!mbuf_get_uint16be(&pkt->data, &columns)) {
disconnect_server(server, false, "bad packet");
return false;
}
if (columns != 2u) {
disconnect_server(server, false, "expected 1 column from login query, not %hu", columns);
return false;
}
break;
case 'D': /* DataRow */
memset(&user, 0, sizeof(user));
if (!mbuf_get_uint16be(&pkt->data, &columns)) {
disconnect_server(server, false, "bad packet");
return false;
}
if (columns != 2u) {
disconnect_server(server, false, "expected 1 column from login query, not %hu", columns);
return false;
}
if (!mbuf_get_uint32be(&pkt->data, &length)) {
disconnect_server(server, false, "bad packet");
return false;
}
if (!mbuf_get_chars(&pkt->data, length, &username)) {
disconnect_server(server, false, "bad packet");
return false;
}
if (sizeof(user.name) - 1 < length)
length = sizeof(user.name) - 1;
memcpy(user.name, username, length);
if (!mbuf_get_uint32be(&pkt->data, &length)) {
disconnect_server(server, false, "bad packet");
return false;
}
if (length == (uint32_t)-1) {
/*
* NULL - set an md5 password with an impossible value,
* so that nothing will ever match
*/
password = "md5";
length = 3;
} else {
if (!mbuf_get_chars(&pkt->data, length, &password)) {
disconnect_server(server, false, "bad packet");
return false;
}
}
if (sizeof(user.passwd) - 1 < length)
length = sizeof(user.passwd) - 1;
memcpy(user.passwd, password, length);
client->auth_user = add_db_user(client->db, user.name, user.passwd);
if (!client->auth_user) {
disconnect_server(server, false, "unable to allocate new user for auth");
return false;
}
break;
case 'N': /* NoticeResponse */
break;
case 'C': /* CommandComplete */
break;
case '1': /* ParseComplete */
break;
case '2': /* BindComplete */
break;
case 'Z': /* ReadyForQuery */
sbuf_prepare_skip(&client->link->sbuf, pkt->len);
if (!client->auth_user) {
if (cf_log_connections)
slog_info(client, "login failed: db=%s", client->db->name);
disconnect_client(client, true, "No such user");
} else {
slog_noise(client, "auth query complete");
client->link->resetting = true;
sbuf_continue(&client->sbuf);
}
/*
* either sbuf_continue or disconnect_client could disconnect the server
* way down in their bowels of other callbacks. so check that, and
* return appropriately (similar to reuse_on_release)
*/
if (server->state == SV_FREE || server->state == SV_JUSTFREE)
return false;
return true;
default:
disconnect_server(server, false, "unexpected response from login query");
return false;
}
sbuf_prepare_skip(&server->sbuf, pkt->len);
return true;
}
static void set_appname(PgSocket *client, const char *app_name)
{
char buf[400], abuf[300];
const char *details;
if (cf_application_name_add_host) {
/* give app a name */
if (!app_name)
app_name = "app";
/* add details */
details = pga_details(&client->remote_addr, abuf, sizeof(abuf));
snprintf(buf, sizeof(buf), "%s - %s", app_name, details);
app_name = buf;
}
if (app_name) {
slog_debug(client, "using application_name: %s", app_name);
varcache_set(&client->vars, "application_name", app_name);
}
}
static bool decide_startup_pool(PgSocket *client, PktHdr *pkt)
{
const char *username = NULL, *dbname = NULL;
const char *key, *val;
bool ok;
bool appname_found = false;
while (1) {
ok = mbuf_get_string(&pkt->data, &key);
if (!ok || *key == 0)
break;
ok = mbuf_get_string(&pkt->data, &val);
if (!ok)
break;
if (strcmp(key, "database") == 0) {
slog_debug(client, "got var: %s=%s", key, val);
dbname = val;
} else if (strcmp(key, "user") == 0) {
slog_debug(client, "got var: %s=%s", key, val);
username = val;
} else if (strcmp(key, "application_name") == 0) {
set_appname(client, val);
appname_found = true;
} else if (varcache_set(&client->vars, key, val)) {
slog_debug(client, "got var: %s=%s", key, val);
} else if (strlist_contains(cf_ignore_startup_params, key)) {
slog_debug(client, "ignoring startup parameter: %s=%s", key, val);
} else {
slog_warning(client, "unsupported startup parameter: %s=%s", key, val);
disconnect_client(client, true, "Unsupported startup parameter: %s", key);
return false;
}
}
if (!username || !username[0]) {
disconnect_client(client, true, "No username supplied");
return false;
}
/* if missing dbname, default to username */
if (!dbname || !dbname[0])
dbname = username;
/* create application_name if requested */
if (!appname_found)
set_appname(client, NULL);
/* check if limit allows, don't limit admin db
nb: new incoming conn will be attached to PgSocket, thus
get_active_client_count() counts it */
if (get_active_client_count() > cf_max_client_conn) {
if (strcmp(dbname, "pgbouncer") != 0) {
disconnect_client(client, true, "no more connections allowed (max_client_conn)");
return false;
}
}
/* find pool */
return set_pool(client, dbname, username, "", false);
}
/* decide on packets of client in login phase */
static bool handle_client_startup(PgSocket *client, PktHdr *pkt)
{
const char *passwd;
const uint8_t *key;
bool ok;
SBuf *sbuf = &client->sbuf;
/* don't tolerate partial packets */
if (incomplete_pkt(pkt)) {
disconnect_client(client, true, "client sent partial pkt in startup phase");
return false;
}
if (client->wait_for_welcome) {
if (finish_client_login(client)) {
/* the packet was already parsed */
sbuf_prepare_skip(sbuf, pkt->len);
return true;
} else {
return false;
}
}
switch (pkt->type) {
case PKT_SSLREQ:
slog_noise(client, "C: req SSL");
if (client->sbuf.tls) {
disconnect_client(client, false, "SSL req inside SSL");
return false;
}
if (cf_client_tls_sslmode != SSLMODE_DISABLED) {
slog_noise(client, "P: SSL ack");
if (!sbuf_answer(&client->sbuf, "S", 1)) {
disconnect_client(client, false, "failed to ack SSL");
return false;
}
if (!sbuf_tls_accept(&client->sbuf)) {
disconnect_client(client, false, "failed to accept SSL");
return false;
}
break;
}
/* reject SSL attempt */
slog_noise(client, "P: nak");
if (!sbuf_answer(&client->sbuf, "N", 1)) {
disconnect_client(client, false, "failed to nak SSL");
return false;
}
break;
case PKT_STARTUP_V2:
disconnect_client(client, true, "Old V2 protocol not supported");
return false;
case PKT_STARTUP:
/* require SSL except on unix socket */
if (cf_client_tls_sslmode >= SSLMODE_REQUIRE && !client->sbuf.tls && !pga_is_unix(&client->remote_addr)) {
disconnect_client(client, true, "SSL required");
return false;
}
if (client->pool && !client->wait_for_user_conn && !client->wait_for_user) {
disconnect_client(client, true, "client re-sent startup pkt");
return false;
}
if (client->wait_for_user) {
client->wait_for_user = false;
if (!finish_set_pool(client, false))
return false;
} else if (!decide_startup_pool(client, pkt)) {
return false;
}
break;
case 'p': /* PasswordMessage */
/* too early */
if (!client->auth_user) {
disconnect_client(client, true, "client password pkt before startup packet");
return false;
}
ok = mbuf_get_string(&pkt->data, &passwd);
if (ok && check_client_passwd(client, passwd)) {
if (!finish_client_login(client))
return false;
} else {
disconnect_client(client, true, "Auth failed");
return false;
}
break;
case PKT_CANCEL:
if (mbuf_avail_for_read(&pkt->data) == BACKENDKEY_LEN
&& mbuf_get_bytes(&pkt->data, BACKENDKEY_LEN, &key))
{
memcpy(client->cancel_key, key, BACKENDKEY_LEN);
accept_cancel_request(client);
} else {
disconnect_client(client, false, "bad cancel request");
}
return false;
default:
disconnect_client(client, false, "bad packet");
return false;
}
sbuf_prepare_skip(sbuf, pkt->len);
client->request_time = get_cached_time();
return true;
}
/* decide on packets of logged-in client */
static bool handle_client_work(PgSocket *client, PktHdr *pkt)
{
SBuf *sbuf = &client->sbuf;
switch (pkt->type) {
/* one-packet queries */
case 'Q': /* Query */
if (cf_disable_pqexec) {
slog_error(client, "Client used 'Q' packet type.");
disconnect_client(client, true, "PQexec disallowed");
return false;
}
case 'F': /* FunctionCall */
/* request immediate response from server */
case 'S': /* Sync */
client->expect_rfq_count++;
break;
case 'H': /* Flush */
break;
/* copy end markers */
case 'c': /* CopyDone(F/B) */
case 'f': /* CopyFail(F/B) */
break;
/*
* extended protocol allows server (and thus pooler)
* to buffer packets until sync or flush is sent by client
*/
case 'P': /* Parse */
case 'E': /* Execute */
case 'C': /* Close */
case 'B': /* Bind */
case 'D': /* Describe */
case 'd': /* CopyData(F/B) */
break;
/* client wants to go away */
default:
slog_error(client, "unknown pkt from client: %d/0x%x", pkt->type, pkt->type);
disconnect_client(client, true, "unknown pkt");
return false;
case 'X': /* Terminate */
disconnect_client(client, false, "client close request");
return false;
}
/* update stats */
if (!client->query_start) {
client->pool->stats.request_count++;
client->query_start = get_cached_time();
}
if (client->pool->db->admin)
return admin_handle_client(client, pkt);
/* acquire server */
if (!find_server(client))
return false;
client->pool->stats.client_bytes += pkt->len;
/* tag the server as dirty */
client->link->ready = false;
client->link->idle_tx = false;
/* forward the packet */
sbuf_prepare_send(sbuf, &client->link->sbuf, pkt->len);
return true;
}
/* callback from SBuf */
bool client_proto(SBuf *sbuf, SBufEvent evtype, struct MBuf *data)
{
bool res = false;
PgSocket *client = container_of(sbuf, PgSocket, sbuf);
PktHdr pkt;
Assert(!is_server_socket(client));
Assert(client->sbuf.sock);
Assert(client->state != CL_FREE);
/* may happen if close failed */
if (client->state == CL_JUSTFREE)
return false;
switch (evtype) {
case SBUF_EV_CONNECT_OK:
case SBUF_EV_CONNECT_FAILED:
/* ^ those should not happen */
case SBUF_EV_RECV_FAILED:
disconnect_client(client, false, "client unexpected eof");
break;
case SBUF_EV_SEND_FAILED:
disconnect_server(client->link, false, "Server connection closed");
break;
case SBUF_EV_READ:
/* Wait until full packet headers is available. */
if (incomplete_header(data)) {
slog_noise(client, "C: got partial header, trying to wait a bit");
return false;
}
if (!get_header(data, &pkt)) {
char hex[8*2 + 1];
disconnect_client(client, true, "bad packet header: '%s'",
hdr2hex(data, hex, sizeof(hex)));
return false;
}
slog_noise(client, "pkt='%c' len=%d", pkt_desc(&pkt), pkt.len);
client->request_time = get_cached_time();
switch (client->state) {
case CL_LOGIN:
res = handle_client_startup(client, &pkt);
break;
case CL_ACTIVE:
if (client->wait_for_welcome)
res = handle_client_startup(client, &pkt);
else
res = handle_client_work(client, &pkt);
break;
case CL_WAITING:
fatal("why waiting client in client_proto()");
default:
fatal("bad client state: %d", client->state);
}
break;
case SBUF_EV_FLUSH:
/* client is not interested in it */
break;
case SBUF_EV_PKT_CALLBACK:
/* unused ATM */
break;
case SBUF_EV_TLS_READY:
sbuf_continue(&client->sbuf);
res = true;
break;
}
return res;
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/bad_1723_0 |
crossvul-cpp_data_bad_2756_6 | /*
* X.509 certificate parsing and verification
*
* 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)
*/
/*
* The ITU-T X.509 standard defines a certificate format for PKI.
*
* http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs)
* http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs)
* http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10)
*
* http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf
* http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_X509_CRT_PARSE_C)
#include "mbedtls/x509_crt.h"
#include "mbedtls/oid.h"
#include <stdio.h>
#include <string.h>
#if defined(MBEDTLS_PEM_PARSE_C)
#include "mbedtls/pem.h"
#endif
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#define mbedtls_free free
#define mbedtls_calloc calloc
#define mbedtls_snprintf snprintf
#endif
#if defined(MBEDTLS_THREADING_C)
#include "mbedtls/threading.h"
#endif
#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
#include <windows.h>
#else
#include <time.h>
#endif
#if defined(MBEDTLS_FS_IO)
#include <stdio.h>
#if !defined(_WIN32) || defined(EFIX64) || defined(EFI32)
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#endif /* !_WIN32 || EFIX64 || EFI32 */
#endif
/* 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;
}
/*
* Default profile
*/
const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default =
{
#if defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES)
/* Allow SHA-1 (weak, but still safe in controlled environments) */
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA1 ) |
#endif
/* Only SHA-2 hashes */
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
0xFFFFFFF, /* Any PK alg */
0xFFFFFFF, /* Any curve */
2048,
};
/*
* Next-default profile
*/
const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next =
{
/* Hashes from SHA-256 and above */
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
0xFFFFFFF, /* Any PK alg */
#if defined(MBEDTLS_ECP_C)
/* Curves at or above 128-bit security level */
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP521R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP256R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP384R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP512R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256K1 ),
#else
0,
#endif
2048,
};
/*
* NSA Suite B Profile
*/
const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb =
{
/* Only SHA-256 and 384 */
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ),
/* Only ECDSA */
MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECDSA ),
#if defined(MBEDTLS_ECP_C)
/* Only NIST P-256 and P-384 */
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ),
#else
0,
#endif
0,
};
/*
* Check md_alg against profile
* Return 0 if md_alg acceptable for this profile, -1 otherwise
*/
static int x509_profile_check_md_alg( const mbedtls_x509_crt_profile *profile,
mbedtls_md_type_t md_alg )
{
if( ( profile->allowed_mds & MBEDTLS_X509_ID_FLAG( md_alg ) ) != 0 )
return( 0 );
return( -1 );
}
/*
* Check pk_alg against profile
* Return 0 if pk_alg acceptable for this profile, -1 otherwise
*/
static int x509_profile_check_pk_alg( const mbedtls_x509_crt_profile *profile,
mbedtls_pk_type_t pk_alg )
{
if( ( profile->allowed_pks & MBEDTLS_X509_ID_FLAG( pk_alg ) ) != 0 )
return( 0 );
return( -1 );
}
/*
* Check key against profile
* Return 0 if pk_alg acceptable for this profile, -1 otherwise
*/
static int x509_profile_check_key( const mbedtls_x509_crt_profile *profile,
mbedtls_pk_type_t pk_alg,
const mbedtls_pk_context *pk )
{
#if defined(MBEDTLS_RSA_C)
if( pk_alg == MBEDTLS_PK_RSA || pk_alg == MBEDTLS_PK_RSASSA_PSS )
{
if( mbedtls_pk_get_bitlen( pk ) >= profile->rsa_min_bitlen )
return( 0 );
return( -1 );
}
#endif
#if defined(MBEDTLS_ECP_C)
if( pk_alg == MBEDTLS_PK_ECDSA ||
pk_alg == MBEDTLS_PK_ECKEY ||
pk_alg == MBEDTLS_PK_ECKEY_DH )
{
mbedtls_ecp_group_id gid = mbedtls_pk_ec( *pk )->grp.id;
if( ( profile->allowed_curves & MBEDTLS_X509_ID_FLAG( gid ) ) != 0 )
return( 0 );
return( -1 );
}
#endif
return( -1 );
}
/*
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
*/
static int x509_get_version( unsigned char **p,
const unsigned char *end,
int *ver )
{
int ret;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
{
*ver = 0;
return( 0 );
}
return( ret );
}
end = *p + len;
if( ( ret = mbedtls_asn1_get_int( p, end, ver ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_VERSION + ret );
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_VERSION +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
/*
* Validity ::= SEQUENCE {
* notBefore Time,
* notAfter Time }
*/
static int x509_get_dates( unsigned char **p,
const unsigned char *end,
mbedtls_x509_time *from,
mbedtls_x509_time *to )
{
int ret;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_DATE + ret );
end = *p + len;
if( ( ret = mbedtls_x509_get_time( p, end, from ) ) != 0 )
return( ret );
if( ( ret = mbedtls_x509_get_time( p, end, to ) ) != 0 )
return( ret );
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_DATE +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
/*
* X.509 v2/v3 unique identifier (not parsed)
*/
static int x509_get_uid( unsigned char **p,
const unsigned char *end,
mbedtls_x509_buf *uid, int n )
{
int ret;
if( *p == end )
return( 0 );
uid->tag = **p;
if( ( ret = mbedtls_asn1_get_tag( p, end, &uid->len,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | n ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
return( 0 );
return( ret );
}
uid->p = *p;
*p += uid->len;
return( 0 );
}
static int x509_get_basic_constraints( unsigned char **p,
const unsigned char *end,
int *ca_istrue,
int *max_pathlen )
{
int ret;
size_t len;
/*
* BasicConstraints ::= SEQUENCE {
* cA BOOLEAN DEFAULT FALSE,
* pathLenConstraint INTEGER (0..MAX) OPTIONAL }
*/
*ca_istrue = 0; /* DEFAULT FALSE */
*max_pathlen = 0; /* endless */
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( *p == end )
return( 0 );
if( ( ret = mbedtls_asn1_get_bool( p, end, ca_istrue ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
ret = mbedtls_asn1_get_int( p, end, ca_istrue );
if( ret != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( *ca_istrue != 0 )
*ca_istrue = 1;
}
if( *p == end )
return( 0 );
if( ( ret = mbedtls_asn1_get_int( p, end, max_pathlen ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
(*max_pathlen)++;
return( 0 );
}
static int x509_get_ns_cert_type( unsigned char **p,
const unsigned char *end,
unsigned char *ns_cert_type)
{
int ret;
mbedtls_x509_bitstring bs = { 0, 0, NULL };
if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( bs.len != 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_INVALID_LENGTH );
/* Get actual bitstring */
*ns_cert_type = *bs.p;
return( 0 );
}
static int x509_get_key_usage( unsigned char **p,
const unsigned char *end,
unsigned int *key_usage)
{
int ret;
size_t i;
mbedtls_x509_bitstring bs = { 0, 0, NULL };
if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( bs.len < 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_INVALID_LENGTH );
/* Get actual bitstring */
*key_usage = 0;
for( i = 0; i < bs.len && i < sizeof( unsigned int ); i++ )
{
*key_usage |= (unsigned int) bs.p[i] << (8*i);
}
return( 0 );
}
/*
* ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
*
* KeyPurposeId ::= OBJECT IDENTIFIER
*/
static int x509_get_ext_key_usage( unsigned char **p,
const unsigned char *end,
mbedtls_x509_sequence *ext_key_usage)
{
int ret;
if( ( ret = mbedtls_asn1_get_sequence_of( p, end, ext_key_usage, MBEDTLS_ASN1_OID ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
/* Sequence length must be >= 1 */
if( ext_key_usage->buf.p == NULL )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_INVALID_LENGTH );
return( 0 );
}
/*
* SubjectAltName ::= GeneralNames
*
* GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
*
* GeneralName ::= CHOICE {
* otherName [0] OtherName,
* rfc822Name [1] IA5String,
* dNSName [2] IA5String,
* x400Address [3] ORAddress,
* directoryName [4] Name,
* ediPartyName [5] EDIPartyName,
* uniformResourceIdentifier [6] IA5String,
* iPAddress [7] OCTET STRING,
* registeredID [8] OBJECT IDENTIFIER }
*
* OtherName ::= SEQUENCE {
* type-id OBJECT IDENTIFIER,
* value [0] EXPLICIT ANY DEFINED BY type-id }
*
* EDIPartyName ::= SEQUENCE {
* nameAssigner [0] DirectoryString OPTIONAL,
* partyName [1] DirectoryString }
*
* NOTE: we only parse and use dNSName at this point.
*/
static int x509_get_subject_alt_name( unsigned char **p,
const unsigned char *end,
mbedtls_x509_sequence *subject_alt_name )
{
int ret;
size_t len, tag_len;
mbedtls_asn1_buf *buf;
unsigned char tag;
mbedtls_asn1_sequence *cur = subject_alt_name;
/* Get main sequence tag */
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( *p + len != end )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
while( *p < end )
{
if( ( end - *p ) < 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_OUT_OF_DATA );
tag = **p;
(*p)++;
if( ( ret = mbedtls_asn1_get_len( p, end, &tag_len ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( ( tag & MBEDTLS_ASN1_CONTEXT_SPECIFIC ) != MBEDTLS_ASN1_CONTEXT_SPECIFIC )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
/* Skip everything but DNS name */
if( tag != ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2 ) )
{
*p += tag_len;
continue;
}
/* Allocate and assign next pointer */
if( cur->buf.p != NULL )
{
if( cur->next != NULL )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
cur->next = mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) );
if( cur->next == NULL )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_ALLOC_FAILED );
cur = cur->next;
}
buf = &(cur->buf);
buf->tag = tag;
buf->p = *p;
buf->len = tag_len;
*p += buf->len;
}
/* Set final sequence entry's next pointer to NULL */
cur->next = NULL;
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
/*
* X.509 v3 extensions
*
*/
static int x509_get_crt_ext( unsigned char **p,
const unsigned char *end,
mbedtls_x509_crt *crt )
{
int ret;
size_t len;
unsigned char *end_ext_data, *end_ext_octet;
if( ( ret = mbedtls_x509_get_ext( p, end, &crt->v3_ext, 3 ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
return( 0 );
return( ret );
}
while( *p < end )
{
/*
* Extension ::= SEQUENCE {
* extnID OBJECT IDENTIFIER,
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING }
*/
mbedtls_x509_buf extn_oid = {0, 0, NULL};
int is_critical = 0; /* DEFAULT FALSE */
int ext_type = 0;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
end_ext_data = *p + len;
/* Get extension ID */
extn_oid.tag = **p;
if( ( ret = mbedtls_asn1_get_tag( p, end, &extn_oid.len, MBEDTLS_ASN1_OID ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
extn_oid.p = *p;
*p += extn_oid.len;
if( ( end - *p ) < 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_OUT_OF_DATA );
/* Get optional critical */
if( ( ret = mbedtls_asn1_get_bool( p, end_ext_data, &is_critical ) ) != 0 &&
( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
/* Data should be octet string type */
if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len,
MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
end_ext_octet = *p + len;
if( end_ext_octet != end_ext_data )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
/*
* Detect supported extensions
*/
ret = mbedtls_oid_get_x509_ext_type( &extn_oid, &ext_type );
if( ret != 0 )
{
/* No parser found, skip extension */
*p = end_ext_octet;
#if !defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION)
if( is_critical )
{
/* Data is marked as critical: fail */
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
}
#endif
continue;
}
/* Forbid repeated extensions */
if( ( crt->ext_types & ext_type ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
crt->ext_types |= ext_type;
switch( ext_type )
{
case MBEDTLS_X509_EXT_BASIC_CONSTRAINTS:
/* Parse basic constraints */
if( ( ret = x509_get_basic_constraints( p, end_ext_octet,
&crt->ca_istrue, &crt->max_pathlen ) ) != 0 )
return( ret );
break;
case MBEDTLS_X509_EXT_KEY_USAGE:
/* Parse key usage */
if( ( ret = x509_get_key_usage( p, end_ext_octet,
&crt->key_usage ) ) != 0 )
return( ret );
break;
case MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE:
/* Parse extended key usage */
if( ( ret = x509_get_ext_key_usage( p, end_ext_octet,
&crt->ext_key_usage ) ) != 0 )
return( ret );
break;
case MBEDTLS_X509_EXT_SUBJECT_ALT_NAME:
/* Parse subject alt name */
if( ( ret = x509_get_subject_alt_name( p, end_ext_octet,
&crt->subject_alt_names ) ) != 0 )
return( ret );
break;
case MBEDTLS_X509_EXT_NS_CERT_TYPE:
/* Parse netscape certificate type */
if( ( ret = x509_get_ns_cert_type( p, end_ext_octet,
&crt->ns_cert_type ) ) != 0 )
return( ret );
break;
default:
return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE );
}
}
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
/*
* Parse and fill a single X.509 certificate in DER format
*/
static int x509_crt_parse_der_core( mbedtls_x509_crt *crt, const unsigned char *buf,
size_t buflen )
{
int ret;
size_t len;
unsigned char *p, *end, *crt_end;
mbedtls_x509_buf sig_params1, sig_params2, sig_oid2;
memset( &sig_params1, 0, sizeof( mbedtls_x509_buf ) );
memset( &sig_params2, 0, sizeof( mbedtls_x509_buf ) );
memset( &sig_oid2, 0, sizeof( mbedtls_x509_buf ) );
/*
* Check for valid input
*/
if( crt == NULL || buf == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
// Use the original buffer until we figure out actual length
p = (unsigned char*) buf;
len = buflen;
end = p + len;
/*
* Certificate ::= SEQUENCE {
* tbsCertificate TBSCertificate,
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING }
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT );
}
if( len > (size_t) ( end - p ) )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
}
crt_end = p + len;
// Create and populate a new buffer for the raw field
crt->raw.len = crt_end - buf;
crt->raw.p = p = mbedtls_calloc( 1, crt->raw.len );
if( p == NULL )
return( MBEDTLS_ERR_X509_ALLOC_FAILED );
memcpy( p, buf, crt->raw.len );
// Direct pointers to the new buffer
p += crt->raw.len - len;
end = crt_end = p + len;
/*
* TBSCertificate ::= SEQUENCE {
*/
crt->tbs.p = p;
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
}
end = p + len;
crt->tbs.len = end - crt->tbs.p;
/*
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
*
* CertificateSerialNumber ::= INTEGER
*
* signature AlgorithmIdentifier
*/
if( ( ret = x509_get_version( &p, end, &crt->version ) ) != 0 ||
( ret = mbedtls_x509_get_serial( &p, end, &crt->serial ) ) != 0 ||
( ret = mbedtls_x509_get_alg( &p, end, &crt->sig_oid,
&sig_params1 ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
crt->version++;
if( crt->version > 3 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_UNKNOWN_VERSION );
}
if( ( ret = mbedtls_x509_get_sig_alg( &crt->sig_oid, &sig_params1,
&crt->sig_md, &crt->sig_pk,
&crt->sig_opts ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
/*
* issuer Name
*/
crt->issuer_raw.p = p;
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
}
if( ( ret = mbedtls_x509_get_name( &p, p + len, &crt->issuer ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
crt->issuer_raw.len = p - crt->issuer_raw.p;
/*
* Validity ::= SEQUENCE {
* notBefore Time,
* notAfter Time }
*
*/
if( ( ret = x509_get_dates( &p, end, &crt->valid_from,
&crt->valid_to ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
/*
* subject Name
*/
crt->subject_raw.p = p;
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
}
if( len && ( ret = mbedtls_x509_get_name( &p, p + len, &crt->subject ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
crt->subject_raw.len = p - crt->subject_raw.p;
/*
* SubjectPublicKeyInfo
*/
if( ( ret = mbedtls_pk_parse_subpubkey( &p, end, &crt->pk ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
/*
* issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version shall be v2 or v3
* subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version shall be v2 or v3
* extensions [3] EXPLICIT Extensions OPTIONAL
* -- If present, version shall be v3
*/
if( crt->version == 2 || crt->version == 3 )
{
ret = x509_get_uid( &p, end, &crt->issuer_id, 1 );
if( ret != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
}
if( crt->version == 2 || crt->version == 3 )
{
ret = x509_get_uid( &p, end, &crt->subject_id, 2 );
if( ret != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
}
#if !defined(MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3)
if( crt->version == 3 )
#endif
{
ret = x509_get_crt_ext( &p, end, crt );
if( ret != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
}
if( p != end )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
}
end = crt_end;
/*
* }
* -- end of TBSCertificate
*
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING
*/
if( ( ret = mbedtls_x509_get_alg( &p, end, &sig_oid2, &sig_params2 ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
if( crt->sig_oid.len != sig_oid2.len ||
memcmp( crt->sig_oid.p, sig_oid2.p, crt->sig_oid.len ) != 0 ||
sig_params1.len != sig_params2.len ||
( sig_params1.len != 0 &&
memcmp( sig_params1.p, sig_params2.p, sig_params1.len ) != 0 ) )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_SIG_MISMATCH );
}
if( ( ret = mbedtls_x509_get_sig( &p, end, &crt->sig ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
if( p != end )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
}
return( 0 );
}
/*
* Parse one X.509 certificate in DER format from a buffer and add them to a
* chained list
*/
int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf,
size_t buflen )
{
int ret;
mbedtls_x509_crt *crt = chain, *prev = NULL;
/*
* Check for valid input
*/
if( crt == NULL || buf == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
while( crt->version != 0 && crt->next != NULL )
{
prev = crt;
crt = crt->next;
}
/*
* Add new certificate on the end of the chain if needed.
*/
if( crt->version != 0 && crt->next == NULL )
{
crt->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );
if( crt->next == NULL )
return( MBEDTLS_ERR_X509_ALLOC_FAILED );
prev = crt;
mbedtls_x509_crt_init( crt->next );
crt = crt->next;
}
if( ( ret = x509_crt_parse_der_core( crt, buf, buflen ) ) != 0 )
{
if( prev )
prev->next = NULL;
if( crt != chain )
mbedtls_free( crt );
return( ret );
}
return( 0 );
}
/*
* Parse one or more PEM certificates from a buffer and add them to the chained
* list
*/
int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen )
{
#if defined(MBEDTLS_PEM_PARSE_C)
int success = 0, first_error = 0, total_failed = 0;
int buf_format = MBEDTLS_X509_FORMAT_DER;
#endif
/*
* Check for valid input
*/
if( chain == NULL || buf == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
/*
* Determine buffer content. Buffer contains either one DER certificate or
* one or more PEM certificates.
*/
#if defined(MBEDTLS_PEM_PARSE_C)
if( buflen != 0 && buf[buflen - 1] == '\0' &&
strstr( (const char *) buf, "-----BEGIN CERTIFICATE-----" ) != NULL )
{
buf_format = MBEDTLS_X509_FORMAT_PEM;
}
if( buf_format == MBEDTLS_X509_FORMAT_DER )
return mbedtls_x509_crt_parse_der( chain, buf, buflen );
#else
return mbedtls_x509_crt_parse_der( chain, buf, buflen );
#endif
#if defined(MBEDTLS_PEM_PARSE_C)
if( buf_format == MBEDTLS_X509_FORMAT_PEM )
{
int ret;
mbedtls_pem_context pem;
/* 1 rather than 0 since the terminating NULL byte is counted in */
while( buflen > 1 )
{
size_t use_len;
mbedtls_pem_init( &pem );
/* If we get there, we know the string is null-terminated */
ret = mbedtls_pem_read_buffer( &pem,
"-----BEGIN CERTIFICATE-----",
"-----END CERTIFICATE-----",
buf, NULL, 0, &use_len );
if( ret == 0 )
{
/*
* Was PEM encoded
*/
buflen -= use_len;
buf += use_len;
}
else if( ret == MBEDTLS_ERR_PEM_BAD_INPUT_DATA )
{
return( ret );
}
else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
{
mbedtls_pem_free( &pem );
/*
* PEM header and footer were found
*/
buflen -= use_len;
buf += use_len;
if( first_error == 0 )
first_error = ret;
total_failed++;
continue;
}
else
break;
ret = mbedtls_x509_crt_parse_der( chain, pem.buf, pem.buflen );
mbedtls_pem_free( &pem );
if( ret != 0 )
{
/*
* Quit parsing on a memory error
*/
if( ret == MBEDTLS_ERR_X509_ALLOC_FAILED )
return( ret );
if( first_error == 0 )
first_error = ret;
total_failed++;
continue;
}
success = 1;
}
}
if( success )
return( total_failed );
else if( first_error )
return( first_error );
else
return( MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT );
#endif /* MBEDTLS_PEM_PARSE_C */
}
#if defined(MBEDTLS_FS_IO)
/*
* Load one or more certificates and add them to the chained list
*/
int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path )
{
int ret;
size_t n;
unsigned char *buf;
if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )
return( ret );
ret = mbedtls_x509_crt_parse( chain, buf, n );
mbedtls_zeroize( buf, n );
mbedtls_free( buf );
return( ret );
}
int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path )
{
int ret = 0;
#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
int w_ret;
WCHAR szDir[MAX_PATH];
char filename[MAX_PATH];
char *p;
size_t len = strlen( path );
WIN32_FIND_DATAW file_data;
HANDLE hFind;
if( len > MAX_PATH - 3 )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
memset( szDir, 0, sizeof(szDir) );
memset( filename, 0, MAX_PATH );
memcpy( filename, path, len );
filename[len++] = '\\';
p = filename + len;
filename[len++] = '*';
w_ret = MultiByteToWideChar( CP_ACP, 0, filename, (int)len, szDir,
MAX_PATH - 3 );
if( w_ret == 0 )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
hFind = FindFirstFileW( szDir, &file_data );
if( hFind == INVALID_HANDLE_VALUE )
return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
len = MAX_PATH - len;
do
{
memset( p, 0, len );
if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
continue;
w_ret = WideCharToMultiByte( CP_ACP, 0, file_data.cFileName,
lstrlenW( file_data.cFileName ),
p, (int) len - 1,
NULL, NULL );
if( w_ret == 0 )
return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
w_ret = mbedtls_x509_crt_parse_file( chain, filename );
if( w_ret < 0 )
ret++;
else
ret += w_ret;
}
while( FindNextFileW( hFind, &file_data ) != 0 );
if( GetLastError() != ERROR_NO_MORE_FILES )
ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
FindClose( hFind );
#else /* _WIN32 */
int t_ret;
int snp_ret;
struct stat sb;
struct dirent *entry;
char entry_name[MBEDTLS_X509_MAX_FILE_PATH_LEN];
DIR *dir = opendir( path );
if( dir == NULL )
return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
#if defined(MBEDTLS_THREADING_PTHREAD)
if( ( ret = mbedtls_mutex_lock( &mbedtls_threading_readdir_mutex ) ) != 0 )
{
closedir( dir );
return( ret );
}
#endif
while( ( entry = readdir( dir ) ) != NULL )
{
snp_ret = mbedtls_snprintf( entry_name, sizeof entry_name,
"%s/%s", path, entry->d_name );
if( snp_ret < 0 || (size_t)snp_ret >= sizeof entry_name )
{
ret = MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
goto cleanup;
}
else if( stat( entry_name, &sb ) == -1 )
{
ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
goto cleanup;
}
if( !S_ISREG( sb.st_mode ) )
continue;
// Ignore parse errors
//
t_ret = mbedtls_x509_crt_parse_file( chain, entry_name );
if( t_ret < 0 )
ret++;
else
ret += t_ret;
}
cleanup:
closedir( dir );
#if defined(MBEDTLS_THREADING_PTHREAD)
if( mbedtls_mutex_unlock( &mbedtls_threading_readdir_mutex ) != 0 )
ret = MBEDTLS_ERR_THREADING_MUTEX_ERROR;
#endif
#endif /* _WIN32 */
return( ret );
}
#endif /* MBEDTLS_FS_IO */
static int x509_info_subject_alt_name( char **buf, size_t *size,
const mbedtls_x509_sequence *subject_alt_name )
{
size_t i;
size_t n = *size;
char *p = *buf;
const mbedtls_x509_sequence *cur = subject_alt_name;
const char *sep = "";
size_t sep_len = 0;
while( cur != NULL )
{
if( cur->buf.len + sep_len >= n )
{
*p = '\0';
return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL );
}
n -= cur->buf.len + sep_len;
for( i = 0; i < sep_len; i++ )
*p++ = sep[i];
for( i = 0; i < cur->buf.len; i++ )
*p++ = cur->buf.p[i];
sep = ", ";
sep_len = 2;
cur = cur->next;
}
*p = '\0';
*size = n;
*buf = p;
return( 0 );
}
#define PRINT_ITEM(i) \
{ \
ret = mbedtls_snprintf( p, n, "%s" i, sep ); \
MBEDTLS_X509_SAFE_SNPRINTF; \
sep = ", "; \
}
#define CERT_TYPE(type,name) \
if( ns_cert_type & type ) \
PRINT_ITEM( name );
static int x509_info_cert_type( char **buf, size_t *size,
unsigned char ns_cert_type )
{
int ret;
size_t n = *size;
char *p = *buf;
const char *sep = "";
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT, "SSL Client" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER, "SSL Server" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL, "Email" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING, "Object Signing" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_RESERVED, "Reserved" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CA, "SSL CA" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA, "Email CA" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA, "Object Signing CA" );
*size = n;
*buf = p;
return( 0 );
}
#define KEY_USAGE(code,name) \
if( key_usage & code ) \
PRINT_ITEM( name );
static int x509_info_key_usage( char **buf, size_t *size,
unsigned int key_usage )
{
int ret;
size_t n = *size;
char *p = *buf;
const char *sep = "";
KEY_USAGE( MBEDTLS_X509_KU_DIGITAL_SIGNATURE, "Digital Signature" );
KEY_USAGE( MBEDTLS_X509_KU_NON_REPUDIATION, "Non Repudiation" );
KEY_USAGE( MBEDTLS_X509_KU_KEY_ENCIPHERMENT, "Key Encipherment" );
KEY_USAGE( MBEDTLS_X509_KU_DATA_ENCIPHERMENT, "Data Encipherment" );
KEY_USAGE( MBEDTLS_X509_KU_KEY_AGREEMENT, "Key Agreement" );
KEY_USAGE( MBEDTLS_X509_KU_KEY_CERT_SIGN, "Key Cert Sign" );
KEY_USAGE( MBEDTLS_X509_KU_CRL_SIGN, "CRL Sign" );
KEY_USAGE( MBEDTLS_X509_KU_ENCIPHER_ONLY, "Encipher Only" );
KEY_USAGE( MBEDTLS_X509_KU_DECIPHER_ONLY, "Decipher Only" );
*size = n;
*buf = p;
return( 0 );
}
static int x509_info_ext_key_usage( char **buf, size_t *size,
const mbedtls_x509_sequence *extended_key_usage )
{
int ret;
const char *desc;
size_t n = *size;
char *p = *buf;
const mbedtls_x509_sequence *cur = extended_key_usage;
const char *sep = "";
while( cur != NULL )
{
if( mbedtls_oid_get_extended_key_usage( &cur->buf, &desc ) != 0 )
desc = "???";
ret = mbedtls_snprintf( p, n, "%s%s", sep, desc );
MBEDTLS_X509_SAFE_SNPRINTF;
sep = ", ";
cur = cur->next;
}
*size = n;
*buf = p;
return( 0 );
}
/*
* Return an informational string about the certificate.
*/
#define BEFORE_COLON 18
#define BC "18"
int mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix,
const mbedtls_x509_crt *crt )
{
int ret;
size_t n;
char *p;
char key_size_str[BEFORE_COLON];
p = buf;
n = size;
if( NULL == crt )
{
ret = mbedtls_snprintf( p, n, "\nCertificate is uninitialised!\n" );
MBEDTLS_X509_SAFE_SNPRINTF;
return( (int) ( size - n ) );
}
ret = mbedtls_snprintf( p, n, "%scert. version : %d\n",
prefix, crt->version );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "%sserial number : ",
prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_serial_gets( p, n, &crt->serial );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%sissuer name : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_dn_gets( p, n, &crt->issuer );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%ssubject name : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_dn_gets( p, n, &crt->subject );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%sissued on : " \
"%04d-%02d-%02d %02d:%02d:%02d", prefix,
crt->valid_from.year, crt->valid_from.mon,
crt->valid_from.day, crt->valid_from.hour,
crt->valid_from.min, crt->valid_from.sec );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%sexpires on : " \
"%04d-%02d-%02d %02d:%02d:%02d", prefix,
crt->valid_to.year, crt->valid_to.mon,
crt->valid_to.day, crt->valid_to.hour,
crt->valid_to.min, crt->valid_to.sec );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%ssigned using : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_sig_alg_gets( p, n, &crt->sig_oid, crt->sig_pk,
crt->sig_md, crt->sig_opts );
MBEDTLS_X509_SAFE_SNPRINTF;
/* Key size */
if( ( ret = mbedtls_x509_key_size_helper( key_size_str, BEFORE_COLON,
mbedtls_pk_get_name( &crt->pk ) ) ) != 0 )
{
return( ret );
}
ret = mbedtls_snprintf( p, n, "\n%s%-" BC "s: %d bits", prefix, key_size_str,
(int) mbedtls_pk_get_bitlen( &crt->pk ) );
MBEDTLS_X509_SAFE_SNPRINTF;
/*
* Optional extensions
*/
if( crt->ext_types & MBEDTLS_X509_EXT_BASIC_CONSTRAINTS )
{
ret = mbedtls_snprintf( p, n, "\n%sbasic constraints : CA=%s", prefix,
crt->ca_istrue ? "true" : "false" );
MBEDTLS_X509_SAFE_SNPRINTF;
if( crt->max_pathlen > 0 )
{
ret = mbedtls_snprintf( p, n, ", max_pathlen=%d", crt->max_pathlen - 1 );
MBEDTLS_X509_SAFE_SNPRINTF;
}
}
if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
{
ret = mbedtls_snprintf( p, n, "\n%ssubject alt name : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
if( ( ret = x509_info_subject_alt_name( &p, &n,
&crt->subject_alt_names ) ) != 0 )
return( ret );
}
if( crt->ext_types & MBEDTLS_X509_EXT_NS_CERT_TYPE )
{
ret = mbedtls_snprintf( p, n, "\n%scert. type : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
if( ( ret = x509_info_cert_type( &p, &n, crt->ns_cert_type ) ) != 0 )
return( ret );
}
if( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE )
{
ret = mbedtls_snprintf( p, n, "\n%skey usage : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
if( ( ret = x509_info_key_usage( &p, &n, crt->key_usage ) ) != 0 )
return( ret );
}
if( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE )
{
ret = mbedtls_snprintf( p, n, "\n%sext key usage : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
if( ( ret = x509_info_ext_key_usage( &p, &n,
&crt->ext_key_usage ) ) != 0 )
return( ret );
}
ret = mbedtls_snprintf( p, n, "\n" );
MBEDTLS_X509_SAFE_SNPRINTF;
return( (int) ( size - n ) );
}
struct x509_crt_verify_string {
int code;
const char *string;
};
static const struct x509_crt_verify_string x509_crt_verify_strings[] = {
{ MBEDTLS_X509_BADCERT_EXPIRED, "The certificate validity has expired" },
{ MBEDTLS_X509_BADCERT_REVOKED, "The certificate has been revoked (is on a CRL)" },
{ MBEDTLS_X509_BADCERT_CN_MISMATCH, "The certificate Common Name (CN) does not match with the expected CN" },
{ MBEDTLS_X509_BADCERT_NOT_TRUSTED, "The certificate is not correctly signed by the trusted CA" },
{ MBEDTLS_X509_BADCRL_NOT_TRUSTED, "The CRL is not correctly signed by the trusted CA" },
{ MBEDTLS_X509_BADCRL_EXPIRED, "The CRL is expired" },
{ MBEDTLS_X509_BADCERT_MISSING, "Certificate was missing" },
{ MBEDTLS_X509_BADCERT_SKIP_VERIFY, "Certificate verification was skipped" },
{ MBEDTLS_X509_BADCERT_OTHER, "Other reason (can be used by verify callback)" },
{ MBEDTLS_X509_BADCERT_FUTURE, "The certificate validity starts in the future" },
{ MBEDTLS_X509_BADCRL_FUTURE, "The CRL is from the future" },
{ MBEDTLS_X509_BADCERT_KEY_USAGE, "Usage does not match the keyUsage extension" },
{ MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, "Usage does not match the extendedKeyUsage extension" },
{ MBEDTLS_X509_BADCERT_NS_CERT_TYPE, "Usage does not match the nsCertType extension" },
{ MBEDTLS_X509_BADCERT_BAD_MD, "The certificate is signed with an unacceptable hash." },
{ MBEDTLS_X509_BADCERT_BAD_PK, "The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA)." },
{ MBEDTLS_X509_BADCERT_BAD_KEY, "The certificate is signed with an unacceptable key (eg bad curve, RSA too short)." },
{ MBEDTLS_X509_BADCRL_BAD_MD, "The CRL is signed with an unacceptable hash." },
{ MBEDTLS_X509_BADCRL_BAD_PK, "The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA)." },
{ MBEDTLS_X509_BADCRL_BAD_KEY, "The CRL is signed with an unacceptable key (eg bad curve, RSA too short)." },
{ 0, NULL }
};
int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
uint32_t flags )
{
int ret;
const struct x509_crt_verify_string *cur;
char *p = buf;
size_t n = size;
for( cur = x509_crt_verify_strings; cur->string != NULL ; cur++ )
{
if( ( flags & cur->code ) == 0 )
continue;
ret = mbedtls_snprintf( p, n, "%s%s\n", prefix, cur->string );
MBEDTLS_X509_SAFE_SNPRINTF;
flags ^= cur->code;
}
if( flags != 0 )
{
ret = mbedtls_snprintf( p, n, "%sUnknown reason "
"(this should not happen)\n", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
}
return( (int) ( size - n ) );
}
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
unsigned int usage )
{
unsigned int usage_must, usage_may;
unsigned int may_mask = MBEDTLS_X509_KU_ENCIPHER_ONLY
| MBEDTLS_X509_KU_DECIPHER_ONLY;
if( ( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE ) == 0 )
return( 0 );
usage_must = usage & ~may_mask;
if( ( ( crt->key_usage & ~may_mask ) & usage_must ) != usage_must )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
usage_may = usage & may_mask;
if( ( ( crt->key_usage & may_mask ) | usage_may ) != usage_may )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
return( 0 );
}
#endif
#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,
const char *usage_oid,
size_t usage_len )
{
const mbedtls_x509_sequence *cur;
/* Extension is not mandatory, absent means no restriction */
if( ( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE ) == 0 )
return( 0 );
/*
* Look for the requested usage (or wildcard ANY) in our list
*/
for( cur = &crt->ext_key_usage; cur != NULL; cur = cur->next )
{
const mbedtls_x509_buf *cur_oid = &cur->buf;
if( cur_oid->len == usage_len &&
memcmp( cur_oid->p, usage_oid, usage_len ) == 0 )
{
return( 0 );
}
if( MBEDTLS_OID_CMP( MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE, cur_oid ) == 0 )
return( 0 );
}
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
}
#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
#if defined(MBEDTLS_X509_CRL_PARSE_C)
/*
* Return 1 if the certificate is revoked, or 0 otherwise.
*/
int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl )
{
const mbedtls_x509_crl_entry *cur = &crl->entry;
while( cur != NULL && cur->serial.len != 0 )
{
if( crt->serial.len == cur->serial.len &&
memcmp( crt->serial.p, cur->serial.p, crt->serial.len ) == 0 )
{
if( mbedtls_x509_time_is_past( &cur->revocation_date ) )
return( 1 );
}
cur = cur->next;
}
return( 0 );
}
/*
* Check that the given certificate is not revoked according to the CRL.
* Skip validation is no CRL for the given CA is present.
*/
static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca,
mbedtls_x509_crl *crl_list,
const mbedtls_x509_crt_profile *profile )
{
int flags = 0;
unsigned char hash[MBEDTLS_MD_MAX_SIZE];
const mbedtls_md_info_t *md_info;
if( ca == NULL )
return( flags );
while( crl_list != NULL )
{
if( crl_list->version == 0 ||
crl_list->issuer_raw.len != ca->subject_raw.len ||
memcmp( crl_list->issuer_raw.p, ca->subject_raw.p,
crl_list->issuer_raw.len ) != 0 )
{
crl_list = crl_list->next;
continue;
}
/*
* Check if the CA is configured to sign CRLs
*/
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
if( mbedtls_x509_crt_check_key_usage( ca, MBEDTLS_X509_KU_CRL_SIGN ) != 0 )
{
flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
break;
}
#endif
/*
* Check if CRL is correctly signed by the trusted CA
*/
if( x509_profile_check_md_alg( profile, crl_list->sig_md ) != 0 )
flags |= MBEDTLS_X509_BADCRL_BAD_MD;
if( x509_profile_check_pk_alg( profile, crl_list->sig_pk ) != 0 )
flags |= MBEDTLS_X509_BADCRL_BAD_PK;
md_info = mbedtls_md_info_from_type( crl_list->sig_md );
if( md_info == NULL )
{
/*
* Cannot check 'unknown' hash
*/
flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
break;
}
mbedtls_md( md_info, crl_list->tbs.p, crl_list->tbs.len, hash );
if( x509_profile_check_key( profile, crl_list->sig_pk, &ca->pk ) != 0 )
flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
if( mbedtls_pk_verify_ext( crl_list->sig_pk, crl_list->sig_opts, &ca->pk,
crl_list->sig_md, hash, mbedtls_md_get_size( md_info ),
crl_list->sig.p, crl_list->sig.len ) != 0 )
{
flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
break;
}
/*
* Check for validity of CRL (Do not drop out)
*/
if( mbedtls_x509_time_is_past( &crl_list->next_update ) )
flags |= MBEDTLS_X509_BADCRL_EXPIRED;
if( mbedtls_x509_time_is_future( &crl_list->this_update ) )
flags |= MBEDTLS_X509_BADCRL_FUTURE;
/*
* Check if certificate is revoked
*/
if( mbedtls_x509_crt_is_revoked( crt, crl_list ) )
{
flags |= MBEDTLS_X509_BADCERT_REVOKED;
break;
}
crl_list = crl_list->next;
}
return( flags );
}
#endif /* MBEDTLS_X509_CRL_PARSE_C */
/*
* Like memcmp, but case-insensitive and always returns -1 if different
*/
static int x509_memcasecmp( const void *s1, const void *s2, size_t len )
{
size_t i;
unsigned char diff;
const unsigned char *n1 = s1, *n2 = s2;
for( i = 0; i < len; i++ )
{
diff = n1[i] ^ n2[i];
if( diff == 0 )
continue;
if( diff == 32 &&
( ( n1[i] >= 'a' && n1[i] <= 'z' ) ||
( n1[i] >= 'A' && n1[i] <= 'Z' ) ) )
{
continue;
}
return( -1 );
}
return( 0 );
}
/*
* Return 0 if name matches wildcard, -1 otherwise
*/
static int x509_check_wildcard( const char *cn, mbedtls_x509_buf *name )
{
size_t i;
size_t cn_idx = 0, cn_len = strlen( cn );
if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' )
return( 0 );
for( i = 0; i < cn_len; ++i )
{
if( cn[i] == '.' )
{
cn_idx = i;
break;
}
}
if( cn_idx == 0 )
return( -1 );
if( cn_len - cn_idx == name->len - 1 &&
x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )
{
return( 0 );
}
return( -1 );
}
/*
* Compare two X.509 strings, case-insensitive, and allowing for some encoding
* variations (but not all).
*
* Return 0 if equal, -1 otherwise.
*/
static int x509_string_cmp( const mbedtls_x509_buf *a, const mbedtls_x509_buf *b )
{
if( a->tag == b->tag &&
a->len == b->len &&
memcmp( a->p, b->p, b->len ) == 0 )
{
return( 0 );
}
if( ( a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
( b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
a->len == b->len &&
x509_memcasecmp( a->p, b->p, b->len ) == 0 )
{
return( 0 );
}
return( -1 );
}
/*
* Compare two X.509 Names (aka rdnSequence).
*
* See RFC 5280 section 7.1, though we don't implement the whole algorithm:
* we sometimes return unequal when the full algorithm would return equal,
* but never the other way. (In particular, we don't do Unicode normalisation
* or space folding.)
*
* Return 0 if equal, -1 otherwise.
*/
static int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b )
{
/* Avoid recursion, it might not be optimised by the compiler */
while( a != NULL || b != NULL )
{
if( a == NULL || b == NULL )
return( -1 );
/* type */
if( a->oid.tag != b->oid.tag ||
a->oid.len != b->oid.len ||
memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 )
{
return( -1 );
}
/* value */
if( x509_string_cmp( &a->val, &b->val ) != 0 )
return( -1 );
/* structure of the list of sets */
if( a->next_merged != b->next_merged )
return( -1 );
a = a->next;
b = b->next;
}
/* a == NULL == b */
return( 0 );
}
/*
* Check if 'parent' is a suitable parent (signing CA) for 'child'.
* Return 0 if yes, -1 if not.
*
* top means parent is a locally-trusted certificate
* bottom means child is the end entity cert
*/
static int x509_crt_check_parent( const mbedtls_x509_crt *child,
const mbedtls_x509_crt *parent,
int top, int bottom )
{
int need_ca_bit;
/* Parent must be the issuer */
if( x509_name_cmp( &child->issuer, &parent->subject ) != 0 )
return( -1 );
/* Parent must have the basicConstraints CA bit set as a general rule */
need_ca_bit = 1;
/* Exception: v1/v2 certificates that are locally trusted. */
if( top && parent->version < 3 )
need_ca_bit = 0;
/* Exception: self-signed end-entity certs that are locally trusted. */
if( top && bottom &&
child->raw.len == parent->raw.len &&
memcmp( child->raw.p, parent->raw.p, child->raw.len ) == 0 )
{
need_ca_bit = 0;
}
if( need_ca_bit && ! parent->ca_istrue )
return( -1 );
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
if( need_ca_bit &&
mbedtls_x509_crt_check_key_usage( parent, MBEDTLS_X509_KU_KEY_CERT_SIGN ) != 0 )
{
return( -1 );
}
#endif
return( 0 );
}
static int x509_crt_verify_top(
mbedtls_x509_crt *child, mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
int path_cnt, int self_cnt, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
int ret;
uint32_t ca_flags = 0;
int check_path_cnt;
unsigned char hash[MBEDTLS_MD_MAX_SIZE];
const mbedtls_md_info_t *md_info;
mbedtls_x509_crt *future_past_ca = NULL;
if( mbedtls_x509_time_is_past( &child->valid_to ) )
*flags |= MBEDTLS_X509_BADCERT_EXPIRED;
if( mbedtls_x509_time_is_future( &child->valid_from ) )
*flags |= MBEDTLS_X509_BADCERT_FUTURE;
if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_MD;
if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
/*
* Child is the top of the chain. Check against the trust_ca list.
*/
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
md_info = mbedtls_md_info_from_type( child->sig_md );
if( md_info == NULL )
{
/*
* Cannot check 'unknown', no need to try any CA
*/
trust_ca = NULL;
}
else
mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash );
for( /* trust_ca */ ; trust_ca != NULL; trust_ca = trust_ca->next )
{
if( x509_crt_check_parent( child, trust_ca, 1, path_cnt == 0 ) != 0 )
continue;
check_path_cnt = path_cnt + 1;
/*
* Reduce check_path_cnt to check against if top of the chain is
* the same as the trusted CA
*/
if( child->subject_raw.len == trust_ca->subject_raw.len &&
memcmp( child->subject_raw.p, trust_ca->subject_raw.p,
child->issuer_raw.len ) == 0 )
{
check_path_cnt--;
}
/* Self signed certificates do not count towards the limit */
if( trust_ca->max_pathlen > 0 &&
trust_ca->max_pathlen < check_path_cnt - self_cnt )
{
continue;
}
if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &trust_ca->pk,
child->sig_md, hash, mbedtls_md_get_size( md_info ),
child->sig.p, child->sig.len ) != 0 )
{
continue;
}
if( mbedtls_x509_time_is_past( &trust_ca->valid_to ) ||
mbedtls_x509_time_is_future( &trust_ca->valid_from ) )
{
if ( future_past_ca == NULL )
future_past_ca = trust_ca;
continue;
}
break;
}
if( trust_ca != NULL || ( trust_ca = future_past_ca ) != NULL )
{
/*
* Top of chain is signed by a trusted CA
*/
*flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
if( x509_profile_check_key( profile, child->sig_pk, &trust_ca->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
}
/*
* If top of chain is not the same as the trusted CA send a verify request
* to the callback for any issues with validity and CRL presence for the
* trusted CA certificate.
*/
if( trust_ca != NULL &&
( child->subject_raw.len != trust_ca->subject_raw.len ||
memcmp( child->subject_raw.p, trust_ca->subject_raw.p,
child->issuer_raw.len ) != 0 ) )
{
#if defined(MBEDTLS_X509_CRL_PARSE_C)
/* Check trusted CA's CRL for the chain's top crt */
*flags |= x509_crt_verifycrl( child, trust_ca, ca_crl, profile );
#else
((void) ca_crl);
#endif
if( mbedtls_x509_time_is_past( &trust_ca->valid_to ) )
ca_flags |= MBEDTLS_X509_BADCERT_EXPIRED;
if( mbedtls_x509_time_is_future( &trust_ca->valid_from ) )
ca_flags |= MBEDTLS_X509_BADCERT_FUTURE;
if( NULL != f_vrfy )
{
if( ( ret = f_vrfy( p_vrfy, trust_ca, path_cnt + 1,
&ca_flags ) ) != 0 )
{
return( ret );
}
}
}
/* Call callback on top cert */
if( NULL != f_vrfy )
{
if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 )
return( ret );
}
*flags |= ca_flags;
return( 0 );
}
static int x509_crt_verify_child(
mbedtls_x509_crt *child, mbedtls_x509_crt *parent,
mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
int path_cnt, int self_cnt, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
int ret;
uint32_t parent_flags = 0;
unsigned char hash[MBEDTLS_MD_MAX_SIZE];
mbedtls_x509_crt *grandparent;
const mbedtls_md_info_t *md_info;
/* Counting intermediate self signed certificates */
if( ( path_cnt != 0 ) && x509_name_cmp( &child->issuer, &child->subject ) == 0 )
self_cnt++;
/* path_cnt is 0 for the first intermediate CA */
if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA )
{
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
}
if( mbedtls_x509_time_is_past( &child->valid_to ) )
*flags |= MBEDTLS_X509_BADCERT_EXPIRED;
if( mbedtls_x509_time_is_future( &child->valid_from ) )
*flags |= MBEDTLS_X509_BADCERT_FUTURE;
if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_MD;
if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
md_info = mbedtls_md_info_from_type( child->sig_md );
if( md_info == NULL )
{
/*
* Cannot check 'unknown' hash
*/
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
}
else
{
mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash );
if( x509_profile_check_key( profile, child->sig_pk, &parent->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk,
child->sig_md, hash, mbedtls_md_get_size( md_info ),
child->sig.p, child->sig.len ) != 0 )
{
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
}
}
#if defined(MBEDTLS_X509_CRL_PARSE_C)
/* Check trusted CA's CRL for the given crt */
*flags |= x509_crt_verifycrl(child, parent, ca_crl, profile );
#endif
/* Look for a grandparent in trusted CAs */
for( grandparent = trust_ca;
grandparent != NULL;
grandparent = grandparent->next )
{
if( x509_crt_check_parent( parent, grandparent,
0, path_cnt == 0 ) == 0 )
break;
}
if( grandparent != NULL )
{
ret = x509_crt_verify_top( parent, grandparent, ca_crl, profile,
path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
else
{
/* Look for a grandparent upwards the chain */
for( grandparent = parent->next;
grandparent != NULL;
grandparent = grandparent->next )
{
/* +2 because the current step is not yet accounted for
* and because max_pathlen is one higher than it should be.
* Also self signed certificates do not count to the limit. */
if( grandparent->max_pathlen > 0 &&
grandparent->max_pathlen < 2 + path_cnt - self_cnt )
{
continue;
}
if( x509_crt_check_parent( parent, grandparent,
0, path_cnt == 0 ) == 0 )
break;
}
/* Is our parent part of the chain or at the top? */
if( grandparent != NULL )
{
ret = x509_crt_verify_child( parent, grandparent, trust_ca, ca_crl,
profile, path_cnt + 1, self_cnt, &parent_flags,
f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
else
{
ret = x509_crt_verify_top( parent, trust_ca, ca_crl, profile,
path_cnt + 1, self_cnt, &parent_flags,
f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
}
/* child is verified to be a child of the parent, call verify callback */
if( NULL != f_vrfy )
if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 )
return( ret );
*flags |= parent_flags;
return( 0 );
}
/*
* Verify the certificate validity
*/
int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
return( mbedtls_x509_crt_verify_with_profile( crt, trust_ca, ca_crl,
&mbedtls_x509_crt_profile_default, cn, flags, f_vrfy, p_vrfy ) );
}
/*
* Verify the certificate validity, with profile
*/
int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
size_t cn_len;
int ret;
int pathlen = 0, selfsigned = 0;
mbedtls_x509_crt *parent;
mbedtls_x509_name *name;
mbedtls_x509_sequence *cur = NULL;
mbedtls_pk_type_t pk_type;
*flags = 0;
if( profile == NULL )
{
ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA;
goto exit;
}
if( cn != NULL )
{
name = &crt->subject;
cn_len = strlen( cn );
if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
{
cur = &crt->subject_alt_names;
while( cur != NULL )
{
if( cur->buf.len == cn_len &&
x509_memcasecmp( cn, cur->buf.p, cn_len ) == 0 )
break;
if( cur->buf.len > 2 &&
memcmp( cur->buf.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &cur->buf ) == 0 )
{
break;
}
cur = cur->next;
}
if( cur == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
else
{
while( name != NULL )
{
if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 )
{
if( name->val.len == cn_len &&
x509_memcasecmp( name->val.p, cn, cn_len ) == 0 )
break;
if( name->val.len > 2 &&
memcmp( name->val.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &name->val ) == 0 )
break;
}
name = name->next;
}
if( name == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
}
/* Check the type and size of the key */
pk_type = mbedtls_pk_get_type( &crt->pk );
if( x509_profile_check_pk_alg( profile, pk_type ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
if( x509_profile_check_key( profile, pk_type, &crt->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
/* Look for a parent in trusted CAs */
for( parent = trust_ca; parent != NULL; parent = parent->next )
{
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
}
if( parent != NULL )
{
ret = x509_crt_verify_top( crt, parent, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
else
{
/* Look for a parent upwards the chain */
for( parent = crt->next; parent != NULL; parent = parent->next )
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
/* Are we part of the chain or at the top? */
if( parent != NULL )
{
ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
else
{
ret = x509_crt_verify_top( crt, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
}
exit:
if( ret != 0 )
{
*flags = (uint32_t) -1;
return( ret );
}
if( *flags != 0 )
return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
return( 0 );
}
/*
* Initialize a certificate chain
*/
void mbedtls_x509_crt_init( mbedtls_x509_crt *crt )
{
memset( crt, 0, sizeof(mbedtls_x509_crt) );
}
/*
* Unallocate all certificate data
*/
void mbedtls_x509_crt_free( mbedtls_x509_crt *crt )
{
mbedtls_x509_crt *cert_cur = crt;
mbedtls_x509_crt *cert_prv;
mbedtls_x509_name *name_cur;
mbedtls_x509_name *name_prv;
mbedtls_x509_sequence *seq_cur;
mbedtls_x509_sequence *seq_prv;
if( crt == NULL )
return;
do
{
mbedtls_pk_free( &cert_cur->pk );
#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
mbedtls_free( cert_cur->sig_opts );
#endif
name_cur = cert_cur->issuer.next;
while( name_cur != NULL )
{
name_prv = name_cur;
name_cur = name_cur->next;
mbedtls_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
mbedtls_free( name_prv );
}
name_cur = cert_cur->subject.next;
while( name_cur != NULL )
{
name_prv = name_cur;
name_cur = name_cur->next;
mbedtls_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
mbedtls_free( name_prv );
}
seq_cur = cert_cur->ext_key_usage.next;
while( seq_cur != NULL )
{
seq_prv = seq_cur;
seq_cur = seq_cur->next;
mbedtls_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) );
mbedtls_free( seq_prv );
}
seq_cur = cert_cur->subject_alt_names.next;
while( seq_cur != NULL )
{
seq_prv = seq_cur;
seq_cur = seq_cur->next;
mbedtls_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) );
mbedtls_free( seq_prv );
}
if( cert_cur->raw.p != NULL )
{
mbedtls_zeroize( cert_cur->raw.p, cert_cur->raw.len );
mbedtls_free( cert_cur->raw.p );
}
cert_cur = cert_cur->next;
}
while( cert_cur != NULL );
cert_cur = crt;
do
{
cert_prv = cert_cur;
cert_cur = cert_cur->next;
mbedtls_zeroize( cert_prv, sizeof( mbedtls_x509_crt ) );
if( cert_prv != crt )
mbedtls_free( cert_prv );
}
while( cert_cur != NULL );
}
#endif /* MBEDTLS_X509_CRT_PARSE_C */
| ./CrossVul/dataset_final_sorted/CWE-287/c/bad_2756_6 |
crossvul-cpp_data_bad_3281_0 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* COPYRIGHT (C) 2006,2007
* THE REGENTS OF THE UNIVERSITY OF MICHIGAN
* ALL RIGHTS RESERVED
*
* Permission is granted to use, copy, create derivative works
* and redistribute this software and such derivative works
* for any purpose, so long as the name of The University of
* Michigan is not used in any advertising or publicity
* pertaining to the use of distribution of this software
* without specific, written prior authorization. If the
* above copyright notice or any other identification of the
* University of Michigan is included in any copy of any
* portion of this software, then the disclaimer below must
* also be included.
*
* THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION
* FROM THE UNIVERSITY OF MICHIGAN AS TO ITS FITNESS FOR ANY
* PURPOSE, AND WITHOUT WARRANTY BY THE UNIVERSITY OF
* MICHIGAN OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
* REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE LIABLE
* FOR ANY DAMAGES, INCLUDING SPECIAL, INDIRECT, INCIDENTAL, OR
* CONSEQUENTIAL DAMAGES, WITH RESPECT TO ANY CLAIM ARISING
* OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, EVEN
* IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES.
*/
#include "pkinit_crypto_openssl.h"
#include "k5-buf.h"
#include <dlfcn.h>
#include <unistd.h>
#include <dirent.h>
#include <arpa/inet.h>
static krb5_error_code pkinit_init_pkinit_oids(pkinit_plg_crypto_context );
static void pkinit_fini_pkinit_oids(pkinit_plg_crypto_context );
static krb5_error_code pkinit_init_dh_params(pkinit_plg_crypto_context );
static void pkinit_fini_dh_params(pkinit_plg_crypto_context );
static krb5_error_code pkinit_init_certs(pkinit_identity_crypto_context ctx);
static void pkinit_fini_certs(pkinit_identity_crypto_context ctx);
static krb5_error_code pkinit_init_pkcs11(pkinit_identity_crypto_context ctx);
static void pkinit_fini_pkcs11(pkinit_identity_crypto_context ctx);
static krb5_error_code pkinit_encode_dh_params
(const BIGNUM *, const BIGNUM *, const BIGNUM *, uint8_t **, unsigned int *);
static DH *decode_dh_params(const uint8_t *, unsigned int );
static int pkinit_check_dh_params(DH *dh1, DH *dh2);
static krb5_error_code pkinit_sign_data
(krb5_context context, pkinit_identity_crypto_context cryptoctx,
unsigned char *data, unsigned int data_len,
unsigned char **sig, unsigned int *sig_len);
static krb5_error_code create_signature
(unsigned char **, unsigned int *, unsigned char *, unsigned int,
EVP_PKEY *pkey);
static krb5_error_code pkinit_decode_data
(krb5_context context, pkinit_identity_crypto_context cryptoctx,
const uint8_t *data, unsigned int data_len, uint8_t **decoded,
unsigned int *decoded_len);
#ifdef DEBUG_DH
static void print_dh(DH *, char *);
static void print_pubkey(BIGNUM *, char *);
#endif
static int prepare_enc_data
(const uint8_t *indata, int indata_len, uint8_t **outdata, int *outdata_len);
static int openssl_callback (int, X509_STORE_CTX *);
static int openssl_callback_ignore_crls (int, X509_STORE_CTX *);
static int pkcs7_decrypt
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
PKCS7 *p7, BIO *bio);
static BIO * pkcs7_dataDecode
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
PKCS7 *p7);
static ASN1_OBJECT * pkinit_pkcs7type2oid
(pkinit_plg_crypto_context plg_cryptoctx, int pkcs7_type);
static krb5_error_code pkinit_create_sequence_of_principal_identifiers
(krb5_context context, pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int type, krb5_pa_data ***e_data_out);
#ifndef WITHOUT_PKCS11
static krb5_error_code pkinit_find_private_key
(pkinit_identity_crypto_context, CK_ATTRIBUTE_TYPE usage,
CK_OBJECT_HANDLE *objp);
static krb5_error_code pkinit_login
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
CK_TOKEN_INFO *tip, const char *password);
static krb5_error_code pkinit_open_session
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx);
static void * pkinit_C_LoadModule(const char *modname, CK_FUNCTION_LIST_PTR_PTR p11p);
static CK_RV pkinit_C_UnloadModule(void *handle);
#ifdef SILLYDECRYPT
CK_RV pkinit_C_Decrypt
(pkinit_identity_crypto_context id_cryptoctx,
CK_BYTE_PTR pEncryptedData, CK_ULONG ulEncryptedDataLen,
CK_BYTE_PTR pData, CK_ULONG_PTR pulDataLen);
#endif
static krb5_error_code pkinit_sign_data_pkcs11
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data, unsigned int data_len,
unsigned char **sig, unsigned int *sig_len);
static krb5_error_code pkinit_decode_data_pkcs11
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
const uint8_t *data, unsigned int data_len, uint8_t **decoded_data,
unsigned int *decoded_data_len);
#endif /* WITHOUT_PKCS11 */
static krb5_error_code pkinit_sign_data_fs
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data, unsigned int data_len,
unsigned char **sig, unsigned int *sig_len);
static krb5_error_code pkinit_decode_data_fs
(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
const uint8_t *data, unsigned int data_len, uint8_t **decoded_data,
unsigned int *decoded_data_len);
static krb5_error_code
create_krb5_invalidCertificates(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_external_principal_identifier *** ids);
static krb5_error_code
create_identifiers_from_stack(STACK_OF(X509) *sk,
krb5_external_principal_identifier *** ids);
static int
wrap_signeddata(unsigned char *data, unsigned int data_len,
unsigned char **out, unsigned int *out_len);
static char *
pkinit_pkcs11_code_to_text(int err);
#ifdef HAVE_OPENSSL_CMS
/* Use CMS support present in OpenSSL. */
#include <openssl/cms.h>
#define pkinit_CMS_get0_content_signed(_cms) CMS_get0_content(_cms)
#define pkinit_CMS_get0_content_data(_cms) CMS_get0_content(_cms)
#define pkinit_CMS_free1_crls(_sk_x509crl) \
sk_X509_CRL_pop_free((_sk_x509crl), X509_CRL_free)
#define pkinit_CMS_free1_certs(_sk_x509) \
sk_X509_pop_free((_sk_x509), X509_free)
#define pkinit_CMS_SignerInfo_get_cert(_cms,_si,_x509_pp) \
CMS_SignerInfo_get0_algs(_si,NULL,_x509_pp,NULL,NULL)
#else
/* Fake up CMS support using PKCS7. */
#define pkinit_CMS_free1_crls(_stack_of_x509crls) /* Don't free these */
#define pkinit_CMS_free1_certs(_stack_of_x509certs) /* Don't free these */
#define CMS_NO_SIGNER_CERT_VERIFY PKCS7_NOVERIFY
#define CMS_NOATTR PKCS7_NOATTR
#define CMS_ContentInfo PKCS7
#define CMS_SignerInfo PKCS7_SIGNER_INFO
#define d2i_CMS_ContentInfo d2i_PKCS7
#define CMS_get0_type(_p7) ((_p7)->type)
#define pkinit_CMS_get0_content_signed(_p7) (&((_p7)->d.sign->contents->d.other->value.octet_string))
#define pkinit_CMS_get0_content_data(_p7) (&((_p7)->d.other->value.octet_string))
#define CMS_set1_signers_certs(_p7,_stack_of_x509,_uint)
#define CMS_get0_SignerInfos PKCS7_get_signer_info
#define stack_st_CMS_SignerInfo stack_st_PKCS7_SIGNER_INFO
#undef sk_CMS_SignerInfo_value
#define sk_CMS_SignerInfo_value sk_PKCS7_SIGNER_INFO_value
#define CMS_get0_eContentType(_p7) (_p7->d.sign->contents->type)
#define CMS_verify PKCS7_verify
#define CMS_get1_crls(_p7) (_p7->d.sign->crl)
#define CMS_get1_certs(_p7) (_p7->d.sign->cert)
#define CMS_ContentInfo_free(_p7) PKCS7_free(_p7)
#define pkinit_CMS_SignerInfo_get_cert(_p7,_si,_x509_pp) \
(*_x509_pp) = PKCS7_cert_from_signer_info(_p7,_si)
#endif
#if OPENSSL_VERSION_NUMBER < 0x10100000L
/* 1.1 standardizes constructor and destructor names, renaming
* EVP_MD_CTX_{create,destroy} and deprecating ASN1_STRING_data. */
#define EVP_MD_CTX_new EVP_MD_CTX_create
#define EVP_MD_CTX_free EVP_MD_CTX_destroy
#define ASN1_STRING_get0_data ASN1_STRING_data
/* 1.1 makes many handle types opaque and adds accessors. Add compatibility
* versions of the new accessors we use for pre-1.1. */
#define OBJ_get0_data(o) ((o)->data)
#define OBJ_length(o) ((o)->length)
#define DH_set0_pqg compat_dh_set0_pqg
static int compat_dh_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g)
{
/* The real function frees the old values and does argument checking, but
* our code doesn't need that. */
dh->p = p;
dh->q = q;
dh->g = g;
return 1;
}
#define DH_get0_pqg compat_dh_get0_pqg
static void compat_dh_get0_pqg(const DH *dh, const BIGNUM **p,
const BIGNUM **q, const BIGNUM **g)
{
if (p != NULL)
*p = dh->p;
if (q != NULL)
*q = dh->q;
if (g != NULL)
*g = dh->g;
}
#define DH_get0_key compat_dh_get0_key
static void compat_dh_get0_key(const DH *dh, const BIGNUM **pub,
const BIGNUM **priv)
{
if (pub != NULL)
*pub = dh->pub_key;
if (priv != NULL)
*priv = dh->priv_key;
}
/* Return true if the cert c includes a key usage which doesn't include u.
* Define using direct member access for pre-1.1. */
#define ku_reject(c, u) \
(((c)->ex_flags & EXFLAG_KUSAGE) && !((c)->ex_kusage & (u)))
#else /* OPENSSL_VERSION_NUMBER >= 0x10100000L */
/* Return true if the cert x includes a key usage which doesn't include u. */
#define ku_reject(c, u) (!(X509_get_key_usage(c) & (u)))
#endif
static struct pkcs11_errstrings {
short code;
char *text;
} pkcs11_errstrings[] = {
{ 0x0, "ok" },
{ 0x1, "cancel" },
{ 0x2, "host memory" },
{ 0x3, "slot id invalid" },
{ 0x5, "general error" },
{ 0x6, "function failed" },
{ 0x7, "arguments bad" },
{ 0x8, "no event" },
{ 0x9, "need to create threads" },
{ 0xa, "cant lock" },
{ 0x10, "attribute read only" },
{ 0x11, "attribute sensitive" },
{ 0x12, "attribute type invalid" },
{ 0x13, "attribute value invalid" },
{ 0x20, "data invalid" },
{ 0x21, "data len range" },
{ 0x30, "device error" },
{ 0x31, "device memory" },
{ 0x32, "device removed" },
{ 0x40, "encrypted data invalid" },
{ 0x41, "encrypted data len range" },
{ 0x50, "function canceled" },
{ 0x51, "function not parallel" },
{ 0x54, "function not supported" },
{ 0x60, "key handle invalid" },
{ 0x62, "key size range" },
{ 0x63, "key type inconsistent" },
{ 0x64, "key not needed" },
{ 0x65, "key changed" },
{ 0x66, "key needed" },
{ 0x67, "key indigestible" },
{ 0x68, "key function not permitted" },
{ 0x69, "key not wrappable" },
{ 0x6a, "key unextractable" },
{ 0x70, "mechanism invalid" },
{ 0x71, "mechanism param invalid" },
{ 0x82, "object handle invalid" },
{ 0x90, "operation active" },
{ 0x91, "operation not initialized" },
{ 0xa0, "pin incorrect" },
{ 0xa1, "pin invalid" },
{ 0xa2, "pin len range" },
{ 0xa3, "pin expired" },
{ 0xa4, "pin locked" },
{ 0xb0, "session closed" },
{ 0xb1, "session count" },
{ 0xb3, "session handle invalid" },
{ 0xb4, "session parallel not supported" },
{ 0xb5, "session read only" },
{ 0xb6, "session exists" },
{ 0xb7, "session read only exists" },
{ 0xb8, "session read write so exists" },
{ 0xc0, "signature invalid" },
{ 0xc1, "signature len range" },
{ 0xd0, "template incomplete" },
{ 0xd1, "template inconsistent" },
{ 0xe0, "token not present" },
{ 0xe1, "token not recognized" },
{ 0xe2, "token write protected" },
{ 0xf0, "unwrapping key handle invalid" },
{ 0xf1, "unwrapping key size range" },
{ 0xf2, "unwrapping key type inconsistent" },
{ 0x100, "user already logged in" },
{ 0x101, "user not logged in" },
{ 0x102, "user pin not initialized" },
{ 0x103, "user type invalid" },
{ 0x104, "user another already logged in" },
{ 0x105, "user too many types" },
{ 0x110, "wrapped key invalid" },
{ 0x112, "wrapped key len range" },
{ 0x113, "wrapping key handle invalid" },
{ 0x114, "wrapping key size range" },
{ 0x115, "wrapping key type inconsistent" },
{ 0x120, "random seed not supported" },
{ 0x121, "random no rng" },
{ 0x130, "domain params invalid" },
{ 0x150, "buffer too small" },
{ 0x160, "saved state invalid" },
{ 0x170, "information sensitive" },
{ 0x180, "state unsaveable" },
{ 0x190, "cryptoki not initialized" },
{ 0x191, "cryptoki already initialized" },
{ 0x1a0, "mutex bad" },
{ 0x1a1, "mutex not locked" },
{ 0x200, "function rejected" },
{ -1, NULL }
};
/* DH parameters */
static uint8_t oakley_1024[128] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1,
0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22,
0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B,
0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45,
0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B,
0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5,
0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE6, 0x53, 0x81,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t oakley_2048[2048/8] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1,
0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22,
0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B,
0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45,
0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B,
0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5,
0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D,
0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,
0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A,
0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,
0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96,
0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,
0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D,
0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,
0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C,
0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B,
0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03,
0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F,
0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9,
0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18,
0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5,
0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10,
0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAC, 0xAA, 0x68,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
static uint8_t oakley_4096[4096/8] = {
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34,
0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1,
0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74,
0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22,
0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD,
0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B,
0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37,
0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45,
0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6,
0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B,
0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED,
0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5,
0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6,
0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D,
0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05,
0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A,
0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F,
0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96,
0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB,
0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D,
0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04,
0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C,
0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B,
0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03,
0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F,
0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9,
0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18,
0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5,
0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10,
0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D,
0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33,
0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64,
0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A,
0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D,
0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7,
0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7,
0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D,
0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B,
0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64,
0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64,
0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C,
0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C,
0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2,
0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31,
0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E,
0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x21, 0x08, 0x01,
0x1A, 0x72, 0x3C, 0x12, 0xA7, 0x87, 0xE6, 0xD7,
0x88, 0x71, 0x9A, 0x10, 0xBD, 0xBA, 0x5B, 0x26,
0x99, 0xC3, 0x27, 0x18, 0x6A, 0xF4, 0xE2, 0x3C,
0x1A, 0x94, 0x68, 0x34, 0xB6, 0x15, 0x0B, 0xDA,
0x25, 0x83, 0xE9, 0xCA, 0x2A, 0xD4, 0x4C, 0xE8,
0xDB, 0xBB, 0xC2, 0xDB, 0x04, 0xDE, 0x8E, 0xF9,
0x2E, 0x8E, 0xFC, 0x14, 0x1F, 0xBE, 0xCA, 0xA6,
0x28, 0x7C, 0x59, 0x47, 0x4E, 0x6B, 0xC0, 0x5D,
0x99, 0xB2, 0x96, 0x4F, 0xA0, 0x90, 0xC3, 0xA2,
0x23, 0x3B, 0xA1, 0x86, 0x51, 0x5B, 0xE7, 0xED,
0x1F, 0x61, 0x29, 0x70, 0xCE, 0xE2, 0xD7, 0xAF,
0xB8, 0x1B, 0xDD, 0x76, 0x21, 0x70, 0x48, 0x1C,
0xD0, 0x06, 0x91, 0x27, 0xD5, 0xB0, 0x5A, 0xA9,
0x93, 0xB4, 0xEA, 0x98, 0x8D, 0x8F, 0xDD, 0xC1,
0x86, 0xFF, 0xB7, 0xDC, 0x90, 0xA6, 0xC0, 0x8F,
0x4D, 0xF4, 0x35, 0xC9, 0x34, 0x06, 0x31, 0x99,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};
MAKE_INIT_FUNCTION(pkinit_openssl_init);
static krb5_error_code oerr(krb5_context context, krb5_error_code code,
const char *fmt, ...)
#if !defined(__cplusplus) && (__GNUC__ > 2)
__attribute__((__format__(__printf__, 3, 4)))
#endif
;
/*
* Set an error string containing the formatted arguments and the first pending
* OpenSSL error. Write the formatted arguments and all pending OpenSSL error
* messages to the trace log. Return code, or KRB5KDC_ERR_PREAUTH_FAILED if
* code is 0.
*/
static krb5_error_code
oerr(krb5_context context, krb5_error_code code, const char *fmt, ...)
{
unsigned long err;
va_list ap;
char *str, buf[128];
int r;
if (!code)
code = KRB5KDC_ERR_PREAUTH_FAILED;
va_start(ap, fmt);
r = vasprintf(&str, fmt, ap);
va_end(ap);
if (r < 0)
return code;
err = ERR_peek_error();
if (err) {
krb5_set_error_message(context, code, _("%s: %s"), str,
ERR_reason_error_string(err));
} else {
krb5_set_error_message(context, code, "%s", str);
}
TRACE_PKINIT_OPENSSL_ERROR(context, str);
while ((err = ERR_get_error()) != 0) {
ERR_error_string_n(err, buf, sizeof(buf));
TRACE_PKINIT_OPENSSL_ERROR(context, buf);
}
free(str);
return code;
}
/*
* Set an appropriate error string containing msg for a certificate
* verification failure from certctx. Write the message and all pending
* OpenSSL error messages to the trace log. Return code, or
* KRB5KDC_ERR_PREAUTH_FAILED if code is 0.
*/
static krb5_error_code
oerr_cert(krb5_context context, krb5_error_code code, X509_STORE_CTX *certctx,
const char *msg)
{
int depth = X509_STORE_CTX_get_error_depth(certctx);
int err = X509_STORE_CTX_get_error(certctx);
const char *errstr = X509_verify_cert_error_string(err);
return oerr(context, code, _("%s (depth %d): %s"), msg, depth, errstr);
}
krb5_error_code
pkinit_init_plg_crypto(pkinit_plg_crypto_context *cryptoctx)
{
krb5_error_code retval = ENOMEM;
pkinit_plg_crypto_context ctx = NULL;
(void)CALL_INIT_FUNCTION(pkinit_openssl_init);
ctx = malloc(sizeof(*ctx));
if (ctx == NULL)
goto out;
memset(ctx, 0, sizeof(*ctx));
pkiDebug("%s: initializing openssl crypto context at %p\n",
__FUNCTION__, ctx);
retval = pkinit_init_pkinit_oids(ctx);
if (retval)
goto out;
retval = pkinit_init_dh_params(ctx);
if (retval)
goto out;
*cryptoctx = ctx;
out:
if (retval && ctx != NULL)
pkinit_fini_plg_crypto(ctx);
return retval;
}
void
pkinit_fini_plg_crypto(pkinit_plg_crypto_context cryptoctx)
{
pkiDebug("%s: freeing context at %p\n", __FUNCTION__, cryptoctx);
if (cryptoctx == NULL)
return;
pkinit_fini_pkinit_oids(cryptoctx);
pkinit_fini_dh_params(cryptoctx);
free(cryptoctx);
}
krb5_error_code
pkinit_init_identity_crypto(pkinit_identity_crypto_context *idctx)
{
krb5_error_code retval = ENOMEM;
pkinit_identity_crypto_context ctx = NULL;
ctx = malloc(sizeof(*ctx));
if (ctx == NULL)
goto out;
memset(ctx, 0, sizeof(*ctx));
ctx->identity = NULL;
retval = pkinit_init_certs(ctx);
if (retval)
goto out;
retval = pkinit_init_pkcs11(ctx);
if (retval)
goto out;
pkiDebug("%s: returning ctx at %p\n", __FUNCTION__, ctx);
*idctx = ctx;
out:
if (retval) {
if (ctx)
pkinit_fini_identity_crypto(ctx);
}
return retval;
}
void
pkinit_fini_identity_crypto(pkinit_identity_crypto_context idctx)
{
if (idctx == NULL)
return;
pkiDebug("%s: freeing ctx at %p\n", __FUNCTION__, idctx);
if (idctx->deferred_ids != NULL)
pkinit_free_deferred_ids(idctx->deferred_ids);
free(idctx->identity);
pkinit_fini_certs(idctx);
pkinit_fini_pkcs11(idctx);
free(idctx);
}
krb5_error_code
pkinit_init_req_crypto(pkinit_req_crypto_context *cryptoctx)
{
krb5_error_code retval = ENOMEM;
pkinit_req_crypto_context ctx = NULL;
ctx = malloc(sizeof(*ctx));
if (ctx == NULL)
goto out;
memset(ctx, 0, sizeof(*ctx));
ctx->dh = NULL;
ctx->received_cert = NULL;
*cryptoctx = ctx;
pkiDebug("%s: returning ctx at %p\n", __FUNCTION__, ctx);
retval = 0;
out:
if (retval)
free(ctx);
return retval;
}
void
pkinit_fini_req_crypto(pkinit_req_crypto_context req_cryptoctx)
{
if (req_cryptoctx == NULL)
return;
pkiDebug("%s: freeing ctx at %p\n", __FUNCTION__, req_cryptoctx);
if (req_cryptoctx->dh != NULL)
DH_free(req_cryptoctx->dh);
if (req_cryptoctx->received_cert != NULL)
X509_free(req_cryptoctx->received_cert);
free(req_cryptoctx);
}
static krb5_error_code
pkinit_init_pkinit_oids(pkinit_plg_crypto_context ctx)
{
ctx->id_pkinit_san = OBJ_txt2obj("1.3.6.1.5.2.2", 1);
if (ctx->id_pkinit_san == NULL)
return ENOMEM;
ctx->id_pkinit_authData = OBJ_txt2obj("1.3.6.1.5.2.3.1", 1);
if (ctx->id_pkinit_authData == NULL)
return ENOMEM;
ctx->id_pkinit_DHKeyData = OBJ_txt2obj("1.3.6.1.5.2.3.2", 1);
if (ctx->id_pkinit_DHKeyData == NULL)
return ENOMEM;
ctx->id_pkinit_rkeyData = OBJ_txt2obj("1.3.6.1.5.2.3.3", 1);
if (ctx->id_pkinit_rkeyData == NULL)
return ENOMEM;
ctx->id_pkinit_KPClientAuth = OBJ_txt2obj("1.3.6.1.5.2.3.4", 1);
if (ctx->id_pkinit_KPClientAuth == NULL)
return ENOMEM;
ctx->id_pkinit_KPKdc = OBJ_txt2obj("1.3.6.1.5.2.3.5", 1);
if (ctx->id_pkinit_KPKdc == NULL)
return ENOMEM;
ctx->id_ms_kp_sc_logon = OBJ_txt2obj("1.3.6.1.4.1.311.20.2.2", 1);
if (ctx->id_ms_kp_sc_logon == NULL)
return ENOMEM;
ctx->id_ms_san_upn = OBJ_txt2obj("1.3.6.1.4.1.311.20.2.3", 1);
if (ctx->id_ms_san_upn == NULL)
return ENOMEM;
ctx->id_kp_serverAuth = OBJ_txt2obj("1.3.6.1.5.5.7.3.1", 1);
if (ctx->id_kp_serverAuth == NULL)
return ENOMEM;
return 0;
}
static krb5_error_code
get_cert(char *filename, X509 **retcert)
{
X509 *cert = NULL;
BIO *tmp = NULL;
int code;
krb5_error_code retval;
if (filename == NULL || retcert == NULL)
return EINVAL;
*retcert = NULL;
tmp = BIO_new(BIO_s_file());
if (tmp == NULL)
return ENOMEM;
code = BIO_read_filename(tmp, filename);
if (code == 0) {
retval = errno;
goto cleanup;
}
cert = (X509 *) PEM_read_bio_X509(tmp, NULL, NULL, NULL);
if (cert == NULL) {
retval = EIO;
pkiDebug("failed to read certificate from %s\n", filename);
goto cleanup;
}
*retcert = cert;
retval = 0;
cleanup:
if (tmp != NULL)
BIO_free(tmp);
return retval;
}
struct get_key_cb_data {
krb5_context context;
pkinit_identity_crypto_context id_cryptoctx;
const char *fsname;
char *filename;
const char *password;
};
static int
get_key_cb(char *buf, int size, int rwflag, void *userdata)
{
struct get_key_cb_data *data = userdata;
pkinit_identity_crypto_context id_cryptoctx;
krb5_data rdat;
krb5_prompt kprompt;
krb5_prompt_type prompt_type;
krb5_error_code retval;
char *prompt;
if (data->id_cryptoctx->defer_id_prompt) {
/* Supply the identity name to be passed to a responder callback. */
pkinit_set_deferred_id(&data->id_cryptoctx->deferred_ids,
data->fsname, 0, NULL);
return -1;
}
if (data->password == NULL) {
/* We don't already have a password to use, so prompt for one. */
if (data->id_cryptoctx->prompter == NULL)
return -1;
if (asprintf(&prompt, "%s %s", _("Pass phrase for"),
data->filename) < 0)
return -1;
rdat.data = buf;
rdat.length = size;
kprompt.prompt = prompt;
kprompt.hidden = 1;
kprompt.reply = &rdat;
prompt_type = KRB5_PROMPT_TYPE_PREAUTH;
/* PROMPTER_INVOCATION */
k5int_set_prompt_types(data->context, &prompt_type);
id_cryptoctx = data->id_cryptoctx;
retval = (data->id_cryptoctx->prompter)(data->context,
id_cryptoctx->prompter_data,
NULL, NULL, 1, &kprompt);
k5int_set_prompt_types(data->context, 0);
free(prompt);
if (retval != 0)
return -1;
} else {
/* Just use the already-supplied password. */
rdat.length = strlen(data->password);
if ((int)rdat.length >= size)
return -1;
snprintf(buf, size, "%s", data->password);
}
return (int)rdat.length;
}
static krb5_error_code
get_key(krb5_context context, pkinit_identity_crypto_context id_cryptoctx,
char *filename, const char *fsname, EVP_PKEY **retkey,
const char *password)
{
EVP_PKEY *pkey = NULL;
BIO *tmp = NULL;
struct get_key_cb_data cb_data;
int code;
krb5_error_code retval;
if (filename == NULL || retkey == NULL)
return EINVAL;
tmp = BIO_new(BIO_s_file());
if (tmp == NULL)
return ENOMEM;
code = BIO_read_filename(tmp, filename);
if (code == 0) {
retval = errno;
goto cleanup;
}
cb_data.context = context;
cb_data.id_cryptoctx = id_cryptoctx;
cb_data.filename = filename;
cb_data.fsname = fsname;
cb_data.password = password;
pkey = PEM_read_bio_PrivateKey(tmp, NULL, get_key_cb, &cb_data);
if (pkey == NULL && !id_cryptoctx->defer_id_prompt) {
retval = EIO;
pkiDebug("failed to read private key from %s\n", filename);
goto cleanup;
}
*retkey = pkey;
retval = 0;
cleanup:
if (tmp != NULL)
BIO_free(tmp);
return retval;
}
static void
pkinit_fini_pkinit_oids(pkinit_plg_crypto_context ctx)
{
if (ctx == NULL)
return;
ASN1_OBJECT_free(ctx->id_pkinit_san);
ASN1_OBJECT_free(ctx->id_pkinit_authData);
ASN1_OBJECT_free(ctx->id_pkinit_DHKeyData);
ASN1_OBJECT_free(ctx->id_pkinit_rkeyData);
ASN1_OBJECT_free(ctx->id_pkinit_KPClientAuth);
ASN1_OBJECT_free(ctx->id_pkinit_KPKdc);
ASN1_OBJECT_free(ctx->id_ms_kp_sc_logon);
ASN1_OBJECT_free(ctx->id_ms_san_upn);
ASN1_OBJECT_free(ctx->id_kp_serverAuth);
}
/* Construct an OpenSSL DH object for an Oakley group. */
static DH *
make_oakley_dh(uint8_t *prime, size_t len)
{
DH *dh = NULL;
BIGNUM *p = NULL, *q = NULL, *g = NULL;
p = BN_bin2bn(prime, len, NULL);
if (p == NULL)
goto cleanup;
q = BN_new();
if (q == NULL)
goto cleanup;
if (!BN_rshift1(q, p))
goto cleanup;
g = BN_new();
if (g == NULL)
goto cleanup;
if (!BN_set_word(g, DH_GENERATOR_2))
goto cleanup;
dh = DH_new();
if (dh == NULL)
goto cleanup;
DH_set0_pqg(dh, p, q, g);
p = g = q = NULL;
cleanup:
BN_free(p);
BN_free(q);
BN_free(g);
return dh;
}
static krb5_error_code
pkinit_init_dh_params(pkinit_plg_crypto_context plgctx)
{
krb5_error_code retval = ENOMEM;
plgctx->dh_1024 = make_oakley_dh(oakley_1024, sizeof(oakley_1024));
if (plgctx->dh_1024 == NULL)
goto cleanup;
plgctx->dh_2048 = make_oakley_dh(oakley_2048, sizeof(oakley_2048));
if (plgctx->dh_2048 == NULL)
goto cleanup;
plgctx->dh_4096 = make_oakley_dh(oakley_4096, sizeof(oakley_4096));
if (plgctx->dh_4096 == NULL)
goto cleanup;
retval = 0;
cleanup:
if (retval)
pkinit_fini_dh_params(plgctx);
return retval;
}
static void
pkinit_fini_dh_params(pkinit_plg_crypto_context plgctx)
{
if (plgctx->dh_1024 != NULL)
DH_free(plgctx->dh_1024);
if (plgctx->dh_2048 != NULL)
DH_free(plgctx->dh_2048);
if (plgctx->dh_4096 != NULL)
DH_free(plgctx->dh_4096);
plgctx->dh_1024 = plgctx->dh_2048 = plgctx->dh_4096 = NULL;
}
static krb5_error_code
pkinit_init_certs(pkinit_identity_crypto_context ctx)
{
krb5_error_code retval = ENOMEM;
int i;
for (i = 0; i < MAX_CREDS_ALLOWED; i++)
ctx->creds[i] = NULL;
ctx->my_certs = NULL;
ctx->cert_index = 0;
ctx->my_key = NULL;
ctx->trustedCAs = NULL;
ctx->intermediateCAs = NULL;
ctx->revoked = NULL;
retval = 0;
return retval;
}
static void
pkinit_fini_certs(pkinit_identity_crypto_context ctx)
{
if (ctx == NULL)
return;
if (ctx->my_certs != NULL)
sk_X509_pop_free(ctx->my_certs, X509_free);
if (ctx->my_key != NULL)
EVP_PKEY_free(ctx->my_key);
if (ctx->trustedCAs != NULL)
sk_X509_pop_free(ctx->trustedCAs, X509_free);
if (ctx->intermediateCAs != NULL)
sk_X509_pop_free(ctx->intermediateCAs, X509_free);
if (ctx->revoked != NULL)
sk_X509_CRL_pop_free(ctx->revoked, X509_CRL_free);
}
static krb5_error_code
pkinit_init_pkcs11(pkinit_identity_crypto_context ctx)
{
krb5_error_code retval = ENOMEM;
#ifndef WITHOUT_PKCS11
ctx->p11_module_name = strdup(PKCS11_MODNAME);
if (ctx->p11_module_name == NULL)
return retval;
ctx->p11_module = NULL;
ctx->slotid = PK_NOSLOT;
ctx->token_label = NULL;
ctx->cert_label = NULL;
ctx->session = CK_INVALID_HANDLE;
ctx->p11 = NULL;
#endif
ctx->pkcs11_method = 0;
retval = 0;
return retval;
}
static void
pkinit_fini_pkcs11(pkinit_identity_crypto_context ctx)
{
#ifndef WITHOUT_PKCS11
if (ctx == NULL)
return;
if (ctx->p11 != NULL) {
if (ctx->session != CK_INVALID_HANDLE) {
ctx->p11->C_CloseSession(ctx->session);
ctx->session = CK_INVALID_HANDLE;
}
ctx->p11->C_Finalize(NULL_PTR);
ctx->p11 = NULL;
}
if (ctx->p11_module != NULL) {
pkinit_C_UnloadModule(ctx->p11_module);
ctx->p11_module = NULL;
}
free(ctx->p11_module_name);
free(ctx->token_label);
free(ctx->cert_id);
free(ctx->cert_label);
#endif
}
krb5_error_code
pkinit_identity_set_prompter(pkinit_identity_crypto_context id_cryptoctx,
krb5_prompter_fct prompter,
void *prompter_data)
{
id_cryptoctx->prompter = prompter;
id_cryptoctx->prompter_data = prompter_data;
return 0;
}
/* Create a CMS ContentInfo of type oid containing the octet string in data. */
static krb5_error_code
create_contentinfo(krb5_context context, ASN1_OBJECT *oid,
unsigned char *data, size_t data_len, PKCS7 **p7_out)
{
PKCS7 *p7 = NULL;
ASN1_OCTET_STRING *ostr = NULL;
*p7_out = NULL;
ostr = ASN1_OCTET_STRING_new();
if (ostr == NULL)
goto oom;
if (!ASN1_OCTET_STRING_set(ostr, (unsigned char *)data, data_len))
goto oom;
p7 = PKCS7_new();
if (p7 == NULL)
goto oom;
p7->type = OBJ_dup(oid);
if (p7->type == NULL)
goto oom;
if (OBJ_obj2nid(oid) == NID_pkcs7_data) {
/* Draft 9 uses id-pkcs7-data for signed data. For this type OpenSSL
* expects an octet string in d.data. */
p7->d.data = ostr;
} else {
p7->d.other = ASN1_TYPE_new();
if (p7->d.other == NULL)
goto oom;
p7->d.other->type = V_ASN1_OCTET_STRING;
p7->d.other->value.octet_string = ostr;
}
*p7_out = p7;
return 0;
oom:
if (ostr != NULL)
ASN1_OCTET_STRING_free(ostr);
if (p7 != NULL)
PKCS7_free(p7);
return ENOMEM;
}
krb5_error_code
cms_contentinfo_create(krb5_context context, /* IN */
pkinit_plg_crypto_context plg_cryptoctx, /* IN */
pkinit_req_crypto_context req_cryptoctx, /* IN */
pkinit_identity_crypto_context id_cryptoctx, /* IN */
int cms_msg_type,
unsigned char *data, unsigned int data_len,
unsigned char **out_data, unsigned int *out_data_len)
{
krb5_error_code retval = ENOMEM;
ASN1_OBJECT *oid;
PKCS7 *p7 = NULL;
unsigned char *p;
/* Pick the correct oid for the eContentInfo. */
oid = pkinit_pkcs7type2oid(plg_cryptoctx, cms_msg_type);
if (oid == NULL)
goto cleanup;
retval = create_contentinfo(context, oid, data, data_len, &p7);
if (retval != 0)
goto cleanup;
*out_data_len = i2d_PKCS7(p7, NULL);
if (!(*out_data_len)) {
retval = oerr(context, 0, _("Failed to DER encode PKCS7"));
goto cleanup;
}
retval = ENOMEM;
if ((p = *out_data = malloc(*out_data_len)) == NULL)
goto cleanup;
/* DER encode PKCS7 data */
retval = i2d_PKCS7(p7, &p);
if (!retval) {
retval = oerr(context, 0, _("Failed to DER encode PKCS7"));
goto cleanup;
}
retval = 0;
cleanup:
if (p7)
PKCS7_free(p7);
return retval;
}
krb5_error_code
cms_signeddata_create(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int cms_msg_type,
int include_certchain,
unsigned char *data,
unsigned int data_len,
unsigned char **signed_data,
unsigned int *signed_data_len)
{
krb5_error_code retval = ENOMEM;
PKCS7 *p7 = NULL, *inner_p7 = NULL;
PKCS7_SIGNED *p7s = NULL;
PKCS7_SIGNER_INFO *p7si = NULL;
unsigned char *p;
STACK_OF(X509) * cert_stack = NULL;
ASN1_OCTET_STRING *digest_attr = NULL;
EVP_MD_CTX *ctx;
const EVP_MD *md_tmp = NULL;
unsigned char md_data[EVP_MAX_MD_SIZE], md_data2[EVP_MAX_MD_SIZE];
unsigned char *digestInfo_buf = NULL, *abuf = NULL;
unsigned int md_len, md_len2, alen, digestInfo_len;
STACK_OF(X509_ATTRIBUTE) * sk;
unsigned char *sig = NULL;
unsigned int sig_len = 0;
X509_ALGOR *alg = NULL;
ASN1_OCTET_STRING *digest = NULL;
unsigned int alg_len = 0, digest_len = 0;
unsigned char *y = NULL;
X509 *cert = NULL;
ASN1_OBJECT *oid = NULL, *oid_copy;
/* Start creating PKCS7 data. */
if ((p7 = PKCS7_new()) == NULL)
goto cleanup;
p7->type = OBJ_nid2obj(NID_pkcs7_signed);
if ((p7s = PKCS7_SIGNED_new()) == NULL)
goto cleanup;
p7->d.sign = p7s;
if (!ASN1_INTEGER_set(p7s->version, 3))
goto cleanup;
/* pick the correct oid for the eContentInfo */
oid = pkinit_pkcs7type2oid(plg_cryptoctx, cms_msg_type);
if (oid == NULL)
goto cleanup;
if (id_cryptoctx->my_certs != NULL) {
/* create a cert chain that has at least the signer's certificate */
if ((cert_stack = sk_X509_new_null()) == NULL)
goto cleanup;
cert = sk_X509_value(id_cryptoctx->my_certs, id_cryptoctx->cert_index);
if (!include_certchain) {
pkiDebug("only including signer's certificate\n");
sk_X509_push(cert_stack, X509_dup(cert));
} else {
/* create a cert chain */
X509_STORE *certstore = NULL;
X509_STORE_CTX *certctx;
STACK_OF(X509) *certstack = NULL;
char buf[DN_BUF_LEN];
unsigned int i = 0, size = 0;
if ((certstore = X509_STORE_new()) == NULL)
goto cleanup;
pkiDebug("building certificate chain\n");
X509_STORE_set_verify_cb(certstore, openssl_callback);
certctx = X509_STORE_CTX_new();
if (certctx == NULL)
goto cleanup;
X509_STORE_CTX_init(certctx, certstore, cert,
id_cryptoctx->intermediateCAs);
X509_STORE_CTX_trusted_stack(certctx, id_cryptoctx->trustedCAs);
if (!X509_verify_cert(certctx)) {
retval = oerr_cert(context, 0, certctx,
_("Failed to verify own certificate"));
goto cleanup;
}
certstack = X509_STORE_CTX_get1_chain(certctx);
size = sk_X509_num(certstack);
pkiDebug("size of certificate chain = %d\n", size);
for(i = 0; i < size - 1; i++) {
X509 *x = sk_X509_value(certstack, i);
X509_NAME_oneline(X509_get_subject_name(x), buf, sizeof(buf));
pkiDebug("cert #%d: %s\n", i, buf);
sk_X509_push(cert_stack, X509_dup(x));
}
X509_STORE_CTX_free(certctx);
X509_STORE_free(certstore);
sk_X509_pop_free(certstack, X509_free);
}
p7s->cert = cert_stack;
/* fill-in PKCS7_SIGNER_INFO */
if ((p7si = PKCS7_SIGNER_INFO_new()) == NULL)
goto cleanup;
if (!ASN1_INTEGER_set(p7si->version, 1))
goto cleanup;
if (!X509_NAME_set(&p7si->issuer_and_serial->issuer,
X509_get_issuer_name(cert)))
goto cleanup;
/* because ASN1_INTEGER_set is used to set a 'long' we will do
* things the ugly way. */
ASN1_INTEGER_free(p7si->issuer_and_serial->serial);
if (!(p7si->issuer_and_serial->serial =
ASN1_INTEGER_dup(X509_get_serialNumber(cert))))
goto cleanup;
/* will not fill-out EVP_PKEY because it's on the smartcard */
/* Set digest algs */
p7si->digest_alg->algorithm = OBJ_nid2obj(NID_sha1);
if (p7si->digest_alg->parameter != NULL)
ASN1_TYPE_free(p7si->digest_alg->parameter);
if ((p7si->digest_alg->parameter = ASN1_TYPE_new()) == NULL)
goto cleanup;
p7si->digest_alg->parameter->type = V_ASN1_NULL;
/* Set sig algs */
if (p7si->digest_enc_alg->parameter != NULL)
ASN1_TYPE_free(p7si->digest_enc_alg->parameter);
p7si->digest_enc_alg->algorithm = OBJ_nid2obj(NID_sha1WithRSAEncryption);
if (!(p7si->digest_enc_alg->parameter = ASN1_TYPE_new()))
goto cleanup;
p7si->digest_enc_alg->parameter->type = V_ASN1_NULL;
if (cms_msg_type == CMS_SIGN_DRAFT9){
/* don't include signed attributes for pa-type 15 request */
abuf = data;
alen = data_len;
} else {
/* add signed attributes */
/* compute sha1 digest over the EncapsulatedContentInfo */
ctx = EVP_MD_CTX_new();
if (ctx == NULL)
goto cleanup;
EVP_DigestInit_ex(ctx, EVP_sha1(), NULL);
EVP_DigestUpdate(ctx, data, data_len);
md_tmp = EVP_MD_CTX_md(ctx);
EVP_DigestFinal_ex(ctx, md_data, &md_len);
EVP_MD_CTX_free(ctx);
/* create a message digest attr */
digest_attr = ASN1_OCTET_STRING_new();
ASN1_OCTET_STRING_set(digest_attr, md_data, (int)md_len);
PKCS7_add_signed_attribute(p7si, NID_pkcs9_messageDigest,
V_ASN1_OCTET_STRING, (char *) digest_attr);
/* create a content-type attr */
oid_copy = OBJ_dup(oid);
if (oid_copy == NULL)
goto cleanup2;
PKCS7_add_signed_attribute(p7si, NID_pkcs9_contentType,
V_ASN1_OBJECT, oid_copy);
/* create the signature over signed attributes. get DER encoded value */
/* This is the place where smartcard signature needs to be calculated */
sk = p7si->auth_attr;
alen = ASN1_item_i2d((ASN1_VALUE *) sk, &abuf,
ASN1_ITEM_rptr(PKCS7_ATTR_SIGN));
if (abuf == NULL)
goto cleanup2;
} /* signed attributes */
#ifndef WITHOUT_PKCS11
/* Some tokens can only do RSAEncryption without sha1 hash */
/* to compute sha1WithRSAEncryption, encode the algorithm ID for the hash
* function and the hash value into an ASN.1 value of type DigestInfo
* DigestInfo::=SEQUENCE {
* digestAlgorithm AlgorithmIdentifier,
* digest OCTET STRING }
*/
if (id_cryptoctx->pkcs11_method == 1 &&
id_cryptoctx->mech == CKM_RSA_PKCS) {
pkiDebug("mech = CKM_RSA_PKCS\n");
ctx = EVP_MD_CTX_new();
if (ctx == NULL)
goto cleanup;
/* if this is not draft9 request, include digest signed attribute */
if (cms_msg_type != CMS_SIGN_DRAFT9)
EVP_DigestInit_ex(ctx, md_tmp, NULL);
else
EVP_DigestInit_ex(ctx, EVP_sha1(), NULL);
EVP_DigestUpdate(ctx, abuf, alen);
EVP_DigestFinal_ex(ctx, md_data2, &md_len2);
EVP_MD_CTX_free(ctx);
alg = X509_ALGOR_new();
if (alg == NULL)
goto cleanup2;
X509_ALGOR_set0(alg, OBJ_nid2obj(NID_sha1), V_ASN1_NULL, NULL);
alg_len = i2d_X509_ALGOR(alg, NULL);
digest = ASN1_OCTET_STRING_new();
if (digest == NULL)
goto cleanup2;
ASN1_OCTET_STRING_set(digest, md_data2, (int)md_len2);
digest_len = i2d_ASN1_OCTET_STRING(digest, NULL);
digestInfo_len = ASN1_object_size(1, (int)(alg_len + digest_len),
V_ASN1_SEQUENCE);
y = digestInfo_buf = malloc(digestInfo_len);
if (digestInfo_buf == NULL)
goto cleanup2;
ASN1_put_object(&y, 1, (int)(alg_len + digest_len), V_ASN1_SEQUENCE,
V_ASN1_UNIVERSAL);
i2d_X509_ALGOR(alg, &y);
i2d_ASN1_OCTET_STRING(digest, &y);
#ifdef DEBUG_SIG
pkiDebug("signing buffer\n");
print_buffer(digestInfo_buf, digestInfo_len);
print_buffer_bin(digestInfo_buf, digestInfo_len, "/tmp/pkcs7_tosign");
#endif
retval = pkinit_sign_data(context, id_cryptoctx, digestInfo_buf,
digestInfo_len, &sig, &sig_len);
} else
#endif
{
pkiDebug("mech = %s\n",
id_cryptoctx->pkcs11_method == 1 ? "CKM_SHA1_RSA_PKCS" : "FS");
retval = pkinit_sign_data(context, id_cryptoctx, abuf, alen,
&sig, &sig_len);
}
#ifdef DEBUG_SIG
print_buffer(sig, sig_len);
#endif
if (cms_msg_type != CMS_SIGN_DRAFT9 )
free(abuf);
if (retval)
goto cleanup2;
/* Add signature */
if (!ASN1_STRING_set(p7si->enc_digest, (unsigned char *) sig,
(int)sig_len)) {
retval = oerr(context, 0, _("Failed to add digest attribute"));
goto cleanup2;
}
/* adder signer_info to pkcs7 signed */
if (!PKCS7_add_signer(p7, p7si))
goto cleanup2;
} /* we have a certificate */
/* start on adding data to the pkcs7 signed */
retval = create_contentinfo(context, oid, data, data_len, &inner_p7);
if (p7s->contents != NULL)
PKCS7_free(p7s->contents);
p7s->contents = inner_p7;
*signed_data_len = i2d_PKCS7(p7, NULL);
if (!(*signed_data_len)) {
retval = oerr(context, 0, _("Failed to DER encode PKCS7"));
goto cleanup2;
}
retval = ENOMEM;
if ((p = *signed_data = malloc(*signed_data_len)) == NULL)
goto cleanup2;
/* DER encode PKCS7 data */
retval = i2d_PKCS7(p7, &p);
if (!retval) {
retval = oerr(context, 0, _("Failed to DER encode PKCS7"));
goto cleanup2;
}
retval = 0;
#ifdef DEBUG_ASN1
if (cms_msg_type == CMS_SIGN_CLIENT) {
print_buffer_bin(*signed_data, *signed_data_len,
"/tmp/client_pkcs7_signeddata");
} else {
if (cms_msg_type == CMS_SIGN_SERVER) {
print_buffer_bin(*signed_data, *signed_data_len,
"/tmp/kdc_pkcs7_signeddata");
} else {
print_buffer_bin(*signed_data, *signed_data_len,
"/tmp/draft9_pkcs7_signeddata");
}
}
#endif
cleanup2:
if (p7si) {
if (cms_msg_type != CMS_SIGN_DRAFT9)
#ifndef WITHOUT_PKCS11
if (id_cryptoctx->pkcs11_method == 1 &&
id_cryptoctx->mech == CKM_RSA_PKCS) {
free(digestInfo_buf);
if (digest != NULL)
ASN1_OCTET_STRING_free(digest);
}
#endif
if (alg != NULL)
X509_ALGOR_free(alg);
}
cleanup:
if (p7 != NULL)
PKCS7_free(p7);
free(sig);
return retval;
}
krb5_error_code
cms_signeddata_verify(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
pkinit_identity_crypto_context idctx,
int cms_msg_type,
int require_crl_checking,
unsigned char *signed_data,
unsigned int signed_data_len,
unsigned char **data,
unsigned int *data_len,
unsigned char **authz_data,
unsigned int *authz_data_len,
int *is_signed)
{
/*
* Warning: Since most openssl functions do not set retval, large chunks of
* this function assume that retval is always a failure and may go to
* cleanup without setting retval explicitly. Make sure retval is not set
* to 0 or errors such as signature verification failure may be converted
* to success with significant security consequences.
*/
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
CMS_ContentInfo *cms = NULL;
BIO *out = NULL;
int flags = CMS_NO_SIGNER_CERT_VERIFY;
int valid_oid = 0;
unsigned int i = 0;
unsigned int vflags = 0, size = 0;
const unsigned char *p = signed_data;
STACK_OF(CMS_SignerInfo) *si_sk = NULL;
CMS_SignerInfo *si = NULL;
X509 *x = NULL;
X509_STORE *store = NULL;
X509_STORE_CTX *cert_ctx;
STACK_OF(X509) *signerCerts = NULL;
STACK_OF(X509) *intermediateCAs = NULL;
STACK_OF(X509_CRL) *signerRevoked = NULL;
STACK_OF(X509_CRL) *revoked = NULL;
STACK_OF(X509) *verified_chain = NULL;
ASN1_OBJECT *oid = NULL;
const ASN1_OBJECT *type = NULL, *etype = NULL;
ASN1_OCTET_STRING **octets;
krb5_external_principal_identifier **krb5_verified_chain = NULL;
krb5_data *authz = NULL;
char buf[DN_BUF_LEN];
#ifdef DEBUG_ASN1
print_buffer_bin(signed_data, signed_data_len,
"/tmp/client_received_pkcs7_signeddata");
#endif
if (is_signed)
*is_signed = 1;
oid = pkinit_pkcs7type2oid(plgctx, cms_msg_type);
if (oid == NULL)
goto cleanup;
/* decode received CMS message */
if ((cms = d2i_CMS_ContentInfo(NULL, &p, (int)signed_data_len)) == NULL) {
retval = oerr(context, 0, _("Failed to decode CMS message"));
goto cleanup;
}
etype = CMS_get0_eContentType(cms);
/*
* Prior to 1.10 the MIT client incorrectly emitted the pkinit structure
* directly in a CMS ContentInfo rather than using SignedData with no
* signers. Handle that case.
*/
type = CMS_get0_type(cms);
if (is_signed && !OBJ_cmp(type, oid)) {
unsigned char *d;
*is_signed = 0;
octets = pkinit_CMS_get0_content_data(cms);
if (!octets || ((*octets)->type != V_ASN1_OCTET_STRING)) {
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval,
_("Invalid pkinit packet: octet string "
"expected"));
goto cleanup;
}
*data_len = ASN1_STRING_length(*octets);
d = malloc(*data_len);
if (d == NULL) {
retval = ENOMEM;
goto cleanup;
}
memcpy(d, ASN1_STRING_get0_data(*octets), *data_len);
*data = d;
goto out;
} else {
/* Verify that the received message is CMS SignedData message. */
if (OBJ_obj2nid(type) != NID_pkcs7_signed) {
pkiDebug("Expected id-signedData CMS msg (received type = %d)\n",
OBJ_obj2nid(type));
krb5_set_error_message(context, retval, _("wrong oid\n"));
goto cleanup;
}
}
/* setup to verify X509 certificate used to sign CMS message */
if (!(store = X509_STORE_new()))
goto cleanup;
/* check if we are inforcing CRL checking */
vflags = X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL;
if (require_crl_checking)
X509_STORE_set_verify_cb(store, openssl_callback);
else
X509_STORE_set_verify_cb(store, openssl_callback_ignore_crls);
X509_STORE_set_flags(store, vflags);
/*
* Get the signer's information from the CMS message. Match signer ID
* against anchors and intermediate CAs in case no certs are present in the
* SignedData. If we start sending kdcPkId values in requests, we'll need
* to match against the source of that information too.
*/
CMS_set1_signers_certs(cms, NULL, 0);
CMS_set1_signers_certs(cms, idctx->trustedCAs, CMS_NOINTERN);
CMS_set1_signers_certs(cms, idctx->intermediateCAs, CMS_NOINTERN);
if (((si_sk = CMS_get0_SignerInfos(cms)) == NULL) ||
((si = sk_CMS_SignerInfo_value(si_sk, 0)) == NULL)) {
/* Not actually signed; anonymous case */
if (!is_signed)
goto cleanup;
*is_signed = 0;
/* We cannot use CMS_dataInit because there may be no digest */
octets = pkinit_CMS_get0_content_signed(cms);
if (octets)
out = BIO_new_mem_buf((*octets)->data, (*octets)->length);
if (out == NULL)
goto cleanup;
} else {
pkinit_CMS_SignerInfo_get_cert(cms, si, &x);
if (x == NULL)
goto cleanup;
/* create available CRL information (get local CRLs and include CRLs
* received in the CMS message
*/
signerRevoked = CMS_get1_crls(cms);
if (idctx->revoked == NULL)
revoked = signerRevoked;
else if (signerRevoked == NULL)
revoked = idctx->revoked;
else {
size = sk_X509_CRL_num(idctx->revoked);
revoked = sk_X509_CRL_new_null();
for (i = 0; i < size; i++)
sk_X509_CRL_push(revoked, sk_X509_CRL_value(idctx->revoked, i));
size = sk_X509_CRL_num(signerRevoked);
for (i = 0; i < size; i++)
sk_X509_CRL_push(revoked, sk_X509_CRL_value(signerRevoked, i));
}
/* create available intermediate CAs chains (get local intermediateCAs and
* include the CA chain received in the CMS message
*/
signerCerts = CMS_get1_certs(cms);
if (idctx->intermediateCAs == NULL)
intermediateCAs = signerCerts;
else if (signerCerts == NULL)
intermediateCAs = idctx->intermediateCAs;
else {
size = sk_X509_num(idctx->intermediateCAs);
intermediateCAs = sk_X509_new_null();
for (i = 0; i < size; i++) {
sk_X509_push(intermediateCAs,
sk_X509_value(idctx->intermediateCAs, i));
}
size = sk_X509_num(signerCerts);
for (i = 0; i < size; i++) {
sk_X509_push(intermediateCAs, sk_X509_value(signerCerts, i));
}
}
/* initialize x509 context with the received certificate and
* trusted and intermediate CA chains and CRLs
*/
cert_ctx = X509_STORE_CTX_new();
if (cert_ctx == NULL)
goto cleanup;
if (!X509_STORE_CTX_init(cert_ctx, store, x, intermediateCAs))
goto cleanup;
X509_STORE_CTX_set0_crls(cert_ctx, revoked);
/* add trusted CAs certificates for cert verification */
if (idctx->trustedCAs != NULL)
X509_STORE_CTX_trusted_stack(cert_ctx, idctx->trustedCAs);
else {
pkiDebug("unable to find any trusted CAs\n");
goto cleanup;
}
#ifdef DEBUG_CERTCHAIN
if (intermediateCAs != NULL) {
size = sk_X509_num(intermediateCAs);
pkiDebug("untrusted cert chain of size %d\n", size);
for (i = 0; i < size; i++) {
X509_NAME_oneline(X509_get_subject_name(
sk_X509_value(intermediateCAs, i)), buf, sizeof(buf));
pkiDebug("cert #%d: %s\n", i, buf);
}
}
if (idctx->trustedCAs != NULL) {
size = sk_X509_num(idctx->trustedCAs);
pkiDebug("trusted cert chain of size %d\n", size);
for (i = 0; i < size; i++) {
X509_NAME_oneline(X509_get_subject_name(
sk_X509_value(idctx->trustedCAs, i)), buf, sizeof(buf));
pkiDebug("cert #%d: %s\n", i, buf);
}
}
if (revoked != NULL) {
size = sk_X509_CRL_num(revoked);
pkiDebug("CRL chain of size %d\n", size);
for (i = 0; i < size; i++) {
X509_CRL *crl = sk_X509_CRL_value(revoked, i);
X509_NAME_oneline(X509_CRL_get_issuer(crl), buf, sizeof(buf));
pkiDebug("crls by CA #%d: %s\n", i , buf);
}
}
#endif
i = X509_verify_cert(cert_ctx);
if (i <= 0) {
int j = X509_STORE_CTX_get_error(cert_ctx);
X509 *cert;
cert = X509_STORE_CTX_get_current_cert(cert_ctx);
reqctx->received_cert = X509_dup(cert);
switch(j) {
case X509_V_ERR_CERT_REVOKED:
retval = KRB5KDC_ERR_REVOKED_CERTIFICATE;
break;
case X509_V_ERR_UNABLE_TO_GET_CRL:
retval = KRB5KDC_ERR_REVOCATION_STATUS_UNKNOWN;
break;
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
retval = KRB5KDC_ERR_CANT_VERIFY_CERTIFICATE;
break;
default:
retval = KRB5KDC_ERR_INVALID_CERTIFICATE;
}
(void)oerr_cert(context, retval, cert_ctx,
_("Failed to verify received certificate"));
if (reqctx->received_cert == NULL)
strlcpy(buf, "(none)", sizeof(buf));
else
X509_NAME_oneline(X509_get_subject_name(reqctx->received_cert),
buf, sizeof(buf));
pkiDebug("problem with cert DN = %s (error=%d) %s\n", buf, j,
X509_verify_cert_error_string(j));
#ifdef DEBUG_CERTCHAIN
size = sk_X509_num(signerCerts);
pkiDebug("received cert chain of size %d\n", size);
for (j = 0; j < size; j++) {
X509 *tmp_cert = sk_X509_value(signerCerts, j);
X509_NAME_oneline(X509_get_subject_name(tmp_cert), buf, sizeof(buf));
pkiDebug("cert #%d: %s\n", j, buf);
}
#endif
} else {
/* retrieve verified certificate chain */
if (cms_msg_type == CMS_SIGN_CLIENT || cms_msg_type == CMS_SIGN_DRAFT9)
verified_chain = X509_STORE_CTX_get1_chain(cert_ctx);
}
X509_STORE_CTX_free(cert_ctx);
if (i <= 0)
goto cleanup;
out = BIO_new(BIO_s_mem());
if (cms_msg_type == CMS_SIGN_DRAFT9)
flags |= CMS_NOATTR;
if (CMS_verify(cms, NULL, store, NULL, out, flags) == 0) {
unsigned long err = ERR_peek_error();
switch(ERR_GET_REASON(err)) {
case PKCS7_R_DIGEST_FAILURE:
retval = KRB5KDC_ERR_DIGEST_IN_SIGNED_DATA_NOT_ACCEPTED;
break;
case PKCS7_R_SIGNATURE_FAILURE:
default:
retval = KRB5KDC_ERR_INVALID_SIG;
}
(void)oerr(context, retval, _("Failed to verify CMS message"));
goto cleanup;
}
} /* message was signed */
if (!OBJ_cmp(etype, oid))
valid_oid = 1;
else if (cms_msg_type == CMS_SIGN_DRAFT9) {
/*
* Various implementations of the pa-type 15 request use
* different OIDS. We check that the returned object
* has any of the acceptable OIDs
*/
ASN1_OBJECT *client_oid = NULL, *server_oid = NULL, *rsa_oid = NULL;
client_oid = pkinit_pkcs7type2oid(plgctx, CMS_SIGN_CLIENT);
server_oid = pkinit_pkcs7type2oid(plgctx, CMS_SIGN_SERVER);
rsa_oid = pkinit_pkcs7type2oid(plgctx, CMS_ENVEL_SERVER);
if (!OBJ_cmp(etype, client_oid) ||
!OBJ_cmp(etype, server_oid) ||
!OBJ_cmp(etype, rsa_oid))
valid_oid = 1;
}
if (valid_oid)
pkiDebug("CMS Verification successful\n");
else {
pkiDebug("wrong oid in eContentType\n");
print_buffer(OBJ_get0_data(etype), OBJ_length(etype));
retval = KRB5KDC_ERR_PREAUTH_FAILED;
krb5_set_error_message(context, retval, "wrong oid\n");
goto cleanup;
}
/* transfer the data from CMS message into return buffer */
for (size = 0;;) {
int remain;
retval = ENOMEM;
if ((*data = realloc(*data, size + 1024 * 10)) == NULL)
goto cleanup;
remain = BIO_read(out, &((*data)[size]), 1024 * 10);
if (remain <= 0)
break;
else
size += remain;
}
*data_len = size;
if (x) {
reqctx->received_cert = X509_dup(x);
/* generate authorization data */
if (cms_msg_type == CMS_SIGN_CLIENT || cms_msg_type == CMS_SIGN_DRAFT9) {
if (authz_data == NULL || authz_data_len == NULL)
goto out;
*authz_data = NULL;
retval = create_identifiers_from_stack(verified_chain,
&krb5_verified_chain);
if (retval) {
pkiDebug("create_identifiers_from_stack failed\n");
goto cleanup;
}
retval = k5int_encode_krb5_td_trusted_certifiers((krb5_external_principal_identifier *const *)krb5_verified_chain, &authz);
if (retval) {
pkiDebug("encode_krb5_td_trusted_certifiers failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)authz->data, authz->length,
"/tmp/kdc_ad_initial_verified_cas");
#endif
*authz_data = malloc(authz->length);
if (*authz_data == NULL) {
retval = ENOMEM;
goto cleanup;
}
memcpy(*authz_data, authz->data, authz->length);
*authz_data_len = authz->length;
}
}
out:
retval = 0;
cleanup:
if (out != NULL)
BIO_free(out);
if (store != NULL)
X509_STORE_free(store);
if (cms != NULL) {
if (signerCerts != NULL)
pkinit_CMS_free1_certs(signerCerts);
if (idctx->intermediateCAs != NULL && signerCerts)
sk_X509_free(intermediateCAs);
if (signerRevoked != NULL)
pkinit_CMS_free1_crls(signerRevoked);
if (idctx->revoked != NULL && signerRevoked)
sk_X509_CRL_free(revoked);
CMS_ContentInfo_free(cms);
}
if (verified_chain != NULL)
sk_X509_pop_free(verified_chain, X509_free);
if (krb5_verified_chain != NULL)
free_krb5_external_principal_identifier(&krb5_verified_chain);
if (authz != NULL)
krb5_free_data(context, authz);
return retval;
}
krb5_error_code
cms_envelopeddata_create(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
pkinit_identity_crypto_context idctx,
krb5_preauthtype pa_type,
int include_certchain,
unsigned char *key_pack,
unsigned int key_pack_len,
unsigned char **out,
unsigned int *out_len)
{
krb5_error_code retval = ENOMEM;
PKCS7 *p7 = NULL;
BIO *in = NULL;
unsigned char *p = NULL, *signed_data = NULL, *enc_data = NULL;
int signed_data_len = 0, enc_data_len = 0, flags = PKCS7_BINARY;
STACK_OF(X509) *encerts = NULL;
const EVP_CIPHER *cipher = NULL;
int cms_msg_type;
/* create the PKCS7 SignedData portion of the PKCS7 EnvelopedData */
switch ((int)pa_type) {
case KRB5_PADATA_PK_AS_REQ_OLD:
case KRB5_PADATA_PK_AS_REP_OLD:
cms_msg_type = CMS_SIGN_DRAFT9;
break;
case KRB5_PADATA_PK_AS_REQ:
cms_msg_type = CMS_ENVEL_SERVER;
break;
default:
goto cleanup;
}
retval = cms_signeddata_create(context, plgctx, reqctx, idctx,
cms_msg_type, include_certchain, key_pack, key_pack_len,
&signed_data, (unsigned int *)&signed_data_len);
if (retval) {
pkiDebug("failed to create pkcs7 signed data\n");
goto cleanup;
}
/* check we have client's certificate */
if (reqctx->received_cert == NULL) {
retval = KRB5KDC_ERR_PREAUTH_FAILED;
goto cleanup;
}
encerts = sk_X509_new_null();
sk_X509_push(encerts, reqctx->received_cert);
cipher = EVP_des_ede3_cbc();
in = BIO_new(BIO_s_mem());
switch (pa_type) {
case KRB5_PADATA_PK_AS_REQ:
prepare_enc_data(signed_data, signed_data_len, &enc_data,
&enc_data_len);
retval = BIO_write(in, enc_data, enc_data_len);
if (retval != enc_data_len) {
pkiDebug("BIO_write only wrote %d\n", retval);
goto cleanup;
}
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
retval = BIO_write(in, signed_data, signed_data_len);
if (retval != signed_data_len) {
pkiDebug("BIO_write only wrote %d\n", retval);
goto cleanup;
}
break;
default:
retval = -1;
goto cleanup;
}
p7 = PKCS7_encrypt(encerts, in, cipher, flags);
if (p7 == NULL) {
retval = oerr(context, 0, _("Failed to encrypt PKCS7 object"));
goto cleanup;
}
switch (pa_type) {
case KRB5_PADATA_PK_AS_REQ:
p7->d.enveloped->enc_data->content_type =
OBJ_nid2obj(NID_pkcs7_signed);
break;
case KRB5_PADATA_PK_AS_REP_OLD:
case KRB5_PADATA_PK_AS_REQ_OLD:
p7->d.enveloped->enc_data->content_type =
OBJ_nid2obj(NID_pkcs7_data);
break;
break;
break;
break;
}
*out_len = i2d_PKCS7(p7, NULL);
if (!*out_len || (p = *out = malloc(*out_len)) == NULL) {
retval = ENOMEM;
goto cleanup;
}
retval = i2d_PKCS7(p7, &p);
if (!retval) {
retval = oerr(context, 0, _("Failed to DER encode PKCS7"));
goto cleanup;
}
retval = 0;
#ifdef DEBUG_ASN1
print_buffer_bin(*out, *out_len, "/tmp/kdc_enveloped_data");
#endif
cleanup:
if (p7 != NULL)
PKCS7_free(p7);
if (in != NULL)
BIO_free(in);
free(signed_data);
free(enc_data);
if (encerts != NULL)
sk_X509_free(encerts);
return retval;
}
krb5_error_code
cms_envelopeddata_verify(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_preauthtype pa_type,
int require_crl_checking,
unsigned char *enveloped_data,
unsigned int enveloped_data_len,
unsigned char **data,
unsigned int *data_len)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
PKCS7 *p7 = NULL;
BIO *out = NULL;
int i = 0;
unsigned int size = 0;
const unsigned char *p = enveloped_data;
unsigned int tmp_buf_len = 0, tmp_buf2_len = 0, vfy_buf_len = 0;
unsigned char *tmp_buf = NULL, *tmp_buf2 = NULL, *vfy_buf = NULL;
int msg_type = 0;
#ifdef DEBUG_ASN1
print_buffer_bin(enveloped_data, enveloped_data_len,
"/tmp/client_envelopeddata");
#endif
/* decode received PKCS7 message */
if ((p7 = d2i_PKCS7(NULL, &p, (int)enveloped_data_len)) == NULL) {
retval = oerr(context, 0, _("Failed to decode PKCS7"));
goto cleanup;
}
/* verify that the received message is PKCS7 EnvelopedData message */
if (OBJ_obj2nid(p7->type) != NID_pkcs7_enveloped) {
pkiDebug("Expected id-enveloped PKCS7 msg (received type = %d)\n",
OBJ_obj2nid(p7->type));
krb5_set_error_message(context, retval, "wrong oid\n");
goto cleanup;
}
/* decrypt received PKCS7 message */
out = BIO_new(BIO_s_mem());
if (pkcs7_decrypt(context, id_cryptoctx, p7, out)) {
pkiDebug("PKCS7 decryption successful\n");
} else {
retval = oerr(context, 0, _("Failed to decrypt PKCS7 message"));
goto cleanup;
}
/* transfer the decoded PKCS7 SignedData message into a separate buffer */
for (;;) {
if ((tmp_buf = realloc(tmp_buf, size + 1024 * 10)) == NULL)
goto cleanup;
i = BIO_read(out, &(tmp_buf[size]), 1024 * 10);
if (i <= 0)
break;
else
size += i;
}
tmp_buf_len = size;
#ifdef DEBUG_ASN1
print_buffer_bin(tmp_buf, tmp_buf_len, "/tmp/client_enc_keypack");
#endif
/* verify PKCS7 SignedData message */
switch (pa_type) {
case KRB5_PADATA_PK_AS_REP:
msg_type = CMS_ENVEL_SERVER;
break;
case KRB5_PADATA_PK_AS_REP_OLD:
msg_type = CMS_SIGN_DRAFT9;
break;
default:
pkiDebug("%s: unrecognized pa_type = %d\n", __FUNCTION__, pa_type);
retval = KRB5KDC_ERR_PREAUTH_FAILED;
goto cleanup;
}
/*
* If this is the RFC style, wrap the signed data to make
* decoding easier in the verify routine.
* For draft9-compatible, we don't do anything because it
* is already wrapped.
*/
if (msg_type == CMS_ENVEL_SERVER) {
retval = wrap_signeddata(tmp_buf, tmp_buf_len,
&tmp_buf2, &tmp_buf2_len);
if (retval) {
pkiDebug("failed to encode signeddata\n");
goto cleanup;
}
vfy_buf = tmp_buf2;
vfy_buf_len = tmp_buf2_len;
} else {
vfy_buf = tmp_buf;
vfy_buf_len = tmp_buf_len;
}
#ifdef DEBUG_ASN1
print_buffer_bin(vfy_buf, vfy_buf_len, "/tmp/client_enc_keypack2");
#endif
retval = cms_signeddata_verify(context, plg_cryptoctx, req_cryptoctx,
id_cryptoctx, msg_type,
require_crl_checking,
vfy_buf, vfy_buf_len,
data, data_len, NULL, NULL, NULL);
if (!retval)
pkiDebug("PKCS7 Verification Success\n");
else {
pkiDebug("PKCS7 Verification Failure\n");
goto cleanup;
}
retval = 0;
cleanup:
if (p7 != NULL)
PKCS7_free(p7);
if (out != NULL)
BIO_free(out);
free(tmp_buf);
free(tmp_buf2);
return retval;
}
static krb5_error_code
crypto_retrieve_X509_sans(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
X509 *cert,
krb5_principal **princs_ret,
krb5_principal **upn_ret,
unsigned char ***dns_ret)
{
krb5_error_code retval = EINVAL;
char buf[DN_BUF_LEN];
int p = 0, u = 0, d = 0, ret = 0, l;
krb5_principal *princs = NULL;
krb5_principal *upns = NULL;
unsigned char **dnss = NULL;
unsigned int i, num_found = 0, num_sans = 0;
X509_EXTENSION *ext = NULL;
GENERAL_NAMES *ialt = NULL;
GENERAL_NAME *gen = NULL;
if (princs_ret != NULL)
*princs_ret = NULL;
if (upn_ret != NULL)
*upn_ret = NULL;
if (dns_ret != NULL)
*dns_ret = NULL;
if (princs_ret == NULL && upn_ret == NULL && dns_ret == NULL) {
pkiDebug("%s: nowhere to return any values!\n", __FUNCTION__);
return retval;
}
if (cert == NULL) {
pkiDebug("%s: no certificate!\n", __FUNCTION__);
return retval;
}
X509_NAME_oneline(X509_get_subject_name(cert),
buf, sizeof(buf));
pkiDebug("%s: looking for SANs in cert = %s\n", __FUNCTION__, buf);
l = X509_get_ext_by_NID(cert, NID_subject_alt_name, -1);
if (l < 0)
return 0;
if (!(ext = X509_get_ext(cert, l)) || !(ialt = X509V3_EXT_d2i(ext))) {
pkiDebug("%s: found no subject alt name extensions\n", __FUNCTION__);
retval = ENOENT;
goto cleanup;
}
num_sans = sk_GENERAL_NAME_num(ialt);
pkiDebug("%s: found %d subject alt name extension(s)\n", __FUNCTION__,
num_sans);
/* OK, we're likely returning something. Allocate return values */
if (princs_ret != NULL) {
princs = calloc(num_sans + 1, sizeof(krb5_principal));
if (princs == NULL) {
retval = ENOMEM;
goto cleanup;
}
}
if (upn_ret != NULL) {
upns = calloc(num_sans + 1, sizeof(krb5_principal));
if (upns == NULL) {
retval = ENOMEM;
goto cleanup;
}
}
if (dns_ret != NULL) {
dnss = calloc(num_sans + 1, sizeof(*dnss));
if (dnss == NULL) {
retval = ENOMEM;
goto cleanup;
}
}
for (i = 0; i < num_sans; i++) {
krb5_data name = { 0, 0, NULL };
gen = sk_GENERAL_NAME_value(ialt, i);
switch (gen->type) {
case GEN_OTHERNAME:
name.length = gen->d.otherName->value->value.sequence->length;
name.data = (char *)gen->d.otherName->value->value.sequence->data;
if (princs != NULL &&
OBJ_cmp(plgctx->id_pkinit_san,
gen->d.otherName->type_id) == 0) {
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)name.data, name.length,
"/tmp/pkinit_san");
#endif
ret = k5int_decode_krb5_principal_name(&name, &princs[p]);
if (ret) {
pkiDebug("%s: failed decoding pkinit san value\n",
__FUNCTION__);
} else {
p++;
num_found++;
}
} else if (upns != NULL &&
OBJ_cmp(plgctx->id_ms_san_upn,
gen->d.otherName->type_id) == 0) {
/* Prevent abuse of embedded null characters. */
if (memchr(name.data, '\0', name.length))
break;
ret = krb5_parse_name_flags(context, name.data,
KRB5_PRINCIPAL_PARSE_ENTERPRISE,
&upns[u]);
if (ret) {
pkiDebug("%s: failed parsing ms-upn san value\n",
__FUNCTION__);
} else {
u++;
num_found++;
}
} else {
pkiDebug("%s: unrecognized othername oid in SAN\n",
__FUNCTION__);
continue;
}
break;
case GEN_DNS:
if (dnss != NULL) {
/* Prevent abuse of embedded null characters. */
if (memchr(gen->d.dNSName->data, '\0', gen->d.dNSName->length))
break;
pkiDebug("%s: found dns name = %s\n", __FUNCTION__,
gen->d.dNSName->data);
dnss[d] = (unsigned char *)
strdup((char *)gen->d.dNSName->data);
if (dnss[d] == NULL) {
pkiDebug("%s: failed to duplicate dns name\n",
__FUNCTION__);
} else {
d++;
num_found++;
}
}
break;
default:
pkiDebug("%s: SAN type = %d expecting %d\n", __FUNCTION__,
gen->type, GEN_OTHERNAME);
}
}
sk_GENERAL_NAME_pop_free(ialt, GENERAL_NAME_free);
retval = 0;
if (princs)
*princs_ret = princs;
if (upns)
*upn_ret = upns;
if (dnss)
*dns_ret = dnss;
cleanup:
if (retval) {
if (princs != NULL) {
for (i = 0; princs[i] != NULL; i++)
krb5_free_principal(context, princs[i]);
free(princs);
}
if (upns != NULL) {
for (i = 0; upns[i] != NULL; i++)
krb5_free_principal(context, upns[i]);
free(upns);
}
if (dnss != NULL) {
for (i = 0; dnss[i] != NULL; i++)
free(dnss[i]);
free(dnss);
}
}
return retval;
}
krb5_error_code
crypto_retrieve_signer_identity(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
const char **identity)
{
*identity = id_cryptoctx->identity;
if (*identity == NULL)
return ENOENT;
return 0;
}
krb5_error_code
crypto_retrieve_cert_sans(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
pkinit_identity_crypto_context idctx,
krb5_principal **princs_ret,
krb5_principal **upn_ret,
unsigned char ***dns_ret)
{
krb5_error_code retval = EINVAL;
if (reqctx->received_cert == NULL) {
pkiDebug("%s: No certificate!\n", __FUNCTION__);
return retval;
}
return crypto_retrieve_X509_sans(context, plgctx, reqctx,
reqctx->received_cert, princs_ret,
upn_ret, dns_ret);
}
krb5_error_code
crypto_check_cert_eku(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
pkinit_identity_crypto_context idctx,
int checking_kdc_cert,
int allow_secondary_usage,
int *valid_eku)
{
char buf[DN_BUF_LEN];
int found_eku = 0;
krb5_error_code retval = EINVAL;
int i;
*valid_eku = 0;
if (reqctx->received_cert == NULL)
goto cleanup;
X509_NAME_oneline(X509_get_subject_name(reqctx->received_cert),
buf, sizeof(buf));
if ((i = X509_get_ext_by_NID(reqctx->received_cert,
NID_ext_key_usage, -1)) >= 0) {
EXTENDED_KEY_USAGE *extusage;
extusage = X509_get_ext_d2i(reqctx->received_cert, NID_ext_key_usage,
NULL, NULL);
if (extusage) {
pkiDebug("%s: found eku info in the cert\n", __FUNCTION__);
for (i = 0; found_eku == 0 && i < sk_ASN1_OBJECT_num(extusage); i++) {
ASN1_OBJECT *tmp_oid;
tmp_oid = sk_ASN1_OBJECT_value(extusage, i);
pkiDebug("%s: checking eku %d of %d, allow_secondary = %d\n",
__FUNCTION__, i+1, sk_ASN1_OBJECT_num(extusage),
allow_secondary_usage);
if (checking_kdc_cert) {
if ((OBJ_cmp(tmp_oid, plgctx->id_pkinit_KPKdc) == 0)
|| (allow_secondary_usage
&& OBJ_cmp(tmp_oid, plgctx->id_kp_serverAuth) == 0))
found_eku = 1;
} else {
if ((OBJ_cmp(tmp_oid, plgctx->id_pkinit_KPClientAuth) == 0)
|| (allow_secondary_usage
&& OBJ_cmp(tmp_oid, plgctx->id_ms_kp_sc_logon) == 0))
found_eku = 1;
}
}
}
EXTENDED_KEY_USAGE_free(extusage);
if (found_eku) {
ASN1_BIT_STRING *usage = NULL;
/* check that digitalSignature KeyUsage is present */
X509_check_ca(reqctx->received_cert);
if ((usage = X509_get_ext_d2i(reqctx->received_cert,
NID_key_usage, NULL, NULL))) {
if (!ku_reject(reqctx->received_cert,
X509v3_KU_DIGITAL_SIGNATURE)) {
TRACE_PKINIT_EKU(context);
*valid_eku = 1;
} else
TRACE_PKINIT_EKU_NO_KU(context);
}
ASN1_BIT_STRING_free(usage);
}
}
retval = 0;
cleanup:
pkiDebug("%s: returning retval %d, valid_eku %d\n",
__FUNCTION__, retval, *valid_eku);
return retval;
}
krb5_error_code
pkinit_octetstring2key(krb5_context context,
krb5_enctype etype,
unsigned char *key,
unsigned int dh_key_len,
krb5_keyblock *key_block)
{
krb5_error_code retval;
unsigned char *buf = NULL;
unsigned char md[SHA_DIGEST_LENGTH];
unsigned char counter;
size_t keybytes, keylength, offset;
krb5_data random_data;
if ((buf = malloc(dh_key_len)) == NULL) {
retval = ENOMEM;
goto cleanup;
}
memset(buf, 0, dh_key_len);
counter = 0;
offset = 0;
do {
SHA_CTX c;
SHA1_Init(&c);
SHA1_Update(&c, &counter, 1);
SHA1_Update(&c, key, dh_key_len);
SHA1_Final(md, &c);
if (dh_key_len - offset < sizeof(md))
memcpy(buf + offset, md, dh_key_len - offset);
else
memcpy(buf + offset, md, sizeof(md));
offset += sizeof(md);
counter++;
} while (offset < dh_key_len);
key_block->magic = 0;
key_block->enctype = etype;
retval = krb5_c_keylengths(context, etype, &keybytes, &keylength);
if (retval)
goto cleanup;
key_block->length = keylength;
key_block->contents = malloc(keylength);
if (key_block->contents == NULL) {
retval = ENOMEM;
goto cleanup;
}
random_data.length = keybytes;
random_data.data = (char *)buf;
retval = krb5_c_random_to_key(context, etype, &random_data, key_block);
cleanup:
free(buf);
/* If this is an error return, free the allocated keyblock, if any */
if (retval) {
krb5_free_keyblock_contents(context, key_block);
}
return retval;
}
/**
* Given an algorithm_identifier, this function returns the hash length
* and EVP function associated with that algorithm.
*/
static krb5_error_code
pkinit_alg_values(krb5_context context,
const krb5_data *alg_id,
size_t *hash_bytes,
const EVP_MD *(**func)(void))
{
*hash_bytes = 0;
*func = NULL;
if ((alg_id->length == krb5_pkinit_sha1_oid_len) &&
(0 == memcmp(alg_id->data, &krb5_pkinit_sha1_oid,
krb5_pkinit_sha1_oid_len))) {
*hash_bytes = 20;
*func = &EVP_sha1;
return 0;
} else if ((alg_id->length == krb5_pkinit_sha256_oid_len) &&
(0 == memcmp(alg_id->data, krb5_pkinit_sha256_oid,
krb5_pkinit_sha256_oid_len))) {
*hash_bytes = 32;
*func = &EVP_sha256;
return 0;
} else if ((alg_id->length == krb5_pkinit_sha512_oid_len) &&
(0 == memcmp(alg_id->data, krb5_pkinit_sha512_oid,
krb5_pkinit_sha512_oid_len))) {
*hash_bytes = 64;
*func = &EVP_sha512;
return 0;
} else {
krb5_set_error_message(context, KRB5_ERR_BAD_S2K_PARAMS,
"Bad algorithm ID passed to PK-INIT KDF.");
return KRB5_ERR_BAD_S2K_PARAMS;
}
} /* pkinit_alg_values() */
/* pkinit_alg_agility_kdf() --
* This function generates a key using the KDF described in
* draft_ietf_krb_wg_pkinit_alg_agility-04.txt. The algorithm is
* described as follows:
*
* 1. reps = keydatalen (K) / hash length (H)
*
* 2. Initialize a 32-bit, big-endian bit string counter as 1.
*
* 3. For i = 1 to reps by 1, do the following:
*
* - Compute Hashi = H(counter || Z || OtherInfo).
*
* - Increment counter (modulo 2^32)
*
* 4. Set key = Hash1 || Hash2 || ... so that length of key is K bytes.
*/
krb5_error_code
pkinit_alg_agility_kdf(krb5_context context,
krb5_data *secret,
krb5_data *alg_oid,
krb5_const_principal party_u_info,
krb5_const_principal party_v_info,
krb5_enctype enctype,
krb5_data *as_req,
krb5_data *pk_as_rep,
krb5_keyblock *key_block)
{
krb5_error_code retval = 0;
unsigned int reps = 0;
uint32_t counter = 1; /* Does this type work on Windows? */
size_t offset = 0;
size_t hash_len = 0;
size_t rand_len = 0;
size_t key_len = 0;
krb5_data random_data;
krb5_sp80056a_other_info other_info_fields;
krb5_pkinit_supp_pub_info supp_pub_info_fields;
krb5_data *other_info = NULL;
krb5_data *supp_pub_info = NULL;
krb5_algorithm_identifier alg_id;
EVP_MD_CTX *ctx = NULL;
const EVP_MD *(*EVP_func)(void);
/* initialize random_data here to make clean-up safe */
random_data.length = 0;
random_data.data = NULL;
/* allocate and initialize the key block */
key_block->magic = 0;
key_block->enctype = enctype;
if (0 != (retval = krb5_c_keylengths(context, enctype, &rand_len,
&key_len)))
goto cleanup;
random_data.length = rand_len;
key_block->length = key_len;
if (NULL == (key_block->contents = malloc(key_block->length))) {
retval = ENOMEM;
goto cleanup;
}
memset (key_block->contents, 0, key_block->length);
/* If this is anonymous pkinit, use the anonymous principle for party_u_info */
if (party_u_info && krb5_principal_compare_any_realm(context, party_u_info,
krb5_anonymous_principal()))
party_u_info = (krb5_principal)krb5_anonymous_principal();
if (0 != (retval = pkinit_alg_values(context, alg_oid, &hash_len, &EVP_func)))
goto cleanup;
/* 1. reps = keydatalen (K) / hash length (H) */
reps = key_block->length/hash_len;
/* ... and round up, if necessary */
if (key_block->length > (reps * hash_len))
reps++;
/* Allocate enough space in the random data buffer to hash directly into
* it, even if the last hash will make it bigger than the key length. */
if (NULL == (random_data.data = malloc(reps * hash_len))) {
retval = ENOMEM;
goto cleanup;
}
/* Encode the ASN.1 octet string for "SuppPubInfo" */
supp_pub_info_fields.enctype = enctype;
supp_pub_info_fields.as_req = *as_req;
supp_pub_info_fields.pk_as_rep = *pk_as_rep;
if (0 != ((retval = encode_krb5_pkinit_supp_pub_info(&supp_pub_info_fields,
&supp_pub_info))))
goto cleanup;
/* Now encode the ASN.1 octet string for "OtherInfo" */
memset(&alg_id, 0, sizeof alg_id);
alg_id.algorithm = *alg_oid; /*alias*/
other_info_fields.algorithm_identifier = alg_id;
other_info_fields.party_u_info = (krb5_principal) party_u_info;
other_info_fields.party_v_info = (krb5_principal) party_v_info;
other_info_fields.supp_pub_info = *supp_pub_info;
if (0 != (retval = encode_krb5_sp80056a_other_info(&other_info_fields, &other_info)))
goto cleanup;
/* 2. Initialize a 32-bit, big-endian bit string counter as 1.
* 3. For i = 1 to reps by 1, do the following:
* - Compute Hashi = H(counter || Z || OtherInfo).
* - Increment counter (modulo 2^32)
*/
for (counter = 1; counter <= reps; counter++) {
uint s = 0;
uint32_t be_counter = htonl(counter);
ctx = EVP_MD_CTX_new();
if (ctx == NULL) {
retval = KRB5_CRYPTO_INTERNAL;
goto cleanup;
}
/* - Compute Hashi = H(counter || Z || OtherInfo). */
if (!EVP_DigestInit(ctx, EVP_func())) {
krb5_set_error_message(context, KRB5_CRYPTO_INTERNAL,
"Call to OpenSSL EVP_DigestInit() returned an error.");
retval = KRB5_CRYPTO_INTERNAL;
goto cleanup;
}
if (!EVP_DigestUpdate(ctx, &be_counter, 4) ||
!EVP_DigestUpdate(ctx, secret->data, secret->length) ||
!EVP_DigestUpdate(ctx, other_info->data, other_info->length)) {
krb5_set_error_message(context, KRB5_CRYPTO_INTERNAL,
"Call to OpenSSL EVP_DigestUpdate() returned an error.");
retval = KRB5_CRYPTO_INTERNAL;
goto cleanup;
}
/* 4. Set key = Hash1 || Hash2 || ... so that length of key is K bytes. */
if (!EVP_DigestFinal(ctx, (uint8_t *)random_data.data + offset, &s)) {
krb5_set_error_message(context, KRB5_CRYPTO_INTERNAL,
"Call to OpenSSL EVP_DigestUpdate() returned an error.");
retval = KRB5_CRYPTO_INTERNAL;
goto cleanup;
}
offset += s;
assert(s == hash_len);
EVP_MD_CTX_free(ctx);
ctx = NULL;
}
retval = krb5_c_random_to_key(context, enctype, &random_data,
key_block);
cleanup:
EVP_MD_CTX_free(ctx);
/* If this has been an error, free the allocated key_block, if any */
if (retval) {
krb5_free_keyblock_contents(context, key_block);
}
/* free other allocated resources, either way */
if (random_data.data)
free(random_data.data);
krb5_free_data(context, other_info);
krb5_free_data(context, supp_pub_info);
return retval;
} /*pkinit_alg_agility_kdf() */
/* Call DH_compute_key() and ensure that we left-pad short results instead of
* leaving junk bytes at the end of the buffer. */
static void
compute_dh(unsigned char *buf, int size, BIGNUM *server_pub_key, DH *dh)
{
int len, pad;
len = DH_compute_key(buf, server_pub_key, dh);
assert(len >= 0 && len <= size);
if (len < size) {
pad = size - len;
memmove(buf + pad, buf, len);
memset(buf, 0, pad);
}
}
krb5_error_code
client_create_dh(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int dh_size,
unsigned char **dh_params,
unsigned int *dh_params_len,
unsigned char **dh_pubkey,
unsigned int *dh_pubkey_len)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
unsigned char *buf = NULL;
int dh_err = 0;
ASN1_INTEGER *pub_key = NULL;
const BIGNUM *pubkey_bn, *p, *q, *g;
if (cryptoctx->dh == NULL) {
if (dh_size == 1024)
cryptoctx->dh = make_oakley_dh(oakley_1024, sizeof(oakley_1024));
else if (dh_size == 2048)
cryptoctx->dh = make_oakley_dh(oakley_2048, sizeof(oakley_2048));
else if (dh_size == 4096)
cryptoctx->dh = make_oakley_dh(oakley_4096, sizeof(oakley_4096));
if (cryptoctx->dh == NULL)
goto cleanup;
}
DH_generate_key(cryptoctx->dh);
DH_get0_key(cryptoctx->dh, &pubkey_bn, NULL);
DH_check(cryptoctx->dh, &dh_err);
if (dh_err != 0) {
pkiDebug("Warning: dh_check failed with %d\n", dh_err);
if (dh_err & DH_CHECK_P_NOT_PRIME)
pkiDebug("p value is not prime\n");
if (dh_err & DH_CHECK_P_NOT_SAFE_PRIME)
pkiDebug("p value is not a safe prime\n");
if (dh_err & DH_UNABLE_TO_CHECK_GENERATOR)
pkiDebug("unable to check the generator value\n");
if (dh_err & DH_NOT_SUITABLE_GENERATOR)
pkiDebug("the g value is not a generator\n");
}
#ifdef DEBUG_DH
print_dh(cryptoctx->dh, "client's DH params\n");
print_pubkey(cryptoctx->dh->pub_key, "client's pub_key=");
#endif
DH_check_pub_key(cryptoctx->dh, pubkey_bn, &dh_err);
if (dh_err != 0) {
pkiDebug("dh_check_pub_key failed with %d\n", dh_err);
goto cleanup;
}
/* pack DHparams */
/* aglo: usually we could just call i2d_DHparams to encode DH params
* however, PKINIT requires RFC3279 encoding and openssl does pkcs#3.
*/
DH_get0_pqg(cryptoctx->dh, &p, &q, &g);
retval = pkinit_encode_dh_params(p, g, q, dh_params, dh_params_len);
if (retval)
goto cleanup;
/* pack DH public key */
/* Diffie-Hellman public key must be ASN1 encoded as an INTEGER; this
* encoding shall be used as the contents (the value) of the
* subjectPublicKey component (a BIT STRING) of the SubjectPublicKeyInfo
* data element
*/
pub_key = BN_to_ASN1_INTEGER(pubkey_bn, NULL);
if (pub_key == NULL) {
retval = ENOMEM;
goto cleanup;
}
*dh_pubkey_len = i2d_ASN1_INTEGER(pub_key, NULL);
if ((buf = *dh_pubkey = malloc(*dh_pubkey_len)) == NULL) {
retval = ENOMEM;
goto cleanup;
}
i2d_ASN1_INTEGER(pub_key, &buf);
if (pub_key != NULL)
ASN1_INTEGER_free(pub_key);
retval = 0;
return retval;
cleanup:
if (cryptoctx->dh != NULL)
DH_free(cryptoctx->dh);
cryptoctx->dh = NULL;
free(*dh_params);
*dh_params = NULL;
free(*dh_pubkey);
*dh_pubkey = NULL;
if (pub_key != NULL)
ASN1_INTEGER_free(pub_key);
return retval;
}
krb5_error_code
client_process_dh(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *subjectPublicKey_data,
unsigned int subjectPublicKey_length,
unsigned char **client_key,
unsigned int *client_key_len)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
BIGNUM *server_pub_key = NULL;
ASN1_INTEGER *pub_key = NULL;
const unsigned char *p = NULL;
*client_key_len = DH_size(cryptoctx->dh);
if ((*client_key = malloc(*client_key_len)) == NULL) {
retval = ENOMEM;
goto cleanup;
}
p = subjectPublicKey_data;
pub_key = d2i_ASN1_INTEGER(NULL, &p, (long)subjectPublicKey_length);
if (pub_key == NULL)
goto cleanup;
if ((server_pub_key = ASN1_INTEGER_to_BN(pub_key, NULL)) == NULL)
goto cleanup;
compute_dh(*client_key, *client_key_len, server_pub_key, cryptoctx->dh);
#ifdef DEBUG_DH
print_pubkey(server_pub_key, "server's pub_key=");
pkiDebug("client computed key (%d)= ", *client_key_len);
print_buffer(*client_key, *client_key_len);
#endif
retval = 0;
if (server_pub_key != NULL)
BN_free(server_pub_key);
if (pub_key != NULL)
ASN1_INTEGER_free(pub_key);
return retval;
cleanup:
free(*client_key);
*client_key = NULL;
if (pub_key != NULL)
ASN1_INTEGER_free(pub_key);
return retval;
}
/* Return 1 if dh is a permitted well-known group, otherwise return 0. */
static int
check_dh_wellknown(pkinit_plg_crypto_context cryptoctx, DH *dh, int nbits)
{
switch (nbits) {
case 1024:
/* Oakley MODP group 2 */
if (pkinit_check_dh_params(cryptoctx->dh_1024, dh) == 0)
return 1;
break;
case 2048:
/* Oakley MODP group 14 */
if (pkinit_check_dh_params(cryptoctx->dh_2048, dh) == 0)
return 1;
break;
case 4096:
/* Oakley MODP group 16 */
if (pkinit_check_dh_params(cryptoctx->dh_4096, dh) == 0)
return 1;
break;
default:
break;
}
return 0;
}
krb5_error_code
server_check_dh(krb5_context context,
pkinit_plg_crypto_context cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_data *dh_params,
int minbits)
{
DH *dh = NULL;
const BIGNUM *p;
int dh_prime_bits;
krb5_error_code retval = KRB5KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
dh = decode_dh_params((uint8_t *)dh_params->data, dh_params->length);
if (dh == NULL) {
pkiDebug("failed to decode dhparams\n");
goto cleanup;
}
/* KDC SHOULD check to see if the key parameters satisfy its policy */
DH_get0_pqg(dh, &p, NULL, NULL);
dh_prime_bits = BN_num_bits(p);
if (minbits && dh_prime_bits < minbits) {
pkiDebug("client sent dh params with %d bits, we require %d\n",
dh_prime_bits, minbits);
goto cleanup;
}
if (check_dh_wellknown(cryptoctx, dh, dh_prime_bits))
retval = 0;
cleanup:
if (retval == 0)
req_cryptoctx->dh = dh;
else
DH_free(dh);
return retval;
}
/* Duplicate a DH handle (parameters only, not public or private key). */
static DH *
dup_dh_params(const DH *src)
{
const BIGNUM *oldp, *oldq, *oldg;
BIGNUM *p = NULL, *q = NULL, *g = NULL;
DH *dh;
DH_get0_pqg(src, &oldp, &oldq, &oldg);
p = BN_dup(oldp);
q = BN_dup(oldq);
g = BN_dup(oldg);
dh = DH_new();
if (p == NULL || q == NULL || g == NULL || dh == NULL) {
BN_free(p);
BN_free(q);
BN_free(g);
DH_free(dh);
return NULL;
}
DH_set0_pqg(dh, p, q, g);
return dh;
}
/* kdc's dh function */
krb5_error_code
server_process_dh(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data,
unsigned int data_len,
unsigned char **dh_pubkey,
unsigned int *dh_pubkey_len,
unsigned char **server_key,
unsigned int *server_key_len)
{
krb5_error_code retval = ENOMEM;
DH *dh = NULL, *dh_server = NULL;
unsigned char *p = NULL;
ASN1_INTEGER *pub_key = NULL;
BIGNUM *client_pubkey = NULL;
const BIGNUM *server_pubkey;
*dh_pubkey = *server_key = NULL;
*dh_pubkey_len = *server_key_len = 0;
/* get client's received DH parameters that we saved in server_check_dh */
dh = cryptoctx->dh;
dh_server = dup_dh_params(dh);
if (dh_server == NULL)
goto cleanup;
/* decode client's public key */
p = data;
pub_key = d2i_ASN1_INTEGER(NULL, (const unsigned char **)&p, (int)data_len);
if (pub_key == NULL)
goto cleanup;
client_pubkey = ASN1_INTEGER_to_BN(pub_key, NULL);
if (client_pubkey == NULL)
goto cleanup;
ASN1_INTEGER_free(pub_key);
if (!DH_generate_key(dh_server))
goto cleanup;
DH_get0_key(dh_server, &server_pubkey, NULL);
/* generate DH session key */
*server_key_len = DH_size(dh_server);
if ((*server_key = malloc(*server_key_len)) == NULL)
goto cleanup;
compute_dh(*server_key, *server_key_len, client_pubkey, dh_server);
#ifdef DEBUG_DH
print_dh(dh_server, "client&server's DH params\n");
print_pubkey(client_pubkey, "client's pub_key=");
print_pubkey(server_pubkey, "server's pub_key=");
pkiDebug("server computed key=");
print_buffer(*server_key, *server_key_len);
#endif
/* KDC reply */
/* pack DH public key */
/* Diffie-Hellman public key must be ASN1 encoded as an INTEGER; this
* encoding shall be used as the contents (the value) of the
* subjectPublicKey component (a BIT STRING) of the SubjectPublicKeyInfo
* data element
*/
pub_key = BN_to_ASN1_INTEGER(server_pubkey, NULL);
if (pub_key == NULL)
goto cleanup;
*dh_pubkey_len = i2d_ASN1_INTEGER(pub_key, NULL);
if ((p = *dh_pubkey = malloc(*dh_pubkey_len)) == NULL)
goto cleanup;
i2d_ASN1_INTEGER(pub_key, &p);
if (pub_key != NULL)
ASN1_INTEGER_free(pub_key);
retval = 0;
if (dh_server != NULL)
DH_free(dh_server);
return retval;
cleanup:
BN_free(client_pubkey);
DH_free(dh_server);
free(*dh_pubkey);
free(*server_key);
return retval;
}
int
pkinit_openssl_init()
{
/* Initialize OpenSSL. */
ERR_load_crypto_strings();
OpenSSL_add_all_algorithms();
return 0;
}
static krb5_error_code
pkinit_encode_dh_params(const BIGNUM *p, const BIGNUM *g, const BIGNUM *q,
uint8_t **buf, unsigned int *buf_len)
{
krb5_error_code retval = ENOMEM;
int bufsize = 0, r = 0;
unsigned char *tmp = NULL;
ASN1_INTEGER *ap = NULL, *ag = NULL, *aq = NULL;
if ((ap = BN_to_ASN1_INTEGER(p, NULL)) == NULL)
goto cleanup;
if ((ag = BN_to_ASN1_INTEGER(g, NULL)) == NULL)
goto cleanup;
if ((aq = BN_to_ASN1_INTEGER(q, NULL)) == NULL)
goto cleanup;
bufsize = i2d_ASN1_INTEGER(ap, NULL);
bufsize += i2d_ASN1_INTEGER(ag, NULL);
bufsize += i2d_ASN1_INTEGER(aq, NULL);
r = ASN1_object_size(1, bufsize, V_ASN1_SEQUENCE);
tmp = *buf = malloc((size_t) r);
if (tmp == NULL)
goto cleanup;
ASN1_put_object(&tmp, 1, bufsize, V_ASN1_SEQUENCE, V_ASN1_UNIVERSAL);
i2d_ASN1_INTEGER(ap, &tmp);
i2d_ASN1_INTEGER(ag, &tmp);
i2d_ASN1_INTEGER(aq, &tmp);
*buf_len = r;
retval = 0;
cleanup:
if (ap != NULL)
ASN1_INTEGER_free(ap);
if (ag != NULL)
ASN1_INTEGER_free(ag);
if (aq != NULL)
ASN1_INTEGER_free(aq);
return retval;
}
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
/*
* We need to decode DomainParameters from RFC 3279 section 2.3.3. We would
* like to just call d2i_DHxparams(), but Microsoft's implementation may omit
* the q value in violation of the RFC. Instead we must copy the internal
* structures and sequence declarations from dh_asn1.c, modified to make the q
* field optional.
*/
typedef struct {
ASN1_BIT_STRING *seed;
BIGNUM *counter;
} int_dhvparams;
typedef struct {
BIGNUM *p;
BIGNUM *q;
BIGNUM *g;
BIGNUM *j;
int_dhvparams *vparams;
} int_dhx942_dh;
ASN1_SEQUENCE(DHvparams) = {
ASN1_SIMPLE(int_dhvparams, seed, ASN1_BIT_STRING),
ASN1_SIMPLE(int_dhvparams, counter, BIGNUM)
} static_ASN1_SEQUENCE_END_name(int_dhvparams, DHvparams)
ASN1_SEQUENCE(DHxparams) = {
ASN1_SIMPLE(int_dhx942_dh, p, BIGNUM),
ASN1_SIMPLE(int_dhx942_dh, g, BIGNUM),
ASN1_OPT(int_dhx942_dh, q, BIGNUM),
ASN1_OPT(int_dhx942_dh, j, BIGNUM),
ASN1_OPT(int_dhx942_dh, vparams, DHvparams),
} static_ASN1_SEQUENCE_END_name(int_dhx942_dh, DHxparams)
static DH *
decode_dh_params(const uint8_t *p, unsigned int len)
{
int_dhx942_dh *params;
DH *dh;
dh = DH_new();
if (dh == NULL)
return NULL;
params = (int_dhx942_dh *)ASN1_item_d2i(NULL, &p, len,
ASN1_ITEM_rptr(DHxparams));
if (params == NULL) {
DH_free(dh);
return NULL;
}
/* Steal the p, q, and g values from dhparams for dh. Ignore j and
* vparams. */
DH_set0_pqg(dh, params->p, params->q, params->g);
params->p = params->q = params->g = NULL;
ASN1_item_free((ASN1_VALUE *)params, ASN1_ITEM_rptr(DHxparams));
return dh;
}
#else /* OPENSSL_VERSION_NUMBER < 0x10100000L */
/*
* Do the same decoding (except without decoding j and vparams or checking the
* sequence length) using the pre-OpenSSL-1.1 asn1_mac.h. Define an internal
* function in the form demanded by the macros, then wrap it for caller
* convenience.
*/
static DH *
decode_dh_params_int(DH ** a, uint8_t **pp, unsigned int len)
{
ASN1_INTEGER ai, *aip = NULL;
long length = (long) len;
M_ASN1_D2I_vars(a, DH *, DH_new);
M_ASN1_D2I_Init();
M_ASN1_D2I_start_sequence();
aip = &ai;
ai.data = NULL;
ai.length = 0;
M_ASN1_D2I_get_x(ASN1_INTEGER, aip, d2i_ASN1_INTEGER);
if (aip == NULL)
return NULL;
else {
ret->p = ASN1_INTEGER_to_BN(aip, NULL);
if (ret->p == NULL)
return NULL;
if (ai.data != NULL) {
OPENSSL_free(ai.data);
ai.data = NULL;
ai.length = 0;
}
}
M_ASN1_D2I_get_x(ASN1_INTEGER, aip, d2i_ASN1_INTEGER);
if (aip == NULL)
return NULL;
else {
ret->g = ASN1_INTEGER_to_BN(aip, NULL);
if (ret->g == NULL)
return NULL;
if (ai.data != NULL) {
OPENSSL_free(ai.data);
ai.data = NULL;
ai.length = 0;
}
}
M_ASN1_D2I_get_opt(aip, d2i_ASN1_INTEGER, V_ASN1_INTEGER);
if (aip == NULL || ai.data == NULL)
ret->q = NULL;
else {
ret->q = ASN1_INTEGER_to_BN(aip, NULL);
if (ret->q == NULL)
return NULL;
if (ai.data != NULL) {
OPENSSL_free(ai.data);
ai.data = NULL;
ai.length = 0;
}
}
M_ASN1_D2I_end_sequence();
M_ASN1_D2I_Finish(a, DH_free, 0);
}
static DH *
decode_dh_params(const uint8_t *p, unsigned int len)
{
uint8_t *ptr = (uint8_t *)p;
return decode_dh_params_int(NULL, &ptr, len);
}
#endif /* OPENSSL_VERSION_NUMBER < 0x10100000L */
static krb5_error_code
pkinit_create_sequence_of_principal_identifiers(
krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int type,
krb5_pa_data ***e_data_out)
{
krb5_error_code retval = KRB5KRB_ERR_GENERIC;
krb5_external_principal_identifier **krb5_trusted_certifiers = NULL;
krb5_data *td_certifiers = NULL;
krb5_pa_data **pa_data = NULL;
switch(type) {
case TD_TRUSTED_CERTIFIERS:
retval = create_krb5_trustedCertifiers(context, plg_cryptoctx,
req_cryptoctx, id_cryptoctx, &krb5_trusted_certifiers);
if (retval) {
pkiDebug("create_krb5_trustedCertifiers failed\n");
goto cleanup;
}
break;
case TD_INVALID_CERTIFICATES:
retval = create_krb5_invalidCertificates(context, plg_cryptoctx,
req_cryptoctx, id_cryptoctx, &krb5_trusted_certifiers);
if (retval) {
pkiDebug("create_krb5_invalidCertificates failed\n");
goto cleanup;
}
break;
default:
retval = -1;
goto cleanup;
}
retval = k5int_encode_krb5_td_trusted_certifiers((krb5_external_principal_identifier *const *)krb5_trusted_certifiers, &td_certifiers);
if (retval) {
pkiDebug("encode_krb5_td_trusted_certifiers failed\n");
goto cleanup;
}
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)td_certifiers->data,
td_certifiers->length, "/tmp/kdc_td_certifiers");
#endif
pa_data = malloc(2 * sizeof(krb5_pa_data *));
if (pa_data == NULL) {
retval = ENOMEM;
goto cleanup;
}
pa_data[1] = NULL;
pa_data[0] = malloc(sizeof(krb5_pa_data));
if (pa_data[0] == NULL) {
free(pa_data);
retval = ENOMEM;
goto cleanup;
}
pa_data[0]->pa_type = type;
pa_data[0]->length = td_certifiers->length;
pa_data[0]->contents = (krb5_octet *)td_certifiers->data;
*e_data_out = pa_data;
retval = 0;
cleanup:
if (krb5_trusted_certifiers != NULL)
free_krb5_external_principal_identifier(&krb5_trusted_certifiers);
free(td_certifiers);
return retval;
}
krb5_error_code
pkinit_create_td_trusted_certifiers(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_pa_data ***e_data_out)
{
krb5_error_code retval = KRB5KRB_ERR_GENERIC;
retval = pkinit_create_sequence_of_principal_identifiers(context,
plg_cryptoctx, req_cryptoctx, id_cryptoctx,
TD_TRUSTED_CERTIFIERS, e_data_out);
return retval;
}
krb5_error_code
pkinit_create_td_invalid_certificate(
krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_pa_data ***e_data_out)
{
krb5_error_code retval = KRB5KRB_ERR_GENERIC;
retval = pkinit_create_sequence_of_principal_identifiers(context,
plg_cryptoctx, req_cryptoctx, id_cryptoctx,
TD_INVALID_CERTIFICATES, e_data_out);
return retval;
}
krb5_error_code
pkinit_create_td_dh_parameters(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
pkinit_plg_opts *opts,
krb5_pa_data ***e_data_out)
{
krb5_error_code retval = ENOMEM;
unsigned int buf1_len = 0, buf2_len = 0, buf3_len = 0, i = 0;
unsigned char *buf1 = NULL, *buf2 = NULL, *buf3 = NULL;
krb5_pa_data **pa_data = NULL;
krb5_data *encoded_algId = NULL;
krb5_algorithm_identifier **algId = NULL;
const BIGNUM *p, *q, *g;
if (opts->dh_min_bits > 4096)
goto cleanup;
if (opts->dh_min_bits <= 1024) {
DH_get0_pqg(plg_cryptoctx->dh_1024, &p, &q, &g);
retval = pkinit_encode_dh_params(p, g, q, &buf1, &buf1_len);
if (retval)
goto cleanup;
}
if (opts->dh_min_bits <= 2048) {
DH_get0_pqg(plg_cryptoctx->dh_2048, &p, &q, &g);
retval = pkinit_encode_dh_params(p, g, q, &buf2, &buf2_len);
if (retval)
goto cleanup;
}
DH_get0_pqg(plg_cryptoctx->dh_4096, &p, &q, &g);
retval = pkinit_encode_dh_params(p, g, q, &buf3, &buf3_len);
if (retval)
goto cleanup;
if (opts->dh_min_bits <= 1024) {
algId = malloc(4 * sizeof(krb5_algorithm_identifier *));
if (algId == NULL)
goto cleanup;
algId[3] = NULL;
algId[0] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[0] == NULL)
goto cleanup;
algId[0]->parameters.data = malloc(buf2_len);
if (algId[0]->parameters.data == NULL)
goto cleanup;
memcpy(algId[0]->parameters.data, buf2, buf2_len);
algId[0]->parameters.length = buf2_len;
algId[0]->algorithm = dh_oid;
algId[1] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[1] == NULL)
goto cleanup;
algId[1]->parameters.data = malloc(buf3_len);
if (algId[1]->parameters.data == NULL)
goto cleanup;
memcpy(algId[1]->parameters.data, buf3, buf3_len);
algId[1]->parameters.length = buf3_len;
algId[1]->algorithm = dh_oid;
algId[2] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[2] == NULL)
goto cleanup;
algId[2]->parameters.data = malloc(buf1_len);
if (algId[2]->parameters.data == NULL)
goto cleanup;
memcpy(algId[2]->parameters.data, buf1, buf1_len);
algId[2]->parameters.length = buf1_len;
algId[2]->algorithm = dh_oid;
} else if (opts->dh_min_bits <= 2048) {
algId = malloc(3 * sizeof(krb5_algorithm_identifier *));
if (algId == NULL)
goto cleanup;
algId[2] = NULL;
algId[0] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[0] == NULL)
goto cleanup;
algId[0]->parameters.data = malloc(buf2_len);
if (algId[0]->parameters.data == NULL)
goto cleanup;
memcpy(algId[0]->parameters.data, buf2, buf2_len);
algId[0]->parameters.length = buf2_len;
algId[0]->algorithm = dh_oid;
algId[1] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[1] == NULL)
goto cleanup;
algId[1]->parameters.data = malloc(buf3_len);
if (algId[1]->parameters.data == NULL)
goto cleanup;
memcpy(algId[1]->parameters.data, buf3, buf3_len);
algId[1]->parameters.length = buf3_len;
algId[1]->algorithm = dh_oid;
} else if (opts->dh_min_bits <= 4096) {
algId = malloc(2 * sizeof(krb5_algorithm_identifier *));
if (algId == NULL)
goto cleanup;
algId[1] = NULL;
algId[0] = malloc(sizeof(krb5_algorithm_identifier));
if (algId[0] == NULL)
goto cleanup;
algId[0]->parameters.data = malloc(buf3_len);
if (algId[0]->parameters.data == NULL)
goto cleanup;
memcpy(algId[0]->parameters.data, buf3, buf3_len);
algId[0]->parameters.length = buf3_len;
algId[0]->algorithm = dh_oid;
}
retval = k5int_encode_krb5_td_dh_parameters((krb5_algorithm_identifier *const *)algId, &encoded_algId);
if (retval)
goto cleanup;
#ifdef DEBUG_ASN1
print_buffer_bin((unsigned char *)encoded_algId->data,
encoded_algId->length, "/tmp/kdc_td_dh_params");
#endif
pa_data = malloc(2 * sizeof(krb5_pa_data *));
if (pa_data == NULL) {
retval = ENOMEM;
goto cleanup;
}
pa_data[1] = NULL;
pa_data[0] = malloc(sizeof(krb5_pa_data));
if (pa_data[0] == NULL) {
free(pa_data);
retval = ENOMEM;
goto cleanup;
}
pa_data[0]->pa_type = TD_DH_PARAMETERS;
pa_data[0]->length = encoded_algId->length;
pa_data[0]->contents = (krb5_octet *)encoded_algId->data;
*e_data_out = pa_data;
retval = 0;
cleanup:
free(buf1);
free(buf2);
free(buf3);
free(encoded_algId);
if (algId != NULL) {
while(algId[i] != NULL) {
free(algId[i]->parameters.data);
free(algId[i]);
i++;
}
free(algId);
}
return retval;
}
krb5_error_code
pkinit_check_kdc_pkid(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *pdid_buf,
unsigned int pkid_len,
int *valid_kdcPkId)
{
PKCS7_ISSUER_AND_SERIAL *is = NULL;
const unsigned char *p = pdid_buf;
int status = 1;
X509 *kdc_cert = sk_X509_value(id_cryptoctx->my_certs, id_cryptoctx->cert_index);
*valid_kdcPkId = 0;
pkiDebug("found kdcPkId in AS REQ\n");
is = d2i_PKCS7_ISSUER_AND_SERIAL(NULL, &p, (int)pkid_len);
if (is == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
status = X509_NAME_cmp(X509_get_issuer_name(kdc_cert), is->issuer);
if (!status) {
status = ASN1_INTEGER_cmp(X509_get_serialNumber(kdc_cert), is->serial);
if (!status)
*valid_kdcPkId = 1;
}
X509_NAME_free(is->issuer);
ASN1_INTEGER_free(is->serial);
free(is);
return 0;
}
/* Check parameters against a well-known DH group. */
static int
pkinit_check_dh_params(DH *dh1, DH *dh2)
{
const BIGNUM *p1, *p2, *g1, *g2;
DH_get0_pqg(dh1, &p1, NULL, &g1);
DH_get0_pqg(dh2, &p2, NULL, &g2);
if (BN_cmp(p1, p2) != 0) {
pkiDebug("p is not well-known group dhparameter\n");
return -1;
}
if (BN_cmp(g1, g2) != 0) {
pkiDebug("bad g dhparameter\n");
return -1;
}
pkiDebug("good %d dhparams\n", BN_num_bits(p1));
return 0;
}
krb5_error_code
pkinit_process_td_dh_params(krb5_context context,
pkinit_plg_crypto_context cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_algorithm_identifier **algId,
int *new_dh_size)
{
krb5_error_code retval = KRB5KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
int i = 0, use_sent_dh = 0, ok = 0;
pkiDebug("dh parameters\n");
while (algId[i] != NULL) {
DH *dh = NULL;
const BIGNUM *p;
int dh_prime_bits = 0;
if (algId[i]->algorithm.length != dh_oid.length ||
memcmp(algId[i]->algorithm.data, dh_oid.data, dh_oid.length))
goto cleanup;
dh = decode_dh_params((uint8_t *)algId[i]->parameters.data,
algId[i]->parameters.length);
if (dh == NULL)
goto cleanup;
DH_get0_pqg(dh, &p, NULL, NULL);
dh_prime_bits = BN_num_bits(p);
pkiDebug("client sent %d DH bits server prefers %d DH bits\n",
*new_dh_size, dh_prime_bits);
ok = check_dh_wellknown(cryptoctx, dh, dh_prime_bits);
if (ok) {
*new_dh_size = dh_prime_bits;
}
if (!ok) {
DH_check(dh, &retval);
if (retval != 0) {
pkiDebug("DH parameters provided by server are unacceptable\n");
retval = KRB5KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED;
}
else {
use_sent_dh = 1;
ok = 1;
}
}
if (!use_sent_dh)
DH_free(dh);
if (ok) {
if (req_cryptoctx->dh != NULL) {
DH_free(req_cryptoctx->dh);
req_cryptoctx->dh = NULL;
}
if (use_sent_dh)
req_cryptoctx->dh = dh;
break;
}
i++;
}
if (ok)
retval = 0;
cleanup:
return retval;
}
static int
openssl_callback(int ok, X509_STORE_CTX * ctx)
{
#ifdef DEBUG
if (!ok) {
X509 *cert = X509_STORE_CTX_get_current_cert(ctx);
int err = X509_STORE_CTX_get_error(ctx);
const char *errmsg = X509_verify_cert_error_string(err);
char buf[DN_BUF_LEN];
X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
pkiDebug("cert = %s\n", buf);
pkiDebug("callback function: %d (%s)\n", err, errmsg);
}
#endif
return ok;
}
static int
openssl_callback_ignore_crls(int ok, X509_STORE_CTX * ctx)
{
if (ok)
return ok;
return X509_STORE_CTX_get_error(ctx) == X509_V_ERR_UNABLE_TO_GET_CRL;
}
static ASN1_OBJECT *
pkinit_pkcs7type2oid(pkinit_plg_crypto_context cryptoctx, int pkcs7_type)
{
switch (pkcs7_type) {
case CMS_SIGN_CLIENT:
return cryptoctx->id_pkinit_authData;
case CMS_SIGN_DRAFT9:
return OBJ_nid2obj(NID_pkcs7_data);
case CMS_SIGN_SERVER:
return cryptoctx->id_pkinit_DHKeyData;
case CMS_ENVEL_SERVER:
return cryptoctx->id_pkinit_rkeyData;
default:
return NULL;
}
}
static int
wrap_signeddata(unsigned char *data, unsigned int data_len,
unsigned char **out, unsigned int *out_len)
{
unsigned int orig_len = 0, oid_len = 0, tot_len = 0;
ASN1_OBJECT *oid = NULL;
unsigned char *p = NULL;
/* Get length to wrap the original data with SEQUENCE tag */
tot_len = orig_len = ASN1_object_size(1, (int)data_len, V_ASN1_SEQUENCE);
/* Add the signedData OID and adjust lengths */
oid = OBJ_nid2obj(NID_pkcs7_signed);
oid_len = i2d_ASN1_OBJECT(oid, NULL);
tot_len = ASN1_object_size(1, (int)(orig_len+oid_len), V_ASN1_SEQUENCE);
p = *out = malloc(tot_len);
if (p == NULL) return -1;
ASN1_put_object(&p, 1, (int)(orig_len+oid_len),
V_ASN1_SEQUENCE, V_ASN1_UNIVERSAL);
i2d_ASN1_OBJECT(oid, &p);
ASN1_put_object(&p, 1, (int)data_len, 0, V_ASN1_CONTEXT_SPECIFIC);
memcpy(p, data, data_len);
*out_len = tot_len;
return 0;
}
static int
prepare_enc_data(const uint8_t *indata, int indata_len, uint8_t **outdata,
int *outdata_len)
{
int tag, class;
long tlen, slen;
const uint8_t *p = indata, *oldp;
if (ASN1_get_object(&p, &slen, &tag, &class, indata_len) & 0x80)
return EINVAL;
if (tag != V_ASN1_SEQUENCE)
return EINVAL;
oldp = p;
if (ASN1_get_object(&p, &tlen, &tag, &class, slen) & 0x80)
return EINVAL;
p += tlen;
slen -= (p - oldp);
if (ASN1_get_object(&p, &tlen, &tag, &class, slen) & 0x80)
return EINVAL;
*outdata = malloc(tlen);
if (*outdata == NULL)
return ENOMEM;
memcpy(*outdata, p, tlen);
*outdata_len = tlen;
return 0;
}
#ifndef WITHOUT_PKCS11
static void *
pkinit_C_LoadModule(const char *modname, CK_FUNCTION_LIST_PTR_PTR p11p)
{
void *handle;
CK_RV (*getflist)(CK_FUNCTION_LIST_PTR_PTR);
pkiDebug("loading module \"%s\"... ", modname);
handle = dlopen(modname, RTLD_NOW);
if (handle == NULL) {
pkiDebug("not found\n");
return NULL;
}
getflist = (CK_RV (*)(CK_FUNCTION_LIST_PTR_PTR)) dlsym(handle, "C_GetFunctionList");
if (getflist == NULL || (*getflist)(p11p) != CKR_OK) {
dlclose(handle);
pkiDebug("failed\n");
return NULL;
}
pkiDebug("ok\n");
return handle;
}
static CK_RV
pkinit_C_UnloadModule(void *handle)
{
dlclose(handle);
return CKR_OK;
}
static krb5_error_code
pkinit_login(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
CK_TOKEN_INFO *tip, const char *password)
{
krb5_data rdat;
char *prompt;
const char *warning;
krb5_prompt kprompt;
krb5_prompt_type prompt_type;
int r = 0;
if (tip->flags & CKF_PROTECTED_AUTHENTICATION_PATH) {
rdat.data = NULL;
rdat.length = 0;
} else if (password != NULL) {
rdat.data = strdup(password);
rdat.length = strlen(password);
} else if (id_cryptoctx->prompter == NULL) {
r = KRB5_LIBOS_CANTREADPWD;
rdat.data = NULL;
} else {
if (tip->flags & CKF_USER_PIN_LOCKED)
warning = " (Warning: PIN locked)";
else if (tip->flags & CKF_USER_PIN_FINAL_TRY)
warning = " (Warning: PIN final try)";
else if (tip->flags & CKF_USER_PIN_COUNT_LOW)
warning = " (Warning: PIN count low)";
else
warning = "";
if (asprintf(&prompt, "%.*s PIN%s", (int) sizeof (tip->label),
tip->label, warning) < 0)
return ENOMEM;
rdat.data = malloc(tip->ulMaxPinLen + 2);
rdat.length = tip->ulMaxPinLen + 1;
kprompt.prompt = prompt;
kprompt.hidden = 1;
kprompt.reply = &rdat;
prompt_type = KRB5_PROMPT_TYPE_PREAUTH;
/* PROMPTER_INVOCATION */
k5int_set_prompt_types(context, &prompt_type);
r = (*id_cryptoctx->prompter)(context, id_cryptoctx->prompter_data,
NULL, NULL, 1, &kprompt);
k5int_set_prompt_types(context, 0);
free(prompt);
}
if (r == 0) {
r = id_cryptoctx->p11->C_Login(id_cryptoctx->session, CKU_USER,
(u_char *) rdat.data, rdat.length);
if (r != CKR_OK) {
pkiDebug("C_Login: %s\n", pkinit_pkcs11_code_to_text(r));
r = KRB5KDC_ERR_PREAUTH_FAILED;
}
}
free(rdat.data);
return r;
}
static krb5_error_code
pkinit_open_session(krb5_context context,
pkinit_identity_crypto_context cctx)
{
CK_ULONG i, r;
unsigned char *cp;
size_t label_len;
CK_ULONG count = 0;
CK_SLOT_ID_PTR slotlist;
CK_TOKEN_INFO tinfo;
char *p11name;
const char *password;
if (cctx->p11_module != NULL)
return 0; /* session already open */
/* Load module */
cctx->p11_module =
pkinit_C_LoadModule(cctx->p11_module_name, &cctx->p11);
if (cctx->p11_module == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
/* Init */
if ((r = cctx->p11->C_Initialize(NULL)) != CKR_OK) {
pkiDebug("C_Initialize: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
/* Get the list of available slots */
if (cctx->p11->C_GetSlotList(TRUE, NULL, &count) != CKR_OK)
return KRB5KDC_ERR_PREAUTH_FAILED;
if (count == 0)
return KRB5KDC_ERR_PREAUTH_FAILED;
slotlist = calloc(count, sizeof(CK_SLOT_ID));
if (slotlist == NULL)
return ENOMEM;
if (cctx->p11->C_GetSlotList(TRUE, slotlist, &count) != CKR_OK)
return KRB5KDC_ERR_PREAUTH_FAILED;
/* Look for the given token label, or if none given take the first one */
for (i = 0; i < count; i++) {
/* Skip slots that don't match the specified slotid, if given. */
if (cctx->slotid != PK_NOSLOT && cctx->slotid != slotlist[i])
continue;
/* Open session */
if ((r = cctx->p11->C_OpenSession(slotlist[i], CKF_SERIAL_SESSION,
NULL, NULL, &cctx->session)) != CKR_OK) {
pkiDebug("C_OpenSession: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
/* Get token info */
if ((r = cctx->p11->C_GetTokenInfo(slotlist[i], &tinfo)) != CKR_OK) {
pkiDebug("C_GetTokenInfo: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
/* tinfo.label is zero-filled but not necessarily zero-terminated.
* Find the length, ignoring any trailing spaces. */
for (cp = tinfo.label + sizeof(tinfo.label); cp > tinfo.label; cp--) {
if (cp[-1] != '\0' && cp[-1] != ' ')
break;
}
label_len = cp - tinfo.label;
pkiDebug("open_session: slotid %d token \"%.*s\"\n",
(int)slotlist[i], (int)label_len, tinfo.label);
if (cctx->token_label == NULL ||
(strlen(cctx->token_label) == label_len &&
memcmp(cctx->token_label, tinfo.label, label_len) == 0))
break;
cctx->p11->C_CloseSession(cctx->session);
}
if (i >= count) {
free(slotlist);
pkiDebug("open_session: no matching token found\n");
return KRB5KDC_ERR_PREAUTH_FAILED;
}
cctx->slotid = slotlist[i];
free(slotlist);
pkiDebug("open_session: slotid %d (%lu of %d)\n", (int)cctx->slotid,
i + 1, (int) count);
/* Login if needed */
if (tinfo.flags & CKF_LOGIN_REQUIRED) {
if (cctx->p11_module_name != NULL) {
if (cctx->slotid != PK_NOSLOT) {
if (asprintf(&p11name,
"PKCS11:module_name=%s:slotid=%ld:token=%.*s",
cctx->p11_module_name, (long)cctx->slotid,
(int)label_len, tinfo.label) < 0)
p11name = NULL;
} else {
if (asprintf(&p11name,
"PKCS11:module_name=%s,token=%.*s",
cctx->p11_module_name,
(int)label_len, tinfo.label) < 0)
p11name = NULL;
}
} else {
p11name = NULL;
}
if (cctx->defer_id_prompt) {
/* Supply the identity name to be passed to the responder. */
pkinit_set_deferred_id(&cctx->deferred_ids,
p11name, tinfo.flags, NULL);
free(p11name);
return KRB5KRB_ERR_GENERIC;
}
/* Look up a responder-supplied password for the token. */
password = pkinit_find_deferred_id(cctx->deferred_ids, p11name);
free(p11name);
r = pkinit_login(context, cctx, &tinfo, password);
}
return r;
}
/*
* Look for a key that's:
* 1. private
* 2. capable of the specified operation (usually signing or decrypting)
* 3. RSA (this may be wrong but it's all we can do for now)
* 4. matches the id of the cert we chose
*
* You must call pkinit_get_certs before calling pkinit_find_private_key
* (that's because we need the ID of the private key)
*
* pkcs11 says the id of the key doesn't have to match that of the cert, but
* I can't figure out any other way to decide which key to use.
*
* We should only find one key that fits all the requirements.
* If there are more than one, we just take the first one.
*/
krb5_error_code
pkinit_find_private_key(pkinit_identity_crypto_context id_cryptoctx,
CK_ATTRIBUTE_TYPE usage,
CK_OBJECT_HANDLE *objp)
{
CK_OBJECT_CLASS cls;
CK_ATTRIBUTE attrs[4];
CK_ULONG count;
CK_KEY_TYPE keytype;
unsigned int nattrs = 0;
int r;
#ifdef PKINIT_USE_KEY_USAGE
CK_BBOOL true_false;
#endif
cls = CKO_PRIVATE_KEY;
attrs[nattrs].type = CKA_CLASS;
attrs[nattrs].pValue = &cls;
attrs[nattrs].ulValueLen = sizeof cls;
nattrs++;
#ifdef PKINIT_USE_KEY_USAGE
/*
* Some cards get confused if you try to specify a key usage,
* so don't, and hope for the best. This will fail if you have
* several keys with the same id and different usages but I have
* not seen this on real cards.
*/
true_false = TRUE;
attrs[nattrs].type = usage;
attrs[nattrs].pValue = &true_false;
attrs[nattrs].ulValueLen = sizeof true_false;
nattrs++;
#endif
keytype = CKK_RSA;
attrs[nattrs].type = CKA_KEY_TYPE;
attrs[nattrs].pValue = &keytype;
attrs[nattrs].ulValueLen = sizeof keytype;
nattrs++;
attrs[nattrs].type = CKA_ID;
attrs[nattrs].pValue = id_cryptoctx->cert_id;
attrs[nattrs].ulValueLen = id_cryptoctx->cert_id_len;
nattrs++;
r = id_cryptoctx->p11->C_FindObjectsInit(id_cryptoctx->session, attrs, nattrs);
if (r != CKR_OK) {
pkiDebug("krb5_pkinit_sign_data: C_FindObjectsInit: %s\n",
pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
r = id_cryptoctx->p11->C_FindObjects(id_cryptoctx->session, objp, 1, &count);
id_cryptoctx->p11->C_FindObjectsFinal(id_cryptoctx->session);
pkiDebug("found %d private keys (%s)\n", (int) count, pkinit_pkcs11_code_to_text(r));
if (r != CKR_OK || count < 1)
return KRB5KDC_ERR_PREAUTH_FAILED;
return 0;
}
#endif
static krb5_error_code
pkinit_decode_data_fs(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
const uint8_t *data, unsigned int data_len,
uint8_t **decoded_data, unsigned int *decoded_data_len)
{
X509 *cert = sk_X509_value(id_cryptoctx->my_certs,
id_cryptoctx->cert_index);
EVP_PKEY *pkey = id_cryptoctx->my_key;
uint8_t *buf;
int buf_len, decrypt_len;
*decoded_data = NULL;
*decoded_data_len = 0;
if (cert != NULL && !X509_check_private_key(cert, pkey)) {
pkiDebug("private key does not match certificate\n");
return KRB5KDC_ERR_PREAUTH_FAILED;
}
buf_len = EVP_PKEY_size(pkey);
buf = malloc(buf_len + 10);
if (buf == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
decrypt_len = EVP_PKEY_decrypt_old(buf, data, data_len, pkey);
if (decrypt_len <= 0) {
pkiDebug("unable to decrypt received data (len=%d)\n", data_len);
free(buf);
return KRB5KDC_ERR_PREAUTH_FAILED;
}
*decoded_data = buf;
*decoded_data_len = decrypt_len;
return 0;
}
#ifndef WITHOUT_PKCS11
/*
* When using the ActivCard Linux pkcs11 library (v2.0.1), the decrypt function
* fails. By inserting an extra function call, which serves nothing but to
* change the stack, we were able to work around the issue. If the ActivCard
* library is fixed in the future, this function can be inlined back into the
* caller.
*/
static CK_RV
pkinit_C_Decrypt(pkinit_identity_crypto_context id_cryptoctx,
CK_BYTE_PTR pEncryptedData,
CK_ULONG ulEncryptedDataLen,
CK_BYTE_PTR pData,
CK_ULONG_PTR pulDataLen)
{
CK_RV rv = CKR_OK;
rv = id_cryptoctx->p11->C_Decrypt(id_cryptoctx->session, pEncryptedData,
ulEncryptedDataLen, pData, pulDataLen);
if (rv == CKR_OK) {
pkiDebug("pData %p *pulDataLen %d\n", (void *) pData,
(int) *pulDataLen);
}
return rv;
}
static krb5_error_code
pkinit_decode_data_pkcs11(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
const uint8_t *data, unsigned int data_len,
uint8_t **decoded_data,
unsigned int *decoded_data_len)
{
CK_OBJECT_HANDLE obj;
CK_ULONG len;
CK_MECHANISM mech;
uint8_t *cp;
int r;
*decoded_data = NULL;
*decoded_data_len = 0;
if (pkinit_open_session(context, id_cryptoctx)) {
pkiDebug("can't open pkcs11 session\n");
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkinit_find_private_key(id_cryptoctx, CKA_DECRYPT, &obj);
mech.mechanism = CKM_RSA_PKCS;
mech.pParameter = NULL;
mech.ulParameterLen = 0;
if ((r = id_cryptoctx->p11->C_DecryptInit(id_cryptoctx->session, &mech,
obj)) != CKR_OK) {
pkiDebug("C_DecryptInit: 0x%x\n", (int) r);
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkiDebug("data_len = %d\n", data_len);
cp = malloc((size_t) data_len);
if (cp == NULL)
return ENOMEM;
len = data_len;
pkiDebug("session %p edata %p edata_len %d data %p datalen @%p %d\n",
(void *) id_cryptoctx->session, (void *) data, (int) data_len,
(void *) cp, (void *) &len, (int) len);
r = pkinit_C_Decrypt(id_cryptoctx, (CK_BYTE_PTR) data, (CK_ULONG) data_len,
cp, &len);
if (r != CKR_OK) {
pkiDebug("C_Decrypt: %s\n", pkinit_pkcs11_code_to_text(r));
if (r == CKR_BUFFER_TOO_SMALL)
pkiDebug("decrypt %d needs %d\n", (int) data_len, (int) len);
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkiDebug("decrypt %d -> %d\n", (int) data_len, (int) len);
*decoded_data_len = len;
*decoded_data = cp;
return 0;
}
#endif
krb5_error_code
pkinit_decode_data(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
const uint8_t *data, unsigned int data_len,
uint8_t **decoded_data, unsigned int *decoded_data_len)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
*decoded_data = NULL;
*decoded_data_len = 0;
if (id_cryptoctx->pkcs11_method != 1)
retval = pkinit_decode_data_fs(context, id_cryptoctx, data, data_len,
decoded_data, decoded_data_len);
#ifndef WITHOUT_PKCS11
else
retval = pkinit_decode_data_pkcs11(context, id_cryptoctx, data,
data_len, decoded_data, decoded_data_len);
#endif
return retval;
}
static krb5_error_code
pkinit_sign_data_fs(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data,
unsigned int data_len,
unsigned char **sig,
unsigned int *sig_len)
{
if (create_signature(sig, sig_len, data, data_len,
id_cryptoctx->my_key) != 0) {
pkiDebug("failed to create the signature\n");
return KRB5KDC_ERR_PREAUTH_FAILED;
}
return 0;
}
#ifndef WITHOUT_PKCS11
static krb5_error_code
pkinit_sign_data_pkcs11(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data,
unsigned int data_len,
unsigned char **sig,
unsigned int *sig_len)
{
CK_OBJECT_HANDLE obj;
CK_ULONG len;
CK_MECHANISM mech;
unsigned char *cp;
int r;
if (pkinit_open_session(context, id_cryptoctx)) {
pkiDebug("can't open pkcs11 session\n");
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkinit_find_private_key(id_cryptoctx, CKA_SIGN, &obj);
mech.mechanism = id_cryptoctx->mech;
mech.pParameter = NULL;
mech.ulParameterLen = 0;
if ((r = id_cryptoctx->p11->C_SignInit(id_cryptoctx->session, &mech,
obj)) != CKR_OK) {
pkiDebug("C_SignInit: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
/*
* Key len would give an upper bound on sig size, but there's no way to
* get that. So guess, and if it's too small, re-malloc.
*/
len = PK_SIGLEN_GUESS;
cp = malloc((size_t) len);
if (cp == NULL)
return ENOMEM;
r = id_cryptoctx->p11->C_Sign(id_cryptoctx->session, data,
(CK_ULONG) data_len, cp, &len);
if (r == CKR_BUFFER_TOO_SMALL || (r == CKR_OK && len >= PK_SIGLEN_GUESS)) {
free(cp);
pkiDebug("C_Sign realloc %d\n", (int) len);
cp = malloc((size_t) len);
r = id_cryptoctx->p11->C_Sign(id_cryptoctx->session, data,
(CK_ULONG) data_len, cp, &len);
}
if (r != CKR_OK) {
pkiDebug("C_Sign: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkiDebug("sign %d -> %d\n", (int) data_len, (int) len);
*sig_len = len;
*sig = cp;
return 0;
}
#endif
krb5_error_code
pkinit_sign_data(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char *data,
unsigned int data_len,
unsigned char **sig,
unsigned int *sig_len)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
if (id_cryptoctx == NULL || id_cryptoctx->pkcs11_method != 1)
retval = pkinit_sign_data_fs(context, id_cryptoctx, data, data_len,
sig, sig_len);
#ifndef WITHOUT_PKCS11
else
retval = pkinit_sign_data_pkcs11(context, id_cryptoctx, data, data_len,
sig, sig_len);
#endif
return retval;
}
static krb5_error_code
create_signature(unsigned char **sig, unsigned int *sig_len,
unsigned char *data, unsigned int data_len, EVP_PKEY *pkey)
{
krb5_error_code retval = ENOMEM;
EVP_MD_CTX *ctx;
if (pkey == NULL)
return retval;
ctx = EVP_MD_CTX_new();
if (ctx == NULL)
return ENOMEM;
EVP_SignInit(ctx, EVP_sha1());
EVP_SignUpdate(ctx, data, data_len);
*sig_len = EVP_PKEY_size(pkey);
if ((*sig = malloc(*sig_len)) == NULL)
goto cleanup;
EVP_SignFinal(ctx, *sig, sig_len, pkey);
retval = 0;
cleanup:
EVP_MD_CTX_free(ctx);
return retval;
}
/*
* Note:
* This is not the routine the KDC uses to get its certificate.
* This routine is intended to be called by the client
* to obtain the KDC's certificate from some local storage
* to be sent as a hint in its request to the KDC.
*/
krb5_error_code
pkinit_get_kdc_cert(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
req_cryptoctx->received_cert = NULL;
retval = 0;
return retval;
}
static char *
reassemble_pkcs12_name(const char *filename)
{
char *ret;
if (asprintf(&ret, "PKCS12:%s", filename) < 0)
return NULL;
return ret;
}
static krb5_error_code
pkinit_get_certs_pkcs12(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
char *prompt_string = NULL;
X509 *x = NULL;
PKCS12 *p12 = NULL;
int ret;
FILE *fp;
EVP_PKEY *y = NULL;
if (idopts->cert_filename == NULL) {
pkiDebug("%s: failed to get user's cert location\n", __FUNCTION__);
goto cleanup;
}
if (idopts->key_filename == NULL) {
pkiDebug("%s: failed to get user's private key location\n", __FUNCTION__);
goto cleanup;
}
fp = fopen(idopts->cert_filename, "rb");
if (fp == NULL) {
TRACE_PKINIT_PKCS_OPEN_FAIL(context, idopts->cert_filename, errno);
goto cleanup;
}
set_cloexec_file(fp);
p12 = d2i_PKCS12_fp(fp, NULL);
fclose(fp);
if (p12 == NULL) {
TRACE_PKINIT_PKCS_DECODE_FAIL(context, idopts->cert_filename);
goto cleanup;
}
/*
* Try parsing with no pass phrase first. If that fails,
* prompt for the pass phrase and try again.
*/
ret = PKCS12_parse(p12, NULL, &y, &x, NULL);
if (ret == 0) {
krb5_data rdat;
krb5_prompt kprompt;
krb5_prompt_type prompt_type;
krb5_error_code r;
char prompt_reply[128];
char *prompt_prefix = _("Pass phrase for");
char *p12name = reassemble_pkcs12_name(idopts->cert_filename);
const char *tmp;
TRACE_PKINIT_PKCS_PARSE_FAIL_FIRST(context);
if (id_cryptoctx->defer_id_prompt) {
/* Supply the identity name to be passed to the responder. */
pkinit_set_deferred_id(&id_cryptoctx->deferred_ids, p12name, 0,
NULL);
free(p12name);
retval = 0;
goto cleanup;
}
/* Try to read a responder-supplied password. */
tmp = pkinit_find_deferred_id(id_cryptoctx->deferred_ids, p12name);
free(p12name);
if (tmp != NULL) {
/* Try using the responder-supplied password. */
rdat.data = (char *)tmp;
rdat.length = strlen(tmp);
} else if (id_cryptoctx->prompter == NULL) {
/* We can't use a prompter. */
goto cleanup;
} else {
/* Ask using a prompter. */
memset(prompt_reply, '\0', sizeof(prompt_reply));
rdat.data = prompt_reply;
rdat.length = sizeof(prompt_reply);
if (asprintf(&prompt_string, "%s %s", prompt_prefix,
idopts->cert_filename) < 0) {
prompt_string = NULL;
goto cleanup;
}
kprompt.prompt = prompt_string;
kprompt.hidden = 1;
kprompt.reply = &rdat;
prompt_type = KRB5_PROMPT_TYPE_PREAUTH;
/* PROMPTER_INVOCATION */
k5int_set_prompt_types(context, &prompt_type);
r = (*id_cryptoctx->prompter)(context, id_cryptoctx->prompter_data,
NULL, NULL, 1, &kprompt);
k5int_set_prompt_types(context, 0);
if (r) {
TRACE_PKINIT_PKCS_PROMPT_FAIL(context);
goto cleanup;
}
}
ret = PKCS12_parse(p12, rdat.data, &y, &x, NULL);
if (ret == 0) {
TRACE_PKINIT_PKCS_PARSE_FAIL_SECOND(context);
goto cleanup;
}
}
id_cryptoctx->creds[0] = malloc(sizeof(struct _pkinit_cred_info));
if (id_cryptoctx->creds[0] == NULL)
goto cleanup;
id_cryptoctx->creds[0]->name =
reassemble_pkcs12_name(idopts->cert_filename);
id_cryptoctx->creds[0]->cert = x;
#ifndef WITHOUT_PKCS11
id_cryptoctx->creds[0]->cert_id = NULL;
id_cryptoctx->creds[0]->cert_id_len = 0;
#endif
id_cryptoctx->creds[0]->key = y;
id_cryptoctx->creds[1] = NULL;
retval = 0;
cleanup:
free(prompt_string);
if (p12)
PKCS12_free(p12);
if (retval) {
if (x != NULL)
X509_free(x);
if (y != NULL)
EVP_PKEY_free(y);
}
return retval;
}
static char *
reassemble_files_name(const char *certfile, const char *keyfile)
{
char *ret;
if (keyfile != NULL) {
if (asprintf(&ret, "FILE:%s,%s", certfile, keyfile) < 0)
return NULL;
} else {
if (asprintf(&ret, "FILE:%s", certfile) < 0)
return NULL;
}
return ret;
}
static krb5_error_code
pkinit_load_fs_cert_and_key(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
char *certname,
char *keyname,
int cindex)
{
krb5_error_code retval;
X509 *x = NULL;
EVP_PKEY *y = NULL;
char *fsname = NULL;
const char *password;
fsname = reassemble_files_name(certname, keyname);
/* Try to read a responder-supplied password. */
password = pkinit_find_deferred_id(id_cryptoctx->deferred_ids, fsname);
/* Load the certificate. */
retval = get_cert(certname, &x);
if (retval != 0 || x == NULL) {
retval = oerr(context, 0, _("Cannot read certificate file '%s'"),
certname);
goto cleanup;
}
/* Load the key. */
retval = get_key(context, id_cryptoctx, keyname, fsname, &y, password);
if (retval != 0 || y == NULL) {
retval = oerr(context, 0, _("Cannot read key file '%s'"), fsname);
goto cleanup;
}
id_cryptoctx->creds[cindex] = malloc(sizeof(struct _pkinit_cred_info));
if (id_cryptoctx->creds[cindex] == NULL) {
retval = ENOMEM;
goto cleanup;
}
id_cryptoctx->creds[cindex]->name = reassemble_files_name(certname,
keyname);
id_cryptoctx->creds[cindex]->cert = x;
#ifndef WITHOUT_PKCS11
id_cryptoctx->creds[cindex]->cert_id = NULL;
id_cryptoctx->creds[cindex]->cert_id_len = 0;
#endif
id_cryptoctx->creds[cindex]->key = y;
id_cryptoctx->creds[cindex+1] = NULL;
retval = 0;
cleanup:
free(fsname);
if (retval != 0 || y == NULL) {
if (x != NULL)
X509_free(x);
if (y != NULL)
EVP_PKEY_free(y);
}
return retval;
}
static krb5_error_code
pkinit_get_certs_fs(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ)
{
krb5_error_code retval = KRB5KDC_ERR_PREAUTH_FAILED;
if (idopts->cert_filename == NULL) {
pkiDebug("%s: failed to get user's cert location\n", __FUNCTION__);
goto cleanup;
}
if (idopts->key_filename == NULL) {
TRACE_PKINIT_NO_PRIVKEY(context);
goto cleanup;
}
retval = pkinit_load_fs_cert_and_key(context, id_cryptoctx,
idopts->cert_filename,
idopts->key_filename, 0);
cleanup:
return retval;
}
static krb5_error_code
pkinit_get_certs_dir(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ)
{
krb5_error_code retval = ENOMEM;
DIR *d = NULL;
struct dirent *dentry = NULL;
char certname[1024];
char keyname[1024];
int i = 0, len;
char *dirname, *suf;
if (idopts->cert_filename == NULL) {
TRACE_PKINIT_NO_CERT(context);
return ENOENT;
}
dirname = idopts->cert_filename;
d = opendir(dirname);
if (d == NULL)
return errno;
/*
* We'll assume that certs are named XXX.crt and the corresponding
* key is named XXX.key
*/
while ((i < MAX_CREDS_ALLOWED) && (dentry = readdir(d)) != NULL) {
/* Ignore subdirectories and anything starting with a dot */
#ifdef DT_DIR
if (dentry->d_type == DT_DIR)
continue;
#endif
if (dentry->d_name[0] == '.')
continue;
len = strlen(dentry->d_name);
if (len < 5)
continue;
suf = dentry->d_name + (len - 4);
if (strncmp(suf, ".crt", 4) != 0)
continue;
/* Checked length */
if (strlen(dirname) + strlen(dentry->d_name) + 2 > sizeof(certname)) {
pkiDebug("%s: Path too long -- directory '%s' and file '%s'\n",
__FUNCTION__, dirname, dentry->d_name);
continue;
}
snprintf(certname, sizeof(certname), "%s/%s", dirname, dentry->d_name);
snprintf(keyname, sizeof(keyname), "%s/%s", dirname, dentry->d_name);
len = strlen(keyname);
keyname[len - 3] = 'k';
keyname[len - 2] = 'e';
keyname[len - 1] = 'y';
retval = pkinit_load_fs_cert_and_key(context, id_cryptoctx,
certname, keyname, i);
if (retval == 0) {
TRACE_PKINIT_LOADED_CERT(context, dentry->d_name);
i++;
}
else
continue;
}
if (!id_cryptoctx->defer_id_prompt && i == 0) {
TRACE_PKINIT_NO_CERT_AND_KEY(context, idopts->cert_filename);
retval = ENOENT;
goto cleanup;
}
retval = 0;
cleanup:
if (d)
closedir(d);
return retval;
}
#ifndef WITHOUT_PKCS11
static char *
reassemble_pkcs11_name(pkinit_identity_opts *idopts)
{
struct k5buf buf;
int n = 0;
char *ret;
k5_buf_init_dynamic(&buf);
k5_buf_add(&buf, "PKCS11:");
n = 0;
if (idopts->p11_module_name != NULL) {
k5_buf_add_fmt(&buf, "%smodule_name=%s", n++ ? ":" : "",
idopts->p11_module_name);
}
if (idopts->token_label != NULL) {
k5_buf_add_fmt(&buf, "%stoken=%s", n++ ? ":" : "",
idopts->token_label);
}
if (idopts->cert_label != NULL) {
k5_buf_add_fmt(&buf, "%scertlabel=%s", n++ ? ":" : "",
idopts->cert_label);
}
if (idopts->cert_id_string != NULL) {
k5_buf_add_fmt(&buf, "%scertid=%s", n++ ? ":" : "",
idopts->cert_id_string);
}
if (idopts->slotid != PK_NOSLOT) {
k5_buf_add_fmt(&buf, "%sslotid=%ld", n++ ? ":" : "",
(long)idopts->slotid);
}
if (k5_buf_status(&buf) == 0)
ret = strdup(buf.data);
else
ret = NULL;
k5_buf_free(&buf);
return ret;
}
static krb5_error_code
pkinit_get_certs_pkcs11(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ)
{
#ifdef PKINIT_USE_MECH_LIST
CK_MECHANISM_TYPE_PTR mechp;
CK_MECHANISM_INFO info;
#endif
CK_OBJECT_CLASS cls;
CK_OBJECT_HANDLE obj;
CK_ATTRIBUTE attrs[4];
CK_ULONG count;
CK_CERTIFICATE_TYPE certtype;
CK_BYTE_PTR cert = NULL, cert_id;
const unsigned char *cp;
int i, r;
unsigned int nattrs;
X509 *x = NULL;
/* Copy stuff from idopts -> id_cryptoctx */
if (idopts->p11_module_name != NULL) {
free(id_cryptoctx->p11_module_name);
id_cryptoctx->p11_module_name = strdup(idopts->p11_module_name);
if (id_cryptoctx->p11_module_name == NULL)
return ENOMEM;
}
if (idopts->token_label != NULL) {
id_cryptoctx->token_label = strdup(idopts->token_label);
if (id_cryptoctx->token_label == NULL)
return ENOMEM;
}
if (idopts->cert_label != NULL) {
id_cryptoctx->cert_label = strdup(idopts->cert_label);
if (id_cryptoctx->cert_label == NULL)
return ENOMEM;
}
/* Convert the ascii cert_id string into a binary blob */
if (idopts->cert_id_string != NULL) {
BIGNUM *bn = NULL;
BN_hex2bn(&bn, idopts->cert_id_string);
if (bn == NULL)
return ENOMEM;
id_cryptoctx->cert_id_len = BN_num_bytes(bn);
id_cryptoctx->cert_id = malloc((size_t) id_cryptoctx->cert_id_len);
if (id_cryptoctx->cert_id == NULL) {
BN_free(bn);
return ENOMEM;
}
BN_bn2bin(bn, id_cryptoctx->cert_id);
BN_free(bn);
}
id_cryptoctx->slotid = idopts->slotid;
id_cryptoctx->pkcs11_method = 1;
if (pkinit_open_session(context, id_cryptoctx)) {
pkiDebug("can't open pkcs11 session\n");
if (!id_cryptoctx->defer_id_prompt)
return KRB5KDC_ERR_PREAUTH_FAILED;
}
if (id_cryptoctx->defer_id_prompt) {
/*
* We need to reset all of the PKCS#11 state, so that the next time we
* poke at it, it'll be in as close to the state it was in after we
* loaded it the first time as we can make it.
*/
pkinit_fini_pkcs11(id_cryptoctx);
pkinit_init_pkcs11(id_cryptoctx);
return 0;
}
#ifndef PKINIT_USE_MECH_LIST
/*
* We'd like to use CKM_SHA1_RSA_PKCS for signing if it's available, but
* many cards seems to be confused about whether they are capable of
* this or not. The safe thing seems to be to ignore the mechanism list,
* always use CKM_RSA_PKCS and calculate the sha1 digest ourselves.
*/
id_cryptoctx->mech = CKM_RSA_PKCS;
#else
if ((r = id_cryptoctx->p11->C_GetMechanismList(id_cryptoctx->slotid, NULL,
&count)) != CKR_OK || count <= 0) {
pkiDebug("C_GetMechanismList: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
mechp = malloc(count * sizeof (CK_MECHANISM_TYPE));
if (mechp == NULL)
return ENOMEM;
if ((r = id_cryptoctx->p11->C_GetMechanismList(id_cryptoctx->slotid,
mechp, &count)) != CKR_OK)
return KRB5KDC_ERR_PREAUTH_FAILED;
for (i = 0; i < count; i++) {
if ((r = id_cryptoctx->p11->C_GetMechanismInfo(id_cryptoctx->slotid,
mechp[i], &info)) != CKR_OK)
return KRB5KDC_ERR_PREAUTH_FAILED;
#ifdef DEBUG_MECHINFO
pkiDebug("mech %x flags %x\n", (int) mechp[i], (int) info.flags);
if ((info.flags & (CKF_SIGN|CKF_DECRYPT)) == (CKF_SIGN|CKF_DECRYPT))
pkiDebug(" this mech is good for sign & decrypt\n");
#endif
if (mechp[i] == CKM_RSA_PKCS) {
/* This seems backwards... */
id_cryptoctx->mech =
(info.flags & CKF_SIGN) ? CKM_SHA1_RSA_PKCS : CKM_RSA_PKCS;
}
}
free(mechp);
pkiDebug("got %d mechs from card\n", (int) count);
#endif
cls = CKO_CERTIFICATE;
attrs[0].type = CKA_CLASS;
attrs[0].pValue = &cls;
attrs[0].ulValueLen = sizeof cls;
certtype = CKC_X_509;
attrs[1].type = CKA_CERTIFICATE_TYPE;
attrs[1].pValue = &certtype;
attrs[1].ulValueLen = sizeof certtype;
nattrs = 2;
/* If a cert id and/or label were given, use them too */
if (id_cryptoctx->cert_id_len > 0) {
attrs[nattrs].type = CKA_ID;
attrs[nattrs].pValue = id_cryptoctx->cert_id;
attrs[nattrs].ulValueLen = id_cryptoctx->cert_id_len;
nattrs++;
}
if (id_cryptoctx->cert_label != NULL) {
attrs[nattrs].type = CKA_LABEL;
attrs[nattrs].pValue = id_cryptoctx->cert_label;
attrs[nattrs].ulValueLen = strlen(id_cryptoctx->cert_label);
nattrs++;
}
r = id_cryptoctx->p11->C_FindObjectsInit(id_cryptoctx->session, attrs, nattrs);
if (r != CKR_OK) {
pkiDebug("C_FindObjectsInit: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
for (i = 0; ; i++) {
if (i >= MAX_CREDS_ALLOWED)
return KRB5KDC_ERR_PREAUTH_FAILED;
/* Look for x.509 cert */
if ((r = id_cryptoctx->p11->C_FindObjects(id_cryptoctx->session,
&obj, 1, &count)) != CKR_OK || count <= 0) {
id_cryptoctx->creds[i] = NULL;
break;
}
/* Get cert and id len */
attrs[0].type = CKA_VALUE;
attrs[0].pValue = NULL;
attrs[0].ulValueLen = 0;
attrs[1].type = CKA_ID;
attrs[1].pValue = NULL;
attrs[1].ulValueLen = 0;
if ((r = id_cryptoctx->p11->C_GetAttributeValue(id_cryptoctx->session,
obj, attrs, 2)) != CKR_OK && r != CKR_BUFFER_TOO_SMALL) {
pkiDebug("C_GetAttributeValue: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
cert = (CK_BYTE_PTR) malloc((size_t) attrs[0].ulValueLen + 1);
cert_id = (CK_BYTE_PTR) malloc((size_t) attrs[1].ulValueLen + 1);
if (cert == NULL || cert_id == NULL)
return ENOMEM;
/* Read the cert and id off the card */
attrs[0].type = CKA_VALUE;
attrs[0].pValue = cert;
attrs[1].type = CKA_ID;
attrs[1].pValue = cert_id;
if ((r = id_cryptoctx->p11->C_GetAttributeValue(id_cryptoctx->session,
obj, attrs, 2)) != CKR_OK) {
pkiDebug("C_GetAttributeValue: %s\n", pkinit_pkcs11_code_to_text(r));
return KRB5KDC_ERR_PREAUTH_FAILED;
}
pkiDebug("cert %d size %d id %d idlen %d\n", i,
(int) attrs[0].ulValueLen, (int) cert_id[0],
(int) attrs[1].ulValueLen);
cp = (unsigned char *) cert;
x = d2i_X509(NULL, &cp, (int) attrs[0].ulValueLen);
if (x == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
id_cryptoctx->creds[i] = malloc(sizeof(struct _pkinit_cred_info));
if (id_cryptoctx->creds[i] == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
id_cryptoctx->creds[i]->name = reassemble_pkcs11_name(idopts);
id_cryptoctx->creds[i]->cert = x;
id_cryptoctx->creds[i]->key = NULL;
id_cryptoctx->creds[i]->cert_id = cert_id;
id_cryptoctx->creds[i]->cert_id_len = attrs[1].ulValueLen;
free(cert);
}
id_cryptoctx->p11->C_FindObjectsFinal(id_cryptoctx->session);
if (cert == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
return 0;
}
#endif
static void
free_cred_info(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
struct _pkinit_cred_info *cred)
{
if (cred != NULL) {
if (cred->cert != NULL)
X509_free(cred->cert);
if (cred->key != NULL)
EVP_PKEY_free(cred->key);
#ifndef WITHOUT_PKCS11
free(cred->cert_id);
#endif
free(cred->name);
free(cred);
}
}
krb5_error_code
crypto_free_cert_info(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx)
{
int i;
if (id_cryptoctx == NULL)
return EINVAL;
for (i = 0; i < MAX_CREDS_ALLOWED; i++) {
if (id_cryptoctx->creds[i] != NULL) {
free_cred_info(context, id_cryptoctx, id_cryptoctx->creds[i]);
id_cryptoctx->creds[i] = NULL;
}
}
return 0;
}
krb5_error_code
crypto_load_certs(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
krb5_principal princ,
krb5_boolean defer_id_prompts)
{
krb5_error_code retval;
id_cryptoctx->defer_id_prompt = defer_id_prompts;
switch(idopts->idtype) {
case IDTYPE_FILE:
retval = pkinit_get_certs_fs(context, plg_cryptoctx,
req_cryptoctx, idopts,
id_cryptoctx, princ);
break;
case IDTYPE_DIR:
retval = pkinit_get_certs_dir(context, plg_cryptoctx,
req_cryptoctx, idopts,
id_cryptoctx, princ);
break;
#ifndef WITHOUT_PKCS11
case IDTYPE_PKCS11:
retval = pkinit_get_certs_pkcs11(context, plg_cryptoctx,
req_cryptoctx, idopts,
id_cryptoctx, princ);
break;
#endif
case IDTYPE_PKCS12:
retval = pkinit_get_certs_pkcs12(context, plg_cryptoctx,
req_cryptoctx, idopts,
id_cryptoctx, princ);
break;
default:
retval = EINVAL;
}
if (retval)
goto cleanup;
cleanup:
return retval;
}
/*
* Get certificate Key Usage and Extended Key Usage
*/
static krb5_error_code
crypto_retrieve_X509_key_usage(krb5_context context,
pkinit_plg_crypto_context plgcctx,
pkinit_req_crypto_context reqcctx,
X509 *x,
unsigned int *ret_ku_bits,
unsigned int *ret_eku_bits)
{
krb5_error_code retval = 0;
int i;
unsigned int eku_bits = 0, ku_bits = 0;
ASN1_BIT_STRING *usage = NULL;
if (ret_ku_bits == NULL && ret_eku_bits == NULL)
return EINVAL;
if (ret_eku_bits)
*ret_eku_bits = 0;
else {
pkiDebug("%s: EKUs not requested, not checking\n", __FUNCTION__);
goto check_kus;
}
/* Start with Extended Key usage */
i = X509_get_ext_by_NID(x, NID_ext_key_usage, -1);
if (i >= 0) {
EXTENDED_KEY_USAGE *eku;
eku = X509_get_ext_d2i(x, NID_ext_key_usage, NULL, NULL);
if (eku) {
for (i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
ASN1_OBJECT *certoid;
certoid = sk_ASN1_OBJECT_value(eku, i);
if ((OBJ_cmp(certoid, plgcctx->id_pkinit_KPClientAuth)) == 0)
eku_bits |= PKINIT_EKU_PKINIT;
else if ((OBJ_cmp(certoid, OBJ_nid2obj(NID_ms_smartcard_login))) == 0)
eku_bits |= PKINIT_EKU_MSSCLOGIN;
else if ((OBJ_cmp(certoid, OBJ_nid2obj(NID_client_auth))) == 0)
eku_bits |= PKINIT_EKU_CLIENTAUTH;
else if ((OBJ_cmp(certoid, OBJ_nid2obj(NID_email_protect))) == 0)
eku_bits |= PKINIT_EKU_EMAILPROTECTION;
}
EXTENDED_KEY_USAGE_free(eku);
}
}
pkiDebug("%s: returning eku 0x%08x\n", __FUNCTION__, eku_bits);
*ret_eku_bits = eku_bits;
check_kus:
/* Now the Key Usage bits */
if (ret_ku_bits)
*ret_ku_bits = 0;
else {
pkiDebug("%s: KUs not requested, not checking\n", __FUNCTION__);
goto out;
}
/* Make sure usage exists before checking bits */
X509_check_ca(x);
usage = X509_get_ext_d2i(x, NID_key_usage, NULL, NULL);
if (usage) {
if (!ku_reject(x, X509v3_KU_DIGITAL_SIGNATURE))
ku_bits |= PKINIT_KU_DIGITALSIGNATURE;
if (!ku_reject(x, X509v3_KU_KEY_ENCIPHERMENT))
ku_bits |= PKINIT_KU_KEYENCIPHERMENT;
ASN1_BIT_STRING_free(usage);
}
pkiDebug("%s: returning ku 0x%08x\n", __FUNCTION__, ku_bits);
*ret_ku_bits = ku_bits;
retval = 0;
out:
return retval;
}
/*
* Return a string format of an X509_NAME in buf where
* size is an in/out parameter. On input it is the size
* of the buffer, and on output it is the actual length
* of the name.
* If buf is NULL, returns the length req'd to hold name
*/
static char *
X509_NAME_oneline_ex(X509_NAME * a,
char *buf,
unsigned int *size,
unsigned long flag)
{
BIO *out = NULL;
out = BIO_new(BIO_s_mem ());
if (X509_NAME_print_ex(out, a, 0, flag) > 0) {
if (buf != NULL && (*size) > (unsigned int) BIO_number_written(out)) {
memset(buf, 0, *size);
BIO_read(out, buf, (int) BIO_number_written(out));
}
else {
*size = BIO_number_written(out);
}
}
BIO_free(out);
return (buf);
}
/*
* Get number of certificates available after crypto_load_certs()
*/
static krb5_error_code
crypto_cert_get_count(pkinit_identity_crypto_context id_cryptoctx,
int *cert_count)
{
int count;
*cert_count = 0;
if (id_cryptoctx == NULL || id_cryptoctx->creds[0] == NULL)
return EINVAL;
for (count = 0;
count <= MAX_CREDS_ALLOWED && id_cryptoctx->creds[count] != NULL;
count++);
*cert_count = count;
return 0;
}
void
crypto_cert_free_matching_data(krb5_context context,
pkinit_cert_matching_data *md)
{
int i;
if (md == NULL)
return;
free(md->subject_dn);
free(md->issuer_dn);
for (i = 0; md->sans != NULL && md->sans[i] != NULL; i++)
krb5_free_principal(context, md->sans[i]);
free(md->sans);
free(md);
}
/*
* Free certificate matching data.
*/
void
crypto_cert_free_matching_data_list(krb5_context context,
pkinit_cert_matching_data **list)
{
int i;
for (i = 0; list != NULL && list[i] != NULL; i++)
crypto_cert_free_matching_data(context, list[i]);
free(list);
}
/*
* Get certificate matching data for cert.
*/
static krb5_error_code
get_matching_data(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx, X509 *cert,
pkinit_cert_matching_data **md_out)
{
krb5_error_code ret = ENOMEM;
pkinit_cert_matching_data *md = NULL;
krb5_principal *pkinit_sans = NULL, *upn_sans = NULL;
size_t i, j;
char buf[DN_BUF_LEN];
unsigned int bufsize = sizeof(buf);
*md_out = NULL;
md = calloc(1, sizeof(*md));
if (md == NULL)
goto cleanup;
/* Get the subject name (in rfc2253 format). */
X509_NAME_oneline_ex(X509_get_subject_name(cert), buf, &bufsize,
XN_FLAG_SEP_COMMA_PLUS);
md->subject_dn = strdup(buf);
if (md->subject_dn == NULL) {
ret = ENOMEM;
goto cleanup;
}
/* Get the issuer name (in rfc2253 format). */
X509_NAME_oneline_ex(X509_get_issuer_name(cert), buf, &bufsize,
XN_FLAG_SEP_COMMA_PLUS);
md->issuer_dn = strdup(buf);
if (md->issuer_dn == NULL) {
ret = ENOMEM;
goto cleanup;
}
/* Get the SAN data. */
ret = crypto_retrieve_X509_sans(context, plg_cryptoctx, req_cryptoctx,
cert, &pkinit_sans, &upn_sans, NULL);
if (ret)
goto cleanup;
j = 0;
if (pkinit_sans != NULL) {
for (i = 0; pkinit_sans[i] != NULL; i++)
j++;
}
if (upn_sans != NULL) {
for (i = 0; upn_sans[i] != NULL; i++)
j++;
}
if (j != 0) {
md->sans = calloc((size_t)j+1, sizeof(*md->sans));
if (md->sans == NULL) {
ret = ENOMEM;
goto cleanup;
}
j = 0;
if (pkinit_sans != NULL) {
for (i = 0; pkinit_sans[i] != NULL; i++)
md->sans[j++] = pkinit_sans[i];
free(pkinit_sans);
}
if (upn_sans != NULL) {
for (i = 0; upn_sans[i] != NULL; i++)
md->sans[j++] = upn_sans[i];
free(upn_sans);
}
md->sans[j] = NULL;
} else
md->sans = NULL;
/* Get the KU and EKU data. */
ret = crypto_retrieve_X509_key_usage(context, plg_cryptoctx,
req_cryptoctx, cert, &md->ku_bits,
&md->eku_bits);
if (ret)
goto cleanup;
*md_out = md;
md = NULL;
cleanup:
crypto_cert_free_matching_data(context, md);
return ret;
}
krb5_error_code
crypto_cert_get_matching_data(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
pkinit_cert_matching_data ***md_out)
{
krb5_error_code ret;
pkinit_cert_matching_data **md_list = NULL;
int count, i;
ret = crypto_cert_get_count(id_cryptoctx, &count);
if (ret)
goto cleanup;
md_list = calloc(count + 1, sizeof(*md_list));
if (md_list == NULL) {
ret = ENOMEM;
goto cleanup;
}
for (i = 0; i < count; i++) {
ret = get_matching_data(context, plg_cryptoctx, req_cryptoctx,
id_cryptoctx->creds[i]->cert, &md_list[i]);
if (ret) {
pkiDebug("%s: crypto_cert_get_matching_data error %d, %s\n",
__FUNCTION__, ret, error_message(ret));
goto cleanup;
}
}
*md_out = md_list;
md_list = NULL;
cleanup:
crypto_cert_free_matching_data_list(context, md_list);
return ret;
}
/*
* Set the certificate in idctx->creds[cred_index] as the selected certificate.
*/
krb5_error_code
crypto_cert_select(krb5_context context, pkinit_identity_crypto_context idctx,
size_t cred_index)
{
pkinit_cred_info ci = NULL;
if (cred_index >= MAX_CREDS_ALLOWED || idctx->creds[cred_index] == NULL)
return ENOENT;
ci = idctx->creds[cred_index];
/* copy the selected cert into our id_cryptoctx */
if (idctx->my_certs != NULL)
sk_X509_pop_free(idctx->my_certs, X509_free);
idctx->my_certs = sk_X509_new_null();
sk_X509_push(idctx->my_certs, ci->cert);
free(idctx->identity);
/* hang on to the selected credential name */
if (ci->name != NULL)
idctx->identity = strdup(ci->name);
else
idctx->identity = NULL;
ci->cert = NULL; /* Don't free it twice */
idctx->cert_index = 0;
if (idctx->pkcs11_method != 1) {
idctx->my_key = ci->key;
ci->key = NULL; /* Don't free it twice */
}
#ifndef WITHOUT_PKCS11
else {
idctx->cert_id = ci->cert_id;
ci->cert_id = NULL; /* Don't free it twice */
idctx->cert_id_len = ci->cert_id_len;
}
#endif
return 0;
}
/*
* Choose the default certificate as "the chosen one"
*/
krb5_error_code
crypto_cert_select_default(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx)
{
krb5_error_code retval;
int cert_count;
retval = crypto_cert_get_count(id_cryptoctx, &cert_count);
if (retval)
goto errout;
if (cert_count != 1) {
TRACE_PKINIT_NO_DEFAULT_CERT(context, cert_count);
retval = EINVAL;
goto errout;
}
/* copy the selected cert into our id_cryptoctx */
if (id_cryptoctx->my_certs != NULL) {
sk_X509_pop_free(id_cryptoctx->my_certs, X509_free);
}
id_cryptoctx->my_certs = sk_X509_new_null();
sk_X509_push(id_cryptoctx->my_certs, id_cryptoctx->creds[0]->cert);
id_cryptoctx->creds[0]->cert = NULL; /* Don't free it twice */
id_cryptoctx->cert_index = 0;
/* hang on to the selected credential name */
if (id_cryptoctx->creds[0]->name != NULL)
id_cryptoctx->identity = strdup(id_cryptoctx->creds[0]->name);
else
id_cryptoctx->identity = NULL;
if (id_cryptoctx->pkcs11_method != 1) {
id_cryptoctx->my_key = id_cryptoctx->creds[0]->key;
id_cryptoctx->creds[0]->key = NULL; /* Don't free it twice */
}
#ifndef WITHOUT_PKCS11
else {
id_cryptoctx->cert_id = id_cryptoctx->creds[0]->cert_id;
id_cryptoctx->creds[0]->cert_id = NULL; /* Don't free it twice */
id_cryptoctx->cert_id_len = id_cryptoctx->creds[0]->cert_id_len;
}
#endif
retval = 0;
errout:
return retval;
}
static krb5_error_code
load_cas_and_crls(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int catype,
char *filename)
{
STACK_OF(X509_INFO) *sk = NULL;
STACK_OF(X509) *ca_certs = NULL;
STACK_OF(X509_CRL) *ca_crls = NULL;
BIO *in = NULL;
krb5_error_code retval = ENOMEM;
int i = 0;
/* If there isn't already a stack in the context,
* create a temporary one now */
switch(catype) {
case CATYPE_ANCHORS:
if (id_cryptoctx->trustedCAs != NULL)
ca_certs = id_cryptoctx->trustedCAs;
else {
ca_certs = sk_X509_new_null();
if (ca_certs == NULL)
return ENOMEM;
}
break;
case CATYPE_INTERMEDIATES:
if (id_cryptoctx->intermediateCAs != NULL)
ca_certs = id_cryptoctx->intermediateCAs;
else {
ca_certs = sk_X509_new_null();
if (ca_certs == NULL)
return ENOMEM;
}
break;
case CATYPE_CRLS:
if (id_cryptoctx->revoked != NULL)
ca_crls = id_cryptoctx->revoked;
else {
ca_crls = sk_X509_CRL_new_null();
if (ca_crls == NULL)
return ENOMEM;
}
break;
default:
return ENOTSUP;
}
if (!(in = BIO_new_file(filename, "r"))) {
retval = oerr(context, 0, _("Cannot open file '%s'"), filename);
goto cleanup;
}
/* This loads from a file, a stack of x509/crl/pkey sets */
if ((sk = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL)) == NULL) {
pkiDebug("%s: error reading file '%s'\n", __FUNCTION__, filename);
retval = oerr(context, 0, _("Cannot read file '%s'"), filename);
goto cleanup;
}
/* scan over the stack created from loading the file contents,
* weed out duplicates, and push new ones onto the return stack
*/
for (i = 0; i < sk_X509_INFO_num(sk); i++) {
X509_INFO *xi = sk_X509_INFO_value(sk, i);
if (xi != NULL && xi->x509 != NULL && catype != CATYPE_CRLS) {
int j = 0, size = sk_X509_num(ca_certs), flag = 0;
if (!size) {
sk_X509_push(ca_certs, xi->x509);
xi->x509 = NULL;
continue;
}
for (j = 0; j < size; j++) {
X509 *x = sk_X509_value(ca_certs, j);
flag = X509_cmp(x, xi->x509);
if (flag == 0)
break;
else
continue;
}
if (flag != 0) {
sk_X509_push(ca_certs, X509_dup(xi->x509));
}
} else if (xi != NULL && xi->crl != NULL && catype == CATYPE_CRLS) {
int j = 0, size = sk_X509_CRL_num(ca_crls), flag = 0;
if (!size) {
sk_X509_CRL_push(ca_crls, xi->crl);
xi->crl = NULL;
continue;
}
for (j = 0; j < size; j++) {
X509_CRL *x = sk_X509_CRL_value(ca_crls, j);
flag = X509_CRL_cmp(x, xi->crl);
if (flag == 0)
break;
else
continue;
}
if (flag != 0) {
sk_X509_CRL_push(ca_crls, X509_CRL_dup(xi->crl));
}
}
}
/* If we added something and there wasn't a stack in the
* context before, add the temporary stack to the context.
*/
switch(catype) {
case CATYPE_ANCHORS:
if (sk_X509_num(ca_certs) == 0) {
TRACE_PKINIT_NO_CA_ANCHOR(context, filename);
if (id_cryptoctx->trustedCAs == NULL)
sk_X509_free(ca_certs);
} else {
if (id_cryptoctx->trustedCAs == NULL)
id_cryptoctx->trustedCAs = ca_certs;
}
break;
case CATYPE_INTERMEDIATES:
if (sk_X509_num(ca_certs) == 0) {
TRACE_PKINIT_NO_CA_INTERMEDIATE(context, filename);
if (id_cryptoctx->intermediateCAs == NULL)
sk_X509_free(ca_certs);
} else {
if (id_cryptoctx->intermediateCAs == NULL)
id_cryptoctx->intermediateCAs = ca_certs;
}
break;
case CATYPE_CRLS:
if (sk_X509_CRL_num(ca_crls) == 0) {
TRACE_PKINIT_NO_CRL(context, filename);
if (id_cryptoctx->revoked == NULL)
sk_X509_CRL_free(ca_crls);
} else {
if (id_cryptoctx->revoked == NULL)
id_cryptoctx->revoked = ca_crls;
}
break;
default:
/* Should have been caught above! */
retval = EINVAL;
goto cleanup;
break;
}
retval = 0;
cleanup:
if (in != NULL)
BIO_free(in);
if (sk != NULL)
sk_X509_INFO_pop_free(sk, X509_INFO_free);
return retval;
}
static krb5_error_code
load_cas_and_crls_dir(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
int catype,
char *dirname)
{
krb5_error_code retval = EINVAL;
DIR *d = NULL;
struct dirent *dentry = NULL;
char filename[1024];
if (dirname == NULL)
return EINVAL;
d = opendir(dirname);
if (d == NULL)
return ENOENT;
while ((dentry = readdir(d))) {
if (strlen(dirname) + strlen(dentry->d_name) + 2 > sizeof(filename)) {
pkiDebug("%s: Path too long -- directory '%s' and file '%s'\n",
__FUNCTION__, dirname, dentry->d_name);
goto cleanup;
}
/* Ignore subdirectories and anything starting with a dot */
#ifdef DT_DIR
if (dentry->d_type == DT_DIR)
continue;
#endif
if (dentry->d_name[0] == '.')
continue;
snprintf(filename, sizeof(filename), "%s/%s", dirname, dentry->d_name);
retval = load_cas_and_crls(context, plg_cryptoctx, req_cryptoctx,
id_cryptoctx, catype, filename);
if (retval)
goto cleanup;
}
retval = 0;
cleanup:
if (d != NULL)
closedir(d);
return retval;
}
krb5_error_code
crypto_load_cas_and_crls(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_opts *idopts,
pkinit_identity_crypto_context id_cryptoctx,
int idtype,
int catype,
char *id)
{
switch (idtype) {
case IDTYPE_FILE:
TRACE_PKINIT_LOAD_FROM_FILE(context);
return load_cas_and_crls(context, plg_cryptoctx, req_cryptoctx,
id_cryptoctx, catype, id);
break;
case IDTYPE_DIR:
TRACE_PKINIT_LOAD_FROM_DIR(context);
return load_cas_and_crls_dir(context, plg_cryptoctx, req_cryptoctx,
id_cryptoctx, catype, id);
break;
default:
return ENOTSUP;
break;
}
}
static krb5_error_code
create_identifiers_from_stack(STACK_OF(X509) *sk,
krb5_external_principal_identifier *** ids)
{
int i = 0, sk_size = sk_X509_num(sk);
krb5_external_principal_identifier **krb5_cas = NULL;
X509 *x = NULL;
X509_NAME *xn = NULL;
unsigned char *p = NULL;
int len = 0;
PKCS7_ISSUER_AND_SERIAL *is = NULL;
char buf[DN_BUF_LEN];
*ids = NULL;
krb5_cas = calloc(sk_size + 1, sizeof(*krb5_cas));
if (krb5_cas == NULL)
return ENOMEM;
for (i = 0; i < sk_size; i++) {
krb5_cas[i] = malloc(sizeof(krb5_external_principal_identifier));
x = sk_X509_value(sk, i);
X509_NAME_oneline(X509_get_subject_name(x), buf, sizeof(buf));
pkiDebug("#%d cert= %s\n", i, buf);
/* fill-in subjectName */
krb5_cas[i]->subjectName.magic = 0;
krb5_cas[i]->subjectName.length = 0;
krb5_cas[i]->subjectName.data = NULL;
xn = X509_get_subject_name(x);
len = i2d_X509_NAME(xn, NULL);
if ((p = malloc((size_t) len)) == NULL)
goto oom;
krb5_cas[i]->subjectName.data = (char *)p;
i2d_X509_NAME(xn, &p);
krb5_cas[i]->subjectName.length = len;
/* fill-in issuerAndSerialNumber */
krb5_cas[i]->issuerAndSerialNumber.length = 0;
krb5_cas[i]->issuerAndSerialNumber.magic = 0;
krb5_cas[i]->issuerAndSerialNumber.data = NULL;
is = PKCS7_ISSUER_AND_SERIAL_new();
if (is == NULL)
goto oom;
X509_NAME_set(&is->issuer, X509_get_issuer_name(x));
ASN1_INTEGER_free(is->serial);
is->serial = ASN1_INTEGER_dup(X509_get_serialNumber(x));
if (is->serial == NULL)
goto oom;
len = i2d_PKCS7_ISSUER_AND_SERIAL(is, NULL);
p = malloc(len);
if (p == NULL)
goto oom;
krb5_cas[i]->issuerAndSerialNumber.data = (char *)p;
i2d_PKCS7_ISSUER_AND_SERIAL(is, &p);
krb5_cas[i]->issuerAndSerialNumber.length = len;
/* fill-in subjectKeyIdentifier */
krb5_cas[i]->subjectKeyIdentifier.length = 0;
krb5_cas[i]->subjectKeyIdentifier.magic = 0;
krb5_cas[i]->subjectKeyIdentifier.data = NULL;
if (X509_get_ext_by_NID(x, NID_subject_key_identifier, -1) >= 0) {
ASN1_OCTET_STRING *ikeyid;
ikeyid = X509_get_ext_d2i(x, NID_subject_key_identifier, NULL,
NULL);
if (ikeyid != NULL) {
len = i2d_ASN1_OCTET_STRING(ikeyid, NULL);
p = malloc(len);
if (p == NULL)
goto oom;
krb5_cas[i]->subjectKeyIdentifier.data = (char *)p;
i2d_ASN1_OCTET_STRING(ikeyid, &p);
krb5_cas[i]->subjectKeyIdentifier.length = len;
ASN1_OCTET_STRING_free(ikeyid);
}
}
PKCS7_ISSUER_AND_SERIAL_free(is);
is = NULL;
}
*ids = krb5_cas;
return 0;
oom:
free_krb5_external_principal_identifier(&krb5_cas);
PKCS7_ISSUER_AND_SERIAL_free(is);
return ENOMEM;
}
static krb5_error_code
create_krb5_invalidCertificates(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_external_principal_identifier *** ids)
{
krb5_error_code retval = ENOMEM;
STACK_OF(X509) *sk = NULL;
*ids = NULL;
if (req_cryptoctx->received_cert == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
sk = sk_X509_new_null();
if (sk == NULL)
goto cleanup;
sk_X509_push(sk, req_cryptoctx->received_cert);
retval = create_identifiers_from_stack(sk, ids);
sk_X509_free(sk);
cleanup:
return retval;
}
krb5_error_code
create_krb5_supportedCMSTypes(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_algorithm_identifier ***oids)
{
krb5_error_code retval = ENOMEM;
krb5_algorithm_identifier **loids = NULL;
krb5_data des3oid = {0, 8, "\x2A\x86\x48\x86\xF7\x0D\x03\x07" };
*oids = NULL;
loids = malloc(2 * sizeof(krb5_algorithm_identifier *));
if (loids == NULL)
goto cleanup;
loids[1] = NULL;
loids[0] = malloc(sizeof(krb5_algorithm_identifier));
if (loids[0] == NULL) {
free(loids);
goto cleanup;
}
retval = pkinit_copy_krb5_data(&loids[0]->algorithm, &des3oid);
if (retval) {
free(loids[0]);
free(loids);
goto cleanup;
}
loids[0]->parameters.length = 0;
loids[0]->parameters.data = NULL;
*oids = loids;
retval = 0;
cleanup:
return retval;
}
krb5_error_code
create_krb5_trustedCertifiers(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_external_principal_identifier *** ids)
{
krb5_error_code retval = ENOMEM;
STACK_OF(X509) *sk = id_cryptoctx->trustedCAs;
*ids = NULL;
if (id_cryptoctx->trustedCAs == NULL)
return KRB5KDC_ERR_PREAUTH_FAILED;
retval = create_identifiers_from_stack(sk, ids);
return retval;
}
krb5_error_code
create_issuerAndSerial(krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
unsigned char **out,
unsigned int *out_len)
{
unsigned char *p = NULL;
PKCS7_ISSUER_AND_SERIAL *is = NULL;
int len = 0;
krb5_error_code retval = ENOMEM;
X509 *cert = req_cryptoctx->received_cert;
*out = NULL;
*out_len = 0;
if (req_cryptoctx->received_cert == NULL)
return 0;
is = PKCS7_ISSUER_AND_SERIAL_new();
X509_NAME_set(&is->issuer, X509_get_issuer_name(cert));
ASN1_INTEGER_free(is->serial);
is->serial = ASN1_INTEGER_dup(X509_get_serialNumber(cert));
len = i2d_PKCS7_ISSUER_AND_SERIAL(is, NULL);
if ((p = *out = malloc((size_t) len)) == NULL)
goto cleanup;
i2d_PKCS7_ISSUER_AND_SERIAL(is, &p);
*out_len = len;
retval = 0;
cleanup:
X509_NAME_free(is->issuer);
ASN1_INTEGER_free(is->serial);
free(is);
return retval;
}
static int
pkcs7_decrypt(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
PKCS7 *p7,
BIO *data)
{
BIO *tmpmem = NULL;
int retval = 0, i = 0;
char buf[4096];
if(p7 == NULL)
return 0;
if(!PKCS7_type_is_enveloped(p7)) {
pkiDebug("wrong pkcs7 content type\n");
return 0;
}
if(!(tmpmem = pkcs7_dataDecode(context, id_cryptoctx, p7))) {
pkiDebug("unable to decrypt pkcs7 object\n");
return 0;
}
for(;;) {
i = BIO_read(tmpmem, buf, sizeof(buf));
if (i <= 0) break;
BIO_write(data, buf, i);
BIO_free_all(tmpmem);
return 1;
}
return retval;
}
krb5_error_code
pkinit_process_td_trusted_certifiers(
krb5_context context,
pkinit_plg_crypto_context plg_cryptoctx,
pkinit_req_crypto_context req_cryptoctx,
pkinit_identity_crypto_context id_cryptoctx,
krb5_external_principal_identifier **krb5_trusted_certifiers,
int td_type)
{
krb5_error_code retval = ENOMEM;
STACK_OF(X509_NAME) *sk_xn = NULL;
X509_NAME *xn = NULL;
PKCS7_ISSUER_AND_SERIAL *is = NULL;
ASN1_OCTET_STRING *id = NULL;
const unsigned char *p = NULL;
char buf[DN_BUF_LEN];
int i = 0;
if (td_type == TD_TRUSTED_CERTIFIERS)
pkiDebug("received trusted certifiers\n");
else
pkiDebug("received invalid certificate\n");
sk_xn = sk_X509_NAME_new_null();
while(krb5_trusted_certifiers[i] != NULL) {
if (krb5_trusted_certifiers[i]->subjectName.data != NULL) {
p = (unsigned char *)krb5_trusted_certifiers[i]->subjectName.data;
xn = d2i_X509_NAME(NULL, &p,
(int)krb5_trusted_certifiers[i]->subjectName.length);
if (xn == NULL)
goto cleanup;
X509_NAME_oneline(xn, buf, sizeof(buf));
if (td_type == TD_TRUSTED_CERTIFIERS)
pkiDebug("#%d cert = %s is trusted by kdc\n", i, buf);
else
pkiDebug("#%d cert = %s is invalid\n", i, buf);
sk_X509_NAME_push(sk_xn, xn);
}
if (krb5_trusted_certifiers[i]->issuerAndSerialNumber.data != NULL) {
p = (unsigned char *)
krb5_trusted_certifiers[i]->issuerAndSerialNumber.data;
is = d2i_PKCS7_ISSUER_AND_SERIAL(NULL, &p,
(int)krb5_trusted_certifiers[i]->issuerAndSerialNumber.length);
if (is == NULL)
goto cleanup;
X509_NAME_oneline(is->issuer, buf, sizeof(buf));
if (td_type == TD_TRUSTED_CERTIFIERS)
pkiDebug("#%d issuer = %s serial = %ld is trusted bu kdc\n", i,
buf, ASN1_INTEGER_get(is->serial));
else
pkiDebug("#%d issuer = %s serial = %ld is invalid\n", i, buf,
ASN1_INTEGER_get(is->serial));
PKCS7_ISSUER_AND_SERIAL_free(is);
}
if (krb5_trusted_certifiers[i]->subjectKeyIdentifier.data != NULL) {
p = (unsigned char *)
krb5_trusted_certifiers[i]->subjectKeyIdentifier.data;
id = d2i_ASN1_OCTET_STRING(NULL, &p,
(int)krb5_trusted_certifiers[i]->subjectKeyIdentifier.length);
if (id == NULL)
goto cleanup;
/* XXX */
ASN1_OCTET_STRING_free(id);
}
i++;
}
/* XXX Since we not doing anything with received trusted certifiers
* return an error. this is the place where we can pick a different
* client certificate based on the information in td_trusted_certifiers
*/
retval = KRB5KDC_ERR_PREAUTH_FAILED;
cleanup:
if (sk_xn != NULL)
sk_X509_NAME_pop_free(sk_xn, X509_NAME_free);
return retval;
}
static BIO *
pkcs7_dataDecode(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
PKCS7 *p7)
{
unsigned int eklen=0, tkeylen=0;
BIO *out=NULL,*etmp=NULL,*bio=NULL;
unsigned char *ek=NULL, *tkey=NULL;
ASN1_OCTET_STRING *data_body=NULL;
const EVP_CIPHER *evp_cipher=NULL;
EVP_CIPHER_CTX *evp_ctx=NULL;
X509_ALGOR *enc_alg=NULL;
STACK_OF(PKCS7_RECIP_INFO) *rsk=NULL;
PKCS7_RECIP_INFO *ri=NULL;
p7->state=PKCS7_S_HEADER;
rsk=p7->d.enveloped->recipientinfo;
enc_alg=p7->d.enveloped->enc_data->algorithm;
data_body=p7->d.enveloped->enc_data->enc_data;
evp_cipher=EVP_get_cipherbyobj(enc_alg->algorithm);
if (evp_cipher == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,PKCS7_R_UNSUPPORTED_CIPHER_TYPE);
goto cleanup;
}
if ((etmp=BIO_new(BIO_f_cipher())) == NULL) {
PKCS7err(PKCS7_F_PKCS7_DATADECODE,ERR_R_BIO_LIB);
goto cleanup;
}
/* It was encrypted, we need to decrypt the secret key
* with the private key */
/* RFC 4556 section 3.2.3.2 requires that there be exactly one
* recipientInfo. */
if (sk_PKCS7_RECIP_INFO_num(rsk) != 1) {
pkiDebug("invalid number of EnvelopedData RecipientInfos\n");
goto cleanup;
}
ri = sk_PKCS7_RECIP_INFO_value(rsk, 0);
(void)pkinit_decode_data(context, id_cryptoctx,
ASN1_STRING_get0_data(ri->enc_key),
ASN1_STRING_length(ri->enc_key), &ek, &eklen);
evp_ctx=NULL;
BIO_get_cipher_ctx(etmp,&evp_ctx);
if (EVP_CipherInit_ex(evp_ctx,evp_cipher,NULL,NULL,NULL,0) <= 0)
goto cleanup;
if (EVP_CIPHER_asn1_to_param(evp_ctx,enc_alg->parameter) < 0)
goto cleanup;
/* Generate a random symmetric key to avoid exposing timing data if RSA
* decryption fails the padding check. */
tkeylen = EVP_CIPHER_CTX_key_length(evp_ctx);
tkey = OPENSSL_malloc(tkeylen);
if (tkey == NULL)
goto cleanup;
if (EVP_CIPHER_CTX_rand_key(evp_ctx, tkey) <= 0)
goto cleanup;
if (ek == NULL) {
ek = tkey;
eklen = tkeylen;
tkey = NULL;
}
if (eklen != (unsigned)EVP_CIPHER_CTX_key_length(evp_ctx)) {
/* Some S/MIME clients don't use the same key
* and effective key length. The key length is
* determined by the size of the decrypted RSA key.
*/
if (!EVP_CIPHER_CTX_set_key_length(evp_ctx, (int)eklen)) {
ek = tkey;
eklen = tkeylen;
tkey = NULL;
}
}
if (EVP_CipherInit_ex(evp_ctx,NULL,NULL,ek,NULL,0) <= 0)
goto cleanup;
if (out == NULL)
out=etmp;
else
BIO_push(out,etmp);
etmp=NULL;
if (data_body->length > 0)
bio = BIO_new_mem_buf(data_body->data, data_body->length);
else {
bio=BIO_new(BIO_s_mem());
BIO_set_mem_eof_return(bio,0);
}
BIO_push(out,bio);
bio=NULL;
if (0) {
cleanup:
if (out != NULL) BIO_free_all(out);
if (etmp != NULL) BIO_free_all(etmp);
if (bio != NULL) BIO_free_all(bio);
out=NULL;
}
if (ek != NULL) {
OPENSSL_cleanse(ek, eklen);
OPENSSL_free(ek);
}
if (tkey != NULL) {
OPENSSL_cleanse(tkey, tkeylen);
OPENSSL_free(tkey);
}
return(out);
}
#ifdef DEBUG_DH
static void
print_dh(DH * dh, char *msg)
{
BIO *bio_err = NULL;
bio_err = BIO_new(BIO_s_file());
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
if (msg)
BIO_puts(bio_err, (const char *)msg);
if (dh)
DHparams_print(bio_err, dh);
BIO_puts(bio_err, "private key: ");
BN_print(bio_err, dh->priv_key);
BIO_puts(bio_err, (const char *)"\n");
BIO_free(bio_err);
}
static void
print_pubkey(BIGNUM * key, char *msg)
{
BIO *bio_err = NULL;
bio_err = BIO_new(BIO_s_file());
BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT);
if (msg)
BIO_puts(bio_err, (const char *)msg);
if (key)
BN_print(bio_err, key);
BIO_puts(bio_err, "\n");
BIO_free(bio_err);
}
#endif
static char *
pkinit_pkcs11_code_to_text(int err)
{
int i;
static char uc[32];
for (i = 0; pkcs11_errstrings[i].text != NULL; i++)
if (pkcs11_errstrings[i].code == err)
break;
if (pkcs11_errstrings[i].text != NULL)
return (pkcs11_errstrings[i].text);
snprintf(uc, sizeof(uc), _("unknown code 0x%x"), err);
return (uc);
}
/*
* Add an item to the pkinit_identity_crypto_context's list of deferred
* identities.
*/
krb5_error_code
crypto_set_deferred_id(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx,
const char *identity, const char *password)
{
unsigned long ck_flags;
ck_flags = pkinit_get_deferred_id_flags(id_cryptoctx->deferred_ids,
identity);
return pkinit_set_deferred_id(&id_cryptoctx->deferred_ids,
identity, ck_flags, password);
}
/*
* Retrieve a read-only copy of the pkinit_identity_crypto_context's list of
* deferred identities, sure to be valid only until the next time someone calls
* either pkinit_set_deferred_id() or crypto_set_deferred_id().
*/
const pkinit_deferred_id *
crypto_get_deferred_ids(krb5_context context,
pkinit_identity_crypto_context id_cryptoctx)
{
pkinit_deferred_id *deferred;
const pkinit_deferred_id *ret;
deferred = id_cryptoctx->deferred_ids;
ret = (const pkinit_deferred_id *)deferred;
return ret;
}
/* Return the received certificate as DER-encoded data. */
krb5_error_code
crypto_encode_der_cert(krb5_context context, pkinit_req_crypto_context reqctx,
uint8_t **der_out, size_t *der_len)
{
int len;
unsigned char *der, *p;
*der_out = NULL;
*der_len = 0;
if (reqctx->received_cert == NULL)
return EINVAL;
p = NULL;
len = i2d_X509(reqctx->received_cert, NULL);
if (len <= 0)
return EINVAL;
p = der = malloc(len);
if (der == NULL)
return ENOMEM;
if (i2d_X509(reqctx->received_cert, &p) <= 0) {
free(der);
return EINVAL;
}
*der_out = der;
*der_len = len;
return 0;
}
/*
* Get the certificate matching data from the request certificate.
*/
krb5_error_code
crypto_req_cert_matching_data(krb5_context context,
pkinit_plg_crypto_context plgctx,
pkinit_req_crypto_context reqctx,
pkinit_cert_matching_data **md_out)
{
*md_out = NULL;
if (reqctx == NULL || reqctx->received_cert == NULL)
return ENOENT;
return get_matching_data(context, plgctx, reqctx, reqctx->received_cert,
md_out);
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/bad_3281_0 |
crossvul-cpp_data_good_5268_0 | /*
* IRC - Internet Relay Chat, ircd/m_authenticate.c
* Copyright (C) 2013 Matthew Beeching (Jobe)
* Copyright (C) 1990 Jarkko Oikarinen and
* University of Oulu, Computing Center
*
* See file AUTHORS in IRC package for additional names of
* the programmers.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 1, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id:$
*/
/*
* m_functions execute protocol messages on this server:
*
* cptr is always NON-NULL, pointing to a *LOCAL* client
* structure (with an open socket connected!). This
* identifies the physical socket where the message
* originated (or which caused the m_function to be
* executed--some m_functions may call others...).
*
* sptr is the source of the message, defined by the
* prefix part of the message if present. If not
* or prefix not found, then sptr==cptr.
*
* (!IsServer(cptr)) => (cptr == sptr), because
* prefixes are taken *only* from servers...
*
* (IsServer(cptr))
* (sptr == cptr) => the message didn't
* have the prefix.
*
* (sptr != cptr && IsServer(sptr) means
* the prefix specified servername. (?)
*
* (sptr != cptr && !IsServer(sptr) means
* that message originated from a remote
* user (not local).
*
* combining
*
* (!IsServer(sptr)) means that, sptr can safely
* taken as defining the target structure of the
* message in this server.
*
* *Always* true (if 'parse' and others are working correct):
*
* 1) sptr->from == cptr (note: cptr->from == cptr)
*
* 2) MyConnect(sptr) <=> sptr == cptr (e.g. sptr
* *cannot* be a local connection, unless it's
* actually cptr!). [MyConnect(x) should probably
* be defined as (x == x->from) --msa ]
*
* parc number of variable parameter strings (if zero,
* parv is allowed to be NULL)
*
* parv a NULL terminated list of parameter pointers,
*
* parv[0], sender (prefix string), if not present
* this points to an empty string.
* parv[1]...parv[parc-1]
* pointers to additional parameters
* parv[parc] == NULL, *always*
*
* note: it is guaranteed that parv[0]..parv[parc-1] are all
* non-NULL pointers.
*/
#include "config.h"
#include "client.h"
#include "ircd.h"
#include "ircd_features.h"
#include "ircd_log.h"
#include "ircd_reply.h"
#include "ircd_string.h"
#include "ircd_snprintf.h"
#include "msg.h"
#include "numeric.h"
#include "numnicks.h"
#include "random.h"
#include "send.h"
#include "s_misc.h"
#include "s_user.h"
/* #include <assert.h> -- Now using assert in ircd_log.h */
static void sasl_timeout_callback(struct Event* ev);
int m_authenticate(struct Client* cptr, struct Client* sptr, int parc, char* parv[])
{
struct Client* acptr;
int first = 0;
char realhost[HOSTLEN + 3];
char *hoststr = (cli_sockhost(cptr) ? cli_sockhost(cptr) : cli_sock_ip(cptr));
if (!CapActive(cptr, CAP_SASL))
return 0;
if (parc < 2) /* have enough parameters? */
return need_more_params(cptr, "AUTHENTICATE");
if (strlen(parv[1]) > 400)
return send_reply(cptr, ERR_SASLTOOLONG);
if (IsSASLComplete(cptr))
return send_reply(cptr, ERR_SASLALREADY);
/* Look up the target server */
if (!(acptr = cli_saslagent(cptr))) {
if (strcmp(feature_str(FEAT_SASL_SERVER), "*"))
acptr = find_match_server((char *)feature_str(FEAT_SASL_SERVER));
else
acptr = NULL;
}
if (!acptr && strcmp(feature_str(FEAT_SASL_SERVER), "*"))
return send_reply(cptr, ERR_SASLFAIL, ": service unavailable");
/* If it's to us, do nothing; otherwise, forward the query */
if (acptr && IsMe(acptr))
return 0;
/* Generate an SASL session cookie if not already generated */
if (!cli_saslcookie(cptr)) {
do {
cli_saslcookie(cptr) = ircrandom() & 0x7fffffff;
} while (!cli_saslcookie(cptr));
first = 1;
}
if (strchr(hoststr, ':') != NULL)
ircd_snprintf(0, realhost, sizeof(realhost), "[%s]", hoststr);
else
ircd_strncpy(realhost, hoststr, sizeof(realhost));
if (acptr) {
if (first) {
if (*parv[1] == ':' || strchr(parv[1], ' '))
return exit_client(cptr, sptr, sptr, "Malformed AUTHENTICATE");
if (!EmptyString(cli_sslclifp(cptr)))
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u S %s :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr),
parv[1], cli_sslclifp(cptr));
else
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u S :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
if (feature_bool(FEAT_SASL_SENDHOST))
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u H :%s@%s:%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), cli_username(cptr),
realhost, cli_sock_ip(cptr));
} else {
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u C :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
}
} else {
if (first) {
if (*parv[1] == ':' || strchr(parv[1], ' '))
return exit_client(cptr, sptr, sptr, "Malformed AUTHENTICATE");
if (!EmptyString(cli_sslclifp(cptr)))
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u S %s :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr),
parv[1], cli_sslclifp(cptr));
else
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u S :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
if (feature_bool(FEAT_SASL_SENDHOST))
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u H :%s@%s:%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), cli_username(cptr),
realhost, cli_sock_ip(cptr));
} else {
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u C :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
}
}
if (!t_active(&cli_sasltimeout(cptr)))
timer_add(timer_init(&cli_sasltimeout(cptr)), sasl_timeout_callback, (void*) cptr,
TT_RELATIVE, feature_int(FEAT_SASL_TIMEOUT));
return 0;
}
/** Timeout a given SASL auth request.
* @param[in] ev A timer event whose associated data is the expired
* struct AuthRequest.
*/
static void sasl_timeout_callback(struct Event* ev)
{
struct Client *cptr;
assert(0 != ev_timer(ev));
assert(0 != t_data(ev_timer(ev)));
if (ev_type(ev) == ET_EXPIRE) {
cptr = (struct Client*) t_data(ev_timer(ev));
abort_sasl(cptr, 1);
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/good_5268_0 |
crossvul-cpp_data_bad_2756_5 | /*
* Error message information
*
* 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_ERROR_C) || defined(MBEDTLS_ERROR_STRERROR_DUMMY)
#include "mbedtls/error.h"
#include <string.h>
#endif
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#define mbedtls_snprintf snprintf
#define mbedtls_time_t time_t
#endif
#if defined(MBEDTLS_ERROR_C)
#include <stdio.h>
#if defined(MBEDTLS_AES_C)
#include "mbedtls/aes.h"
#endif
#if defined(MBEDTLS_BASE64_C)
#include "mbedtls/base64.h"
#endif
#if defined(MBEDTLS_BIGNUM_C)
#include "mbedtls/bignum.h"
#endif
#if defined(MBEDTLS_BLOWFISH_C)
#include "mbedtls/blowfish.h"
#endif
#if defined(MBEDTLS_CAMELLIA_C)
#include "mbedtls/camellia.h"
#endif
#if defined(MBEDTLS_CCM_C)
#include "mbedtls/ccm.h"
#endif
#if defined(MBEDTLS_CIPHER_C)
#include "mbedtls/cipher.h"
#endif
#if defined(MBEDTLS_CTR_DRBG_C)
#include "mbedtls/ctr_drbg.h"
#endif
#if defined(MBEDTLS_DES_C)
#include "mbedtls/des.h"
#endif
#if defined(MBEDTLS_DHM_C)
#include "mbedtls/dhm.h"
#endif
#if defined(MBEDTLS_ECP_C)
#include "mbedtls/ecp.h"
#endif
#if defined(MBEDTLS_ENTROPY_C)
#include "mbedtls/entropy.h"
#endif
#if defined(MBEDTLS_GCM_C)
#include "mbedtls/gcm.h"
#endif
#if defined(MBEDTLS_HMAC_DRBG_C)
#include "mbedtls/hmac_drbg.h"
#endif
#if defined(MBEDTLS_MD_C)
#include "mbedtls/md.h"
#endif
#if defined(MBEDTLS_NET_C)
#include "mbedtls/net_sockets.h"
#endif
#if defined(MBEDTLS_OID_C)
#include "mbedtls/oid.h"
#endif
#if defined(MBEDTLS_PADLOCK_C)
#include "mbedtls/padlock.h"
#endif
#if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C)
#include "mbedtls/pem.h"
#endif
#if defined(MBEDTLS_PK_C)
#include "mbedtls/pk.h"
#endif
#if defined(MBEDTLS_PKCS12_C)
#include "mbedtls/pkcs12.h"
#endif
#if defined(MBEDTLS_PKCS5_C)
#include "mbedtls/pkcs5.h"
#endif
#if defined(MBEDTLS_RSA_C)
#include "mbedtls/rsa.h"
#endif
#if defined(MBEDTLS_SSL_TLS_C)
#include "mbedtls/ssl.h"
#endif
#if defined(MBEDTLS_THREADING_C)
#include "mbedtls/threading.h"
#endif
#if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C)
#include "mbedtls/x509.h"
#endif
#if defined(MBEDTLS_XTEA_C)
#include "mbedtls/xtea.h"
#endif
void mbedtls_strerror( int ret, char *buf, size_t buflen )
{
size_t len;
int use_ret;
if( buflen == 0 )
return;
memset( buf, 0x00, buflen );
if( ret < 0 )
ret = -ret;
if( ret & 0xFF80 )
{
use_ret = ret & 0xFF80;
// High level error codes
//
// BEGIN generated code
#if defined(MBEDTLS_CIPHER_C)
if( use_ret == -(MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "CIPHER - The selected feature is not available" );
if( use_ret == -(MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "CIPHER - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_CIPHER_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "CIPHER - Failed to allocate memory" );
if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_PADDING) )
mbedtls_snprintf( buf, buflen, "CIPHER - Input data contains invalid padding and is rejected" );
if( use_ret == -(MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED) )
mbedtls_snprintf( buf, buflen, "CIPHER - Decryption of block requires a full block" );
if( use_ret == -(MBEDTLS_ERR_CIPHER_AUTH_FAILED) )
mbedtls_snprintf( buf, buflen, "CIPHER - Authentication failed (for AEAD modes)" );
if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_CONTEXT) )
mbedtls_snprintf( buf, buflen, "CIPHER - The context is invalid, eg because it was free()ed" );
#endif /* MBEDTLS_CIPHER_C */
#if defined(MBEDTLS_DHM_C)
if( use_ret == -(MBEDTLS_ERR_DHM_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "DHM - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_DHM_READ_PARAMS_FAILED) )
mbedtls_snprintf( buf, buflen, "DHM - Reading of the DHM parameters failed" );
if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED) )
mbedtls_snprintf( buf, buflen, "DHM - Making of the DHM parameters failed" );
if( use_ret == -(MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED) )
mbedtls_snprintf( buf, buflen, "DHM - Reading of the public values failed" );
if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED) )
mbedtls_snprintf( buf, buflen, "DHM - Making of the public value failed" );
if( use_ret == -(MBEDTLS_ERR_DHM_CALC_SECRET_FAILED) )
mbedtls_snprintf( buf, buflen, "DHM - Calculation of the DHM secret failed" );
if( use_ret == -(MBEDTLS_ERR_DHM_INVALID_FORMAT) )
mbedtls_snprintf( buf, buflen, "DHM - The ASN.1 data is not formatted correctly" );
if( use_ret == -(MBEDTLS_ERR_DHM_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "DHM - Allocation of memory failed" );
if( use_ret == -(MBEDTLS_ERR_DHM_FILE_IO_ERROR) )
mbedtls_snprintf( buf, buflen, "DHM - Read/write of file failed" );
#endif /* MBEDTLS_DHM_C */
#if defined(MBEDTLS_ECP_C)
if( use_ret == -(MBEDTLS_ERR_ECP_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "ECP - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "ECP - The buffer is too small to write to" );
if( use_ret == -(MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "ECP - Requested curve not available" );
if( use_ret == -(MBEDTLS_ERR_ECP_VERIFY_FAILED) )
mbedtls_snprintf( buf, buflen, "ECP - The signature is not valid" );
if( use_ret == -(MBEDTLS_ERR_ECP_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "ECP - Memory allocation failed" );
if( use_ret == -(MBEDTLS_ERR_ECP_RANDOM_FAILED) )
mbedtls_snprintf( buf, buflen, "ECP - Generation of random value, such as (ephemeral) key, failed" );
if( use_ret == -(MBEDTLS_ERR_ECP_INVALID_KEY) )
mbedtls_snprintf( buf, buflen, "ECP - Invalid private or public key" );
if( use_ret == -(MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH) )
mbedtls_snprintf( buf, buflen, "ECP - Signature is valid but shorter than the user-supplied length" );
#endif /* MBEDTLS_ECP_C */
#if defined(MBEDTLS_MD_C)
if( use_ret == -(MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "MD - The selected feature is not available" );
if( use_ret == -(MBEDTLS_ERR_MD_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "MD - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_MD_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "MD - Failed to allocate memory" );
if( use_ret == -(MBEDTLS_ERR_MD_FILE_IO_ERROR) )
mbedtls_snprintf( buf, buflen, "MD - Opening or reading of file failed" );
#endif /* MBEDTLS_MD_C */
#if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C)
if( use_ret == -(MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) )
mbedtls_snprintf( buf, buflen, "PEM - No PEM header or footer found" );
if( use_ret == -(MBEDTLS_ERR_PEM_INVALID_DATA) )
mbedtls_snprintf( buf, buflen, "PEM - PEM string is not as expected" );
if( use_ret == -(MBEDTLS_ERR_PEM_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "PEM - Failed to allocate memory" );
if( use_ret == -(MBEDTLS_ERR_PEM_INVALID_ENC_IV) )
mbedtls_snprintf( buf, buflen, "PEM - RSA IV is not in hex-format" );
if( use_ret == -(MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG) )
mbedtls_snprintf( buf, buflen, "PEM - Unsupported key encryption algorithm" );
if( use_ret == -(MBEDTLS_ERR_PEM_PASSWORD_REQUIRED) )
mbedtls_snprintf( buf, buflen, "PEM - Private key password can't be empty" );
if( use_ret == -(MBEDTLS_ERR_PEM_PASSWORD_MISMATCH) )
mbedtls_snprintf( buf, buflen, "PEM - Given private key password does not allow for correct decryption" );
if( use_ret == -(MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "PEM - Unavailable feature, e.g. hashing/encryption combination" );
if( use_ret == -(MBEDTLS_ERR_PEM_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "PEM - Bad input parameters to function" );
#endif /* MBEDTLS_PEM_PARSE_C || MBEDTLS_PEM_WRITE_C */
#if defined(MBEDTLS_PK_C)
if( use_ret == -(MBEDTLS_ERR_PK_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "PK - Memory allocation failed" );
if( use_ret == -(MBEDTLS_ERR_PK_TYPE_MISMATCH) )
mbedtls_snprintf( buf, buflen, "PK - Type mismatch, eg attempt to encrypt with an ECDSA key" );
if( use_ret == -(MBEDTLS_ERR_PK_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "PK - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_PK_FILE_IO_ERROR) )
mbedtls_snprintf( buf, buflen, "PK - Read/write of file failed" );
if( use_ret == -(MBEDTLS_ERR_PK_KEY_INVALID_VERSION) )
mbedtls_snprintf( buf, buflen, "PK - Unsupported key version" );
if( use_ret == -(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT) )
mbedtls_snprintf( buf, buflen, "PK - Invalid key tag or value" );
if( use_ret == -(MBEDTLS_ERR_PK_UNKNOWN_PK_ALG) )
mbedtls_snprintf( buf, buflen, "PK - Key algorithm is unsupported (only RSA and EC are supported)" );
if( use_ret == -(MBEDTLS_ERR_PK_PASSWORD_REQUIRED) )
mbedtls_snprintf( buf, buflen, "PK - Private key password can't be empty" );
if( use_ret == -(MBEDTLS_ERR_PK_PASSWORD_MISMATCH) )
mbedtls_snprintf( buf, buflen, "PK - Given private key password does not allow for correct decryption" );
if( use_ret == -(MBEDTLS_ERR_PK_INVALID_PUBKEY) )
mbedtls_snprintf( buf, buflen, "PK - The pubkey tag or value is invalid (only RSA and EC are supported)" );
if( use_ret == -(MBEDTLS_ERR_PK_INVALID_ALG) )
mbedtls_snprintf( buf, buflen, "PK - The algorithm tag or value is invalid" );
if( use_ret == -(MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE) )
mbedtls_snprintf( buf, buflen, "PK - Elliptic curve is unsupported (only NIST curves are supported)" );
if( use_ret == -(MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "PK - Unavailable feature, e.g. RSA disabled for RSA key" );
if( use_ret == -(MBEDTLS_ERR_PK_SIG_LEN_MISMATCH) )
mbedtls_snprintf( buf, buflen, "PK - The signature is valid but its length is less than expected" );
#endif /* MBEDTLS_PK_C */
#if defined(MBEDTLS_PKCS12_C)
if( use_ret == -(MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "PKCS12 - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "PKCS12 - Feature not available, e.g. unsupported encryption scheme" );
if( use_ret == -(MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT) )
mbedtls_snprintf( buf, buflen, "PKCS12 - PBE ASN.1 data not as expected" );
if( use_ret == -(MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH) )
mbedtls_snprintf( buf, buflen, "PKCS12 - Given private key password does not allow for correct decryption" );
#endif /* MBEDTLS_PKCS12_C */
#if defined(MBEDTLS_PKCS5_C)
if( use_ret == -(MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "PKCS5 - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_PKCS5_INVALID_FORMAT) )
mbedtls_snprintf( buf, buflen, "PKCS5 - Unexpected ASN.1 data" );
if( use_ret == -(MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "PKCS5 - Requested encryption or digest alg not available" );
if( use_ret == -(MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH) )
mbedtls_snprintf( buf, buflen, "PKCS5 - Given private key password does not allow for correct decryption" );
#endif /* MBEDTLS_PKCS5_C */
#if defined(MBEDTLS_RSA_C)
if( use_ret == -(MBEDTLS_ERR_RSA_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "RSA - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_RSA_INVALID_PADDING) )
mbedtls_snprintf( buf, buflen, "RSA - Input data contains invalid padding and is rejected" );
if( use_ret == -(MBEDTLS_ERR_RSA_KEY_GEN_FAILED) )
mbedtls_snprintf( buf, buflen, "RSA - Something failed during generation of a key" );
if( use_ret == -(MBEDTLS_ERR_RSA_KEY_CHECK_FAILED) )
mbedtls_snprintf( buf, buflen, "RSA - Key failed to pass the library's validity check" );
if( use_ret == -(MBEDTLS_ERR_RSA_PUBLIC_FAILED) )
mbedtls_snprintf( buf, buflen, "RSA - The public key operation failed" );
if( use_ret == -(MBEDTLS_ERR_RSA_PRIVATE_FAILED) )
mbedtls_snprintf( buf, buflen, "RSA - The private key operation failed" );
if( use_ret == -(MBEDTLS_ERR_RSA_VERIFY_FAILED) )
mbedtls_snprintf( buf, buflen, "RSA - The PKCS#1 verification failed" );
if( use_ret == -(MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE) )
mbedtls_snprintf( buf, buflen, "RSA - The output buffer for decryption is not large enough" );
if( use_ret == -(MBEDTLS_ERR_RSA_RNG_FAILED) )
mbedtls_snprintf( buf, buflen, "RSA - The random generator failed to generate non-zeros" );
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_SSL_TLS_C)
if( use_ret == -(MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "SSL - The requested feature is not available" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "SSL - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_MAC) )
mbedtls_snprintf( buf, buflen, "SSL - Verification of the message MAC failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_RECORD) )
mbedtls_snprintf( buf, buflen, "SSL - An invalid SSL record was received" );
if( use_ret == -(MBEDTLS_ERR_SSL_CONN_EOF) )
mbedtls_snprintf( buf, buflen, "SSL - The connection indicated an EOF" );
if( use_ret == -(MBEDTLS_ERR_SSL_UNKNOWN_CIPHER) )
mbedtls_snprintf( buf, buflen, "SSL - An unknown cipher was received" );
if( use_ret == -(MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN) )
mbedtls_snprintf( buf, buflen, "SSL - The server has no ciphersuites in common with the client" );
if( use_ret == -(MBEDTLS_ERR_SSL_NO_RNG) )
mbedtls_snprintf( buf, buflen, "SSL - No RNG was provided to the SSL module" );
if( use_ret == -(MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE) )
mbedtls_snprintf( buf, buflen, "SSL - No client certification received from the client, but required by the authentication mode" );
if( use_ret == -(MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE) )
mbedtls_snprintf( buf, buflen, "SSL - Our own certificate(s) is/are too large to send in an SSL message" );
if( use_ret == -(MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED) )
mbedtls_snprintf( buf, buflen, "SSL - The own certificate is not set, but needed by the server" );
if( use_ret == -(MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED) )
mbedtls_snprintf( buf, buflen, "SSL - The own private key or pre-shared key is not set, but needed" );
if( use_ret == -(MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED) )
mbedtls_snprintf( buf, buflen, "SSL - No CA Chain is set, but required to operate" );
if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE) )
mbedtls_snprintf( buf, buflen, "SSL - An unexpected message was received from our peer" );
if( use_ret == -(MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE) )
{
mbedtls_snprintf( buf, buflen, "SSL - A fatal alert message was received from our peer" );
return;
}
if( use_ret == -(MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED) )
mbedtls_snprintf( buf, buflen, "SSL - Verification of our peer failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) )
mbedtls_snprintf( buf, buflen, "SSL - The peer notified us that the connection is going to be closed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientHello handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerHello handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the Certificate handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the CertificateRequest handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerKeyExchange handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerHelloDone handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Read Public" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Calculate Secret" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the CertificateVerify handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the ChangeCipherSpec handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_FINISHED) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the Finished handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "SSL - Memory allocation failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_HW_ACCEL_FAILED) )
mbedtls_snprintf( buf, buflen, "SSL - Hardware acceleration function returned with error" );
if( use_ret == -(MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH) )
mbedtls_snprintf( buf, buflen, "SSL - Hardware acceleration function skipped / left alone data" );
if( use_ret == -(MBEDTLS_ERR_SSL_COMPRESSION_FAILED) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the compression / decompression failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION) )
mbedtls_snprintf( buf, buflen, "SSL - Handshake protocol not within min/max boundaries" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the NewSessionTicket handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED) )
mbedtls_snprintf( buf, buflen, "SSL - Session ticket has expired" );
if( use_ret == -(MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH) )
mbedtls_snprintf( buf, buflen, "SSL - Public key type mismatch (eg, asked for RSA key exchange and presented EC key)" );
if( use_ret == -(MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY) )
mbedtls_snprintf( buf, buflen, "SSL - Unknown identity received (eg, PSK identity)" );
if( use_ret == -(MBEDTLS_ERR_SSL_INTERNAL_ERROR) )
mbedtls_snprintf( buf, buflen, "SSL - Internal error (eg, unexpected failure in lower-level module)" );
if( use_ret == -(MBEDTLS_ERR_SSL_COUNTER_WRAPPING) )
mbedtls_snprintf( buf, buflen, "SSL - A counter would wrap (eg, too many messages exchanged)" );
if( use_ret == -(MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO) )
mbedtls_snprintf( buf, buflen, "SSL - Unexpected message at ServerHello in renegotiation" );
if( use_ret == -(MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) )
mbedtls_snprintf( buf, buflen, "SSL - DTLS client must retry for hello verification" );
if( use_ret == -(MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "SSL - A buffer is too small to receive or write a message" );
if( use_ret == -(MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE) )
mbedtls_snprintf( buf, buflen, "SSL - None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages)" );
if( use_ret == -(MBEDTLS_ERR_SSL_WANT_READ) )
mbedtls_snprintf( buf, buflen, "SSL - Connection requires a read call" );
if( use_ret == -(MBEDTLS_ERR_SSL_WANT_WRITE) )
mbedtls_snprintf( buf, buflen, "SSL - Connection requires a write call" );
if( use_ret == -(MBEDTLS_ERR_SSL_TIMEOUT) )
mbedtls_snprintf( buf, buflen, "SSL - The operation timed out" );
if( use_ret == -(MBEDTLS_ERR_SSL_CLIENT_RECONNECT) )
mbedtls_snprintf( buf, buflen, "SSL - The client initiated a reconnect from the same port" );
if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_RECORD) )
mbedtls_snprintf( buf, buflen, "SSL - Record header looks valid but is not expected" );
if( use_ret == -(MBEDTLS_ERR_SSL_NON_FATAL) )
mbedtls_snprintf( buf, buflen, "SSL - The alert message received indicates a non-fatal error" );
if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH) )
mbedtls_snprintf( buf, buflen, "SSL - Couldn't set the hash for verifying CertificateVerify" );
#endif /* MBEDTLS_SSL_TLS_C */
#if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C)
if( use_ret == -(MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "X509 - Unavailable feature, e.g. RSA hashing/encryption combination" );
if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_OID) )
mbedtls_snprintf( buf, buflen, "X509 - Requested OID is unknown" );
if( use_ret == -(MBEDTLS_ERR_X509_INVALID_FORMAT) )
mbedtls_snprintf( buf, buflen, "X509 - The CRT/CRL/CSR format is invalid, e.g. different type expected" );
if( use_ret == -(MBEDTLS_ERR_X509_INVALID_VERSION) )
mbedtls_snprintf( buf, buflen, "X509 - The CRT/CRL/CSR version element is invalid" );
if( use_ret == -(MBEDTLS_ERR_X509_INVALID_SERIAL) )
mbedtls_snprintf( buf, buflen, "X509 - The serial tag or value is invalid" );
if( use_ret == -(MBEDTLS_ERR_X509_INVALID_ALG) )
mbedtls_snprintf( buf, buflen, "X509 - The algorithm tag or value is invalid" );
if( use_ret == -(MBEDTLS_ERR_X509_INVALID_NAME) )
mbedtls_snprintf( buf, buflen, "X509 - The name tag or value is invalid" );
if( use_ret == -(MBEDTLS_ERR_X509_INVALID_DATE) )
mbedtls_snprintf( buf, buflen, "X509 - The date tag or value is invalid" );
if( use_ret == -(MBEDTLS_ERR_X509_INVALID_SIGNATURE) )
mbedtls_snprintf( buf, buflen, "X509 - The signature tag or value invalid" );
if( use_ret == -(MBEDTLS_ERR_X509_INVALID_EXTENSIONS) )
mbedtls_snprintf( buf, buflen, "X509 - The extension tag or value is invalid" );
if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_VERSION) )
mbedtls_snprintf( buf, buflen, "X509 - CRT/CRL/CSR has an unsupported version number" );
if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG) )
mbedtls_snprintf( buf, buflen, "X509 - Signature algorithm (oid) is unsupported" );
if( use_ret == -(MBEDTLS_ERR_X509_SIG_MISMATCH) )
mbedtls_snprintf( buf, buflen, "X509 - Signature algorithms do not match. (see \\c ::mbedtls_x509_crt sig_oid)" );
if( use_ret == -(MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) )
mbedtls_snprintf( buf, buflen, "X509 - Certificate verification failed, e.g. CRL, CA or signature check failed" );
if( use_ret == -(MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT) )
mbedtls_snprintf( buf, buflen, "X509 - Format not recognized as DER or PEM" );
if( use_ret == -(MBEDTLS_ERR_X509_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "X509 - Input invalid" );
if( use_ret == -(MBEDTLS_ERR_X509_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "X509 - Allocation of memory failed" );
if( use_ret == -(MBEDTLS_ERR_X509_FILE_IO_ERROR) )
mbedtls_snprintf( buf, buflen, "X509 - Read/write of file failed" );
if( use_ret == -(MBEDTLS_ERR_X509_BUFFER_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "X509 - Destination buffer is too small" );
#endif /* MBEDTLS_X509_USE_C || MBEDTLS_X509_CREATE_C */
// END generated code
if( strlen( buf ) == 0 )
mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret );
}
use_ret = ret & ~0xFF80;
if( use_ret == 0 )
return;
// If high level code is present, make a concatenation between both
// error strings.
//
len = strlen( buf );
if( len > 0 )
{
if( buflen - len < 5 )
return;
mbedtls_snprintf( buf + len, buflen - len, " : " );
buf += len + 3;
buflen -= len + 3;
}
// Low level error codes
//
// BEGIN generated code
#if defined(MBEDTLS_AES_C)
if( use_ret == -(MBEDTLS_ERR_AES_INVALID_KEY_LENGTH) )
mbedtls_snprintf( buf, buflen, "AES - Invalid key length" );
if( use_ret == -(MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH) )
mbedtls_snprintf( buf, buflen, "AES - Invalid data input length" );
#endif /* MBEDTLS_AES_C */
#if defined(MBEDTLS_ASN1_PARSE_C)
if( use_ret == -(MBEDTLS_ERR_ASN1_OUT_OF_DATA) )
mbedtls_snprintf( buf, buflen, "ASN1 - Out of data when parsing an ASN1 data structure" );
if( use_ret == -(MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) )
mbedtls_snprintf( buf, buflen, "ASN1 - ASN1 tag was of an unexpected value" );
if( use_ret == -(MBEDTLS_ERR_ASN1_INVALID_LENGTH) )
mbedtls_snprintf( buf, buflen, "ASN1 - Error when trying to determine the length or invalid length" );
if( use_ret == -(MBEDTLS_ERR_ASN1_LENGTH_MISMATCH) )
mbedtls_snprintf( buf, buflen, "ASN1 - Actual length differs from expected length" );
if( use_ret == -(MBEDTLS_ERR_ASN1_INVALID_DATA) )
mbedtls_snprintf( buf, buflen, "ASN1 - Data is invalid. (not used)" );
if( use_ret == -(MBEDTLS_ERR_ASN1_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "ASN1 - Memory allocation failed" );
if( use_ret == -(MBEDTLS_ERR_ASN1_BUF_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "ASN1 - Buffer too small when writing ASN.1 data structure" );
#endif /* MBEDTLS_ASN1_PARSE_C */
#if defined(MBEDTLS_BASE64_C)
if( use_ret == -(MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "BASE64 - Output buffer too small" );
if( use_ret == -(MBEDTLS_ERR_BASE64_INVALID_CHARACTER) )
mbedtls_snprintf( buf, buflen, "BASE64 - Invalid character in input" );
#endif /* MBEDTLS_BASE64_C */
#if defined(MBEDTLS_BIGNUM_C)
if( use_ret == -(MBEDTLS_ERR_MPI_FILE_IO_ERROR) )
mbedtls_snprintf( buf, buflen, "BIGNUM - An error occurred while reading from or writing to a file" );
if( use_ret == -(MBEDTLS_ERR_MPI_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "BIGNUM - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_MPI_INVALID_CHARACTER) )
mbedtls_snprintf( buf, buflen, "BIGNUM - There is an invalid character in the digit string" );
if( use_ret == -(MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "BIGNUM - The buffer is too small to write to" );
if( use_ret == -(MBEDTLS_ERR_MPI_NEGATIVE_VALUE) )
mbedtls_snprintf( buf, buflen, "BIGNUM - The input arguments are negative or result in illegal output" );
if( use_ret == -(MBEDTLS_ERR_MPI_DIVISION_BY_ZERO) )
mbedtls_snprintf( buf, buflen, "BIGNUM - The input argument for division is zero, which is not allowed" );
if( use_ret == -(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) )
mbedtls_snprintf( buf, buflen, "BIGNUM - The input arguments are not acceptable" );
if( use_ret == -(MBEDTLS_ERR_MPI_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "BIGNUM - Memory allocation failed" );
#endif /* MBEDTLS_BIGNUM_C */
#if defined(MBEDTLS_BLOWFISH_C)
if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH) )
mbedtls_snprintf( buf, buflen, "BLOWFISH - Invalid key length" );
if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH) )
mbedtls_snprintf( buf, buflen, "BLOWFISH - Invalid data input length" );
#endif /* MBEDTLS_BLOWFISH_C */
#if defined(MBEDTLS_CAMELLIA_C)
if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH) )
mbedtls_snprintf( buf, buflen, "CAMELLIA - Invalid key length" );
if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH) )
mbedtls_snprintf( buf, buflen, "CAMELLIA - Invalid data input length" );
#endif /* MBEDTLS_CAMELLIA_C */
#if defined(MBEDTLS_CCM_C)
if( use_ret == -(MBEDTLS_ERR_CCM_BAD_INPUT) )
mbedtls_snprintf( buf, buflen, "CCM - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_CCM_AUTH_FAILED) )
mbedtls_snprintf( buf, buflen, "CCM - Authenticated decryption failed" );
#endif /* MBEDTLS_CCM_C */
#if defined(MBEDTLS_CTR_DRBG_C)
if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED) )
mbedtls_snprintf( buf, buflen, "CTR_DRBG - The entropy source failed" );
if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG) )
mbedtls_snprintf( buf, buflen, "CTR_DRBG - Too many random requested in single call" );
if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG) )
mbedtls_snprintf( buf, buflen, "CTR_DRBG - Input too large (Entropy + additional)" );
if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR) )
mbedtls_snprintf( buf, buflen, "CTR_DRBG - Read/write error in file" );
#endif /* MBEDTLS_CTR_DRBG_C */
#if defined(MBEDTLS_DES_C)
if( use_ret == -(MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH) )
mbedtls_snprintf( buf, buflen, "DES - The data input has an invalid length" );
#endif /* MBEDTLS_DES_C */
#if defined(MBEDTLS_ENTROPY_C)
if( use_ret == -(MBEDTLS_ERR_ENTROPY_SOURCE_FAILED) )
mbedtls_snprintf( buf, buflen, "ENTROPY - Critical entropy source failure" );
if( use_ret == -(MBEDTLS_ERR_ENTROPY_MAX_SOURCES) )
mbedtls_snprintf( buf, buflen, "ENTROPY - No more sources can be added" );
if( use_ret == -(MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED) )
mbedtls_snprintf( buf, buflen, "ENTROPY - No sources have been added to poll" );
if( use_ret == -(MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE) )
mbedtls_snprintf( buf, buflen, "ENTROPY - No strong sources have been added to poll" );
if( use_ret == -(MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR) )
mbedtls_snprintf( buf, buflen, "ENTROPY - Read/write error in file" );
#endif /* MBEDTLS_ENTROPY_C */
#if defined(MBEDTLS_GCM_C)
if( use_ret == -(MBEDTLS_ERR_GCM_AUTH_FAILED) )
mbedtls_snprintf( buf, buflen, "GCM - Authenticated decryption failed" );
if( use_ret == -(MBEDTLS_ERR_GCM_BAD_INPUT) )
mbedtls_snprintf( buf, buflen, "GCM - Bad input parameters to function" );
#endif /* MBEDTLS_GCM_C */
#if defined(MBEDTLS_HMAC_DRBG_C)
if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG) )
mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Too many random requested in single call" );
if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG) )
mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Input too large (Entropy + additional)" );
if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR) )
mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Read/write error in file" );
if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED) )
mbedtls_snprintf( buf, buflen, "HMAC_DRBG - The entropy source failed" );
#endif /* MBEDTLS_HMAC_DRBG_C */
#if defined(MBEDTLS_NET_C)
if( use_ret == -(MBEDTLS_ERR_NET_SOCKET_FAILED) )
mbedtls_snprintf( buf, buflen, "NET - Failed to open a socket" );
if( use_ret == -(MBEDTLS_ERR_NET_CONNECT_FAILED) )
mbedtls_snprintf( buf, buflen, "NET - The connection to the given server / port failed" );
if( use_ret == -(MBEDTLS_ERR_NET_BIND_FAILED) )
mbedtls_snprintf( buf, buflen, "NET - Binding of the socket failed" );
if( use_ret == -(MBEDTLS_ERR_NET_LISTEN_FAILED) )
mbedtls_snprintf( buf, buflen, "NET - Could not listen on the socket" );
if( use_ret == -(MBEDTLS_ERR_NET_ACCEPT_FAILED) )
mbedtls_snprintf( buf, buflen, "NET - Could not accept the incoming connection" );
if( use_ret == -(MBEDTLS_ERR_NET_RECV_FAILED) )
mbedtls_snprintf( buf, buflen, "NET - Reading information from the socket failed" );
if( use_ret == -(MBEDTLS_ERR_NET_SEND_FAILED) )
mbedtls_snprintf( buf, buflen, "NET - Sending information through the socket failed" );
if( use_ret == -(MBEDTLS_ERR_NET_CONN_RESET) )
mbedtls_snprintf( buf, buflen, "NET - Connection was reset by peer" );
if( use_ret == -(MBEDTLS_ERR_NET_UNKNOWN_HOST) )
mbedtls_snprintf( buf, buflen, "NET - Failed to get an IP address for the given hostname" );
if( use_ret == -(MBEDTLS_ERR_NET_BUFFER_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "NET - Buffer is too small to hold the data" );
if( use_ret == -(MBEDTLS_ERR_NET_INVALID_CONTEXT) )
mbedtls_snprintf( buf, buflen, "NET - The context is invalid, eg because it was free()ed" );
#endif /* MBEDTLS_NET_C */
#if defined(MBEDTLS_OID_C)
if( use_ret == -(MBEDTLS_ERR_OID_NOT_FOUND) )
mbedtls_snprintf( buf, buflen, "OID - OID is not found" );
if( use_ret == -(MBEDTLS_ERR_OID_BUF_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "OID - output buffer is too small" );
#endif /* MBEDTLS_OID_C */
#if defined(MBEDTLS_PADLOCK_C)
if( use_ret == -(MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED) )
mbedtls_snprintf( buf, buflen, "PADLOCK - Input data should be aligned" );
#endif /* MBEDTLS_PADLOCK_C */
#if defined(MBEDTLS_THREADING_C)
if( use_ret == -(MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "THREADING - The selected feature is not available" );
if( use_ret == -(MBEDTLS_ERR_THREADING_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "THREADING - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_THREADING_MUTEX_ERROR) )
mbedtls_snprintf( buf, buflen, "THREADING - Locking / unlocking / free failed with error code" );
#endif /* MBEDTLS_THREADING_C */
#if defined(MBEDTLS_XTEA_C)
if( use_ret == -(MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH) )
mbedtls_snprintf( buf, buflen, "XTEA - The data input has an invalid length" );
#endif /* MBEDTLS_XTEA_C */
// END generated code
if( strlen( buf ) != 0 )
return;
mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret );
}
#else /* MBEDTLS_ERROR_C */
#if defined(MBEDTLS_ERROR_STRERROR_DUMMY)
/*
* Provide an non-function in case MBEDTLS_ERROR_C is not defined
*/
void mbedtls_strerror( int ret, char *buf, size_t buflen )
{
((void) ret);
if( buflen > 0 )
buf[0] = '\0';
}
#endif /* MBEDTLS_ERROR_STRERROR_DUMMY */
#endif /* MBEDTLS_ERROR_C */
| ./CrossVul/dataset_final_sorted/CWE-287/c/bad_2756_5 |
crossvul-cpp_data_bad_2222_0 | /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/* Cherokee
*
* Authors:
* Alvaro Lopez Ortega <alvaro@alobbs.com>
*
* Copyright (C) 2001-2014 Alvaro Lopez Ortega
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include "common-internal.h"
#include <errno.h>
#include "plugin_loader.h"
#include "validator_ldap.h"
#include "connection-protected.h"
#include "util.h"
#define ENTRIES "validator,ldap"
#define LDAP_DEFAULT_PORT 389
#ifndef LDAP_OPT_SUCCESS
# define LDAP_OPT_SUCCESS 0
#endif
/* Plug-in initialization
*/
PLUGIN_INFO_VALIDATOR_EASIEST_INIT (ldap, http_auth_basic);
static ret_t
props_free (cherokee_validator_ldap_props_t *props)
{
cherokee_buffer_mrproper (&props->server);
cherokee_buffer_mrproper (&props->binddn);
cherokee_buffer_mrproper (&props->bindpw);
cherokee_buffer_mrproper (&props->basedn);
cherokee_buffer_mrproper (&props->filter);
cherokee_buffer_mrproper (&props->ca_file);
return cherokee_validator_props_free_base (VALIDATOR_PROPS(props));
}
ret_t
cherokee_validator_ldap_configure (cherokee_config_node_t *conf, cherokee_server_t *srv, cherokee_module_props_t **_props)
{
ret_t ret;
cherokee_list_t *i;
cherokee_validator_ldap_props_t *props;
UNUSED(srv);
if (*_props == NULL) {
CHEROKEE_NEW_STRUCT (n, validator_ldap_props);
cherokee_validator_props_init_base (VALIDATOR_PROPS(n), MODULE_PROPS_FREE(props_free));
n->port = LDAP_DEFAULT_PORT;
n->tls = false;
cherokee_buffer_init (&n->server);
cherokee_buffer_init (&n->binddn);
cherokee_buffer_init (&n->bindpw);
cherokee_buffer_init (&n->basedn);
cherokee_buffer_init (&n->filter);
cherokee_buffer_init (&n->ca_file);
*_props = MODULE_PROPS(n);
}
props = PROP_LDAP(*_props);
cherokee_config_node_foreach (i, conf) {
cherokee_config_node_t *subconf = CONFIG_NODE(i);
if (equal_buf_str (&subconf->key, "server")) {
cherokee_buffer_add_buffer (&props->server, &subconf->val);
} else if (equal_buf_str (&subconf->key, "port")) {
ret = cherokee_atoi (subconf->val.buf, &props->port);
if (ret != ret_ok) return ret_error;
} else if (equal_buf_str (&subconf->key, "bind_dn")) {
cherokee_buffer_add_buffer (&props->binddn, &subconf->val);
} else if (equal_buf_str (&subconf->key, "bind_pw")) {
cherokee_buffer_add_buffer (&props->bindpw, &subconf->val);
} else if (equal_buf_str (&subconf->key, "base_dn")) {
cherokee_buffer_add_buffer (&props->basedn, &subconf->val);
} else if (equal_buf_str (&subconf->key, "filter")) {
cherokee_buffer_add_buffer (&props->filter, &subconf->val);
} else if (equal_buf_str (&subconf->key, "tls")) {
ret = cherokee_atob (subconf->val.buf, &props->tls);
if (ret != ret_ok) return ret_error;
} else if (equal_buf_str (&subconf->key, "ca_file")) {
cherokee_buffer_add_buffer (&props->ca_file, &subconf->val);
} else if (equal_buf_str (&subconf->key, "methods") ||
equal_buf_str (&subconf->key, "realm") ||
equal_buf_str (&subconf->key, "users")) {
/* Handled in validator.c
*/
} else {
LOG_WARNING (CHEROKEE_ERROR_VALIDATOR_LDAP_KEY, subconf->key.buf);
}
}
/* Checks
*/
if (cherokee_buffer_is_empty (&props->basedn)) {
LOG_ERROR (CHEROKEE_ERROR_VALIDATOR_LDAP_PROPERTY, "base_dn");
return ret_error;
}
if (cherokee_buffer_is_empty (&props->server)) {
LOG_ERROR (CHEROKEE_ERROR_VALIDATOR_LDAP_PROPERTY, "server");
return ret_error;
}
if ((cherokee_buffer_is_empty (&props->bindpw) &&
(! cherokee_buffer_is_empty (&props->basedn))))
{
LOG_ERROR_S (CHEROKEE_ERROR_VALIDATOR_LDAP_SECURITY);
return ret_error;
}
return ret_ok;
}
static ret_t
init_ldap_connection (cherokee_validator_ldap_t *ldap, cherokee_validator_ldap_props_t *props)
{
int re;
int val;
/* Connect
*/
ldap->conn = ldap_init (props->server.buf, props->port);
if (ldap->conn == NULL) {
LOG_ERRNO (errno, cherokee_err_critical,
CHEROKEE_ERROR_VALIDATOR_LDAP_CONNECT,
props->server.buf, props->port);
return ret_error;
}
TRACE (ENTRIES, "Connected to %s:%d\n", props->server.buf, props->port);
/* Set LDAP protocol version
*/
val = LDAP_VERSION3;
re = ldap_set_option (ldap->conn, LDAP_OPT_PROTOCOL_VERSION, &val);
if (re != LDAP_OPT_SUCCESS) {
LOG_ERROR (CHEROKEE_ERROR_VALIDATOR_LDAP_V3, ldap_err2string(re));
return ret_error;
}
TRACE (ENTRIES, "LDAP protocol version %d set\n", LDAP_VERSION3);
/* Secure connections
*/
if (props->tls) {
#ifdef LDAP_OPT_X_TLS
if (! cherokee_buffer_is_empty (&props->ca_file)) {
re = ldap_set_option (NULL, LDAP_OPT_X_TLS_CACERTFILE, props->ca_file.buf);
if (re != LDAP_OPT_SUCCESS) {
LOG_CRITICAL (CHEROKEE_ERROR_VALIDATOR_LDAP_CA,
props->ca_file.buf, ldap_err2string (re));
return ret_error;
}
}
#else
LOG_ERROR_S (CHEROKEE_ERROR_VALIDATOR_LDAP_STARTTLS);
#endif
}
/* Bind
*/
if (cherokee_buffer_is_empty (&props->binddn)) {
TRACE (ENTRIES, "anonymous bind %s", "\n");
re = ldap_simple_bind_s (ldap->conn, NULL, NULL);
} else {
TRACE (ENTRIES, "bind user=%s password=%s\n",
props->binddn.buf, props->bindpw.buf);
re = ldap_simple_bind_s (ldap->conn, props->binddn.buf, props->bindpw.buf);
}
if (re != LDAP_SUCCESS) {
LOG_CRITICAL (CHEROKEE_ERROR_VALIDATOR_LDAP_BIND,
props->server.buf, props->port, props->binddn.buf,
props->bindpw.buf, ldap_err2string(re));
return ret_error;
}
return ret_ok;
}
ret_t
cherokee_validator_ldap_new (cherokee_validator_ldap_t **ldap, cherokee_module_props_t *props)
{
ret_t ret;
CHEROKEE_NEW_STRUCT(n,validator_ldap);
/* Init
*/
cherokee_validator_init_base (VALIDATOR(n), VALIDATOR_PROPS(props), PLUGIN_INFO_VALIDATOR_PTR(ldap));
VALIDATOR(n)->support = http_auth_basic;
MODULE(n)->free = (module_func_free_t) cherokee_validator_ldap_free;
VALIDATOR(n)->check = (validator_func_check_t) cherokee_validator_ldap_check;
VALIDATOR(n)->add_headers = (validator_func_add_headers_t) cherokee_validator_ldap_add_headers;
/* Init properties
*/
cherokee_buffer_init (&n->filter);
/* Connect to the LDAP server
*/
ret = init_ldap_connection (n, PROP_LDAP(props));
if (ret != ret_ok) {
cherokee_validator_free (VALIDATOR(n));
return ret;
}
*ldap = n;
return ret_ok;
}
ret_t
cherokee_validator_ldap_free (cherokee_validator_ldap_t *ldap)
{
cherokee_buffer_mrproper (&ldap->filter);
if (ldap->conn)
ldap_unbind (ldap->conn);
return ret_ok;
}
static ret_t
validate_dn (cherokee_validator_ldap_props_t *props, char *dn, char *password)
{
int re;
int val;
LDAP *conn;
conn = ldap_init (props->server.buf, props->port);
if (conn == NULL) return ret_error;
val = LDAP_VERSION3;
re = ldap_set_option (conn, LDAP_OPT_PROTOCOL_VERSION, &val);
if (re != LDAP_OPT_SUCCESS)
goto error;
if (props->tls) {
#ifdef LDAP_HAVE_START_TLS_S
re = ldap_start_tls_s (conn, NULL, NULL);
if (re != LDAP_OPT_SUCCESS) {
TRACE (ENTRIES, "Couldn't StartTLS\n");
goto error;
}
#else
LOG_ERROR_S (CHEROKEE_ERROR_VALIDATOR_LDAP_STARTTLS);
#endif
}
re = ldap_simple_bind_s (conn, dn, password);
if (re != LDAP_SUCCESS)
goto error;
return ret_ok;
error:
ldap_unbind_s (conn);
return ret_error;
}
static ret_t
init_filter (cherokee_validator_ldap_t *ldap,
cherokee_validator_ldap_props_t *props,
cherokee_connection_t *conn)
{
if (cherokee_buffer_is_empty (&props->filter)) {
TRACE (ENTRIES, "Empty filter: %s\n", "Ignoring it");
return ret_ok;
}
cherokee_buffer_ensure_size (&ldap->filter, props->filter.len + conn->validator->user.len);
cherokee_buffer_add_buffer (&ldap->filter, &props->filter);
cherokee_buffer_replace_string (&ldap->filter, "${user}", 7, conn->validator->user.buf, conn->validator->user.len);
TRACE (ENTRIES, "filter %s\n", ldap->filter.buf);
return ret_ok;
}
ret_t
cherokee_validator_ldap_check (cherokee_validator_ldap_t *ldap,
cherokee_connection_t *conn)
{
int re;
ret_t ret;
size_t size;
char *dn;
LDAPMessage *message;
LDAPMessage *first;
char *attrs[] = { LDAP_NO_ATTRS, NULL };
cherokee_validator_ldap_props_t *props = VAL_LDAP_PROP(ldap);
/* Sanity checks
*/
if ((conn->validator == NULL) ||
cherokee_buffer_is_empty (&conn->validator->user))
return ret_error;
size = cherokee_buffer_cnt_cspn (&conn->validator->user, 0, "*()");
if (size != conn->validator->user.len)
return ret_error;
/* Build filter
*/
ret = init_filter (ldap, props, conn);
if (ret != ret_ok)
return ret;
/* Search
*/
re = ldap_search_s (ldap->conn, props->basedn.buf, LDAP_SCOPE_SUBTREE, ldap->filter.buf, attrs, 0, &message);
if (re != LDAP_SUCCESS) {
LOG_ERROR (CHEROKEE_ERROR_VALIDATOR_LDAP_SEARCH,
props->filter.buf ? props->filter.buf : "");
return ret_error;
}
TRACE (ENTRIES, "subtree search (%s): done\n", ldap->filter.buf ? ldap->filter.buf : "");
/* Check that there a single entry
*/
re = ldap_count_entries (ldap->conn, message);
if (re != 1) {
ldap_msgfree (message);
return ret_not_found;
}
/* Pick up the first one
*/
first = ldap_first_entry (ldap->conn, message);
if (first == NULL) {
ldap_msgfree (message);
return ret_not_found;
}
/* Get DN
*/
dn = ldap_get_dn (ldap->conn, first);
if (dn == NULL) {
ldap_msgfree (message);
return ret_error;
}
ldap_msgfree (message);
/* Check that it's right
*/
ret = validate_dn (props, dn, conn->validator->passwd.buf);
if (ret != ret_ok)
return ret;
/* Disconnect from the LDAP server
*/
re = ldap_unbind_s (ldap->conn);
if (re != LDAP_SUCCESS)
return ret_error;
/* Validated!
*/
TRACE (ENTRIES, "Access to use %s has been granted\n", conn->validator->user.buf);
return ret_ok;
}
ret_t
cherokee_validator_ldap_add_headers (cherokee_validator_ldap_t *ldap, cherokee_connection_t *conn, cherokee_buffer_t *buf)
{
UNUSED(ldap);
UNUSED(conn);
UNUSED(buf);
return ret_ok;
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/bad_2222_0 |
crossvul-cpp_data_bad_3184_4 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/***************************************************************************
* Copyright (C) 2013-2017 Ping Identity Corporation
* All rights reserved.
*
* For further information please contact:
*
* Ping Identity Corporation
* 1099 18th St Suite 2950
* Denver, CO 80202
* 303.468.2900
* http://www.pingidentity.com
*
* DISCLAIMER OF WARRANTIES:
*
* THE SOFTWARE PROVIDED HEREUNDER IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
* ANY WARRANTIES OR REPRESENTATIONS EXPRESS, IMPLIED OR STATUTORY; INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF QUALITY, PERFORMANCE, NONINFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NOR ARE THERE ANY
* WARRANTIES CREATED BY A COURSE OR DEALING, COURSE OF PERFORMANCE OR TRADE
* USAGE. FURTHERMORE, THERE ARE NO WARRANTIES THAT THE SOFTWARE WILL MEET
* YOUR NEEDS OR BE FREE FROM ERRORS, OR THAT THE OPERATION OF THE SOFTWARE
* WILL BE UNINTERRUPTED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES 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.
*
* @Author: Hans Zandbelt - hans.zandbelt@zmartzone.eu
*/
#include <apr_lib.h>
#include <httpd.h>
#include <http_config.h>
#include <http_log.h>
#include <http_request.h>
#include "mod_auth_openidc.h"
#include "parse.h"
/*
* validate an access token against the validation endpoint of the Authorization server and gets a response back
*/
static apr_byte_t oidc_oauth_validate_access_token(request_rec *r, oidc_cfg *c,
const char *token, const char **response) {
/* assemble parameters to call the token endpoint for validation */
apr_table_t *params = apr_table_make(r->pool, 4);
/* add any configured extra static parameters to the introspection endpoint */
oidc_util_table_add_query_encoded_params(r->pool, params,
c->oauth.introspection_endpoint_params);
/* add the access_token itself */
apr_table_addn(params, c->oauth.introspection_token_param_name, token);
/* see if we want to do basic auth or post-param-based auth */
const char *basic_auth = NULL;
if ((c->oauth.client_id != NULL) && (c->oauth.client_secret != NULL)) {
if ((c->oauth.introspection_endpoint_auth != NULL)
&& (apr_strnatcmp(c->oauth.introspection_endpoint_auth,
"client_secret_post") == 0)) {
apr_table_addn(params, "client_id", c->oauth.client_id);
apr_table_addn(params, "client_secret", c->oauth.client_secret);
} else {
basic_auth = apr_psprintf(r->pool, "%s:%s", c->oauth.client_id,
c->oauth.client_secret);
}
}
/* call the endpoint with the constructed parameter set and return the resulting response */
return apr_strnatcmp(c->oauth.introspection_endpoint_method, OIDC_INTROSPECTION_METHOD_GET) == 0 ?
oidc_util_http_get(r, c->oauth.introspection_endpoint_url, params,
basic_auth, NULL, c->oauth.ssl_validate_server, response,
c->http_timeout_long, c->outgoing_proxy,
oidc_dir_cfg_pass_cookies(r), c->oauth.introspection_endpoint_tls_client_cert, c->oauth.introspection_endpoint_tls_client_key):
oidc_util_http_post_form(r, c->oauth.introspection_endpoint_url,
params, basic_auth, NULL, c->oauth.ssl_validate_server,
response, c->http_timeout_long, c->outgoing_proxy,
oidc_dir_cfg_pass_cookies(r), c->oauth.introspection_endpoint_tls_client_cert, c->oauth.introspection_endpoint_tls_client_key);
}
/*
* get the authorization header that should contain a bearer token
*/
static apr_byte_t oidc_oauth_get_bearer_token(request_rec *r,
const char **access_token) {
/* get the directory specific setting on how the token can be passed in */
int accept_token_in = oidc_cfg_dir_accept_token_in(r);
const char *cookie_name = oidc_cfg_dir_accept_token_in_option(r,
OIDC_OAUTH_ACCEPT_TOKEN_IN_OPTION_COOKIE_NAME);
oidc_debug(r, "accept_token_in=%d", accept_token_in);
*access_token = NULL;
if ((accept_token_in & OIDC_OAUTH_ACCEPT_TOKEN_IN_HEADER)
|| (accept_token_in == OIDC_OAUTH_ACCEPT_TOKEN_IN_DEFAULT)) {
/* get the authorization header */
const char *auth_line;
auth_line = apr_table_get(r->headers_in, "Authorization");
if (auth_line) {
oidc_debug(r, "authorization header found");
/* look for the Bearer keyword */
if (apr_strnatcasecmp(ap_getword(r->pool, &auth_line, ' '),
"Bearer") == 0) {
/* skip any spaces after the Bearer keyword */
while (apr_isspace(*auth_line)) {
auth_line++;
}
/* copy the result in to the access_token */
*access_token = apr_pstrdup(r->pool, auth_line);
} else {
oidc_warn(r,
"client used unsupported authentication scheme: %s",
r->uri);
}
}
}
if ((*access_token == NULL) && (r->method_number == M_POST)
&& (accept_token_in & OIDC_OAUTH_ACCEPT_TOKEN_IN_POST)) {
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params) == TRUE) {
*access_token = apr_table_get(params, "access_token");
}
}
if ((*access_token == NULL)
&& (accept_token_in & OIDC_OAUTH_ACCEPT_TOKEN_IN_QUERY)) {
apr_table_t *params = apr_table_make(r->pool, 8);
oidc_util_read_form_encoded_params(r, params, r->args);
*access_token = apr_table_get(params, "access_token");
}
if ((*access_token == NULL)
&& (accept_token_in & OIDC_OAUTH_ACCEPT_TOKEN_IN_COOKIE)) {
const char *auth_line = oidc_util_get_cookie(r, cookie_name);
if (auth_line != NULL) {
/* copy the result in to the access_token */
*access_token = apr_pstrdup(r->pool, auth_line);
} else {
oidc_warn(r, "no cookie found with name: %s", cookie_name);
}
}
if (*access_token == NULL) {
oidc_debug(r, "no bearer token found in the allowed methods: %s",
oidc_accept_oauth_token_in2str(r->pool, accept_token_in));
return FALSE;
}
/* log some stuff */
oidc_debug(r, "bearer token: %s", *access_token);
return TRUE;
}
/*
* copy over space separated scope value but do it in an array for authorization purposes
*/
/*
static void oidc_oauth_spaced_string_to_array(request_rec *r, json_t *src,
const char *src_key, json_t *dst, const char *dst_key) {
apr_hash_t *ht = NULL;
apr_hash_index_t *hi = NULL;
json_t *arr = NULL;
json_t *src_val = json_object_get(src, src_key);
if (src_val != NULL)
ht = oidc_util_spaced_string_to_hashtable(r->pool,
json_string_value(src_val));
if (ht != NULL) {
arr = json_array();
for (hi = apr_hash_first(NULL, ht); hi; hi = apr_hash_next(hi)) {
const char *k;
const char *v;
apr_hash_this(hi, (const void**) &k, NULL, (void**) &v);
json_array_append_new(arr, json_string(v));
}
json_object_set_new(dst, dst_key, arr);
}
}
*/
/*
* parse (custom/configurable) token expiry claim in introspection result
*/
static apr_byte_t oidc_oauth_parse_and_cache_token_expiry(request_rec *r,
oidc_cfg *c, json_t *introspection_response,
const char *expiry_claim_name, int expiry_format_absolute,
int expiry_claim_is_mandatory, apr_time_t *cache_until) {
oidc_debug(r,
"expiry_claim_name=%s, expiry_format_absolute=%d, expiry_claim_is_mandatory=%d",
expiry_claim_name, expiry_format_absolute,
expiry_claim_is_mandatory);
json_t *expiry = json_object_get(introspection_response, expiry_claim_name);
if (expiry == NULL) {
if (expiry_claim_is_mandatory) {
oidc_error(r,
"introspection response JSON object did not contain an \"%s\" claim",
expiry_claim_name);
return FALSE;
}
return TRUE;
}
if (!json_is_integer(expiry)) {
if (expiry_claim_is_mandatory) {
oidc_error(r,
"introspection response JSON object contains a \"%s\" claim but it is not a JSON integer",
expiry_claim_name);
return FALSE;
}
oidc_warn(r,
"introspection response JSON object contains a \"%s\" claim that is not an (optional) JSON integer: the introspection result will NOT be cached",
expiry_claim_name);
return TRUE;
}
json_int_t value = json_integer_value(expiry);
if (value <= 0) {
oidc_warn(r,
"introspection response JSON object integer number value <= 0 (%ld); introspection result will not be cached",
(long )value);
return TRUE;
}
*cache_until = apr_time_from_sec(value);
if (expiry_format_absolute == FALSE)
(*cache_until) += apr_time_now();
return TRUE;
}
static apr_byte_t oidc_oauth_cache_access_token(request_rec *r, oidc_cfg *c,
apr_time_t cache_until, const char *access_token, json_t *json) {
oidc_debug(r, "caching introspection result");
json_t *cache_entry = json_object();
json_object_set(cache_entry, "response", json);
json_object_set_new(cache_entry, "timestamp",
json_integer(apr_time_sec(apr_time_now())));
char *cache_value = json_dumps(cache_entry, 0);
/* set it in the cache so subsequent request don't need to validate the access_token and get the claims anymore */
c->cache->set(r, OIDC_CACHE_SECTION_ACCESS_TOKEN, access_token, cache_value,
cache_until);
json_decref(cache_entry);
free(cache_value);
return TRUE;
}
static apr_byte_t oidc_oauth_get_cached_access_token(request_rec *r,
oidc_cfg *c, const char *access_token, json_t **json) {
json_t *cache_entry = NULL;
const char *s_cache_entry = NULL;
json_error_t json_error;
/* see if we've got the claims for this access_token cached already */
c->cache->get(r, OIDC_CACHE_SECTION_ACCESS_TOKEN, access_token,
&s_cache_entry);
if (s_cache_entry == NULL)
return FALSE;
/* json decode the cache entry */
cache_entry = json_loads(s_cache_entry, 0, &json_error);
if (cache_entry == NULL) {
oidc_error(r, "cached JSON was corrupted: %s", json_error.text);
*json = NULL;
return FALSE;
}
/* compare the timestamp against the freshness requirement */
json_t *v = json_object_get(cache_entry, "timestamp");
apr_time_t now = apr_time_sec(apr_time_now());
int token_introspection_interval = oidc_cfg_token_introspection_interval(r);
if ((token_introspection_interval > 0)
&& (now > json_integer_value(v) + token_introspection_interval)) {
/* printout info about the event */
char buf[APR_RFC822_DATE_LEN + 1];
apr_rfc822_date(buf, apr_time_from_sec(json_integer_value(v)));
oidc_debug(r,
"token that was validated/cached at: [%s], does not meet token freshness requirement: %d)",
buf, token_introspection_interval);
/* invalidate the cache entry */
*json = NULL;
json_decref(cache_entry);
return FALSE;
}
oidc_debug(r,
"returning cached introspection result that meets freshness requirements: %s",
s_cache_entry);
/* we've got a cached introspection result that is still valid for this path's requirements */
*json = json_deep_copy(json_object_get(cache_entry, "response"));
json_decref(cache_entry);
return TRUE;
}
/*
* resolve and validate an access_token against the configured Authorization Server
*/
static apr_byte_t oidc_oauth_resolve_access_token(request_rec *r, oidc_cfg *c,
const char *access_token, json_t **token, char **response) {
json_t *result = NULL;
/* see if we've got the claims for this access_token cached already */
oidc_oauth_get_cached_access_token(r, c, access_token, &result);
if (result == NULL) {
const char *s_json = NULL;
/* not cached, go out and validate the access_token against the Authorization server and get the JSON claims back */
if (oidc_oauth_validate_access_token(r, c, access_token,
&s_json) == FALSE) {
oidc_error(r,
"could not get a validation response from the Authorization server");
return FALSE;
}
/* decode and see if it is not an error response somehow */
if (oidc_util_decode_json_and_check_error(r, s_json, &result) == FALSE)
return FALSE;
json_t *active = json_object_get(result, "active");
apr_time_t cache_until;
if (active != NULL) {
if (json_is_boolean(active)) {
if (!json_is_true(active)) {
oidc_debug(r,
"\"active\" boolean object with value \"false\" found in response JSON object");
json_decref(result);
return FALSE;
}
} else if (json_is_string(active)) {
if (apr_strnatcasecmp(json_string_value(active), "true") != 0) {
oidc_debug(r,
"\"active\" string object with value that is not equal to \"true\" found in response JSON object: %s",
json_string_value(active));
json_decref(result);
return FALSE;
}
} else {
oidc_debug(r,
"no \"active\" boolean or string object found in response JSON object");
json_decref(result);
return FALSE;
}
if (oidc_oauth_parse_and_cache_token_expiry(r, c, result, "exp",
TRUE, FALSE, &cache_until) == FALSE) {
json_decref(result);
return FALSE;
}
/* set it in the cache so subsequent request don't need to validate the access_token and get the claims anymore */
oidc_oauth_cache_access_token(r, c, cache_until, access_token,
result);
} else {
if (oidc_oauth_parse_and_cache_token_expiry(r, c, result,
c->oauth.introspection_token_expiry_claim_name,
apr_strnatcmp(
c->oauth.introspection_token_expiry_claim_format,
"absolute") == 0,
c->oauth.introspection_token_expiry_claim_required,
&cache_until) == FALSE) {
json_decref(result);
return FALSE;
}
/* set it in the cache so subsequent request don't need to validate the access_token and get the claims anymore */
oidc_oauth_cache_access_token(r, c, cache_until, access_token,
result);
}
}
/* return the access_token JSON object */
json_t *tkn = json_object_get(result, "access_token");
if ((tkn != NULL) && (json_is_object(tkn))) {
/*
* assume PingFederate validation: copy over those claims from the access_token
* that are relevant for authorization purposes
*/
json_object_set(tkn, "client_id", json_object_get(result, "client_id"));
json_object_set(tkn, "scope", json_object_get(result, "scope"));
//oidc_oauth_spaced_string_to_array(r, result, "scope", tkn, "scopes");
/* return only the pimped access_token results */
*token = json_deep_copy(tkn);
json_decref(result);
} else {
//oidc_oauth_spaced_string_to_array(r, result, "scope", result, "scopes");
/* assume spec compliant introspection */
*token = result;
}
char *s_token = json_dumps(*token, 0);
*response = apr_pstrdup(r->pool, s_token);
free(s_token);
return TRUE;
}
/*
* set the unique user identifier that will be propagated in the Apache r->user and REMOTE_USER variables
*/
static apr_byte_t oidc_oauth_set_remote_user(request_rec *r, oidc_cfg *c,
json_t *token) {
/* get the configured claim name to populate REMOTE_USER with (defaults to "Username") */
char *claim_name = apr_pstrdup(r->pool,
c->oauth.remote_user_claim.claim_name);
/* get the claim value from the resolved token JSON response to use as the REMOTE_USER key */
json_t *username = json_object_get(token, claim_name);
if ((username == NULL) || (!json_is_string(username))) {
oidc_warn(r, "response JSON object did not contain a \"%s\" string",
claim_name);
return FALSE;
}
r->user = apr_pstrdup(r->pool, json_string_value(username));
if (c->oauth.remote_user_claim.reg_exp != NULL) {
char *error_str = NULL;
if (oidc_util_regexp_first_match(r->pool, r->user,
c->oauth.remote_user_claim.reg_exp, &r->user,
&error_str) == FALSE) {
oidc_error(r, "oidc_util_regexp_first_match failed: %s", error_str);
r->user = NULL;
return FALSE;
}
}
oidc_debug(r, "set REMOTE_USER to claim %s=%s", claim_name,
json_string_value(username));
return TRUE;
}
/*
* validate a JWT access token (locally)
*
* TODO: document that we're reusing the following settings from the OIDC config section:
* - JWKs URI refresh interval
* - encryption key material (OIDCPrivateKeyFiles)
* - iat slack (OIDCIDTokenIatSlack)
*
* OIDCOAuthRemoteUserClaim client_id
* # 32x 61 hex
* OIDCOAuthVerifySharedKeys aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
*/
static apr_byte_t oidc_oauth_validate_jwt_access_token(request_rec *r,
oidc_cfg *c, const char *access_token, json_t **token, char **response) {
oidc_debug(r, "enter: JWT access_token header=%s",
oidc_proto_peek_jwt_header(r, access_token, NULL));
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret, 0, NULL,
TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwt_t *jwt = NULL;
if (oidc_jwt_parse(r->pool, access_token, &jwt,
oidc_util_merge_symmetric_key(r->pool, c->private_keys, jwk),
&err) == FALSE) {
oidc_error(r, "could not parse JWT from access_token: %s",
oidc_jose_e2s(r->pool, err));
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully parsed JWT with header: %s",
jwt->header.value.str);
/* validate the access token JWT, validating optional exp + iat */
if (oidc_proto_validate_jwt(r, jwt, NULL, FALSE, FALSE,
c->provider.idtoken_iat_slack) == FALSE) {
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_debug(r,
"verify JWT against %d statically configured public keys and %d shared keys, with JWKs URI set to %s",
c->oauth.verify_public_keys ?
apr_hash_count(c->oauth.verify_public_keys) : 0,
c->oauth.verify_shared_keys ?
apr_hash_count(c->oauth.verify_shared_keys) : 0,
c->oauth.verify_jwks_uri);
oidc_jwks_uri_t jwks_uri = { c->oauth.verify_jwks_uri,
c->provider.jwks_refresh_interval, c->oauth.ssl_validate_server };
if (oidc_proto_jwt_verify(r, c, jwt, &jwks_uri,
oidc_util_merge_key_sets(r->pool, c->oauth.verify_public_keys,
c->oauth.verify_shared_keys)) == FALSE) {
oidc_error(r,
"JWT access token signature could not be validated, aborting");
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_debug(r, "successfully verified JWT access token: %s",
jwt->payload.value.str);
*token = jwt->payload.value.json;
*response = jwt->payload.value.str;
return TRUE;
}
/*
* set the WWW-Authenticate response header according to https://tools.ietf.org/html/rfc6750#section-3
*/
int oidc_oauth_return_www_authenticate(request_rec *r, const char *error,
const char *error_description) {
char *hdr = apr_psprintf(r->pool, "Bearer");
if (ap_auth_name(r) != NULL)
hdr = apr_psprintf(r->pool, "%s realm=\"%s\"", hdr, ap_auth_name(r));
if (error != NULL)
hdr = apr_psprintf(r->pool, "%s%s error=\"%s\"", hdr,
(ap_auth_name(r) ? "," : ""), error);
if (error_description != NULL)
hdr = apr_psprintf(r->pool, "%s, error_description=\"%s\"", hdr,
error_description);
apr_table_setn(r->err_headers_out, "WWW-Authenticate", hdr);
return HTTP_UNAUTHORIZED;
}
/*
* main routine: handle OAuth 2.0 authentication/authorization
*/
int oidc_oauth_check_userid(request_rec *r, oidc_cfg *c) {
/* check if this is a sub-request or an initial request */
if (!ap_is_initial_req(r)) {
if (r->main != NULL)
r->user = r->main->user;
else if (r->prev != NULL)
r->user = r->prev->user;
if (r->user != NULL) {
/* this is a sub-request and we have a session */
oidc_debug(r,
"recycling user '%s' from initial request for sub-request",
r->user);
return OK;
}
/* check if this is a request for the public (encryption) keys */
} else if ((c->redirect_uri != NULL)
&& (oidc_util_request_matches_url(r, c->redirect_uri))) {
if (oidc_util_request_has_parameter(r, "jwks")) {
return oidc_handle_jwks(r, c);
}
}
/* we don't have a session yet */
/* get the bearer access token from the Authorization header */
const char *access_token = NULL;
if (oidc_oauth_get_bearer_token(r, &access_token) == FALSE)
return oidc_oauth_return_www_authenticate(r, "invalid_request",
"No bearer token found in the request");
/* validate the obtained access token against the OAuth AS validation endpoint */
json_t *token = NULL;
char *s_token = NULL;
/* check if an introspection endpoint is set */
if (c->oauth.introspection_endpoint_url != NULL) {
/* we'll validate the token remotely */
if (oidc_oauth_resolve_access_token(r, c, access_token, &token,
&s_token) == FALSE)
return oidc_oauth_return_www_authenticate(r, "invalid_token",
"Reference token could not be introspected");
} else {
/* no introspection endpoint is set, assume the token is a JWT and validate it locally */
if (oidc_oauth_validate_jwt_access_token(r, c, access_token, &token,
&s_token) == FALSE)
return oidc_oauth_return_www_authenticate(r, "invalid_token",
"JWT token could not be validated");
}
/* check that we've got something back */
if (token == NULL) {
oidc_error(r, "could not resolve claims (token == NULL)");
return oidc_oauth_return_www_authenticate(r, "invalid_token",
"No claims could be parsed from the token");
}
/* store the parsed token (cq. the claims from the response) in the request state so it can be accessed by the authz routines */
oidc_request_state_set(r, OIDC_CLAIMS_SESSION_KEY, (const char *) s_token);
/* set the REMOTE_USER variable */
if (oidc_oauth_set_remote_user(r, c, token) == FALSE) {
oidc_error(r,
"remote user could not be set, aborting with HTTP_UNAUTHORIZED");
return oidc_oauth_return_www_authenticate(r, "invalid_token",
"Could not set remote user");
}
/* set the user authentication HTTP header if set and required */
char *authn_header = oidc_cfg_dir_authn_header(r);
int pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
int pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
if ((r->user != NULL) && (authn_header != NULL)) {
oidc_debug(r, "setting authn header (%s) to: %s", authn_header,
r->user);
apr_table_set(r->headers_in, authn_header, r->user);
}
/* set the resolved claims in the HTTP headers for the target application */
oidc_util_set_app_infos(r, token, c->claim_prefix, c->claim_delimiter,
pass_headers, pass_envvars);
/* set the access_token in the app headers */
if (access_token != NULL) {
oidc_util_set_app_info(r, "access_token", access_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* free JSON resources */
json_decref(token);
return OK;
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/bad_3184_4 |
crossvul-cpp_data_good_3721_2 | /*
* NET4: Implementation of BSD Unix domain sockets.
*
* Authors: Alan Cox, <alan@lxorguk.ukuu.org.uk>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Fixes:
* Linus Torvalds : Assorted bug cures.
* Niibe Yutaka : async I/O support.
* Carsten Paeth : PF_UNIX check, address fixes.
* Alan Cox : Limit size of allocated blocks.
* Alan Cox : Fixed the stupid socketpair bug.
* Alan Cox : BSD compatibility fine tuning.
* Alan Cox : Fixed a bug in connect when interrupted.
* Alan Cox : Sorted out a proper draft version of
* file descriptor passing hacked up from
* Mike Shaver's work.
* Marty Leisner : Fixes to fd passing
* Nick Nevin : recvmsg bugfix.
* Alan Cox : Started proper garbage collector
* Heiko EiBfeldt : Missing verify_area check
* Alan Cox : Started POSIXisms
* Andreas Schwab : Replace inode by dentry for proper
* reference counting
* Kirk Petersen : Made this a module
* Christoph Rohland : Elegant non-blocking accept/connect algorithm.
* Lots of bug fixes.
* Alexey Kuznetosv : Repaired (I hope) bugs introduces
* by above two patches.
* Andrea Arcangeli : If possible we block in connect(2)
* if the max backlog of the listen socket
* is been reached. This won't break
* old apps and it will avoid huge amount
* of socks hashed (this for unix_gc()
* performances reasons).
* Security fix that limits the max
* number of socks to 2*max_files and
* the number of skb queueable in the
* dgram receiver.
* Artur Skawina : Hash function optimizations
* Alexey Kuznetsov : Full scale SMP. Lot of bugs are introduced 8)
* Malcolm Beattie : Set peercred for socketpair
* Michal Ostrowski : Module initialization cleanup.
* Arnaldo C. Melo : Remove MOD_{INC,DEC}_USE_COUNT,
* the core infrastructure is doing that
* for all net proto families now (2.5.69+)
*
*
* Known differences from reference BSD that was tested:
*
* [TO FIX]
* ECONNREFUSED is not returned from one end of a connected() socket to the
* other the moment one end closes.
* fstat() doesn't return st_dev=0, and give the blksize as high water mark
* and a fake inode identifier (nor the BSD first socket fstat twice bug).
* [NOT TO FIX]
* accept() returns a path name even if the connecting socket has closed
* in the meantime (BSD loses the path and gives up).
* accept() returns 0 length path for an unbound connector. BSD returns 16
* and a null first byte in the path (but not for gethost/peername - BSD bug ??)
* socketpair(...SOCK_RAW..) doesn't panic the kernel.
* BSD af_unix apparently has connect forgetting to block properly.
* (need to check this with the POSIX spec in detail)
*
* Differences from 2.0.0-11-... (ANK)
* Bug fixes and improvements.
* - client shutdown killed server socket.
* - removed all useless cli/sti pairs.
*
* Semantic changes/extensions.
* - generic control message passing.
* - SCM_CREDENTIALS control message.
* - "Abstract" (not FS based) socket bindings.
* Abstract names are sequences of bytes (not zero terminated)
* started by 0, so that this name space does not intersect
* with BSD names.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/stat.h>
#include <linux/dcache.h>
#include <linux/namei.h>
#include <linux/socket.h>
#include <linux/un.h>
#include <linux/fcntl.h>
#include <linux/termios.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/in.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <net/af_unix.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <net/scm.h>
#include <linux/init.h>
#include <linux/poll.h>
#include <linux/rtnetlink.h>
#include <linux/mount.h>
#include <net/checksum.h>
#include <linux/security.h>
struct hlist_head unix_socket_table[2 * UNIX_HASH_SIZE];
EXPORT_SYMBOL_GPL(unix_socket_table);
DEFINE_SPINLOCK(unix_table_lock);
EXPORT_SYMBOL_GPL(unix_table_lock);
static atomic_long_t unix_nr_socks;
static struct hlist_head *unix_sockets_unbound(void *addr)
{
unsigned long hash = (unsigned long)addr;
hash ^= hash >> 16;
hash ^= hash >> 8;
hash %= UNIX_HASH_SIZE;
return &unix_socket_table[UNIX_HASH_SIZE + hash];
}
#define UNIX_ABSTRACT(sk) (unix_sk(sk)->addr->hash < UNIX_HASH_SIZE)
#ifdef CONFIG_SECURITY_NETWORK
static void unix_get_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{
memcpy(UNIXSID(skb), &scm->secid, sizeof(u32));
}
static inline void unix_set_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{
scm->secid = *UNIXSID(skb);
}
#else
static inline void unix_get_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{ }
static inline void unix_set_secdata(struct scm_cookie *scm, struct sk_buff *skb)
{ }
#endif /* CONFIG_SECURITY_NETWORK */
/*
* SMP locking strategy:
* hash table is protected with spinlock unix_table_lock
* each socket state is protected by separate spin lock.
*/
static inline unsigned int unix_hash_fold(__wsum n)
{
unsigned int hash = (__force unsigned int)n;
hash ^= hash>>16;
hash ^= hash>>8;
return hash&(UNIX_HASH_SIZE-1);
}
#define unix_peer(sk) (unix_sk(sk)->peer)
static inline int unix_our_peer(struct sock *sk, struct sock *osk)
{
return unix_peer(osk) == sk;
}
static inline int unix_may_send(struct sock *sk, struct sock *osk)
{
return unix_peer(osk) == NULL || unix_our_peer(sk, osk);
}
static inline int unix_recvq_full(struct sock const *sk)
{
return skb_queue_len(&sk->sk_receive_queue) > sk->sk_max_ack_backlog;
}
struct sock *unix_peer_get(struct sock *s)
{
struct sock *peer;
unix_state_lock(s);
peer = unix_peer(s);
if (peer)
sock_hold(peer);
unix_state_unlock(s);
return peer;
}
EXPORT_SYMBOL_GPL(unix_peer_get);
static inline void unix_release_addr(struct unix_address *addr)
{
if (atomic_dec_and_test(&addr->refcnt))
kfree(addr);
}
/*
* Check unix socket name:
* - should be not zero length.
* - if started by not zero, should be NULL terminated (FS object)
* - if started by zero, it is abstract name.
*/
static int unix_mkname(struct sockaddr_un *sunaddr, int len, unsigned int *hashp)
{
if (len <= sizeof(short) || len > sizeof(*sunaddr))
return -EINVAL;
if (!sunaddr || sunaddr->sun_family != AF_UNIX)
return -EINVAL;
if (sunaddr->sun_path[0]) {
/*
* This may look like an off by one error but it is a bit more
* subtle. 108 is the longest valid AF_UNIX path for a binding.
* sun_path[108] doesn't as such exist. However in kernel space
* we are guaranteed that it is a valid memory location in our
* kernel address buffer.
*/
((char *)sunaddr)[len] = 0;
len = strlen(sunaddr->sun_path)+1+sizeof(short);
return len;
}
*hashp = unix_hash_fold(csum_partial(sunaddr, len, 0));
return len;
}
static void __unix_remove_socket(struct sock *sk)
{
sk_del_node_init(sk);
}
static void __unix_insert_socket(struct hlist_head *list, struct sock *sk)
{
WARN_ON(!sk_unhashed(sk));
sk_add_node(sk, list);
}
static inline void unix_remove_socket(struct sock *sk)
{
spin_lock(&unix_table_lock);
__unix_remove_socket(sk);
spin_unlock(&unix_table_lock);
}
static inline void unix_insert_socket(struct hlist_head *list, struct sock *sk)
{
spin_lock(&unix_table_lock);
__unix_insert_socket(list, sk);
spin_unlock(&unix_table_lock);
}
static struct sock *__unix_find_socket_byname(struct net *net,
struct sockaddr_un *sunname,
int len, int type, unsigned int hash)
{
struct sock *s;
struct hlist_node *node;
sk_for_each(s, node, &unix_socket_table[hash ^ type]) {
struct unix_sock *u = unix_sk(s);
if (!net_eq(sock_net(s), net))
continue;
if (u->addr->len == len &&
!memcmp(u->addr->name, sunname, len))
goto found;
}
s = NULL;
found:
return s;
}
static inline struct sock *unix_find_socket_byname(struct net *net,
struct sockaddr_un *sunname,
int len, int type,
unsigned int hash)
{
struct sock *s;
spin_lock(&unix_table_lock);
s = __unix_find_socket_byname(net, sunname, len, type, hash);
if (s)
sock_hold(s);
spin_unlock(&unix_table_lock);
return s;
}
static struct sock *unix_find_socket_byinode(struct inode *i)
{
struct sock *s;
struct hlist_node *node;
spin_lock(&unix_table_lock);
sk_for_each(s, node,
&unix_socket_table[i->i_ino & (UNIX_HASH_SIZE - 1)]) {
struct dentry *dentry = unix_sk(s)->path.dentry;
if (dentry && dentry->d_inode == i) {
sock_hold(s);
goto found;
}
}
s = NULL;
found:
spin_unlock(&unix_table_lock);
return s;
}
static inline int unix_writable(struct sock *sk)
{
return (atomic_read(&sk->sk_wmem_alloc) << 2) <= sk->sk_sndbuf;
}
static void unix_write_space(struct sock *sk)
{
struct socket_wq *wq;
rcu_read_lock();
if (unix_writable(sk)) {
wq = rcu_dereference(sk->sk_wq);
if (wq_has_sleeper(wq))
wake_up_interruptible_sync_poll(&wq->wait,
POLLOUT | POLLWRNORM | POLLWRBAND);
sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
}
rcu_read_unlock();
}
/* When dgram socket disconnects (or changes its peer), we clear its receive
* queue of packets arrived from previous peer. First, it allows to do
* flow control based only on wmem_alloc; second, sk connected to peer
* may receive messages only from that peer. */
static void unix_dgram_disconnected(struct sock *sk, struct sock *other)
{
if (!skb_queue_empty(&sk->sk_receive_queue)) {
skb_queue_purge(&sk->sk_receive_queue);
wake_up_interruptible_all(&unix_sk(sk)->peer_wait);
/* If one link of bidirectional dgram pipe is disconnected,
* we signal error. Messages are lost. Do not make this,
* when peer was not connected to us.
*/
if (!sock_flag(other, SOCK_DEAD) && unix_peer(other) == sk) {
other->sk_err = ECONNRESET;
other->sk_error_report(other);
}
}
}
static void unix_sock_destructor(struct sock *sk)
{
struct unix_sock *u = unix_sk(sk);
skb_queue_purge(&sk->sk_receive_queue);
WARN_ON(atomic_read(&sk->sk_wmem_alloc));
WARN_ON(!sk_unhashed(sk));
WARN_ON(sk->sk_socket);
if (!sock_flag(sk, SOCK_DEAD)) {
printk(KERN_INFO "Attempt to release alive unix socket: %p\n", sk);
return;
}
if (u->addr)
unix_release_addr(u->addr);
atomic_long_dec(&unix_nr_socks);
local_bh_disable();
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
local_bh_enable();
#ifdef UNIX_REFCNT_DEBUG
printk(KERN_DEBUG "UNIX %p is destroyed, %ld are still alive.\n", sk,
atomic_long_read(&unix_nr_socks));
#endif
}
static int unix_release_sock(struct sock *sk, int embrion)
{
struct unix_sock *u = unix_sk(sk);
struct path path;
struct sock *skpair;
struct sk_buff *skb;
int state;
unix_remove_socket(sk);
/* Clear state */
unix_state_lock(sk);
sock_orphan(sk);
sk->sk_shutdown = SHUTDOWN_MASK;
path = u->path;
u->path.dentry = NULL;
u->path.mnt = NULL;
state = sk->sk_state;
sk->sk_state = TCP_CLOSE;
unix_state_unlock(sk);
wake_up_interruptible_all(&u->peer_wait);
skpair = unix_peer(sk);
if (skpair != NULL) {
if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) {
unix_state_lock(skpair);
/* No more writes */
skpair->sk_shutdown = SHUTDOWN_MASK;
if (!skb_queue_empty(&sk->sk_receive_queue) || embrion)
skpair->sk_err = ECONNRESET;
unix_state_unlock(skpair);
skpair->sk_state_change(skpair);
sk_wake_async(skpair, SOCK_WAKE_WAITD, POLL_HUP);
}
sock_put(skpair); /* It may now die */
unix_peer(sk) = NULL;
}
/* Try to flush out this socket. Throw out buffers at least */
while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) {
if (state == TCP_LISTEN)
unix_release_sock(skb->sk, 1);
/* passed fds are erased in the kfree_skb hook */
kfree_skb(skb);
}
if (path.dentry)
path_put(&path);
sock_put(sk);
/* ---- Socket is dead now and most probably destroyed ---- */
/*
* Fixme: BSD difference: In BSD all sockets connected to use get
* ECONNRESET and we die on the spot. In Linux we behave
* like files and pipes do and wait for the last
* dereference.
*
* Can't we simply set sock->err?
*
* What the above comment does talk about? --ANK(980817)
*/
if (unix_tot_inflight)
unix_gc(); /* Garbage collect fds */
return 0;
}
static void init_peercred(struct sock *sk)
{
put_pid(sk->sk_peer_pid);
if (sk->sk_peer_cred)
put_cred(sk->sk_peer_cred);
sk->sk_peer_pid = get_pid(task_tgid(current));
sk->sk_peer_cred = get_current_cred();
}
static void copy_peercred(struct sock *sk, struct sock *peersk)
{
put_pid(sk->sk_peer_pid);
if (sk->sk_peer_cred)
put_cred(sk->sk_peer_cred);
sk->sk_peer_pid = get_pid(peersk->sk_peer_pid);
sk->sk_peer_cred = get_cred(peersk->sk_peer_cred);
}
static int unix_listen(struct socket *sock, int backlog)
{
int err;
struct sock *sk = sock->sk;
struct unix_sock *u = unix_sk(sk);
struct pid *old_pid = NULL;
const struct cred *old_cred = NULL;
err = -EOPNOTSUPP;
if (sock->type != SOCK_STREAM && sock->type != SOCK_SEQPACKET)
goto out; /* Only stream/seqpacket sockets accept */
err = -EINVAL;
if (!u->addr)
goto out; /* No listens on an unbound socket */
unix_state_lock(sk);
if (sk->sk_state != TCP_CLOSE && sk->sk_state != TCP_LISTEN)
goto out_unlock;
if (backlog > sk->sk_max_ack_backlog)
wake_up_interruptible_all(&u->peer_wait);
sk->sk_max_ack_backlog = backlog;
sk->sk_state = TCP_LISTEN;
/* set credentials so connect can copy them */
init_peercred(sk);
err = 0;
out_unlock:
unix_state_unlock(sk);
put_pid(old_pid);
if (old_cred)
put_cred(old_cred);
out:
return err;
}
static int unix_release(struct socket *);
static int unix_bind(struct socket *, struct sockaddr *, int);
static int unix_stream_connect(struct socket *, struct sockaddr *,
int addr_len, int flags);
static int unix_socketpair(struct socket *, struct socket *);
static int unix_accept(struct socket *, struct socket *, int);
static int unix_getname(struct socket *, struct sockaddr *, int *, int);
static unsigned int unix_poll(struct file *, struct socket *, poll_table *);
static unsigned int unix_dgram_poll(struct file *, struct socket *,
poll_table *);
static int unix_ioctl(struct socket *, unsigned int, unsigned long);
static int unix_shutdown(struct socket *, int);
static int unix_stream_sendmsg(struct kiocb *, struct socket *,
struct msghdr *, size_t);
static int unix_stream_recvmsg(struct kiocb *, struct socket *,
struct msghdr *, size_t, int);
static int unix_dgram_sendmsg(struct kiocb *, struct socket *,
struct msghdr *, size_t);
static int unix_dgram_recvmsg(struct kiocb *, struct socket *,
struct msghdr *, size_t, int);
static int unix_dgram_connect(struct socket *, struct sockaddr *,
int, int);
static int unix_seqpacket_sendmsg(struct kiocb *, struct socket *,
struct msghdr *, size_t);
static int unix_seqpacket_recvmsg(struct kiocb *, struct socket *,
struct msghdr *, size_t, int);
static void unix_set_peek_off(struct sock *sk, int val)
{
struct unix_sock *u = unix_sk(sk);
mutex_lock(&u->readlock);
sk->sk_peek_off = val;
mutex_unlock(&u->readlock);
}
static const struct proto_ops unix_stream_ops = {
.family = PF_UNIX,
.owner = THIS_MODULE,
.release = unix_release,
.bind = unix_bind,
.connect = unix_stream_connect,
.socketpair = unix_socketpair,
.accept = unix_accept,
.getname = unix_getname,
.poll = unix_poll,
.ioctl = unix_ioctl,
.listen = unix_listen,
.shutdown = unix_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = unix_stream_sendmsg,
.recvmsg = unix_stream_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
.set_peek_off = unix_set_peek_off,
};
static const struct proto_ops unix_dgram_ops = {
.family = PF_UNIX,
.owner = THIS_MODULE,
.release = unix_release,
.bind = unix_bind,
.connect = unix_dgram_connect,
.socketpair = unix_socketpair,
.accept = sock_no_accept,
.getname = unix_getname,
.poll = unix_dgram_poll,
.ioctl = unix_ioctl,
.listen = sock_no_listen,
.shutdown = unix_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = unix_dgram_sendmsg,
.recvmsg = unix_dgram_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
.set_peek_off = unix_set_peek_off,
};
static const struct proto_ops unix_seqpacket_ops = {
.family = PF_UNIX,
.owner = THIS_MODULE,
.release = unix_release,
.bind = unix_bind,
.connect = unix_stream_connect,
.socketpair = unix_socketpair,
.accept = unix_accept,
.getname = unix_getname,
.poll = unix_dgram_poll,
.ioctl = unix_ioctl,
.listen = unix_listen,
.shutdown = unix_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = unix_seqpacket_sendmsg,
.recvmsg = unix_seqpacket_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
.set_peek_off = unix_set_peek_off,
};
static struct proto unix_proto = {
.name = "UNIX",
.owner = THIS_MODULE,
.obj_size = sizeof(struct unix_sock),
};
/*
* AF_UNIX sockets do not interact with hardware, hence they
* dont trigger interrupts - so it's safe for them to have
* bh-unsafe locking for their sk_receive_queue.lock. Split off
* this special lock-class by reinitializing the spinlock key:
*/
static struct lock_class_key af_unix_sk_receive_queue_lock_key;
static struct sock *unix_create1(struct net *net, struct socket *sock)
{
struct sock *sk = NULL;
struct unix_sock *u;
atomic_long_inc(&unix_nr_socks);
if (atomic_long_read(&unix_nr_socks) > 2 * get_max_files())
goto out;
sk = sk_alloc(net, PF_UNIX, GFP_KERNEL, &unix_proto);
if (!sk)
goto out;
sock_init_data(sock, sk);
lockdep_set_class(&sk->sk_receive_queue.lock,
&af_unix_sk_receive_queue_lock_key);
sk->sk_write_space = unix_write_space;
sk->sk_max_ack_backlog = net->unx.sysctl_max_dgram_qlen;
sk->sk_destruct = unix_sock_destructor;
u = unix_sk(sk);
u->path.dentry = NULL;
u->path.mnt = NULL;
spin_lock_init(&u->lock);
atomic_long_set(&u->inflight, 0);
INIT_LIST_HEAD(&u->link);
mutex_init(&u->readlock); /* single task reading lock */
init_waitqueue_head(&u->peer_wait);
unix_insert_socket(unix_sockets_unbound(sk), sk);
out:
if (sk == NULL)
atomic_long_dec(&unix_nr_socks);
else {
local_bh_disable();
sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
local_bh_enable();
}
return sk;
}
static int unix_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
if (protocol && protocol != PF_UNIX)
return -EPROTONOSUPPORT;
sock->state = SS_UNCONNECTED;
switch (sock->type) {
case SOCK_STREAM:
sock->ops = &unix_stream_ops;
break;
/*
* Believe it or not BSD has AF_UNIX, SOCK_RAW though
* nothing uses it.
*/
case SOCK_RAW:
sock->type = SOCK_DGRAM;
case SOCK_DGRAM:
sock->ops = &unix_dgram_ops;
break;
case SOCK_SEQPACKET:
sock->ops = &unix_seqpacket_ops;
break;
default:
return -ESOCKTNOSUPPORT;
}
return unix_create1(net, sock) ? 0 : -ENOMEM;
}
static int unix_release(struct socket *sock)
{
struct sock *sk = sock->sk;
if (!sk)
return 0;
sock->sk = NULL;
return unix_release_sock(sk, 0);
}
static int unix_autobind(struct socket *sock)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk);
static u32 ordernum = 1;
struct unix_address *addr;
int err;
unsigned int retries = 0;
mutex_lock(&u->readlock);
err = 0;
if (u->addr)
goto out;
err = -ENOMEM;
addr = kzalloc(sizeof(*addr) + sizeof(short) + 16, GFP_KERNEL);
if (!addr)
goto out;
addr->name->sun_family = AF_UNIX;
atomic_set(&addr->refcnt, 1);
retry:
addr->len = sprintf(addr->name->sun_path+1, "%05x", ordernum) + 1 + sizeof(short);
addr->hash = unix_hash_fold(csum_partial(addr->name, addr->len, 0));
spin_lock(&unix_table_lock);
ordernum = (ordernum+1)&0xFFFFF;
if (__unix_find_socket_byname(net, addr->name, addr->len, sock->type,
addr->hash)) {
spin_unlock(&unix_table_lock);
/*
* __unix_find_socket_byname() may take long time if many names
* are already in use.
*/
cond_resched();
/* Give up if all names seems to be in use. */
if (retries++ == 0xFFFFF) {
err = -ENOSPC;
kfree(addr);
goto out;
}
goto retry;
}
addr->hash ^= sk->sk_type;
__unix_remove_socket(sk);
u->addr = addr;
__unix_insert_socket(&unix_socket_table[addr->hash], sk);
spin_unlock(&unix_table_lock);
err = 0;
out: mutex_unlock(&u->readlock);
return err;
}
static struct sock *unix_find_other(struct net *net,
struct sockaddr_un *sunname, int len,
int type, unsigned int hash, int *error)
{
struct sock *u;
struct path path;
int err = 0;
if (sunname->sun_path[0]) {
struct inode *inode;
err = kern_path(sunname->sun_path, LOOKUP_FOLLOW, &path);
if (err)
goto fail;
inode = path.dentry->d_inode;
err = inode_permission(inode, MAY_WRITE);
if (err)
goto put_fail;
err = -ECONNREFUSED;
if (!S_ISSOCK(inode->i_mode))
goto put_fail;
u = unix_find_socket_byinode(inode);
if (!u)
goto put_fail;
if (u->sk_type == type)
touch_atime(&path);
path_put(&path);
err = -EPROTOTYPE;
if (u->sk_type != type) {
sock_put(u);
goto fail;
}
} else {
err = -ECONNREFUSED;
u = unix_find_socket_byname(net, sunname, len, type, hash);
if (u) {
struct dentry *dentry;
dentry = unix_sk(u)->path.dentry;
if (dentry)
touch_atime(&unix_sk(u)->path);
} else
goto fail;
}
return u;
put_fail:
path_put(&path);
fail:
*error = err;
return NULL;
}
static int unix_mknod(const char *sun_path, umode_t mode, struct path *res)
{
struct dentry *dentry;
struct path path;
int err = 0;
/*
* Get the parent directory, calculate the hash for last
* component.
*/
dentry = kern_path_create(AT_FDCWD, sun_path, &path, 0);
err = PTR_ERR(dentry);
if (IS_ERR(dentry))
return err;
/*
* All right, let's create it.
*/
err = security_path_mknod(&path, dentry, mode, 0);
if (!err) {
err = vfs_mknod(path.dentry->d_inode, dentry, mode, 0);
if (!err) {
res->mnt = mntget(path.mnt);
res->dentry = dget(dentry);
}
}
done_path_create(&path, dentry);
return err;
}
static int unix_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk);
struct sockaddr_un *sunaddr = (struct sockaddr_un *)uaddr;
char *sun_path = sunaddr->sun_path;
int err;
unsigned int hash;
struct unix_address *addr;
struct hlist_head *list;
err = -EINVAL;
if (sunaddr->sun_family != AF_UNIX)
goto out;
if (addr_len == sizeof(short)) {
err = unix_autobind(sock);
goto out;
}
err = unix_mkname(sunaddr, addr_len, &hash);
if (err < 0)
goto out;
addr_len = err;
mutex_lock(&u->readlock);
err = -EINVAL;
if (u->addr)
goto out_up;
err = -ENOMEM;
addr = kmalloc(sizeof(*addr)+addr_len, GFP_KERNEL);
if (!addr)
goto out_up;
memcpy(addr->name, sunaddr, addr_len);
addr->len = addr_len;
addr->hash = hash ^ sk->sk_type;
atomic_set(&addr->refcnt, 1);
if (sun_path[0]) {
struct path path;
umode_t mode = S_IFSOCK |
(SOCK_INODE(sock)->i_mode & ~current_umask());
err = unix_mknod(sun_path, mode, &path);
if (err) {
if (err == -EEXIST)
err = -EADDRINUSE;
unix_release_addr(addr);
goto out_up;
}
addr->hash = UNIX_HASH_SIZE;
hash = path.dentry->d_inode->i_ino & (UNIX_HASH_SIZE-1);
spin_lock(&unix_table_lock);
u->path = path;
list = &unix_socket_table[hash];
} else {
spin_lock(&unix_table_lock);
err = -EADDRINUSE;
if (__unix_find_socket_byname(net, sunaddr, addr_len,
sk->sk_type, hash)) {
unix_release_addr(addr);
goto out_unlock;
}
list = &unix_socket_table[addr->hash];
}
err = 0;
__unix_remove_socket(sk);
u->addr = addr;
__unix_insert_socket(list, sk);
out_unlock:
spin_unlock(&unix_table_lock);
out_up:
mutex_unlock(&u->readlock);
out:
return err;
}
static void unix_state_double_lock(struct sock *sk1, struct sock *sk2)
{
if (unlikely(sk1 == sk2) || !sk2) {
unix_state_lock(sk1);
return;
}
if (sk1 < sk2) {
unix_state_lock(sk1);
unix_state_lock_nested(sk2);
} else {
unix_state_lock(sk2);
unix_state_lock_nested(sk1);
}
}
static void unix_state_double_unlock(struct sock *sk1, struct sock *sk2)
{
if (unlikely(sk1 == sk2) || !sk2) {
unix_state_unlock(sk1);
return;
}
unix_state_unlock(sk1);
unix_state_unlock(sk2);
}
static int unix_dgram_connect(struct socket *sock, struct sockaddr *addr,
int alen, int flags)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct sockaddr_un *sunaddr = (struct sockaddr_un *)addr;
struct sock *other;
unsigned int hash;
int err;
if (addr->sa_family != AF_UNSPEC) {
err = unix_mkname(sunaddr, alen, &hash);
if (err < 0)
goto out;
alen = err;
if (test_bit(SOCK_PASSCRED, &sock->flags) &&
!unix_sk(sk)->addr && (err = unix_autobind(sock)) != 0)
goto out;
restart:
other = unix_find_other(net, sunaddr, alen, sock->type, hash, &err);
if (!other)
goto out;
unix_state_double_lock(sk, other);
/* Apparently VFS overslept socket death. Retry. */
if (sock_flag(other, SOCK_DEAD)) {
unix_state_double_unlock(sk, other);
sock_put(other);
goto restart;
}
err = -EPERM;
if (!unix_may_send(sk, other))
goto out_unlock;
err = security_unix_may_send(sk->sk_socket, other->sk_socket);
if (err)
goto out_unlock;
} else {
/*
* 1003.1g breaking connected state with AF_UNSPEC
*/
other = NULL;
unix_state_double_lock(sk, other);
}
/*
* If it was connected, reconnect.
*/
if (unix_peer(sk)) {
struct sock *old_peer = unix_peer(sk);
unix_peer(sk) = other;
unix_state_double_unlock(sk, other);
if (other != old_peer)
unix_dgram_disconnected(sk, old_peer);
sock_put(old_peer);
} else {
unix_peer(sk) = other;
unix_state_double_unlock(sk, other);
}
return 0;
out_unlock:
unix_state_double_unlock(sk, other);
sock_put(other);
out:
return err;
}
static long unix_wait_for_peer(struct sock *other, long timeo)
{
struct unix_sock *u = unix_sk(other);
int sched;
DEFINE_WAIT(wait);
prepare_to_wait_exclusive(&u->peer_wait, &wait, TASK_INTERRUPTIBLE);
sched = !sock_flag(other, SOCK_DEAD) &&
!(other->sk_shutdown & RCV_SHUTDOWN) &&
unix_recvq_full(other);
unix_state_unlock(other);
if (sched)
timeo = schedule_timeout(timeo);
finish_wait(&u->peer_wait, &wait);
return timeo;
}
static int unix_stream_connect(struct socket *sock, struct sockaddr *uaddr,
int addr_len, int flags)
{
struct sockaddr_un *sunaddr = (struct sockaddr_un *)uaddr;
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk), *newu, *otheru;
struct sock *newsk = NULL;
struct sock *other = NULL;
struct sk_buff *skb = NULL;
unsigned int hash;
int st;
int err;
long timeo;
err = unix_mkname(sunaddr, addr_len, &hash);
if (err < 0)
goto out;
addr_len = err;
if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr &&
(err = unix_autobind(sock)) != 0)
goto out;
timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
/* First of all allocate resources.
If we will make it after state is locked,
we will have to recheck all again in any case.
*/
err = -ENOMEM;
/* create new sock for complete connection */
newsk = unix_create1(sock_net(sk), NULL);
if (newsk == NULL)
goto out;
/* Allocate skb for sending to listening sock */
skb = sock_wmalloc(newsk, 1, 0, GFP_KERNEL);
if (skb == NULL)
goto out;
restart:
/* Find listening sock. */
other = unix_find_other(net, sunaddr, addr_len, sk->sk_type, hash, &err);
if (!other)
goto out;
/* Latch state of peer */
unix_state_lock(other);
/* Apparently VFS overslept socket death. Retry. */
if (sock_flag(other, SOCK_DEAD)) {
unix_state_unlock(other);
sock_put(other);
goto restart;
}
err = -ECONNREFUSED;
if (other->sk_state != TCP_LISTEN)
goto out_unlock;
if (other->sk_shutdown & RCV_SHUTDOWN)
goto out_unlock;
if (unix_recvq_full(other)) {
err = -EAGAIN;
if (!timeo)
goto out_unlock;
timeo = unix_wait_for_peer(other, timeo);
err = sock_intr_errno(timeo);
if (signal_pending(current))
goto out;
sock_put(other);
goto restart;
}
/* Latch our state.
It is tricky place. We need to grab our state lock and cannot
drop lock on peer. It is dangerous because deadlock is
possible. Connect to self case and simultaneous
attempt to connect are eliminated by checking socket
state. other is TCP_LISTEN, if sk is TCP_LISTEN we
check this before attempt to grab lock.
Well, and we have to recheck the state after socket locked.
*/
st = sk->sk_state;
switch (st) {
case TCP_CLOSE:
/* This is ok... continue with connect */
break;
case TCP_ESTABLISHED:
/* Socket is already connected */
err = -EISCONN;
goto out_unlock;
default:
err = -EINVAL;
goto out_unlock;
}
unix_state_lock_nested(sk);
if (sk->sk_state != st) {
unix_state_unlock(sk);
unix_state_unlock(other);
sock_put(other);
goto restart;
}
err = security_unix_stream_connect(sk, other, newsk);
if (err) {
unix_state_unlock(sk);
goto out_unlock;
}
/* The way is open! Fastly set all the necessary fields... */
sock_hold(sk);
unix_peer(newsk) = sk;
newsk->sk_state = TCP_ESTABLISHED;
newsk->sk_type = sk->sk_type;
init_peercred(newsk);
newu = unix_sk(newsk);
RCU_INIT_POINTER(newsk->sk_wq, &newu->peer_wq);
otheru = unix_sk(other);
/* copy address information from listening to new sock*/
if (otheru->addr) {
atomic_inc(&otheru->addr->refcnt);
newu->addr = otheru->addr;
}
if (otheru->path.dentry) {
path_get(&otheru->path);
newu->path = otheru->path;
}
/* Set credentials */
copy_peercred(sk, other);
sock->state = SS_CONNECTED;
sk->sk_state = TCP_ESTABLISHED;
sock_hold(newsk);
smp_mb__after_atomic_inc(); /* sock_hold() does an atomic_inc() */
unix_peer(sk) = newsk;
unix_state_unlock(sk);
/* take ten and and send info to listening sock */
spin_lock(&other->sk_receive_queue.lock);
__skb_queue_tail(&other->sk_receive_queue, skb);
spin_unlock(&other->sk_receive_queue.lock);
unix_state_unlock(other);
other->sk_data_ready(other, 0);
sock_put(other);
return 0;
out_unlock:
if (other)
unix_state_unlock(other);
out:
kfree_skb(skb);
if (newsk)
unix_release_sock(newsk, 0);
if (other)
sock_put(other);
return err;
}
static int unix_socketpair(struct socket *socka, struct socket *sockb)
{
struct sock *ska = socka->sk, *skb = sockb->sk;
/* Join our sockets back to back */
sock_hold(ska);
sock_hold(skb);
unix_peer(ska) = skb;
unix_peer(skb) = ska;
init_peercred(ska);
init_peercred(skb);
if (ska->sk_type != SOCK_DGRAM) {
ska->sk_state = TCP_ESTABLISHED;
skb->sk_state = TCP_ESTABLISHED;
socka->state = SS_CONNECTED;
sockb->state = SS_CONNECTED;
}
return 0;
}
static int unix_accept(struct socket *sock, struct socket *newsock, int flags)
{
struct sock *sk = sock->sk;
struct sock *tsk;
struct sk_buff *skb;
int err;
err = -EOPNOTSUPP;
if (sock->type != SOCK_STREAM && sock->type != SOCK_SEQPACKET)
goto out;
err = -EINVAL;
if (sk->sk_state != TCP_LISTEN)
goto out;
/* If socket state is TCP_LISTEN it cannot change (for now...),
* so that no locks are necessary.
*/
skb = skb_recv_datagram(sk, 0, flags&O_NONBLOCK, &err);
if (!skb) {
/* This means receive shutdown. */
if (err == 0)
err = -EINVAL;
goto out;
}
tsk = skb->sk;
skb_free_datagram(sk, skb);
wake_up_interruptible(&unix_sk(sk)->peer_wait);
/* attach accepted sock to socket */
unix_state_lock(tsk);
newsock->state = SS_CONNECTED;
sock_graft(tsk, newsock);
unix_state_unlock(tsk);
return 0;
out:
return err;
}
static int unix_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer)
{
struct sock *sk = sock->sk;
struct unix_sock *u;
DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, uaddr);
int err = 0;
if (peer) {
sk = unix_peer_get(sk);
err = -ENOTCONN;
if (!sk)
goto out;
err = 0;
} else {
sock_hold(sk);
}
u = unix_sk(sk);
unix_state_lock(sk);
if (!u->addr) {
sunaddr->sun_family = AF_UNIX;
sunaddr->sun_path[0] = 0;
*uaddr_len = sizeof(short);
} else {
struct unix_address *addr = u->addr;
*uaddr_len = addr->len;
memcpy(sunaddr, addr->name, *uaddr_len);
}
unix_state_unlock(sk);
sock_put(sk);
out:
return err;
}
static void unix_detach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
scm->fp = UNIXCB(skb).fp;
UNIXCB(skb).fp = NULL;
for (i = scm->fp->count-1; i >= 0; i--)
unix_notinflight(scm->fp->fp[i]);
}
static void unix_destruct_scm(struct sk_buff *skb)
{
struct scm_cookie scm;
memset(&scm, 0, sizeof(scm));
scm.pid = UNIXCB(skb).pid;
scm.cred = UNIXCB(skb).cred;
if (UNIXCB(skb).fp)
unix_detach_fds(&scm, skb);
/* Alas, it calls VFS */
/* So fscking what? fput() had been SMP-safe since the last Summer */
scm_destroy(&scm);
sock_wfree(skb);
}
#define MAX_RECURSION_LEVEL 4
static int unix_attach_fds(struct scm_cookie *scm, struct sk_buff *skb)
{
int i;
unsigned char max_level = 0;
int unix_sock_count = 0;
for (i = scm->fp->count - 1; i >= 0; i--) {
struct sock *sk = unix_get_socket(scm->fp->fp[i]);
if (sk) {
unix_sock_count++;
max_level = max(max_level,
unix_sk(sk)->recursion_level);
}
}
if (unlikely(max_level > MAX_RECURSION_LEVEL))
return -ETOOMANYREFS;
/*
* Need to duplicate file references for the sake of garbage
* collection. Otherwise a socket in the fps might become a
* candidate for GC while the skb is not yet queued.
*/
UNIXCB(skb).fp = scm_fp_dup(scm->fp);
if (!UNIXCB(skb).fp)
return -ENOMEM;
if (unix_sock_count) {
for (i = scm->fp->count - 1; i >= 0; i--)
unix_inflight(scm->fp->fp[i]);
}
return max_level;
}
static int unix_scm_to_skb(struct scm_cookie *scm, struct sk_buff *skb, bool send_fds)
{
int err = 0;
UNIXCB(skb).pid = get_pid(scm->pid);
if (scm->cred)
UNIXCB(skb).cred = get_cred(scm->cred);
UNIXCB(skb).fp = NULL;
if (scm->fp && send_fds)
err = unix_attach_fds(scm, skb);
skb->destructor = unix_destruct_scm;
return err;
}
/*
* Some apps rely on write() giving SCM_CREDENTIALS
* We include credentials if source or destination socket
* asserted SOCK_PASSCRED.
*/
static void maybe_add_creds(struct sk_buff *skb, const struct socket *sock,
const struct sock *other)
{
if (UNIXCB(skb).cred)
return;
if (test_bit(SOCK_PASSCRED, &sock->flags) ||
!other->sk_socket ||
test_bit(SOCK_PASSCRED, &other->sk_socket->flags)) {
UNIXCB(skb).pid = get_pid(task_tgid(current));
UNIXCB(skb).cred = get_current_cred();
}
}
/*
* Send AF_UNIX data.
*/
static int unix_dgram_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct unix_sock *u = unix_sk(sk);
struct sockaddr_un *sunaddr = msg->msg_name;
struct sock *other = NULL;
int namelen = 0; /* fake GCC */
int err;
unsigned int hash;
struct sk_buff *skb;
long timeo;
struct scm_cookie tmp_scm;
int max_level;
int data_len = 0;
if (NULL == siocb->scm)
siocb->scm = &tmp_scm;
wait_for_unix_gc();
err = scm_send(sock, msg, siocb->scm, false);
if (err < 0)
return err;
err = -EOPNOTSUPP;
if (msg->msg_flags&MSG_OOB)
goto out;
if (msg->msg_namelen) {
err = unix_mkname(sunaddr, msg->msg_namelen, &hash);
if (err < 0)
goto out;
namelen = err;
} else {
sunaddr = NULL;
err = -ENOTCONN;
other = unix_peer_get(sk);
if (!other)
goto out;
}
if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr
&& (err = unix_autobind(sock)) != 0)
goto out;
err = -EMSGSIZE;
if (len > sk->sk_sndbuf - 32)
goto out;
if (len > SKB_MAX_ALLOC)
data_len = min_t(size_t,
len - SKB_MAX_ALLOC,
MAX_SKB_FRAGS * PAGE_SIZE);
skb = sock_alloc_send_pskb(sk, len - data_len, data_len,
msg->msg_flags & MSG_DONTWAIT, &err);
if (skb == NULL)
goto out;
err = unix_scm_to_skb(siocb->scm, skb, true);
if (err < 0)
goto out_free;
max_level = err + 1;
unix_get_secdata(siocb->scm, skb);
skb_put(skb, len - data_len);
skb->data_len = data_len;
skb->len = len;
err = skb_copy_datagram_from_iovec(skb, 0, msg->msg_iov, 0, len);
if (err)
goto out_free;
timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
restart:
if (!other) {
err = -ECONNRESET;
if (sunaddr == NULL)
goto out_free;
other = unix_find_other(net, sunaddr, namelen, sk->sk_type,
hash, &err);
if (other == NULL)
goto out_free;
}
if (sk_filter(other, skb) < 0) {
/* Toss the packet but do not return any error to the sender */
err = len;
goto out_free;
}
unix_state_lock(other);
err = -EPERM;
if (!unix_may_send(sk, other))
goto out_unlock;
if (sock_flag(other, SOCK_DEAD)) {
/*
* Check with 1003.1g - what should
* datagram error
*/
unix_state_unlock(other);
sock_put(other);
err = 0;
unix_state_lock(sk);
if (unix_peer(sk) == other) {
unix_peer(sk) = NULL;
unix_state_unlock(sk);
unix_dgram_disconnected(sk, other);
sock_put(other);
err = -ECONNREFUSED;
} else {
unix_state_unlock(sk);
}
other = NULL;
if (err)
goto out_free;
goto restart;
}
err = -EPIPE;
if (other->sk_shutdown & RCV_SHUTDOWN)
goto out_unlock;
if (sk->sk_type != SOCK_SEQPACKET) {
err = security_unix_may_send(sk->sk_socket, other->sk_socket);
if (err)
goto out_unlock;
}
if (unix_peer(other) != sk && unix_recvq_full(other)) {
if (!timeo) {
err = -EAGAIN;
goto out_unlock;
}
timeo = unix_wait_for_peer(other, timeo);
err = sock_intr_errno(timeo);
if (signal_pending(current))
goto out_free;
goto restart;
}
if (sock_flag(other, SOCK_RCVTSTAMP))
__net_timestamp(skb);
maybe_add_creds(skb, sock, other);
skb_queue_tail(&other->sk_receive_queue, skb);
if (max_level > unix_sk(other)->recursion_level)
unix_sk(other)->recursion_level = max_level;
unix_state_unlock(other);
other->sk_data_ready(other, len);
sock_put(other);
scm_destroy(siocb->scm);
return len;
out_unlock:
unix_state_unlock(other);
out_free:
kfree_skb(skb);
out:
if (other)
sock_put(other);
scm_destroy(siocb->scm);
return err;
}
static int unix_stream_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct sock *sk = sock->sk;
struct sock *other = NULL;
int err, size;
struct sk_buff *skb;
int sent = 0;
struct scm_cookie tmp_scm;
bool fds_sent = false;
int max_level;
if (NULL == siocb->scm)
siocb->scm = &tmp_scm;
wait_for_unix_gc();
err = scm_send(sock, msg, siocb->scm, false);
if (err < 0)
return err;
err = -EOPNOTSUPP;
if (msg->msg_flags&MSG_OOB)
goto out_err;
if (msg->msg_namelen) {
err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
goto out_err;
} else {
err = -ENOTCONN;
other = unix_peer(sk);
if (!other)
goto out_err;
}
if (sk->sk_shutdown & SEND_SHUTDOWN)
goto pipe_err;
while (sent < len) {
/*
* Optimisation for the fact that under 0.01% of X
* messages typically need breaking up.
*/
size = len-sent;
/* Keep two messages in the pipe so it schedules better */
if (size > ((sk->sk_sndbuf >> 1) - 64))
size = (sk->sk_sndbuf >> 1) - 64;
if (size > SKB_MAX_ALLOC)
size = SKB_MAX_ALLOC;
/*
* Grab a buffer
*/
skb = sock_alloc_send_skb(sk, size, msg->msg_flags&MSG_DONTWAIT,
&err);
if (skb == NULL)
goto out_err;
/*
* If you pass two values to the sock_alloc_send_skb
* it tries to grab the large buffer with GFP_NOFS
* (which can fail easily), and if it fails grab the
* fallback size buffer which is under a page and will
* succeed. [Alan]
*/
size = min_t(int, size, skb_tailroom(skb));
/* Only send the fds in the first buffer */
err = unix_scm_to_skb(siocb->scm, skb, !fds_sent);
if (err < 0) {
kfree_skb(skb);
goto out_err;
}
max_level = err + 1;
fds_sent = true;
err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size);
if (err) {
kfree_skb(skb);
goto out_err;
}
unix_state_lock(other);
if (sock_flag(other, SOCK_DEAD) ||
(other->sk_shutdown & RCV_SHUTDOWN))
goto pipe_err_free;
maybe_add_creds(skb, sock, other);
skb_queue_tail(&other->sk_receive_queue, skb);
if (max_level > unix_sk(other)->recursion_level)
unix_sk(other)->recursion_level = max_level;
unix_state_unlock(other);
other->sk_data_ready(other, size);
sent += size;
}
scm_destroy(siocb->scm);
siocb->scm = NULL;
return sent;
pipe_err_free:
unix_state_unlock(other);
kfree_skb(skb);
pipe_err:
if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL))
send_sig(SIGPIPE, current, 0);
err = -EPIPE;
out_err:
scm_destroy(siocb->scm);
siocb->scm = NULL;
return sent ? : err;
}
static int unix_seqpacket_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
int err;
struct sock *sk = sock->sk;
err = sock_error(sk);
if (err)
return err;
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
if (msg->msg_namelen)
msg->msg_namelen = 0;
return unix_dgram_sendmsg(kiocb, sock, msg, len);
}
static int unix_seqpacket_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size,
int flags)
{
struct sock *sk = sock->sk;
if (sk->sk_state != TCP_ESTABLISHED)
return -ENOTCONN;
return unix_dgram_recvmsg(iocb, sock, msg, size, flags);
}
static void unix_copy_addr(struct msghdr *msg, struct sock *sk)
{
struct unix_sock *u = unix_sk(sk);
msg->msg_namelen = 0;
if (u->addr) {
msg->msg_namelen = u->addr->len;
memcpy(msg->msg_name, u->addr->name, u->addr->len);
}
}
static int unix_dgram_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size,
int flags)
{
struct sock_iocb *siocb = kiocb_to_siocb(iocb);
struct scm_cookie tmp_scm;
struct sock *sk = sock->sk;
struct unix_sock *u = unix_sk(sk);
int noblock = flags & MSG_DONTWAIT;
struct sk_buff *skb;
int err;
int peeked, skip;
err = -EOPNOTSUPP;
if (flags&MSG_OOB)
goto out;
msg->msg_namelen = 0;
err = mutex_lock_interruptible(&u->readlock);
if (err) {
err = sock_intr_errno(sock_rcvtimeo(sk, noblock));
goto out;
}
skip = sk_peek_offset(sk, flags);
skb = __skb_recv_datagram(sk, flags, &peeked, &skip, &err);
if (!skb) {
unix_state_lock(sk);
/* Signal EOF on disconnected non-blocking SEQPACKET socket. */
if (sk->sk_type == SOCK_SEQPACKET && err == -EAGAIN &&
(sk->sk_shutdown & RCV_SHUTDOWN))
err = 0;
unix_state_unlock(sk);
goto out_unlock;
}
wake_up_interruptible_sync_poll(&u->peer_wait,
POLLOUT | POLLWRNORM | POLLWRBAND);
if (msg->msg_name)
unix_copy_addr(msg, skb->sk);
if (size > skb->len - skip)
size = skb->len - skip;
else if (size < skb->len - skip)
msg->msg_flags |= MSG_TRUNC;
err = skb_copy_datagram_iovec(skb, skip, msg->msg_iov, size);
if (err)
goto out_free;
if (sock_flag(sk, SOCK_RCVTSTAMP))
__sock_recv_timestamp(msg, sk, skb);
if (!siocb->scm) {
siocb->scm = &tmp_scm;
memset(&tmp_scm, 0, sizeof(tmp_scm));
}
scm_set_cred(siocb->scm, UNIXCB(skb).pid, UNIXCB(skb).cred);
unix_set_secdata(siocb->scm, skb);
if (!(flags & MSG_PEEK)) {
if (UNIXCB(skb).fp)
unix_detach_fds(siocb->scm, skb);
sk_peek_offset_bwd(sk, skb->len);
} else {
/* It is questionable: on PEEK we could:
- do not return fds - good, but too simple 8)
- return fds, and do not return them on read (old strategy,
apparently wrong)
- clone fds (I chose it for now, it is the most universal
solution)
POSIX 1003.1g does not actually define this clearly
at all. POSIX 1003.1g doesn't define a lot of things
clearly however!
*/
sk_peek_offset_fwd(sk, size);
if (UNIXCB(skb).fp)
siocb->scm->fp = scm_fp_dup(UNIXCB(skb).fp);
}
err = (flags & MSG_TRUNC) ? skb->len - skip : size;
scm_recv(sock, msg, siocb->scm, flags);
out_free:
skb_free_datagram(sk, skb);
out_unlock:
mutex_unlock(&u->readlock);
out:
return err;
}
/*
* Sleep until data has arrive. But check for races..
*/
static long unix_stream_data_wait(struct sock *sk, long timeo)
{
DEFINE_WAIT(wait);
unix_state_lock(sk);
for (;;) {
prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
if (!skb_queue_empty(&sk->sk_receive_queue) ||
sk->sk_err ||
(sk->sk_shutdown & RCV_SHUTDOWN) ||
signal_pending(current) ||
!timeo)
break;
set_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
unix_state_unlock(sk);
timeo = schedule_timeout(timeo);
unix_state_lock(sk);
clear_bit(SOCK_ASYNC_WAITDATA, &sk->sk_socket->flags);
}
finish_wait(sk_sleep(sk), &wait);
unix_state_unlock(sk);
return timeo;
}
static int unix_stream_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size,
int flags)
{
struct sock_iocb *siocb = kiocb_to_siocb(iocb);
struct scm_cookie tmp_scm;
struct sock *sk = sock->sk;
struct unix_sock *u = unix_sk(sk);
struct sockaddr_un *sunaddr = msg->msg_name;
int copied = 0;
int check_creds = 0;
int target;
int err = 0;
long timeo;
int skip;
err = -EINVAL;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
err = -EOPNOTSUPP;
if (flags&MSG_OOB)
goto out;
target = sock_rcvlowat(sk, flags&MSG_WAITALL, size);
timeo = sock_rcvtimeo(sk, flags&MSG_DONTWAIT);
msg->msg_namelen = 0;
/* Lock the socket to prevent queue disordering
* while sleeps in memcpy_tomsg
*/
if (!siocb->scm) {
siocb->scm = &tmp_scm;
memset(&tmp_scm, 0, sizeof(tmp_scm));
}
err = mutex_lock_interruptible(&u->readlock);
if (err) {
err = sock_intr_errno(timeo);
goto out;
}
skip = sk_peek_offset(sk, flags);
do {
int chunk;
struct sk_buff *skb;
unix_state_lock(sk);
skb = skb_peek(&sk->sk_receive_queue);
again:
if (skb == NULL) {
unix_sk(sk)->recursion_level = 0;
if (copied >= target)
goto unlock;
/*
* POSIX 1003.1g mandates this order.
*/
err = sock_error(sk);
if (err)
goto unlock;
if (sk->sk_shutdown & RCV_SHUTDOWN)
goto unlock;
unix_state_unlock(sk);
err = -EAGAIN;
if (!timeo)
break;
mutex_unlock(&u->readlock);
timeo = unix_stream_data_wait(sk, timeo);
if (signal_pending(current)
|| mutex_lock_interruptible(&u->readlock)) {
err = sock_intr_errno(timeo);
goto out;
}
continue;
unlock:
unix_state_unlock(sk);
break;
}
if (skip >= skb->len) {
skip -= skb->len;
skb = skb_peek_next(skb, &sk->sk_receive_queue);
goto again;
}
unix_state_unlock(sk);
if (check_creds) {
/* Never glue messages from different writers */
if ((UNIXCB(skb).pid != siocb->scm->pid) ||
(UNIXCB(skb).cred != siocb->scm->cred))
break;
} else {
/* Copy credentials */
scm_set_cred(siocb->scm, UNIXCB(skb).pid, UNIXCB(skb).cred);
check_creds = 1;
}
/* Copy address just once */
if (sunaddr) {
unix_copy_addr(msg, skb->sk);
sunaddr = NULL;
}
chunk = min_t(unsigned int, skb->len - skip, size);
if (memcpy_toiovec(msg->msg_iov, skb->data + skip, chunk)) {
if (copied == 0)
copied = -EFAULT;
break;
}
copied += chunk;
size -= chunk;
/* Mark read part of skb as used */
if (!(flags & MSG_PEEK)) {
skb_pull(skb, chunk);
sk_peek_offset_bwd(sk, chunk);
if (UNIXCB(skb).fp)
unix_detach_fds(siocb->scm, skb);
if (skb->len)
break;
skb_unlink(skb, &sk->sk_receive_queue);
consume_skb(skb);
if (siocb->scm->fp)
break;
} else {
/* It is questionable, see note in unix_dgram_recvmsg.
*/
if (UNIXCB(skb).fp)
siocb->scm->fp = scm_fp_dup(UNIXCB(skb).fp);
sk_peek_offset_fwd(sk, chunk);
break;
}
} while (size);
mutex_unlock(&u->readlock);
scm_recv(sock, msg, siocb->scm, flags);
out:
return copied ? : err;
}
static int unix_shutdown(struct socket *sock, int mode)
{
struct sock *sk = sock->sk;
struct sock *other;
mode = (mode+1)&(RCV_SHUTDOWN|SEND_SHUTDOWN);
if (!mode)
return 0;
unix_state_lock(sk);
sk->sk_shutdown |= mode;
other = unix_peer(sk);
if (other)
sock_hold(other);
unix_state_unlock(sk);
sk->sk_state_change(sk);
if (other &&
(sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET)) {
int peer_mode = 0;
if (mode&RCV_SHUTDOWN)
peer_mode |= SEND_SHUTDOWN;
if (mode&SEND_SHUTDOWN)
peer_mode |= RCV_SHUTDOWN;
unix_state_lock(other);
other->sk_shutdown |= peer_mode;
unix_state_unlock(other);
other->sk_state_change(other);
if (peer_mode == SHUTDOWN_MASK)
sk_wake_async(other, SOCK_WAKE_WAITD, POLL_HUP);
else if (peer_mode & RCV_SHUTDOWN)
sk_wake_async(other, SOCK_WAKE_WAITD, POLL_IN);
}
if (other)
sock_put(other);
return 0;
}
long unix_inq_len(struct sock *sk)
{
struct sk_buff *skb;
long amount = 0;
if (sk->sk_state == TCP_LISTEN)
return -EINVAL;
spin_lock(&sk->sk_receive_queue.lock);
if (sk->sk_type == SOCK_STREAM ||
sk->sk_type == SOCK_SEQPACKET) {
skb_queue_walk(&sk->sk_receive_queue, skb)
amount += skb->len;
} else {
skb = skb_peek(&sk->sk_receive_queue);
if (skb)
amount = skb->len;
}
spin_unlock(&sk->sk_receive_queue.lock);
return amount;
}
EXPORT_SYMBOL_GPL(unix_inq_len);
long unix_outq_len(struct sock *sk)
{
return sk_wmem_alloc_get(sk);
}
EXPORT_SYMBOL_GPL(unix_outq_len);
static int unix_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
struct sock *sk = sock->sk;
long amount = 0;
int err;
switch (cmd) {
case SIOCOUTQ:
amount = unix_outq_len(sk);
err = put_user(amount, (int __user *)arg);
break;
case SIOCINQ:
amount = unix_inq_len(sk);
if (amount < 0)
err = amount;
else
err = put_user(amount, (int __user *)arg);
break;
default:
err = -ENOIOCTLCMD;
break;
}
return err;
}
static unsigned int unix_poll(struct file *file, struct socket *sock, poll_table *wait)
{
struct sock *sk = sock->sk;
unsigned int mask;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
/* exceptional events? */
if (sk->sk_err)
mask |= POLLERR;
if (sk->sk_shutdown == SHUTDOWN_MASK)
mask |= POLLHUP;
if (sk->sk_shutdown & RCV_SHUTDOWN)
mask |= POLLRDHUP | POLLIN | POLLRDNORM;
/* readable? */
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
/* Connection-based need to check for termination and startup */
if ((sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) &&
sk->sk_state == TCP_CLOSE)
mask |= POLLHUP;
/*
* we set writable also when the other side has shut down the
* connection. This prevents stuck sockets.
*/
if (unix_writable(sk))
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
return mask;
}
static unsigned int unix_dgram_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk, *other;
unsigned int mask, writable;
sock_poll_wait(file, sk_sleep(sk), wait);
mask = 0;
/* exceptional events? */
if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
mask |= POLLERR;
if (sk->sk_shutdown & RCV_SHUTDOWN)
mask |= POLLRDHUP | POLLIN | POLLRDNORM;
if (sk->sk_shutdown == SHUTDOWN_MASK)
mask |= POLLHUP;
/* readable? */
if (!skb_queue_empty(&sk->sk_receive_queue))
mask |= POLLIN | POLLRDNORM;
/* Connection-based need to check for termination and startup */
if (sk->sk_type == SOCK_SEQPACKET) {
if (sk->sk_state == TCP_CLOSE)
mask |= POLLHUP;
/* connection hasn't started yet? */
if (sk->sk_state == TCP_SYN_SENT)
return mask;
}
/* No write status requested, avoid expensive OUT tests. */
if (!(poll_requested_events(wait) & (POLLWRBAND|POLLWRNORM|POLLOUT)))
return mask;
writable = unix_writable(sk);
other = unix_peer_get(sk);
if (other) {
if (unix_peer(other) != sk) {
sock_poll_wait(file, &unix_sk(other)->peer_wait, wait);
if (unix_recvq_full(other))
writable = 0;
}
sock_put(other);
}
if (writable)
mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
else
set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
return mask;
}
#ifdef CONFIG_PROC_FS
#define BUCKET_SPACE (BITS_PER_LONG - (UNIX_HASH_BITS + 1) - 1)
#define get_bucket(x) ((x) >> BUCKET_SPACE)
#define get_offset(x) ((x) & ((1L << BUCKET_SPACE) - 1))
#define set_bucket_offset(b, o) ((b) << BUCKET_SPACE | (o))
static struct sock *unix_from_bucket(struct seq_file *seq, loff_t *pos)
{
unsigned long offset = get_offset(*pos);
unsigned long bucket = get_bucket(*pos);
struct sock *sk;
unsigned long count = 0;
for (sk = sk_head(&unix_socket_table[bucket]); sk; sk = sk_next(sk)) {
if (sock_net(sk) != seq_file_net(seq))
continue;
if (++count == offset)
break;
}
return sk;
}
static struct sock *unix_next_socket(struct seq_file *seq,
struct sock *sk,
loff_t *pos)
{
unsigned long bucket;
while (sk > (struct sock *)SEQ_START_TOKEN) {
sk = sk_next(sk);
if (!sk)
goto next_bucket;
if (sock_net(sk) == seq_file_net(seq))
return sk;
}
do {
sk = unix_from_bucket(seq, pos);
if (sk)
return sk;
next_bucket:
bucket = get_bucket(*pos) + 1;
*pos = set_bucket_offset(bucket, 1);
} while (bucket < ARRAY_SIZE(unix_socket_table));
return NULL;
}
static void *unix_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(unix_table_lock)
{
spin_lock(&unix_table_lock);
if (!*pos)
return SEQ_START_TOKEN;
if (get_bucket(*pos) >= ARRAY_SIZE(unix_socket_table))
return NULL;
return unix_next_socket(seq, NULL, pos);
}
static void *unix_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
++*pos;
return unix_next_socket(seq, v, pos);
}
static void unix_seq_stop(struct seq_file *seq, void *v)
__releases(unix_table_lock)
{
spin_unlock(&unix_table_lock);
}
static int unix_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq, "Num RefCount Protocol Flags Type St "
"Inode Path\n");
else {
struct sock *s = v;
struct unix_sock *u = unix_sk(s);
unix_state_lock(s);
seq_printf(seq, "%pK: %08X %08X %08X %04X %02X %5lu",
s,
atomic_read(&s->sk_refcnt),
0,
s->sk_state == TCP_LISTEN ? __SO_ACCEPTCON : 0,
s->sk_type,
s->sk_socket ?
(s->sk_state == TCP_ESTABLISHED ? SS_CONNECTED : SS_UNCONNECTED) :
(s->sk_state == TCP_ESTABLISHED ? SS_CONNECTING : SS_DISCONNECTING),
sock_i_ino(s));
if (u->addr) {
int i, len;
seq_putc(seq, ' ');
i = 0;
len = u->addr->len - sizeof(short);
if (!UNIX_ABSTRACT(s))
len--;
else {
seq_putc(seq, '@');
i++;
}
for ( ; i < len; i++)
seq_putc(seq, u->addr->name->sun_path[i]);
}
unix_state_unlock(s);
seq_putc(seq, '\n');
}
return 0;
}
static const struct seq_operations unix_seq_ops = {
.start = unix_seq_start,
.next = unix_seq_next,
.stop = unix_seq_stop,
.show = unix_seq_show,
};
static int unix_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &unix_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations unix_seq_fops = {
.owner = THIS_MODULE,
.open = unix_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
static const struct net_proto_family unix_family_ops = {
.family = PF_UNIX,
.create = unix_create,
.owner = THIS_MODULE,
};
static int __net_init unix_net_init(struct net *net)
{
int error = -ENOMEM;
net->unx.sysctl_max_dgram_qlen = 10;
if (unix_sysctl_register(net))
goto out;
#ifdef CONFIG_PROC_FS
if (!proc_net_fops_create(net, "unix", 0, &unix_seq_fops)) {
unix_sysctl_unregister(net);
goto out;
}
#endif
error = 0;
out:
return error;
}
static void __net_exit unix_net_exit(struct net *net)
{
unix_sysctl_unregister(net);
proc_net_remove(net, "unix");
}
static struct pernet_operations unix_net_ops = {
.init = unix_net_init,
.exit = unix_net_exit,
};
static int __init af_unix_init(void)
{
int rc = -1;
struct sk_buff *dummy_skb;
BUILD_BUG_ON(sizeof(struct unix_skb_parms) > sizeof(dummy_skb->cb));
rc = proto_register(&unix_proto, 1);
if (rc != 0) {
printk(KERN_CRIT "%s: Cannot create unix_sock SLAB cache!\n",
__func__);
goto out;
}
sock_register(&unix_family_ops);
register_pernet_subsys(&unix_net_ops);
out:
return rc;
}
static void __exit af_unix_exit(void)
{
sock_unregister(PF_UNIX);
proto_unregister(&unix_proto);
unregister_pernet_subsys(&unix_net_ops);
}
/* Earlier than device_initcall() so that other drivers invoking
request_module() don't end up in a loop when modprobe tries
to use a UNIX socket. But later than subsys_initcall() because
we depend on stuff initialised there */
fs_initcall(af_unix_init);
module_exit(af_unix_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_UNIX);
| ./CrossVul/dataset_final_sorted/CWE-287/c/good_3721_2 |
crossvul-cpp_data_bad_5264_1 | /***************************************************************************
* _ _ ____ _
* Project ___| | | | _ \| |
* / __| | | | |_) | |
* | (__| |_| | _ <| |___
* \___|\___/|_| \_\_____|
*
* Copyright (C) 1998 - 2016, Daniel Stenberg, <daniel@haxx.se>, et al.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at https://curl.haxx.se/docs/copyright.html.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of the Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the COPYING file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
***************************************************************************/
/*
* Source file for all NSS-specific code for the TLS/SSL layer. No code
* but vtls.c should ever call or use these functions.
*/
#include "curl_setup.h"
#ifdef USE_NSS
#include "urldata.h"
#include "sendf.h"
#include "formdata.h" /* for the boundary function */
#include "url.h" /* for the ssl config check function */
#include "connect.h"
#include "strequal.h"
#include "select.h"
#include "vtls.h"
#include "llist.h"
#include "curl_printf.h"
#include "nssg.h"
#include <nspr.h>
#include <nss.h>
#include <ssl.h>
#include <sslerr.h>
#include <secerr.h>
#include <secmod.h>
#include <sslproto.h>
#include <prtypes.h>
#include <pk11pub.h>
#include <prio.h>
#include <secitem.h>
#include <secport.h>
#include <certdb.h>
#include <base64.h>
#include <cert.h>
#include <prerror.h>
#include <keyhi.h> /* for SECKEY_DestroyPublicKey() */
#define NSSVERNUM ((NSS_VMAJOR<<16)|(NSS_VMINOR<<8)|NSS_VPATCH)
#if NSSVERNUM >= 0x030f00 /* 3.15.0 */
#include <ocsp.h>
#endif
#include "rawstr.h"
#include "warnless.h"
#include "x509asn1.h"
/* The last #include files should be: */
#include "curl_memory.h"
#include "memdebug.h"
#define SSL_DIR "/etc/pki/nssdb"
/* enough to fit the string "PEM Token #[0|1]" */
#define SLOTSIZE 13
PRFileDesc *PR_ImportTCPSocket(PRInt32 osfd);
static PRLock *nss_initlock = NULL;
static PRLock *nss_crllock = NULL;
static struct curl_llist *nss_crl_list = NULL;
static NSSInitContext *nss_context = NULL;
static volatile int initialized = 0;
typedef struct {
const char *name;
int num;
} cipher_s;
#define PK11_SETATTRS(_attr, _idx, _type, _val, _len) do { \
CK_ATTRIBUTE *ptr = (_attr) + ((_idx)++); \
ptr->type = (_type); \
ptr->pValue = (_val); \
ptr->ulValueLen = (_len); \
} WHILE_FALSE
#define CERT_NewTempCertificate __CERT_NewTempCertificate
#define NUM_OF_CIPHERS sizeof(cipherlist)/sizeof(cipherlist[0])
static const cipher_s cipherlist[] = {
/* SSL2 cipher suites */
{"rc4", SSL_EN_RC4_128_WITH_MD5},
{"rc4-md5", SSL_EN_RC4_128_WITH_MD5},
{"rc4export", SSL_EN_RC4_128_EXPORT40_WITH_MD5},
{"rc2", SSL_EN_RC2_128_CBC_WITH_MD5},
{"rc2export", SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5},
{"des", SSL_EN_DES_64_CBC_WITH_MD5},
{"desede3", SSL_EN_DES_192_EDE3_CBC_WITH_MD5},
/* SSL3/TLS cipher suites */
{"rsa_rc4_128_md5", SSL_RSA_WITH_RC4_128_MD5},
{"rsa_rc4_128_sha", SSL_RSA_WITH_RC4_128_SHA},
{"rsa_3des_sha", SSL_RSA_WITH_3DES_EDE_CBC_SHA},
{"rsa_des_sha", SSL_RSA_WITH_DES_CBC_SHA},
{"rsa_rc4_40_md5", SSL_RSA_EXPORT_WITH_RC4_40_MD5},
{"rsa_rc2_40_md5", SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5},
{"rsa_null_md5", SSL_RSA_WITH_NULL_MD5},
{"rsa_null_sha", SSL_RSA_WITH_NULL_SHA},
{"fips_3des_sha", SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA},
{"fips_des_sha", SSL_RSA_FIPS_WITH_DES_CBC_SHA},
{"fortezza", SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA},
{"fortezza_rc4_128_sha", SSL_FORTEZZA_DMS_WITH_RC4_128_SHA},
{"fortezza_null", SSL_FORTEZZA_DMS_WITH_NULL_SHA},
/* TLS 1.0: Exportable 56-bit Cipher Suites. */
{"rsa_des_56_sha", TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA},
{"rsa_rc4_56_sha", TLS_RSA_EXPORT1024_WITH_RC4_56_SHA},
/* AES ciphers. */
{"dhe_dss_aes_128_cbc_sha", TLS_DHE_DSS_WITH_AES_128_CBC_SHA},
{"dhe_dss_aes_256_cbc_sha", TLS_DHE_DSS_WITH_AES_256_CBC_SHA},
{"dhe_rsa_aes_128_cbc_sha", TLS_DHE_RSA_WITH_AES_128_CBC_SHA},
{"dhe_rsa_aes_256_cbc_sha", TLS_DHE_RSA_WITH_AES_256_CBC_SHA},
{"rsa_aes_128_sha", TLS_RSA_WITH_AES_128_CBC_SHA},
{"rsa_aes_256_sha", TLS_RSA_WITH_AES_256_CBC_SHA},
/* ECC ciphers. */
{"ecdh_ecdsa_null_sha", TLS_ECDH_ECDSA_WITH_NULL_SHA},
{"ecdh_ecdsa_rc4_128_sha", TLS_ECDH_ECDSA_WITH_RC4_128_SHA},
{"ecdh_ecdsa_3des_sha", TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA},
{"ecdh_ecdsa_aes_128_sha", TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA},
{"ecdh_ecdsa_aes_256_sha", TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA},
{"ecdhe_ecdsa_null_sha", TLS_ECDHE_ECDSA_WITH_NULL_SHA},
{"ecdhe_ecdsa_rc4_128_sha", TLS_ECDHE_ECDSA_WITH_RC4_128_SHA},
{"ecdhe_ecdsa_3des_sha", TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA},
{"ecdhe_ecdsa_aes_128_sha", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA},
{"ecdhe_ecdsa_aes_256_sha", TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA},
{"ecdh_rsa_null_sha", TLS_ECDH_RSA_WITH_NULL_SHA},
{"ecdh_rsa_128_sha", TLS_ECDH_RSA_WITH_RC4_128_SHA},
{"ecdh_rsa_3des_sha", TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA},
{"ecdh_rsa_aes_128_sha", TLS_ECDH_RSA_WITH_AES_128_CBC_SHA},
{"ecdh_rsa_aes_256_sha", TLS_ECDH_RSA_WITH_AES_256_CBC_SHA},
{"echde_rsa_null", TLS_ECDHE_RSA_WITH_NULL_SHA},
{"ecdhe_rsa_rc4_128_sha", TLS_ECDHE_RSA_WITH_RC4_128_SHA},
{"ecdhe_rsa_3des_sha", TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA},
{"ecdhe_rsa_aes_128_sha", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},
{"ecdhe_rsa_aes_256_sha", TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA},
{"ecdh_anon_null_sha", TLS_ECDH_anon_WITH_NULL_SHA},
{"ecdh_anon_rc4_128sha", TLS_ECDH_anon_WITH_RC4_128_SHA},
{"ecdh_anon_3des_sha", TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA},
{"ecdh_anon_aes_128_sha", TLS_ECDH_anon_WITH_AES_128_CBC_SHA},
{"ecdh_anon_aes_256_sha", TLS_ECDH_anon_WITH_AES_256_CBC_SHA},
#ifdef TLS_RSA_WITH_NULL_SHA256
/* new HMAC-SHA256 cipher suites specified in RFC */
{"rsa_null_sha_256", TLS_RSA_WITH_NULL_SHA256},
{"rsa_aes_128_cbc_sha_256", TLS_RSA_WITH_AES_128_CBC_SHA256},
{"rsa_aes_256_cbc_sha_256", TLS_RSA_WITH_AES_256_CBC_SHA256},
{"dhe_rsa_aes_128_cbc_sha_256", TLS_DHE_RSA_WITH_AES_128_CBC_SHA256},
{"dhe_rsa_aes_256_cbc_sha_256", TLS_DHE_RSA_WITH_AES_256_CBC_SHA256},
{"ecdhe_ecdsa_aes_128_cbc_sha_256", TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256},
{"ecdhe_rsa_aes_128_cbc_sha_256", TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256},
#endif
#ifdef TLS_RSA_WITH_AES_128_GCM_SHA256
/* AES GCM cipher suites in RFC 5288 and RFC 5289 */
{"rsa_aes_128_gcm_sha_256", TLS_RSA_WITH_AES_128_GCM_SHA256},
{"dhe_rsa_aes_128_gcm_sha_256", TLS_DHE_RSA_WITH_AES_128_GCM_SHA256},
{"dhe_dss_aes_128_gcm_sha_256", TLS_DHE_DSS_WITH_AES_128_GCM_SHA256},
{"ecdhe_ecdsa_aes_128_gcm_sha_256", TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256},
{"ecdh_ecdsa_aes_128_gcm_sha_256", TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256},
{"ecdhe_rsa_aes_128_gcm_sha_256", TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
{"ecdh_rsa_aes_128_gcm_sha_256", TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256},
#endif
};
static const char* pem_library = "libnsspem.so";
static SECMODModule* mod = NULL;
/* NSPR I/O layer we use to detect blocking direction during SSL handshake */
static PRDescIdentity nspr_io_identity = PR_INVALID_IO_LAYER;
static PRIOMethods nspr_io_methods;
static const char* nss_error_to_name(PRErrorCode code)
{
const char *name = PR_ErrorToName(code);
if(name)
return name;
return "unknown error";
}
static void nss_print_error_message(struct Curl_easy *data, PRUint32 err)
{
failf(data, "%s", PR_ErrorToString(err, PR_LANGUAGE_I_DEFAULT));
}
static SECStatus set_ciphers(struct Curl_easy *data, PRFileDesc * model,
char *cipher_list)
{
unsigned int i;
PRBool cipher_state[NUM_OF_CIPHERS];
PRBool found;
char *cipher;
/* use accessors to avoid dynamic linking issues after an update of NSS */
const PRUint16 num_implemented_ciphers = SSL_GetNumImplementedCiphers();
const PRUint16 *implemented_ciphers = SSL_GetImplementedCiphers();
if(!implemented_ciphers)
return SECFailure;
/* First disable all ciphers. This uses a different max value in case
* NSS adds more ciphers later we don't want them available by
* accident
*/
for(i = 0; i < num_implemented_ciphers; i++) {
SSL_CipherPrefSet(model, implemented_ciphers[i], PR_FALSE);
}
/* Set every entry in our list to false */
for(i = 0; i < NUM_OF_CIPHERS; i++) {
cipher_state[i] = PR_FALSE;
}
cipher = cipher_list;
while(cipher_list && (cipher_list[0])) {
while((*cipher) && (ISSPACE(*cipher)))
++cipher;
if((cipher_list = strchr(cipher, ','))) {
*cipher_list++ = '\0';
}
found = PR_FALSE;
for(i=0; i<NUM_OF_CIPHERS; i++) {
if(Curl_raw_equal(cipher, cipherlist[i].name)) {
cipher_state[i] = PR_TRUE;
found = PR_TRUE;
break;
}
}
if(found == PR_FALSE) {
failf(data, "Unknown cipher in list: %s", cipher);
return SECFailure;
}
if(cipher_list) {
cipher = cipher_list;
}
}
/* Finally actually enable the selected ciphers */
for(i=0; i<NUM_OF_CIPHERS; i++) {
if(!cipher_state[i])
continue;
if(SSL_CipherPrefSet(model, cipherlist[i].num, PR_TRUE) != SECSuccess) {
failf(data, "cipher-suite not supported by NSS: %s", cipherlist[i].name);
return SECFailure;
}
}
return SECSuccess;
}
/*
* Return true if at least one cipher-suite is enabled. Used to determine
* if we need to call NSS_SetDomesticPolicy() to enable the default ciphers.
*/
static bool any_cipher_enabled(void)
{
unsigned int i;
for(i=0; i<NUM_OF_CIPHERS; i++) {
PRInt32 policy = 0;
SSL_CipherPolicyGet(cipherlist[i].num, &policy);
if(policy)
return TRUE;
}
return FALSE;
}
/*
* Determine whether the nickname passed in is a filename that needs to
* be loaded as a PEM or a regular NSS nickname.
*
* returns 1 for a file
* returns 0 for not a file (NSS nickname)
*/
static int is_file(const char *filename)
{
struct_stat st;
if(filename == NULL)
return 0;
if(stat(filename, &st) == 0)
if(S_ISREG(st.st_mode))
return 1;
return 0;
}
/* Check if the given string is filename or nickname of a certificate. If the
* given string is recognized as filename, return NULL. If the given string is
* recognized as nickname, return a duplicated string. The returned string
* should be later deallocated using free(). If the OOM failure occurs, we
* return NULL, too.
*/
static char* dup_nickname(struct Curl_easy *data, enum dupstring cert_kind)
{
const char *str = data->set.str[cert_kind];
const char *n;
if(!is_file(str))
/* no such file exists, use the string as nickname */
return strdup(str);
/* search the first slash; we require at least one slash in a file name */
n = strchr(str, '/');
if(!n) {
infof(data, "warning: certificate file name \"%s\" handled as nickname; "
"please use \"./%s\" to force file name\n", str, str);
return strdup(str);
}
/* we'll use the PEM reader to read the certificate from file */
return NULL;
}
/* Call PK11_CreateGenericObject() with the given obj_class and filename. If
* the call succeeds, append the object handle to the list of objects so that
* the object can be destroyed in Curl_nss_close(). */
static CURLcode nss_create_object(struct ssl_connect_data *ssl,
CK_OBJECT_CLASS obj_class,
const char *filename, bool cacert)
{
PK11SlotInfo *slot;
PK11GenericObject *obj;
CK_BBOOL cktrue = CK_TRUE;
CK_BBOOL ckfalse = CK_FALSE;
CK_ATTRIBUTE attrs[/* max count of attributes */ 4];
int attr_cnt = 0;
CURLcode result = (cacert)
? CURLE_SSL_CACERT_BADFILE
: CURLE_SSL_CERTPROBLEM;
const int slot_id = (cacert) ? 0 : 1;
char *slot_name = aprintf("PEM Token #%d", slot_id);
if(!slot_name)
return CURLE_OUT_OF_MEMORY;
slot = PK11_FindSlotByName(slot_name);
free(slot_name);
if(!slot)
return result;
PK11_SETATTRS(attrs, attr_cnt, CKA_CLASS, &obj_class, sizeof(obj_class));
PK11_SETATTRS(attrs, attr_cnt, CKA_TOKEN, &cktrue, sizeof(CK_BBOOL));
PK11_SETATTRS(attrs, attr_cnt, CKA_LABEL, (unsigned char *)filename,
strlen(filename) + 1);
if(CKO_CERTIFICATE == obj_class) {
CK_BBOOL *pval = (cacert) ? (&cktrue) : (&ckfalse);
PK11_SETATTRS(attrs, attr_cnt, CKA_TRUST, pval, sizeof(*pval));
}
obj = PK11_CreateGenericObject(slot, attrs, attr_cnt, PR_FALSE);
PK11_FreeSlot(slot);
if(!obj)
return result;
if(!Curl_llist_insert_next(ssl->obj_list, ssl->obj_list->tail, obj)) {
PK11_DestroyGenericObject(obj);
return CURLE_OUT_OF_MEMORY;
}
if(!cacert && CKO_CERTIFICATE == obj_class)
/* store reference to a client certificate */
ssl->obj_clicert = obj;
return CURLE_OK;
}
/* Destroy the NSS object whose handle is given by ptr. This function is
* a callback of Curl_llist_alloc() used by Curl_llist_destroy() to destroy
* NSS objects in Curl_nss_close() */
static void nss_destroy_object(void *user, void *ptr)
{
PK11GenericObject *obj = (PK11GenericObject *)ptr;
(void) user;
PK11_DestroyGenericObject(obj);
}
/* same as nss_destroy_object() but for CRL items */
static void nss_destroy_crl_item(void *user, void *ptr)
{
SECItem *crl_der = (SECItem *)ptr;
(void) user;
SECITEM_FreeItem(crl_der, PR_TRUE);
}
static CURLcode nss_load_cert(struct ssl_connect_data *ssl,
const char *filename, PRBool cacert)
{
CURLcode result = (cacert)
? CURLE_SSL_CACERT_BADFILE
: CURLE_SSL_CERTPROBLEM;
/* libnsspem.so leaks memory if the requested file does not exist. For more
* details, go to <https://bugzilla.redhat.com/734760>. */
if(is_file(filename))
result = nss_create_object(ssl, CKO_CERTIFICATE, filename, cacert);
if(!result && !cacert) {
/* we have successfully loaded a client certificate */
CERTCertificate *cert;
char *nickname = NULL;
char *n = strrchr(filename, '/');
if(n)
n++;
/* The following undocumented magic helps to avoid a SIGSEGV on call
* of PK11_ReadRawAttribute() from SelectClientCert() when using an
* immature version of libnsspem.so. For more details, go to
* <https://bugzilla.redhat.com/733685>. */
nickname = aprintf("PEM Token #1:%s", n);
if(nickname) {
cert = PK11_FindCertFromNickname(nickname, NULL);
if(cert)
CERT_DestroyCertificate(cert);
free(nickname);
}
}
return result;
}
/* add given CRL to cache if it is not already there */
static CURLcode nss_cache_crl(SECItem *crl_der)
{
CERTCertDBHandle *db = CERT_GetDefaultCertDB();
CERTSignedCrl *crl = SEC_FindCrlByDERCert(db, crl_der, 0);
if(crl) {
/* CRL already cached */
SEC_DestroyCrl(crl);
SECITEM_FreeItem(crl_der, PR_TRUE);
return CURLE_OK;
}
/* acquire lock before call of CERT_CacheCRL() and accessing nss_crl_list */
PR_Lock(nss_crllock);
/* store the CRL item so that we can free it in Curl_nss_cleanup() */
if(!Curl_llist_insert_next(nss_crl_list, nss_crl_list->tail, crl_der)) {
SECITEM_FreeItem(crl_der, PR_TRUE);
PR_Unlock(nss_crllock);
return CURLE_OUT_OF_MEMORY;
}
if(SECSuccess != CERT_CacheCRL(db, crl_der)) {
/* unable to cache CRL */
PR_Unlock(nss_crllock);
return CURLE_SSL_CRL_BADFILE;
}
/* we need to clear session cache, so that the CRL could take effect */
SSL_ClearSessionCache();
PR_Unlock(nss_crllock);
return CURLE_OK;
}
static CURLcode nss_load_crl(const char* crlfilename)
{
PRFileDesc *infile;
PRFileInfo info;
SECItem filedata = { 0, NULL, 0 };
SECItem *crl_der = NULL;
char *body;
infile = PR_Open(crlfilename, PR_RDONLY, 0);
if(!infile)
return CURLE_SSL_CRL_BADFILE;
if(PR_SUCCESS != PR_GetOpenFileInfo(infile, &info))
goto fail;
if(!SECITEM_AllocItem(NULL, &filedata, info.size + /* zero ended */ 1))
goto fail;
if(info.size != PR_Read(infile, filedata.data, info.size))
goto fail;
crl_der = SECITEM_AllocItem(NULL, NULL, 0U);
if(!crl_der)
goto fail;
/* place a trailing zero right after the visible data */
body = (char*)filedata.data;
body[--filedata.len] = '\0';
body = strstr(body, "-----BEGIN");
if(body) {
/* assume ASCII */
char *trailer;
char *begin = PORT_Strchr(body, '\n');
if(!begin)
begin = PORT_Strchr(body, '\r');
if(!begin)
goto fail;
trailer = strstr(++begin, "-----END");
if(!trailer)
goto fail;
/* retrieve DER from ASCII */
*trailer = '\0';
if(ATOB_ConvertAsciiToItem(crl_der, begin))
goto fail;
SECITEM_FreeItem(&filedata, PR_FALSE);
}
else
/* assume DER */
*crl_der = filedata;
PR_Close(infile);
return nss_cache_crl(crl_der);
fail:
PR_Close(infile);
SECITEM_FreeItem(crl_der, PR_TRUE);
SECITEM_FreeItem(&filedata, PR_FALSE);
return CURLE_SSL_CRL_BADFILE;
}
static CURLcode nss_load_key(struct connectdata *conn, int sockindex,
char *key_file)
{
PK11SlotInfo *slot;
SECStatus status;
CURLcode result;
struct ssl_connect_data *ssl = conn->ssl;
(void)sockindex; /* unused */
result = nss_create_object(ssl, CKO_PRIVATE_KEY, key_file, FALSE);
if(result) {
PR_SetError(SEC_ERROR_BAD_KEY, 0);
return result;
}
slot = PK11_FindSlotByName("PEM Token #1");
if(!slot)
return CURLE_SSL_CERTPROBLEM;
/* This will force the token to be seen as re-inserted */
SECMOD_WaitForAnyTokenEvent(mod, 0, 0);
PK11_IsPresent(slot);
status = PK11_Authenticate(slot, PR_TRUE,
conn->data->set.str[STRING_KEY_PASSWD]);
PK11_FreeSlot(slot);
return (SECSuccess == status) ? CURLE_OK : CURLE_SSL_CERTPROBLEM;
}
static int display_error(struct connectdata *conn, PRInt32 err,
const char *filename)
{
switch(err) {
case SEC_ERROR_BAD_PASSWORD:
failf(conn->data, "Unable to load client key: Incorrect password");
return 1;
case SEC_ERROR_UNKNOWN_CERT:
failf(conn->data, "Unable to load certificate %s", filename);
return 1;
default:
break;
}
return 0; /* The caller will print a generic error */
}
static CURLcode cert_stuff(struct connectdata *conn, int sockindex,
char *cert_file, char *key_file)
{
struct Curl_easy *data = conn->data;
CURLcode result;
if(cert_file) {
result = nss_load_cert(&conn->ssl[sockindex], cert_file, PR_FALSE);
if(result) {
const PRErrorCode err = PR_GetError();
if(!display_error(conn, err, cert_file)) {
const char *err_name = nss_error_to_name(err);
failf(data, "unable to load client cert: %d (%s)", err, err_name);
}
return result;
}
}
if(key_file || (is_file(cert_file))) {
if(key_file)
result = nss_load_key(conn, sockindex, key_file);
else
/* In case the cert file also has the key */
result = nss_load_key(conn, sockindex, cert_file);
if(result) {
const PRErrorCode err = PR_GetError();
if(!display_error(conn, err, key_file)) {
const char *err_name = nss_error_to_name(err);
failf(data, "unable to load client key: %d (%s)", err, err_name);
}
return result;
}
}
return CURLE_OK;
}
static char * nss_get_password(PK11SlotInfo * slot, PRBool retry, void *arg)
{
(void)slot; /* unused */
if(retry || NULL == arg)
return NULL;
else
return (char *)PORT_Strdup((char *)arg);
}
/* bypass the default SSL_AuthCertificate() hook in case we do not want to
* verify peer */
static SECStatus nss_auth_cert_hook(void *arg, PRFileDesc *fd, PRBool checksig,
PRBool isServer)
{
struct connectdata *conn = (struct connectdata *)arg;
#ifdef SSL_ENABLE_OCSP_STAPLING
if(conn->data->set.ssl.verifystatus) {
SECStatus cacheResult;
const SECItemArray *csa = SSL_PeerStapledOCSPResponses(fd);
if(!csa) {
failf(conn->data, "Invalid OCSP response");
return SECFailure;
}
if(csa->len == 0) {
failf(conn->data, "No OCSP response received");
return SECFailure;
}
cacheResult = CERT_CacheOCSPResponseFromSideChannel(
CERT_GetDefaultCertDB(), SSL_PeerCertificate(fd),
PR_Now(), &csa->items[0], arg
);
if(cacheResult != SECSuccess) {
failf(conn->data, "Invalid OCSP response");
return cacheResult;
}
}
#endif
if(!conn->data->set.ssl.verifypeer) {
infof(conn->data, "skipping SSL peer certificate verification\n");
return SECSuccess;
}
return SSL_AuthCertificate(CERT_GetDefaultCertDB(), fd, checksig, isServer);
}
/**
* Inform the application that the handshake is complete.
*/
static void HandshakeCallback(PRFileDesc *sock, void *arg)
{
struct connectdata *conn = (struct connectdata*) arg;
unsigned int buflenmax = 50;
unsigned char buf[50];
unsigned int buflen;
SSLNextProtoState state;
if(!conn->bits.tls_enable_npn && !conn->bits.tls_enable_alpn) {
return;
}
if(SSL_GetNextProto(sock, &state, buf, &buflen, buflenmax) == SECSuccess) {
switch(state) {
case SSL_NEXT_PROTO_NO_SUPPORT:
case SSL_NEXT_PROTO_NO_OVERLAP:
infof(conn->data, "ALPN/NPN, server did not agree to a protocol\n");
return;
#ifdef SSL_ENABLE_ALPN
case SSL_NEXT_PROTO_SELECTED:
infof(conn->data, "ALPN, server accepted to use %.*s\n", buflen, buf);
break;
#endif
case SSL_NEXT_PROTO_NEGOTIATED:
infof(conn->data, "NPN, server accepted to use %.*s\n", buflen, buf);
break;
}
#ifdef USE_NGHTTP2
if(buflen == NGHTTP2_PROTO_VERSION_ID_LEN &&
!memcmp(NGHTTP2_PROTO_VERSION_ID, buf, NGHTTP2_PROTO_VERSION_ID_LEN)) {
conn->negnpn = CURL_HTTP_VERSION_2;
}
else
#endif
if(buflen == ALPN_HTTP_1_1_LENGTH &&
!memcmp(ALPN_HTTP_1_1, buf, ALPN_HTTP_1_1_LENGTH)) {
conn->negnpn = CURL_HTTP_VERSION_1_1;
}
}
}
#if NSSVERNUM >= 0x030f04 /* 3.15.4 */
static SECStatus CanFalseStartCallback(PRFileDesc *sock, void *client_data,
PRBool *canFalseStart)
{
struct connectdata *conn = client_data;
struct Curl_easy *data = conn->data;
SSLChannelInfo channelInfo;
SSLCipherSuiteInfo cipherInfo;
SECStatus rv;
PRBool negotiatedExtension;
*canFalseStart = PR_FALSE;
if(SSL_GetChannelInfo(sock, &channelInfo, sizeof(channelInfo)) != SECSuccess)
return SECFailure;
if(SSL_GetCipherSuiteInfo(channelInfo.cipherSuite, &cipherInfo,
sizeof(cipherInfo)) != SECSuccess)
return SECFailure;
/* Prevent version downgrade attacks from TLS 1.2, and avoid False Start for
* TLS 1.3 and later. See https://bugzilla.mozilla.org/show_bug.cgi?id=861310
*/
if(channelInfo.protocolVersion != SSL_LIBRARY_VERSION_TLS_1_2)
goto end;
/* Only allow ECDHE key exchange algorithm.
* See https://bugzilla.mozilla.org/show_bug.cgi?id=952863 */
if(cipherInfo.keaType != ssl_kea_ecdh)
goto end;
/* Prevent downgrade attacks on the symmetric cipher. We do not allow CBC
* mode due to BEAST, POODLE, and other attacks on the MAC-then-Encrypt
* design. See https://bugzilla.mozilla.org/show_bug.cgi?id=1109766 */
if(cipherInfo.symCipher != ssl_calg_aes_gcm)
goto end;
/* Enforce ALPN or NPN to do False Start, as an indicator of server
* compatibility. */
rv = SSL_HandshakeNegotiatedExtension(sock, ssl_app_layer_protocol_xtn,
&negotiatedExtension);
if(rv != SECSuccess || !negotiatedExtension) {
rv = SSL_HandshakeNegotiatedExtension(sock, ssl_next_proto_nego_xtn,
&negotiatedExtension);
}
if(rv != SECSuccess || !negotiatedExtension)
goto end;
*canFalseStart = PR_TRUE;
infof(data, "Trying TLS False Start\n");
end:
return SECSuccess;
}
#endif
static void display_cert_info(struct Curl_easy *data,
CERTCertificate *cert)
{
char *subject, *issuer, *common_name;
PRExplodedTime printableTime;
char timeString[256];
PRTime notBefore, notAfter;
subject = CERT_NameToAscii(&cert->subject);
issuer = CERT_NameToAscii(&cert->issuer);
common_name = CERT_GetCommonName(&cert->subject);
infof(data, "\tsubject: %s\n", subject);
CERT_GetCertTimes(cert, ¬Before, ¬After);
PR_ExplodeTime(notBefore, PR_GMTParameters, &printableTime);
PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
infof(data, "\tstart date: %s\n", timeString);
PR_ExplodeTime(notAfter, PR_GMTParameters, &printableTime);
PR_FormatTime(timeString, 256, "%b %d %H:%M:%S %Y GMT", &printableTime);
infof(data, "\texpire date: %s\n", timeString);
infof(data, "\tcommon name: %s\n", common_name);
infof(data, "\tissuer: %s\n", issuer);
PR_Free(subject);
PR_Free(issuer);
PR_Free(common_name);
}
static CURLcode display_conn_info(struct connectdata *conn, PRFileDesc *sock)
{
CURLcode result = CURLE_OK;
SSLChannelInfo channel;
SSLCipherSuiteInfo suite;
CERTCertificate *cert;
CERTCertificate *cert2;
CERTCertificate *cert3;
PRTime now;
int i;
if(SSL_GetChannelInfo(sock, &channel, sizeof channel) ==
SECSuccess && channel.length == sizeof channel &&
channel.cipherSuite) {
if(SSL_GetCipherSuiteInfo(channel.cipherSuite,
&suite, sizeof suite) == SECSuccess) {
infof(conn->data, "SSL connection using %s\n", suite.cipherSuiteName);
}
}
cert = SSL_PeerCertificate(sock);
if(cert) {
infof(conn->data, "Server certificate:\n");
if(!conn->data->set.ssl.certinfo) {
display_cert_info(conn->data, cert);
CERT_DestroyCertificate(cert);
}
else {
/* Count certificates in chain. */
now = PR_Now();
i = 1;
if(!cert->isRoot) {
cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
while(cert2) {
i++;
if(cert2->isRoot) {
CERT_DestroyCertificate(cert2);
break;
}
cert3 = CERT_FindCertIssuer(cert2, now, certUsageSSLCA);
CERT_DestroyCertificate(cert2);
cert2 = cert3;
}
}
result = Curl_ssl_init_certinfo(conn->data, i);
if(!result) {
for(i = 0; cert; cert = cert2) {
result = Curl_extract_certinfo(conn, i++, (char *)cert->derCert.data,
(char *)cert->derCert.data +
cert->derCert.len);
if(result)
break;
if(cert->isRoot) {
CERT_DestroyCertificate(cert);
break;
}
cert2 = CERT_FindCertIssuer(cert, now, certUsageSSLCA);
CERT_DestroyCertificate(cert);
}
}
}
}
return result;
}
static SECStatus BadCertHandler(void *arg, PRFileDesc *sock)
{
struct connectdata *conn = (struct connectdata *)arg;
struct Curl_easy *data = conn->data;
PRErrorCode err = PR_GetError();
CERTCertificate *cert;
/* remember the cert verification result */
data->set.ssl.certverifyresult = err;
if(err == SSL_ERROR_BAD_CERT_DOMAIN && !data->set.ssl.verifyhost)
/* we are asked not to verify the host name */
return SECSuccess;
/* print only info about the cert, the error is printed off the callback */
cert = SSL_PeerCertificate(sock);
if(cert) {
infof(data, "Server certificate:\n");
display_cert_info(data, cert);
CERT_DestroyCertificate(cert);
}
return SECFailure;
}
/**
*
* Check that the Peer certificate's issuer certificate matches the one found
* by issuer_nickname. This is not exactly the way OpenSSL and GNU TLS do the
* issuer check, so we provide comments that mimic the OpenSSL
* X509_check_issued function (in x509v3/v3_purp.c)
*/
static SECStatus check_issuer_cert(PRFileDesc *sock,
char *issuer_nickname)
{
CERTCertificate *cert, *cert_issuer, *issuer;
SECStatus res=SECSuccess;
void *proto_win = NULL;
cert = SSL_PeerCertificate(sock);
cert_issuer = CERT_FindCertIssuer(cert, PR_Now(), certUsageObjectSigner);
proto_win = SSL_RevealPinArg(sock);
issuer = PK11_FindCertFromNickname(issuer_nickname, proto_win);
if((!cert_issuer) || (!issuer))
res = SECFailure;
else if(SECITEM_CompareItem(&cert_issuer->derCert,
&issuer->derCert)!=SECEqual)
res = SECFailure;
CERT_DestroyCertificate(cert);
CERT_DestroyCertificate(issuer);
CERT_DestroyCertificate(cert_issuer);
return res;
}
static CURLcode cmp_peer_pubkey(struct ssl_connect_data *connssl,
const char *pinnedpubkey)
{
CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
struct Curl_easy *data = connssl->data;
CERTCertificate *cert;
if(!pinnedpubkey)
/* no pinned public key specified */
return CURLE_OK;
/* get peer certificate */
cert = SSL_PeerCertificate(connssl->handle);
if(cert) {
/* extract public key from peer certificate */
SECKEYPublicKey *pubkey = CERT_ExtractPublicKey(cert);
if(pubkey) {
/* encode the public key as DER */
SECItem *cert_der = PK11_DEREncodePublicKey(pubkey);
if(cert_der) {
/* compare the public key with the pinned public key */
result = Curl_pin_peer_pubkey(data, pinnedpubkey, cert_der->data,
cert_der->len);
SECITEM_FreeItem(cert_der, PR_TRUE);
}
SECKEY_DestroyPublicKey(pubkey);
}
CERT_DestroyCertificate(cert);
}
/* report the resulting status */
switch(result) {
case CURLE_OK:
infof(data, "pinned public key verified successfully!\n");
break;
case CURLE_SSL_PINNEDPUBKEYNOTMATCH:
failf(data, "failed to verify pinned public key");
break;
default:
/* OOM, etc. */
break;
}
return result;
}
/**
*
* Callback to pick the SSL client certificate.
*/
static SECStatus SelectClientCert(void *arg, PRFileDesc *sock,
struct CERTDistNamesStr *caNames,
struct CERTCertificateStr **pRetCert,
struct SECKEYPrivateKeyStr **pRetKey)
{
struct ssl_connect_data *connssl = (struct ssl_connect_data *)arg;
struct Curl_easy *data = connssl->data;
const char *nickname = connssl->client_nickname;
if(connssl->obj_clicert) {
/* use the cert/key provided by PEM reader */
static const char pem_slotname[] = "PEM Token #1";
SECItem cert_der = { 0, NULL, 0 };
void *proto_win = SSL_RevealPinArg(sock);
struct CERTCertificateStr *cert;
struct SECKEYPrivateKeyStr *key;
PK11SlotInfo *slot = PK11_FindSlotByName(pem_slotname);
if(NULL == slot) {
failf(data, "NSS: PK11 slot not found: %s", pem_slotname);
return SECFailure;
}
if(PK11_ReadRawAttribute(PK11_TypeGeneric, connssl->obj_clicert, CKA_VALUE,
&cert_der) != SECSuccess) {
failf(data, "NSS: CKA_VALUE not found in PK11 generic object");
PK11_FreeSlot(slot);
return SECFailure;
}
cert = PK11_FindCertFromDERCertItem(slot, &cert_der, proto_win);
SECITEM_FreeItem(&cert_der, PR_FALSE);
if(NULL == cert) {
failf(data, "NSS: client certificate from file not found");
PK11_FreeSlot(slot);
return SECFailure;
}
key = PK11_FindPrivateKeyFromCert(slot, cert, NULL);
PK11_FreeSlot(slot);
if(NULL == key) {
failf(data, "NSS: private key from file not found");
CERT_DestroyCertificate(cert);
return SECFailure;
}
infof(data, "NSS: client certificate from file\n");
display_cert_info(data, cert);
*pRetCert = cert;
*pRetKey = key;
return SECSuccess;
}
/* use the default NSS hook */
if(SECSuccess != NSS_GetClientAuthData((void *)nickname, sock, caNames,
pRetCert, pRetKey)
|| NULL == *pRetCert) {
if(NULL == nickname)
failf(data, "NSS: client certificate not found (nickname not "
"specified)");
else
failf(data, "NSS: client certificate not found: %s", nickname);
return SECFailure;
}
/* get certificate nickname if any */
nickname = (*pRetCert)->nickname;
if(NULL == nickname)
nickname = "[unknown]";
if(NULL == *pRetKey) {
failf(data, "NSS: private key not found for certificate: %s", nickname);
return SECFailure;
}
infof(data, "NSS: using client certificate: %s\n", nickname);
display_cert_info(data, *pRetCert);
return SECSuccess;
}
/* update blocking direction in case of PR_WOULD_BLOCK_ERROR */
static void nss_update_connecting_state(ssl_connect_state state, void *secret)
{
struct ssl_connect_data *connssl = (struct ssl_connect_data *)secret;
if(PR_GetError() != PR_WOULD_BLOCK_ERROR)
/* an unrelated error is passing by */
return;
switch(connssl->connecting_state) {
case ssl_connect_2:
case ssl_connect_2_reading:
case ssl_connect_2_writing:
break;
default:
/* we are not called from an SSL handshake */
return;
}
/* update the state accordingly */
connssl->connecting_state = state;
}
/* recv() wrapper we use to detect blocking direction during SSL handshake */
static PRInt32 nspr_io_recv(PRFileDesc *fd, void *buf, PRInt32 amount,
PRIntn flags, PRIntervalTime timeout)
{
const PRRecvFN recv_fn = fd->lower->methods->recv;
const PRInt32 rv = recv_fn(fd->lower, buf, amount, flags, timeout);
if(rv < 0)
/* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
nss_update_connecting_state(ssl_connect_2_reading, fd->secret);
return rv;
}
/* send() wrapper we use to detect blocking direction during SSL handshake */
static PRInt32 nspr_io_send(PRFileDesc *fd, const void *buf, PRInt32 amount,
PRIntn flags, PRIntervalTime timeout)
{
const PRSendFN send_fn = fd->lower->methods->send;
const PRInt32 rv = send_fn(fd->lower, buf, amount, flags, timeout);
if(rv < 0)
/* check for PR_WOULD_BLOCK_ERROR and update blocking direction */
nss_update_connecting_state(ssl_connect_2_writing, fd->secret);
return rv;
}
/* close() wrapper to avoid assertion failure due to fd->secret != NULL */
static PRStatus nspr_io_close(PRFileDesc *fd)
{
const PRCloseFN close_fn = PR_GetDefaultIOMethods()->close;
fd->secret = NULL;
return close_fn(fd);
}
/* data might be NULL */
static CURLcode nss_init_core(struct Curl_easy *data, const char *cert_dir)
{
NSSInitParameters initparams;
if(nss_context != NULL)
return CURLE_OK;
memset((void *) &initparams, '\0', sizeof(initparams));
initparams.length = sizeof(initparams);
if(cert_dir) {
char *certpath = aprintf("sql:%s", cert_dir);
if(!certpath)
return CURLE_OUT_OF_MEMORY;
infof(data, "Initializing NSS with certpath: %s\n", certpath);
nss_context = NSS_InitContext(certpath, "", "", "", &initparams,
NSS_INIT_READONLY | NSS_INIT_PK11RELOAD);
free(certpath);
if(nss_context != NULL)
return CURLE_OK;
infof(data, "Unable to initialize NSS database\n");
}
infof(data, "Initializing NSS with certpath: none\n");
nss_context = NSS_InitContext("", "", "", "", &initparams, NSS_INIT_READONLY
| NSS_INIT_NOCERTDB | NSS_INIT_NOMODDB | NSS_INIT_FORCEOPEN
| NSS_INIT_NOROOTINIT | NSS_INIT_OPTIMIZESPACE | NSS_INIT_PK11RELOAD);
if(nss_context != NULL)
return CURLE_OK;
infof(data, "Unable to initialize NSS\n");
return CURLE_SSL_CACERT_BADFILE;
}
/* data might be NULL */
static CURLcode nss_init(struct Curl_easy *data)
{
char *cert_dir;
struct_stat st;
CURLcode result;
if(initialized)
return CURLE_OK;
/* list of all CRL items we need to destroy in Curl_nss_cleanup() */
nss_crl_list = Curl_llist_alloc(nss_destroy_crl_item);
if(!nss_crl_list)
return CURLE_OUT_OF_MEMORY;
/* First we check if $SSL_DIR points to a valid dir */
cert_dir = getenv("SSL_DIR");
if(cert_dir) {
if((stat(cert_dir, &st) != 0) ||
(!S_ISDIR(st.st_mode))) {
cert_dir = NULL;
}
}
/* Now we check if the default location is a valid dir */
if(!cert_dir) {
if((stat(SSL_DIR, &st) == 0) &&
(S_ISDIR(st.st_mode))) {
cert_dir = (char *)SSL_DIR;
}
}
if(nspr_io_identity == PR_INVALID_IO_LAYER) {
/* allocate an identity for our own NSPR I/O layer */
nspr_io_identity = PR_GetUniqueIdentity("libcurl");
if(nspr_io_identity == PR_INVALID_IO_LAYER)
return CURLE_OUT_OF_MEMORY;
/* the default methods just call down to the lower I/O layer */
memcpy(&nspr_io_methods, PR_GetDefaultIOMethods(), sizeof nspr_io_methods);
/* override certain methods in the table by our wrappers */
nspr_io_methods.recv = nspr_io_recv;
nspr_io_methods.send = nspr_io_send;
nspr_io_methods.close = nspr_io_close;
}
result = nss_init_core(data, cert_dir);
if(result)
return result;
if(!any_cipher_enabled())
NSS_SetDomesticPolicy();
initialized = 1;
return CURLE_OK;
}
/**
* Global SSL init
*
* @retval 0 error initializing SSL
* @retval 1 SSL initialized successfully
*/
int Curl_nss_init(void)
{
/* curl_global_init() is not thread-safe so this test is ok */
if(nss_initlock == NULL) {
PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256);
nss_initlock = PR_NewLock();
nss_crllock = PR_NewLock();
}
/* We will actually initialize NSS later */
return 1;
}
/* data might be NULL */
CURLcode Curl_nss_force_init(struct Curl_easy *data)
{
CURLcode result;
if(!nss_initlock) {
if(data)
failf(data, "unable to initialize NSS, curl_global_init() should have "
"been called with CURL_GLOBAL_SSL or CURL_GLOBAL_ALL");
return CURLE_FAILED_INIT;
}
PR_Lock(nss_initlock);
result = nss_init(data);
PR_Unlock(nss_initlock);
return result;
}
/* Global cleanup */
void Curl_nss_cleanup(void)
{
/* This function isn't required to be threadsafe and this is only done
* as a safety feature.
*/
PR_Lock(nss_initlock);
if(initialized) {
/* Free references to client certificates held in the SSL session cache.
* Omitting this hampers destruction of the security module owning
* the certificates. */
SSL_ClearSessionCache();
if(mod && SECSuccess == SECMOD_UnloadUserModule(mod)) {
SECMOD_DestroyModule(mod);
mod = NULL;
}
NSS_ShutdownContext(nss_context);
nss_context = NULL;
}
/* destroy all CRL items */
Curl_llist_destroy(nss_crl_list, NULL);
nss_crl_list = NULL;
PR_Unlock(nss_initlock);
PR_DestroyLock(nss_initlock);
PR_DestroyLock(nss_crllock);
nss_initlock = NULL;
initialized = 0;
}
/*
* This function uses SSL_peek to determine connection status.
*
* Return codes:
* 1 means the connection is still in place
* 0 means the connection has been closed
* -1 means the connection status is unknown
*/
int
Curl_nss_check_cxn(struct connectdata *conn)
{
int rc;
char buf;
rc =
PR_Recv(conn->ssl[FIRSTSOCKET].handle, (void *)&buf, 1, PR_MSG_PEEK,
PR_SecondsToInterval(1));
if(rc > 0)
return 1; /* connection still in place */
if(rc == 0)
return 0; /* connection has been closed */
return -1; /* connection status unknown */
}
/*
* This function is called when an SSL connection is closed.
*/
void Curl_nss_close(struct connectdata *conn, int sockindex)
{
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
if(connssl->handle) {
/* NSS closes the socket we previously handed to it, so we must mark it
as closed to avoid double close */
fake_sclose(conn->sock[sockindex]);
conn->sock[sockindex] = CURL_SOCKET_BAD;
if((connssl->client_nickname != NULL) || (connssl->obj_clicert != NULL))
/* A server might require different authentication based on the
* particular path being requested by the client. To support this
* scenario, we must ensure that a connection will never reuse the
* authentication data from a previous connection. */
SSL_InvalidateSession(connssl->handle);
free(connssl->client_nickname);
connssl->client_nickname = NULL;
/* destroy all NSS objects in order to avoid failure of NSS shutdown */
Curl_llist_destroy(connssl->obj_list, NULL);
connssl->obj_list = NULL;
connssl->obj_clicert = NULL;
PR_Close(connssl->handle);
connssl->handle = NULL;
}
}
/* return true if NSS can provide error code (and possibly msg) for the
error */
static bool is_nss_error(CURLcode err)
{
switch(err) {
case CURLE_PEER_FAILED_VERIFICATION:
case CURLE_SSL_CACERT:
case CURLE_SSL_CERTPROBLEM:
case CURLE_SSL_CONNECT_ERROR:
case CURLE_SSL_ISSUER_ERROR:
return true;
default:
return false;
}
}
/* return true if the given error code is related to a client certificate */
static bool is_cc_error(PRInt32 err)
{
switch(err) {
case SSL_ERROR_BAD_CERT_ALERT:
case SSL_ERROR_EXPIRED_CERT_ALERT:
case SSL_ERROR_REVOKED_CERT_ALERT:
return true;
default:
return false;
}
}
static Curl_recv nss_recv;
static Curl_send nss_send;
static CURLcode nss_load_ca_certificates(struct connectdata *conn,
int sockindex)
{
struct Curl_easy *data = conn->data;
const char *cafile = data->set.ssl.CAfile;
const char *capath = data->set.ssl.CApath;
if(cafile) {
CURLcode result = nss_load_cert(&conn->ssl[sockindex], cafile, PR_TRUE);
if(result)
return result;
}
if(capath) {
struct_stat st;
if(stat(capath, &st) == -1)
return CURLE_SSL_CACERT_BADFILE;
if(S_ISDIR(st.st_mode)) {
PRDirEntry *entry;
PRDir *dir = PR_OpenDir(capath);
if(!dir)
return CURLE_SSL_CACERT_BADFILE;
while((entry = PR_ReadDir(dir, PR_SKIP_BOTH | PR_SKIP_HIDDEN))) {
char *fullpath = aprintf("%s/%s", capath, entry->name);
if(!fullpath) {
PR_CloseDir(dir);
return CURLE_OUT_OF_MEMORY;
}
if(CURLE_OK != nss_load_cert(&conn->ssl[sockindex], fullpath, PR_TRUE))
/* This is purposefully tolerant of errors so non-PEM files can
* be in the same directory */
infof(data, "failed to load '%s' from CURLOPT_CAPATH\n", fullpath);
free(fullpath);
}
PR_CloseDir(dir);
}
else
infof(data, "warning: CURLOPT_CAPATH not a directory (%s)\n", capath);
}
infof(data, " CAfile: %s\n CApath: %s\n",
cafile ? cafile : "none",
capath ? capath : "none");
return CURLE_OK;
}
static CURLcode nss_init_sslver(SSLVersionRange *sslver,
struct Curl_easy *data)
{
switch(data->set.ssl.version) {
default:
case CURL_SSLVERSION_DEFAULT:
case CURL_SSLVERSION_TLSv1:
sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
#ifdef SSL_LIBRARY_VERSION_TLS_1_2
sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
#elif defined SSL_LIBRARY_VERSION_TLS_1_1
sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
#else
sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
#endif
return CURLE_OK;
case CURL_SSLVERSION_SSLv2:
sslver->min = SSL_LIBRARY_VERSION_2;
sslver->max = SSL_LIBRARY_VERSION_2;
return CURLE_OK;
case CURL_SSLVERSION_SSLv3:
sslver->min = SSL_LIBRARY_VERSION_3_0;
sslver->max = SSL_LIBRARY_VERSION_3_0;
return CURLE_OK;
case CURL_SSLVERSION_TLSv1_0:
sslver->min = SSL_LIBRARY_VERSION_TLS_1_0;
sslver->max = SSL_LIBRARY_VERSION_TLS_1_0;
return CURLE_OK;
case CURL_SSLVERSION_TLSv1_1:
#ifdef SSL_LIBRARY_VERSION_TLS_1_1
sslver->min = SSL_LIBRARY_VERSION_TLS_1_1;
sslver->max = SSL_LIBRARY_VERSION_TLS_1_1;
return CURLE_OK;
#endif
break;
case CURL_SSLVERSION_TLSv1_2:
#ifdef SSL_LIBRARY_VERSION_TLS_1_2
sslver->min = SSL_LIBRARY_VERSION_TLS_1_2;
sslver->max = SSL_LIBRARY_VERSION_TLS_1_2;
return CURLE_OK;
#endif
break;
}
failf(data, "TLS minor version cannot be set");
return CURLE_SSL_CONNECT_ERROR;
}
static CURLcode nss_fail_connect(struct ssl_connect_data *connssl,
struct Curl_easy *data,
CURLcode curlerr)
{
PRErrorCode err = 0;
if(is_nss_error(curlerr)) {
/* read NSPR error code */
err = PR_GetError();
if(is_cc_error(err))
curlerr = CURLE_SSL_CERTPROBLEM;
/* print the error number and error string */
infof(data, "NSS error %d (%s)\n", err, nss_error_to_name(err));
/* print a human-readable message describing the error if available */
nss_print_error_message(data, err);
}
/* cleanup on connection failure */
Curl_llist_destroy(connssl->obj_list, NULL);
connssl->obj_list = NULL;
return curlerr;
}
/* Switch the SSL socket into non-blocking mode. */
static CURLcode nss_set_nonblock(struct ssl_connect_data *connssl,
struct Curl_easy *data)
{
static PRSocketOptionData sock_opt;
sock_opt.option = PR_SockOpt_Nonblocking;
sock_opt.value.non_blocking = PR_TRUE;
if(PR_SetSocketOption(connssl->handle, &sock_opt) != PR_SUCCESS)
return nss_fail_connect(connssl, data, CURLE_SSL_CONNECT_ERROR);
return CURLE_OK;
}
static CURLcode nss_setup_connect(struct connectdata *conn, int sockindex)
{
PRFileDesc *model = NULL;
PRFileDesc *nspr_io = NULL;
PRFileDesc *nspr_io_stub = NULL;
PRBool ssl_no_cache;
PRBool ssl_cbc_random_iv;
struct Curl_easy *data = conn->data;
curl_socket_t sockfd = conn->sock[sockindex];
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
CURLcode result;
SSLVersionRange sslver = {
SSL_LIBRARY_VERSION_TLS_1_0, /* min */
SSL_LIBRARY_VERSION_TLS_1_0 /* max */
};
connssl->data = data;
/* list of all NSS objects we need to destroy in Curl_nss_close() */
connssl->obj_list = Curl_llist_alloc(nss_destroy_object);
if(!connssl->obj_list)
return CURLE_OUT_OF_MEMORY;
/* FIXME. NSS doesn't support multiple databases open at the same time. */
PR_Lock(nss_initlock);
result = nss_init(conn->data);
if(result) {
PR_Unlock(nss_initlock);
goto error;
}
result = CURLE_SSL_CONNECT_ERROR;
if(!mod) {
char *configstring = aprintf("library=%s name=PEM", pem_library);
if(!configstring) {
PR_Unlock(nss_initlock);
goto error;
}
mod = SECMOD_LoadUserModule(configstring, NULL, PR_FALSE);
free(configstring);
if(!mod || !mod->loaded) {
if(mod) {
SECMOD_DestroyModule(mod);
mod = NULL;
}
infof(data, "WARNING: failed to load NSS PEM library %s. Using "
"OpenSSL PEM certificates will not work.\n", pem_library);
}
}
PK11_SetPasswordFunc(nss_get_password);
PR_Unlock(nss_initlock);
model = PR_NewTCPSocket();
if(!model)
goto error;
model = SSL_ImportFD(NULL, model);
if(SSL_OptionSet(model, SSL_SECURITY, PR_TRUE) != SECSuccess)
goto error;
if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_SERVER, PR_FALSE) != SECSuccess)
goto error;
if(SSL_OptionSet(model, SSL_HANDSHAKE_AS_CLIENT, PR_TRUE) != SECSuccess)
goto error;
/* do not use SSL cache if disabled or we are not going to verify peer */
ssl_no_cache = (conn->ssl_config.sessionid && data->set.ssl.verifypeer) ?
PR_FALSE : PR_TRUE;
if(SSL_OptionSet(model, SSL_NO_CACHE, ssl_no_cache) != SECSuccess)
goto error;
/* enable/disable the requested SSL version(s) */
if(nss_init_sslver(&sslver, data) != CURLE_OK)
goto error;
if(SSL_VersionRangeSet(model, &sslver) != SECSuccess)
goto error;
ssl_cbc_random_iv = !data->set.ssl_enable_beast;
#ifdef SSL_CBC_RANDOM_IV
/* unless the user explicitly asks to allow the protocol vulnerability, we
use the work-around */
if(SSL_OptionSet(model, SSL_CBC_RANDOM_IV, ssl_cbc_random_iv) != SECSuccess)
infof(data, "warning: failed to set SSL_CBC_RANDOM_IV = %d\n",
ssl_cbc_random_iv);
#else
if(ssl_cbc_random_iv)
infof(data, "warning: support for SSL_CBC_RANDOM_IV not compiled in\n");
#endif
if(data->set.ssl.cipher_list) {
if(set_ciphers(data, model, data->set.ssl.cipher_list) != SECSuccess) {
result = CURLE_SSL_CIPHER;
goto error;
}
}
if(!data->set.ssl.verifypeer && data->set.ssl.verifyhost)
infof(data, "warning: ignoring value of ssl.verifyhost\n");
/* bypass the default SSL_AuthCertificate() hook in case we do not want to
* verify peer */
if(SSL_AuthCertificateHook(model, nss_auth_cert_hook, conn) != SECSuccess)
goto error;
data->set.ssl.certverifyresult=0; /* not checked yet */
if(SSL_BadCertHook(model, BadCertHandler, conn) != SECSuccess)
goto error;
if(SSL_HandshakeCallback(model, HandshakeCallback, conn) != SECSuccess)
goto error;
if(data->set.ssl.verifypeer) {
const CURLcode rv = nss_load_ca_certificates(conn, sockindex);
if(rv) {
result = rv;
goto error;
}
}
if(data->set.ssl.CRLfile) {
const CURLcode rv = nss_load_crl(data->set.ssl.CRLfile);
if(rv) {
result = rv;
goto error;
}
infof(data, " CRLfile: %s\n", data->set.ssl.CRLfile);
}
if(data->set.str[STRING_CERT]) {
char *nickname = dup_nickname(data, STRING_CERT);
if(nickname) {
/* we are not going to use libnsspem.so to read the client cert */
connssl->obj_clicert = NULL;
}
else {
CURLcode rv = cert_stuff(conn, sockindex, data->set.str[STRING_CERT],
data->set.str[STRING_KEY]);
if(rv) {
/* failf() is already done in cert_stuff() */
result = rv;
goto error;
}
}
/* store the nickname for SelectClientCert() called during handshake */
connssl->client_nickname = nickname;
}
else
connssl->client_nickname = NULL;
if(SSL_GetClientAuthDataHook(model, SelectClientCert,
(void *)connssl) != SECSuccess) {
result = CURLE_SSL_CERTPROBLEM;
goto error;
}
/* wrap OS file descriptor by NSPR's file descriptor abstraction */
nspr_io = PR_ImportTCPSocket(sockfd);
if(!nspr_io)
goto error;
/* create our own NSPR I/O layer */
nspr_io_stub = PR_CreateIOLayerStub(nspr_io_identity, &nspr_io_methods);
if(!nspr_io_stub) {
PR_Close(nspr_io);
goto error;
}
/* make the per-connection data accessible from NSPR I/O callbacks */
nspr_io_stub->secret = (void *)connssl;
/* push our new layer to the NSPR I/O stack */
if(PR_PushIOLayer(nspr_io, PR_TOP_IO_LAYER, nspr_io_stub) != PR_SUCCESS) {
PR_Close(nspr_io);
PR_Close(nspr_io_stub);
goto error;
}
/* import our model socket onto the current I/O stack */
connssl->handle = SSL_ImportFD(model, nspr_io);
if(!connssl->handle) {
PR_Close(nspr_io);
goto error;
}
PR_Close(model); /* We don't need this any more */
model = NULL;
/* This is the password associated with the cert that we're using */
if(data->set.str[STRING_KEY_PASSWD]) {
SSL_SetPKCS11PinArg(connssl->handle, data->set.str[STRING_KEY_PASSWD]);
}
#ifdef SSL_ENABLE_OCSP_STAPLING
if(data->set.ssl.verifystatus) {
if(SSL_OptionSet(connssl->handle, SSL_ENABLE_OCSP_STAPLING, PR_TRUE)
!= SECSuccess)
goto error;
}
#endif
#ifdef SSL_ENABLE_NPN
if(SSL_OptionSet(connssl->handle, SSL_ENABLE_NPN, conn->bits.tls_enable_npn
? PR_TRUE : PR_FALSE) != SECSuccess)
goto error;
#endif
#ifdef SSL_ENABLE_ALPN
if(SSL_OptionSet(connssl->handle, SSL_ENABLE_ALPN, conn->bits.tls_enable_alpn
? PR_TRUE : PR_FALSE) != SECSuccess)
goto error;
#endif
#if NSSVERNUM >= 0x030f04 /* 3.15.4 */
if(data->set.ssl.falsestart) {
if(SSL_OptionSet(connssl->handle, SSL_ENABLE_FALSE_START, PR_TRUE)
!= SECSuccess)
goto error;
if(SSL_SetCanFalseStartCallback(connssl->handle, CanFalseStartCallback,
conn) != SECSuccess)
goto error;
}
#endif
#if defined(SSL_ENABLE_NPN) || defined(SSL_ENABLE_ALPN)
if(conn->bits.tls_enable_npn || conn->bits.tls_enable_alpn) {
int cur = 0;
unsigned char protocols[128];
#ifdef USE_NGHTTP2
if(data->set.httpversion >= CURL_HTTP_VERSION_2) {
protocols[cur++] = NGHTTP2_PROTO_VERSION_ID_LEN;
memcpy(&protocols[cur], NGHTTP2_PROTO_VERSION_ID,
NGHTTP2_PROTO_VERSION_ID_LEN);
cur += NGHTTP2_PROTO_VERSION_ID_LEN;
}
#endif
protocols[cur++] = ALPN_HTTP_1_1_LENGTH;
memcpy(&protocols[cur], ALPN_HTTP_1_1, ALPN_HTTP_1_1_LENGTH);
cur += ALPN_HTTP_1_1_LENGTH;
if(SSL_SetNextProtoNego(connssl->handle, protocols, cur) != SECSuccess)
goto error;
}
#endif
/* Force handshake on next I/O */
if(SSL_ResetHandshake(connssl->handle, /* asServer */ PR_FALSE)
!= SECSuccess)
goto error;
/* propagate hostname to the TLS layer */
if(SSL_SetURL(connssl->handle, conn->host.name) != SECSuccess)
goto error;
/* prevent NSS from re-using the session for a different hostname */
if(SSL_SetSockPeerID(connssl->handle, conn->host.name) != SECSuccess)
goto error;
return CURLE_OK;
error:
if(model)
PR_Close(model);
return nss_fail_connect(connssl, data, result);
}
static CURLcode nss_do_connect(struct connectdata *conn, int sockindex)
{
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
struct Curl_easy *data = conn->data;
CURLcode result = CURLE_SSL_CONNECT_ERROR;
PRUint32 timeout;
/* check timeout situation */
const long time_left = Curl_timeleft(data, NULL, TRUE);
if(time_left < 0L) {
failf(data, "timed out before SSL handshake");
result = CURLE_OPERATION_TIMEDOUT;
goto error;
}
/* Force the handshake now */
timeout = PR_MillisecondsToInterval((PRUint32) time_left);
if(SSL_ForceHandshakeWithTimeout(connssl->handle, timeout) != SECSuccess) {
if(PR_GetError() == PR_WOULD_BLOCK_ERROR)
/* blocking direction is updated by nss_update_connecting_state() */
return CURLE_AGAIN;
else if(conn->data->set.ssl.certverifyresult == SSL_ERROR_BAD_CERT_DOMAIN)
result = CURLE_PEER_FAILED_VERIFICATION;
else if(conn->data->set.ssl.certverifyresult!=0)
result = CURLE_SSL_CACERT;
goto error;
}
result = display_conn_info(conn, connssl->handle);
if(result)
goto error;
if(data->set.str[STRING_SSL_ISSUERCERT]) {
SECStatus ret = SECFailure;
char *nickname = dup_nickname(data, STRING_SSL_ISSUERCERT);
if(nickname) {
/* we support only nicknames in case of STRING_SSL_ISSUERCERT for now */
ret = check_issuer_cert(connssl->handle, nickname);
free(nickname);
}
if(SECFailure == ret) {
infof(data, "SSL certificate issuer check failed\n");
result = CURLE_SSL_ISSUER_ERROR;
goto error;
}
else {
infof(data, "SSL certificate issuer check ok\n");
}
}
result = cmp_peer_pubkey(connssl, data->set.str[STRING_SSL_PINNEDPUBLICKEY]);
if(result)
/* status already printed */
goto error;
return CURLE_OK;
error:
return nss_fail_connect(connssl, data, result);
}
static CURLcode nss_connect_common(struct connectdata *conn, int sockindex,
bool *done)
{
struct ssl_connect_data *connssl = &conn->ssl[sockindex];
struct Curl_easy *data = conn->data;
const bool blocking = (done == NULL);
CURLcode result;
if(connssl->state == ssl_connection_complete)
return CURLE_OK;
if(connssl->connecting_state == ssl_connect_1) {
result = nss_setup_connect(conn, sockindex);
if(result)
/* we do not expect CURLE_AGAIN from nss_setup_connect() */
return result;
if(!blocking) {
/* in non-blocking mode, set NSS non-blocking mode before handshake */
result = nss_set_nonblock(connssl, data);
if(result)
return result;
}
connssl->connecting_state = ssl_connect_2;
}
result = nss_do_connect(conn, sockindex);
switch(result) {
case CURLE_OK:
break;
case CURLE_AGAIN:
if(!blocking)
/* CURLE_AGAIN in non-blocking mode is not an error */
return CURLE_OK;
/* fall through */
default:
return result;
}
if(blocking) {
/* in blocking mode, set NSS non-blocking mode _after_ SSL handshake */
result = nss_set_nonblock(connssl, data);
if(result)
return result;
}
else
/* signal completed SSL handshake */
*done = TRUE;
connssl->state = ssl_connection_complete;
conn->recv[sockindex] = nss_recv;
conn->send[sockindex] = nss_send;
/* ssl_connect_done is never used outside, go back to the initial state */
connssl->connecting_state = ssl_connect_1;
return CURLE_OK;
}
CURLcode Curl_nss_connect(struct connectdata *conn, int sockindex)
{
return nss_connect_common(conn, sockindex, /* blocking */ NULL);
}
CURLcode Curl_nss_connect_nonblocking(struct connectdata *conn,
int sockindex, bool *done)
{
return nss_connect_common(conn, sockindex, done);
}
static ssize_t nss_send(struct connectdata *conn, /* connection data */
int sockindex, /* socketindex */
const void *mem, /* send this data */
size_t len, /* amount to write */
CURLcode *curlcode)
{
ssize_t rc = PR_Send(conn->ssl[sockindex].handle, mem, (int)len, 0,
PR_INTERVAL_NO_WAIT);
if(rc < 0) {
PRInt32 err = PR_GetError();
if(err == PR_WOULD_BLOCK_ERROR)
*curlcode = CURLE_AGAIN;
else {
/* print the error number and error string */
const char *err_name = nss_error_to_name(err);
infof(conn->data, "SSL write: error %d (%s)\n", err, err_name);
/* print a human-readable message describing the error if available */
nss_print_error_message(conn->data, err);
*curlcode = (is_cc_error(err))
? CURLE_SSL_CERTPROBLEM
: CURLE_SEND_ERROR;
}
return -1;
}
return rc; /* number of bytes */
}
static ssize_t nss_recv(struct connectdata * conn, /* connection data */
int num, /* socketindex */
char *buf, /* store read data here */
size_t buffersize, /* max amount to read */
CURLcode *curlcode)
{
ssize_t nread = PR_Recv(conn->ssl[num].handle, buf, (int)buffersize, 0,
PR_INTERVAL_NO_WAIT);
if(nread < 0) {
/* failed SSL read */
PRInt32 err = PR_GetError();
if(err == PR_WOULD_BLOCK_ERROR)
*curlcode = CURLE_AGAIN;
else {
/* print the error number and error string */
const char *err_name = nss_error_to_name(err);
infof(conn->data, "SSL read: errno %d (%s)\n", err, err_name);
/* print a human-readable message describing the error if available */
nss_print_error_message(conn->data, err);
*curlcode = (is_cc_error(err))
? CURLE_SSL_CERTPROBLEM
: CURLE_RECV_ERROR;
}
return -1;
}
return nread;
}
size_t Curl_nss_version(char *buffer, size_t size)
{
return snprintf(buffer, size, "NSS/%s", NSS_VERSION);
}
/* data might be NULL */
int Curl_nss_seed(struct Curl_easy *data)
{
/* make sure that NSS is initialized */
return !!Curl_nss_force_init(data);
}
/* data might be NULL */
int Curl_nss_random(struct Curl_easy *data,
unsigned char *entropy,
size_t length)
{
Curl_nss_seed(data); /* Initiate the seed if not already done */
if(SECSuccess != PK11_GenerateRandom(entropy, curlx_uztosi(length)))
/* signal a failure */
return -1;
return 0;
}
void Curl_nss_md5sum(unsigned char *tmp, /* input */
size_t tmplen,
unsigned char *md5sum, /* output */
size_t md5len)
{
PK11Context *MD5pw = PK11_CreateDigestContext(SEC_OID_MD5);
unsigned int MD5out;
PK11_DigestOp(MD5pw, tmp, curlx_uztoui(tmplen));
PK11_DigestFinal(MD5pw, md5sum, &MD5out, curlx_uztoui(md5len));
PK11_DestroyContext(MD5pw, PR_TRUE);
}
void Curl_nss_sha256sum(const unsigned char *tmp, /* input */
size_t tmplen,
unsigned char *sha256sum, /* output */
size_t sha256len)
{
PK11Context *SHA256pw = PK11_CreateDigestContext(SEC_OID_SHA256);
unsigned int SHA256out;
PK11_DigestOp(SHA256pw, tmp, curlx_uztoui(tmplen));
PK11_DigestFinal(SHA256pw, sha256sum, &SHA256out, curlx_uztoui(sha256len));
PK11_DestroyContext(SHA256pw, PR_TRUE);
}
bool Curl_nss_cert_status_request(void)
{
#ifdef SSL_ENABLE_OCSP_STAPLING
return TRUE;
#else
return FALSE;
#endif
}
bool Curl_nss_false_start(void) {
#if NSSVERNUM >= 0x030f04 /* 3.15.4 */
return TRUE;
#else
return FALSE;
#endif
}
#endif /* USE_NSS */
| ./CrossVul/dataset_final_sorted/CWE-287/c/bad_5264_1 |
crossvul-cpp_data_bad_5268_0 | /*
* IRC - Internet Relay Chat, ircd/m_authenticate.c
* Copyright (C) 2013 Matthew Beeching (Jobe)
* Copyright (C) 1990 Jarkko Oikarinen and
* University of Oulu, Computing Center
*
* See file AUTHORS in IRC package for additional names of
* the programmers.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 1, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id:$
*/
/*
* m_functions execute protocol messages on this server:
*
* cptr is always NON-NULL, pointing to a *LOCAL* client
* structure (with an open socket connected!). This
* identifies the physical socket where the message
* originated (or which caused the m_function to be
* executed--some m_functions may call others...).
*
* sptr is the source of the message, defined by the
* prefix part of the message if present. If not
* or prefix not found, then sptr==cptr.
*
* (!IsServer(cptr)) => (cptr == sptr), because
* prefixes are taken *only* from servers...
*
* (IsServer(cptr))
* (sptr == cptr) => the message didn't
* have the prefix.
*
* (sptr != cptr && IsServer(sptr) means
* the prefix specified servername. (?)
*
* (sptr != cptr && !IsServer(sptr) means
* that message originated from a remote
* user (not local).
*
* combining
*
* (!IsServer(sptr)) means that, sptr can safely
* taken as defining the target structure of the
* message in this server.
*
* *Always* true (if 'parse' and others are working correct):
*
* 1) sptr->from == cptr (note: cptr->from == cptr)
*
* 2) MyConnect(sptr) <=> sptr == cptr (e.g. sptr
* *cannot* be a local connection, unless it's
* actually cptr!). [MyConnect(x) should probably
* be defined as (x == x->from) --msa ]
*
* parc number of variable parameter strings (if zero,
* parv is allowed to be NULL)
*
* parv a NULL terminated list of parameter pointers,
*
* parv[0], sender (prefix string), if not present
* this points to an empty string.
* parv[1]...parv[parc-1]
* pointers to additional parameters
* parv[parc] == NULL, *always*
*
* note: it is guaranteed that parv[0]..parv[parc-1] are all
* non-NULL pointers.
*/
#include "config.h"
#include "client.h"
#include "ircd.h"
#include "ircd_features.h"
#include "ircd_log.h"
#include "ircd_reply.h"
#include "ircd_string.h"
#include "ircd_snprintf.h"
#include "msg.h"
#include "numeric.h"
#include "numnicks.h"
#include "random.h"
#include "send.h"
#include "s_misc.h"
#include "s_user.h"
/* #include <assert.h> -- Now using assert in ircd_log.h */
static void sasl_timeout_callback(struct Event* ev);
int m_authenticate(struct Client* cptr, struct Client* sptr, int parc, char* parv[])
{
struct Client* acptr;
int first = 0;
char realhost[HOSTLEN + 3];
char *hoststr = (cli_sockhost(cptr) ? cli_sockhost(cptr) : cli_sock_ip(cptr));
if (!CapActive(cptr, CAP_SASL))
return 0;
if (parc < 2) /* have enough parameters? */
return need_more_params(cptr, "AUTHENTICATE");
if (strlen(parv[1]) > 400)
return send_reply(cptr, ERR_SASLTOOLONG);
if (IsSASLComplete(cptr))
return send_reply(cptr, ERR_SASLALREADY);
/* Look up the target server */
if (!(acptr = cli_saslagent(cptr))) {
if (strcmp(feature_str(FEAT_SASL_SERVER), "*"))
acptr = find_match_server((char *)feature_str(FEAT_SASL_SERVER));
else
acptr = NULL;
}
if (!acptr && strcmp(feature_str(FEAT_SASL_SERVER), "*"))
return send_reply(cptr, ERR_SASLFAIL, ": service unavailable");
/* If it's to us, do nothing; otherwise, forward the query */
if (acptr && IsMe(acptr))
return 0;
/* Generate an SASL session cookie if not already generated */
if (!cli_saslcookie(cptr)) {
do {
cli_saslcookie(cptr) = ircrandom() & 0x7fffffff;
} while (!cli_saslcookie(cptr));
first = 1;
}
if (strchr(hoststr, ':') != NULL)
ircd_snprintf(0, realhost, sizeof(realhost), "[%s]", hoststr);
else
ircd_strncpy(realhost, hoststr, sizeof(realhost));
if (acptr) {
if (first) {
if (!EmptyString(cli_sslclifp(cptr)))
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u S %s :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr),
parv[1], cli_sslclifp(cptr));
else
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u S :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
if (feature_bool(FEAT_SASL_SENDHOST))
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u H :%s@%s:%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), cli_username(cptr),
realhost, cli_sock_ip(cptr));
} else {
sendcmdto_one(&me, CMD_SASL, acptr, "%C %C!%u.%u C :%s", acptr, &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
}
} else {
if (first) {
if (!EmptyString(cli_sslclifp(cptr)))
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u S %s :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr),
parv[1], cli_sslclifp(cptr));
else
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u S :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
if (feature_bool(FEAT_SASL_SENDHOST))
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u H :%s@%s:%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), cli_username(cptr),
realhost, cli_sock_ip(cptr));
} else {
sendcmdto_serv_butone(&me, CMD_SASL, cptr, "* %C!%u.%u C :%s", &me,
cli_fd(cptr), cli_saslcookie(cptr), parv[1]);
}
}
if (!t_active(&cli_sasltimeout(cptr)))
timer_add(timer_init(&cli_sasltimeout(cptr)), sasl_timeout_callback, (void*) cptr,
TT_RELATIVE, feature_int(FEAT_SASL_TIMEOUT));
return 0;
}
/** Timeout a given SASL auth request.
* @param[in] ev A timer event whose associated data is the expired
* struct AuthRequest.
*/
static void sasl_timeout_callback(struct Event* ev)
{
struct Client *cptr;
assert(0 != ev_timer(ev));
assert(0 != t_data(ev_timer(ev)));
if (ev_type(ev) == ET_EXPIRE) {
cptr = (struct Client*) t_data(ev_timer(ev));
abort_sasl(cptr, 1);
}
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/bad_5268_0 |
crossvul-cpp_data_good_3721_1 | /*
* NETLINK Kernel-user communication protocol.
*
* Authors: Alan Cox <alan@lxorguk.ukuu.org.uk>
* Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
*
* 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.
*
* Tue Jun 26 14:36:48 MEST 2001 Herbert "herp" Rosmanith
* added netlink_proto_exit
* Tue Jan 22 18:32:44 BRST 2002 Arnaldo C. de Melo <acme@conectiva.com.br>
* use nlk_sk, as sk->protinfo is on a diet 8)
* Fri Jul 22 19:51:12 MEST 2005 Harald Welte <laforge@gnumonks.org>
* - inc module use count of module that owns
* the kernel socket in case userspace opens
* socket of same protocol
* - remove all module support, since netlink is
* mandatory if CONFIG_NET=y these days
*/
#include <linux/module.h>
#include <linux/capability.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/stat.h>
#include <linux/socket.h>
#include <linux/un.h>
#include <linux/fcntl.h>
#include <linux/termios.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/rtnetlink.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/notifier.h>
#include <linux/security.h>
#include <linux/jhash.h>
#include <linux/jiffies.h>
#include <linux/random.h>
#include <linux/bitops.h>
#include <linux/mm.h>
#include <linux/types.h>
#include <linux/audit.h>
#include <linux/mutex.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <net/scm.h>
#include <net/netlink.h>
#define NLGRPSZ(x) (ALIGN(x, sizeof(unsigned long) * 8) / 8)
#define NLGRPLONGS(x) (NLGRPSZ(x)/sizeof(unsigned long))
struct netlink_sock {
/* struct sock has to be the first member of netlink_sock */
struct sock sk;
u32 pid;
u32 dst_pid;
u32 dst_group;
u32 flags;
u32 subscriptions;
u32 ngroups;
unsigned long *groups;
unsigned long state;
wait_queue_head_t wait;
struct netlink_callback *cb;
struct mutex *cb_mutex;
struct mutex cb_def_mutex;
void (*netlink_rcv)(struct sk_buff *skb);
void (*netlink_bind)(int group);
struct module *module;
};
struct listeners {
struct rcu_head rcu;
unsigned long masks[0];
};
#define NETLINK_KERNEL_SOCKET 0x1
#define NETLINK_RECV_PKTINFO 0x2
#define NETLINK_BROADCAST_SEND_ERROR 0x4
#define NETLINK_RECV_NO_ENOBUFS 0x8
static inline struct netlink_sock *nlk_sk(struct sock *sk)
{
return container_of(sk, struct netlink_sock, sk);
}
static inline int netlink_is_kernel(struct sock *sk)
{
return nlk_sk(sk)->flags & NETLINK_KERNEL_SOCKET;
}
struct nl_pid_hash {
struct hlist_head *table;
unsigned long rehash_time;
unsigned int mask;
unsigned int shift;
unsigned int entries;
unsigned int max_shift;
u32 rnd;
};
struct netlink_table {
struct nl_pid_hash hash;
struct hlist_head mc_list;
struct listeners __rcu *listeners;
unsigned int nl_nonroot;
unsigned int groups;
struct mutex *cb_mutex;
struct module *module;
void (*bind)(int group);
int registered;
};
static struct netlink_table *nl_table;
static DECLARE_WAIT_QUEUE_HEAD(nl_table_wait);
static int netlink_dump(struct sock *sk);
static DEFINE_RWLOCK(nl_table_lock);
static atomic_t nl_table_users = ATOMIC_INIT(0);
static ATOMIC_NOTIFIER_HEAD(netlink_chain);
static inline u32 netlink_group_mask(u32 group)
{
return group ? 1 << (group - 1) : 0;
}
static inline struct hlist_head *nl_pid_hashfn(struct nl_pid_hash *hash, u32 pid)
{
return &hash->table[jhash_1word(pid, hash->rnd) & hash->mask];
}
static void netlink_destroy_callback(struct netlink_callback *cb)
{
kfree_skb(cb->skb);
kfree(cb);
}
static void netlink_consume_callback(struct netlink_callback *cb)
{
consume_skb(cb->skb);
kfree(cb);
}
static void netlink_sock_destruct(struct sock *sk)
{
struct netlink_sock *nlk = nlk_sk(sk);
if (nlk->cb) {
if (nlk->cb->done)
nlk->cb->done(nlk->cb);
netlink_destroy_callback(nlk->cb);
}
skb_queue_purge(&sk->sk_receive_queue);
if (!sock_flag(sk, SOCK_DEAD)) {
printk(KERN_ERR "Freeing alive netlink socket %p\n", sk);
return;
}
WARN_ON(atomic_read(&sk->sk_rmem_alloc));
WARN_ON(atomic_read(&sk->sk_wmem_alloc));
WARN_ON(nlk_sk(sk)->groups);
}
/* This lock without WQ_FLAG_EXCLUSIVE is good on UP and it is _very_ bad on
* SMP. Look, when several writers sleep and reader wakes them up, all but one
* immediately hit write lock and grab all the cpus. Exclusive sleep solves
* this, _but_ remember, it adds useless work on UP machines.
*/
void netlink_table_grab(void)
__acquires(nl_table_lock)
{
might_sleep();
write_lock_irq(&nl_table_lock);
if (atomic_read(&nl_table_users)) {
DECLARE_WAITQUEUE(wait, current);
add_wait_queue_exclusive(&nl_table_wait, &wait);
for (;;) {
set_current_state(TASK_UNINTERRUPTIBLE);
if (atomic_read(&nl_table_users) == 0)
break;
write_unlock_irq(&nl_table_lock);
schedule();
write_lock_irq(&nl_table_lock);
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(&nl_table_wait, &wait);
}
}
void netlink_table_ungrab(void)
__releases(nl_table_lock)
{
write_unlock_irq(&nl_table_lock);
wake_up(&nl_table_wait);
}
static inline void
netlink_lock_table(void)
{
/* read_lock() synchronizes us to netlink_table_grab */
read_lock(&nl_table_lock);
atomic_inc(&nl_table_users);
read_unlock(&nl_table_lock);
}
static inline void
netlink_unlock_table(void)
{
if (atomic_dec_and_test(&nl_table_users))
wake_up(&nl_table_wait);
}
static struct sock *netlink_lookup(struct net *net, int protocol, u32 pid)
{
struct nl_pid_hash *hash = &nl_table[protocol].hash;
struct hlist_head *head;
struct sock *sk;
struct hlist_node *node;
read_lock(&nl_table_lock);
head = nl_pid_hashfn(hash, pid);
sk_for_each(sk, node, head) {
if (net_eq(sock_net(sk), net) && (nlk_sk(sk)->pid == pid)) {
sock_hold(sk);
goto found;
}
}
sk = NULL;
found:
read_unlock(&nl_table_lock);
return sk;
}
static struct hlist_head *nl_pid_hash_zalloc(size_t size)
{
if (size <= PAGE_SIZE)
return kzalloc(size, GFP_ATOMIC);
else
return (struct hlist_head *)
__get_free_pages(GFP_ATOMIC | __GFP_ZERO,
get_order(size));
}
static void nl_pid_hash_free(struct hlist_head *table, size_t size)
{
if (size <= PAGE_SIZE)
kfree(table);
else
free_pages((unsigned long)table, get_order(size));
}
static int nl_pid_hash_rehash(struct nl_pid_hash *hash, int grow)
{
unsigned int omask, mask, shift;
size_t osize, size;
struct hlist_head *otable, *table;
int i;
omask = mask = hash->mask;
osize = size = (mask + 1) * sizeof(*table);
shift = hash->shift;
if (grow) {
if (++shift > hash->max_shift)
return 0;
mask = mask * 2 + 1;
size *= 2;
}
table = nl_pid_hash_zalloc(size);
if (!table)
return 0;
otable = hash->table;
hash->table = table;
hash->mask = mask;
hash->shift = shift;
get_random_bytes(&hash->rnd, sizeof(hash->rnd));
for (i = 0; i <= omask; i++) {
struct sock *sk;
struct hlist_node *node, *tmp;
sk_for_each_safe(sk, node, tmp, &otable[i])
__sk_add_node(sk, nl_pid_hashfn(hash, nlk_sk(sk)->pid));
}
nl_pid_hash_free(otable, osize);
hash->rehash_time = jiffies + 10 * 60 * HZ;
return 1;
}
static inline int nl_pid_hash_dilute(struct nl_pid_hash *hash, int len)
{
int avg = hash->entries >> hash->shift;
if (unlikely(avg > 1) && nl_pid_hash_rehash(hash, 1))
return 1;
if (unlikely(len > avg) && time_after(jiffies, hash->rehash_time)) {
nl_pid_hash_rehash(hash, 0);
return 1;
}
return 0;
}
static const struct proto_ops netlink_ops;
static void
netlink_update_listeners(struct sock *sk)
{
struct netlink_table *tbl = &nl_table[sk->sk_protocol];
struct hlist_node *node;
unsigned long mask;
unsigned int i;
for (i = 0; i < NLGRPLONGS(tbl->groups); i++) {
mask = 0;
sk_for_each_bound(sk, node, &tbl->mc_list) {
if (i < NLGRPLONGS(nlk_sk(sk)->ngroups))
mask |= nlk_sk(sk)->groups[i];
}
tbl->listeners->masks[i] = mask;
}
/* this function is only called with the netlink table "grabbed", which
* makes sure updates are visible before bind or setsockopt return. */
}
static int netlink_insert(struct sock *sk, struct net *net, u32 pid)
{
struct nl_pid_hash *hash = &nl_table[sk->sk_protocol].hash;
struct hlist_head *head;
int err = -EADDRINUSE;
struct sock *osk;
struct hlist_node *node;
int len;
netlink_table_grab();
head = nl_pid_hashfn(hash, pid);
len = 0;
sk_for_each(osk, node, head) {
if (net_eq(sock_net(osk), net) && (nlk_sk(osk)->pid == pid))
break;
len++;
}
if (node)
goto err;
err = -EBUSY;
if (nlk_sk(sk)->pid)
goto err;
err = -ENOMEM;
if (BITS_PER_LONG > 32 && unlikely(hash->entries >= UINT_MAX))
goto err;
if (len && nl_pid_hash_dilute(hash, len))
head = nl_pid_hashfn(hash, pid);
hash->entries++;
nlk_sk(sk)->pid = pid;
sk_add_node(sk, head);
err = 0;
err:
netlink_table_ungrab();
return err;
}
static void netlink_remove(struct sock *sk)
{
netlink_table_grab();
if (sk_del_node_init(sk))
nl_table[sk->sk_protocol].hash.entries--;
if (nlk_sk(sk)->subscriptions)
__sk_del_bind_node(sk);
netlink_table_ungrab();
}
static struct proto netlink_proto = {
.name = "NETLINK",
.owner = THIS_MODULE,
.obj_size = sizeof(struct netlink_sock),
};
static int __netlink_create(struct net *net, struct socket *sock,
struct mutex *cb_mutex, int protocol)
{
struct sock *sk;
struct netlink_sock *nlk;
sock->ops = &netlink_ops;
sk = sk_alloc(net, PF_NETLINK, GFP_KERNEL, &netlink_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
nlk = nlk_sk(sk);
if (cb_mutex) {
nlk->cb_mutex = cb_mutex;
} else {
nlk->cb_mutex = &nlk->cb_def_mutex;
mutex_init(nlk->cb_mutex);
}
init_waitqueue_head(&nlk->wait);
sk->sk_destruct = netlink_sock_destruct;
sk->sk_protocol = protocol;
return 0;
}
static int netlink_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct module *module = NULL;
struct mutex *cb_mutex;
struct netlink_sock *nlk;
void (*bind)(int group);
int err = 0;
sock->state = SS_UNCONNECTED;
if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
return -ESOCKTNOSUPPORT;
if (protocol < 0 || protocol >= MAX_LINKS)
return -EPROTONOSUPPORT;
netlink_lock_table();
#ifdef CONFIG_MODULES
if (!nl_table[protocol].registered) {
netlink_unlock_table();
request_module("net-pf-%d-proto-%d", PF_NETLINK, protocol);
netlink_lock_table();
}
#endif
if (nl_table[protocol].registered &&
try_module_get(nl_table[protocol].module))
module = nl_table[protocol].module;
else
err = -EPROTONOSUPPORT;
cb_mutex = nl_table[protocol].cb_mutex;
bind = nl_table[protocol].bind;
netlink_unlock_table();
if (err < 0)
goto out;
err = __netlink_create(net, sock, cb_mutex, protocol);
if (err < 0)
goto out_module;
local_bh_disable();
sock_prot_inuse_add(net, &netlink_proto, 1);
local_bh_enable();
nlk = nlk_sk(sock->sk);
nlk->module = module;
nlk->netlink_bind = bind;
out:
return err;
out_module:
module_put(module);
goto out;
}
static int netlink_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct netlink_sock *nlk;
if (!sk)
return 0;
netlink_remove(sk);
sock_orphan(sk);
nlk = nlk_sk(sk);
/*
* OK. Socket is unlinked, any packets that arrive now
* will be purged.
*/
sock->sk = NULL;
wake_up_interruptible_all(&nlk->wait);
skb_queue_purge(&sk->sk_write_queue);
if (nlk->pid) {
struct netlink_notify n = {
.net = sock_net(sk),
.protocol = sk->sk_protocol,
.pid = nlk->pid,
};
atomic_notifier_call_chain(&netlink_chain,
NETLINK_URELEASE, &n);
}
module_put(nlk->module);
netlink_table_grab();
if (netlink_is_kernel(sk)) {
BUG_ON(nl_table[sk->sk_protocol].registered == 0);
if (--nl_table[sk->sk_protocol].registered == 0) {
kfree(nl_table[sk->sk_protocol].listeners);
nl_table[sk->sk_protocol].module = NULL;
nl_table[sk->sk_protocol].registered = 0;
}
} else if (nlk->subscriptions) {
netlink_update_listeners(sk);
}
netlink_table_ungrab();
kfree(nlk->groups);
nlk->groups = NULL;
local_bh_disable();
sock_prot_inuse_add(sock_net(sk), &netlink_proto, -1);
local_bh_enable();
sock_put(sk);
return 0;
}
static int netlink_autobind(struct socket *sock)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct nl_pid_hash *hash = &nl_table[sk->sk_protocol].hash;
struct hlist_head *head;
struct sock *osk;
struct hlist_node *node;
s32 pid = task_tgid_vnr(current);
int err;
static s32 rover = -4097;
retry:
cond_resched();
netlink_table_grab();
head = nl_pid_hashfn(hash, pid);
sk_for_each(osk, node, head) {
if (!net_eq(sock_net(osk), net))
continue;
if (nlk_sk(osk)->pid == pid) {
/* Bind collision, search negative pid values. */
pid = rover--;
if (rover > -4097)
rover = -4097;
netlink_table_ungrab();
goto retry;
}
}
netlink_table_ungrab();
err = netlink_insert(sk, net, pid);
if (err == -EADDRINUSE)
goto retry;
/* If 2 threads race to autobind, that is fine. */
if (err == -EBUSY)
err = 0;
return err;
}
static inline int netlink_capable(const struct socket *sock, unsigned int flag)
{
return (nl_table[sock->sk->sk_protocol].nl_nonroot & flag) ||
capable(CAP_NET_ADMIN);
}
static void
netlink_update_subscriptions(struct sock *sk, unsigned int subscriptions)
{
struct netlink_sock *nlk = nlk_sk(sk);
if (nlk->subscriptions && !subscriptions)
__sk_del_bind_node(sk);
else if (!nlk->subscriptions && subscriptions)
sk_add_bind_node(sk, &nl_table[sk->sk_protocol].mc_list);
nlk->subscriptions = subscriptions;
}
static int netlink_realloc_groups(struct sock *sk)
{
struct netlink_sock *nlk = nlk_sk(sk);
unsigned int groups;
unsigned long *new_groups;
int err = 0;
netlink_table_grab();
groups = nl_table[sk->sk_protocol].groups;
if (!nl_table[sk->sk_protocol].registered) {
err = -ENOENT;
goto out_unlock;
}
if (nlk->ngroups >= groups)
goto out_unlock;
new_groups = krealloc(nlk->groups, NLGRPSZ(groups), GFP_ATOMIC);
if (new_groups == NULL) {
err = -ENOMEM;
goto out_unlock;
}
memset((char *)new_groups + NLGRPSZ(nlk->ngroups), 0,
NLGRPSZ(groups) - NLGRPSZ(nlk->ngroups));
nlk->groups = new_groups;
nlk->ngroups = groups;
out_unlock:
netlink_table_ungrab();
return err;
}
static int netlink_bind(struct socket *sock, struct sockaddr *addr,
int addr_len)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct netlink_sock *nlk = nlk_sk(sk);
struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
int err;
if (nladdr->nl_family != AF_NETLINK)
return -EINVAL;
/* Only superuser is allowed to listen multicasts */
if (nladdr->nl_groups) {
if (!netlink_capable(sock, NL_NONROOT_RECV))
return -EPERM;
err = netlink_realloc_groups(sk);
if (err)
return err;
}
if (nlk->pid) {
if (nladdr->nl_pid != nlk->pid)
return -EINVAL;
} else {
err = nladdr->nl_pid ?
netlink_insert(sk, net, nladdr->nl_pid) :
netlink_autobind(sock);
if (err)
return err;
}
if (!nladdr->nl_groups && (nlk->groups == NULL || !(u32)nlk->groups[0]))
return 0;
netlink_table_grab();
netlink_update_subscriptions(sk, nlk->subscriptions +
hweight32(nladdr->nl_groups) -
hweight32(nlk->groups[0]));
nlk->groups[0] = (nlk->groups[0] & ~0xffffffffUL) | nladdr->nl_groups;
netlink_update_listeners(sk);
netlink_table_ungrab();
if (nlk->netlink_bind && nlk->groups[0]) {
int i;
for (i=0; i<nlk->ngroups; i++) {
if (test_bit(i, nlk->groups))
nlk->netlink_bind(i);
}
}
return 0;
}
static int netlink_connect(struct socket *sock, struct sockaddr *addr,
int alen, int flags)
{
int err = 0;
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
if (alen < sizeof(addr->sa_family))
return -EINVAL;
if (addr->sa_family == AF_UNSPEC) {
sk->sk_state = NETLINK_UNCONNECTED;
nlk->dst_pid = 0;
nlk->dst_group = 0;
return 0;
}
if (addr->sa_family != AF_NETLINK)
return -EINVAL;
/* Only superuser is allowed to send multicasts */
if (nladdr->nl_groups && !netlink_capable(sock, NL_NONROOT_SEND))
return -EPERM;
if (!nlk->pid)
err = netlink_autobind(sock);
if (err == 0) {
sk->sk_state = NETLINK_CONNECTED;
nlk->dst_pid = nladdr->nl_pid;
nlk->dst_group = ffs(nladdr->nl_groups);
}
return err;
}
static int netlink_getname(struct socket *sock, struct sockaddr *addr,
int *addr_len, int peer)
{
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_nl *, nladdr, addr);
nladdr->nl_family = AF_NETLINK;
nladdr->nl_pad = 0;
*addr_len = sizeof(*nladdr);
if (peer) {
nladdr->nl_pid = nlk->dst_pid;
nladdr->nl_groups = netlink_group_mask(nlk->dst_group);
} else {
nladdr->nl_pid = nlk->pid;
nladdr->nl_groups = nlk->groups ? nlk->groups[0] : 0;
}
return 0;
}
static void netlink_overrun(struct sock *sk)
{
struct netlink_sock *nlk = nlk_sk(sk);
if (!(nlk->flags & NETLINK_RECV_NO_ENOBUFS)) {
if (!test_and_set_bit(0, &nlk_sk(sk)->state)) {
sk->sk_err = ENOBUFS;
sk->sk_error_report(sk);
}
}
atomic_inc(&sk->sk_drops);
}
static struct sock *netlink_getsockbypid(struct sock *ssk, u32 pid)
{
struct sock *sock;
struct netlink_sock *nlk;
sock = netlink_lookup(sock_net(ssk), ssk->sk_protocol, pid);
if (!sock)
return ERR_PTR(-ECONNREFUSED);
/* Don't bother queuing skb if kernel socket has no input function */
nlk = nlk_sk(sock);
if (sock->sk_state == NETLINK_CONNECTED &&
nlk->dst_pid != nlk_sk(ssk)->pid) {
sock_put(sock);
return ERR_PTR(-ECONNREFUSED);
}
return sock;
}
struct sock *netlink_getsockbyfilp(struct file *filp)
{
struct inode *inode = filp->f_path.dentry->d_inode;
struct sock *sock;
if (!S_ISSOCK(inode->i_mode))
return ERR_PTR(-ENOTSOCK);
sock = SOCKET_I(inode)->sk;
if (sock->sk_family != AF_NETLINK)
return ERR_PTR(-EINVAL);
sock_hold(sock);
return sock;
}
/*
* Attach a skb to a netlink socket.
* The caller must hold a reference to the destination socket. On error, the
* reference is dropped. The skb is not send to the destination, just all
* all error checks are performed and memory in the queue is reserved.
* Return values:
* < 0: error. skb freed, reference to sock dropped.
* 0: continue
* 1: repeat lookup - reference dropped while waiting for socket memory.
*/
int netlink_attachskb(struct sock *sk, struct sk_buff *skb,
long *timeo, struct sock *ssk)
{
struct netlink_sock *nlk;
nlk = nlk_sk(sk);
if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
test_bit(0, &nlk->state)) {
DECLARE_WAITQUEUE(wait, current);
if (!*timeo) {
if (!ssk || netlink_is_kernel(ssk))
netlink_overrun(sk);
sock_put(sk);
kfree_skb(skb);
return -EAGAIN;
}
__set_current_state(TASK_INTERRUPTIBLE);
add_wait_queue(&nlk->wait, &wait);
if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
test_bit(0, &nlk->state)) &&
!sock_flag(sk, SOCK_DEAD))
*timeo = schedule_timeout(*timeo);
__set_current_state(TASK_RUNNING);
remove_wait_queue(&nlk->wait, &wait);
sock_put(sk);
if (signal_pending(current)) {
kfree_skb(skb);
return sock_intr_errno(*timeo);
}
return 1;
}
skb_set_owner_r(skb, sk);
return 0;
}
static int __netlink_sendskb(struct sock *sk, struct sk_buff *skb)
{
int len = skb->len;
skb_queue_tail(&sk->sk_receive_queue, skb);
sk->sk_data_ready(sk, len);
return len;
}
int netlink_sendskb(struct sock *sk, struct sk_buff *skb)
{
int len = __netlink_sendskb(sk, skb);
sock_put(sk);
return len;
}
void netlink_detachskb(struct sock *sk, struct sk_buff *skb)
{
kfree_skb(skb);
sock_put(sk);
}
static struct sk_buff *netlink_trim(struct sk_buff *skb, gfp_t allocation)
{
int delta;
skb_orphan(skb);
delta = skb->end - skb->tail;
if (delta * 2 < skb->truesize)
return skb;
if (skb_shared(skb)) {
struct sk_buff *nskb = skb_clone(skb, allocation);
if (!nskb)
return skb;
consume_skb(skb);
skb = nskb;
}
if (!pskb_expand_head(skb, 0, -delta, allocation))
skb->truesize -= delta;
return skb;
}
static void netlink_rcv_wake(struct sock *sk)
{
struct netlink_sock *nlk = nlk_sk(sk);
if (skb_queue_empty(&sk->sk_receive_queue))
clear_bit(0, &nlk->state);
if (!test_bit(0, &nlk->state))
wake_up_interruptible(&nlk->wait);
}
static int netlink_unicast_kernel(struct sock *sk, struct sk_buff *skb)
{
int ret;
struct netlink_sock *nlk = nlk_sk(sk);
ret = -ECONNREFUSED;
if (nlk->netlink_rcv != NULL) {
ret = skb->len;
skb_set_owner_r(skb, sk);
nlk->netlink_rcv(skb);
consume_skb(skb);
} else {
kfree_skb(skb);
}
sock_put(sk);
return ret;
}
int netlink_unicast(struct sock *ssk, struct sk_buff *skb,
u32 pid, int nonblock)
{
struct sock *sk;
int err;
long timeo;
skb = netlink_trim(skb, gfp_any());
timeo = sock_sndtimeo(ssk, nonblock);
retry:
sk = netlink_getsockbypid(ssk, pid);
if (IS_ERR(sk)) {
kfree_skb(skb);
return PTR_ERR(sk);
}
if (netlink_is_kernel(sk))
return netlink_unicast_kernel(sk, skb);
if (sk_filter(sk, skb)) {
err = skb->len;
kfree_skb(skb);
sock_put(sk);
return err;
}
err = netlink_attachskb(sk, skb, &timeo, ssk);
if (err == 1)
goto retry;
if (err)
return err;
return netlink_sendskb(sk, skb);
}
EXPORT_SYMBOL(netlink_unicast);
int netlink_has_listeners(struct sock *sk, unsigned int group)
{
int res = 0;
struct listeners *listeners;
BUG_ON(!netlink_is_kernel(sk));
rcu_read_lock();
listeners = rcu_dereference(nl_table[sk->sk_protocol].listeners);
if (group - 1 < nl_table[sk->sk_protocol].groups)
res = test_bit(group - 1, listeners->masks);
rcu_read_unlock();
return res;
}
EXPORT_SYMBOL_GPL(netlink_has_listeners);
static int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
{
struct netlink_sock *nlk = nlk_sk(sk);
if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
!test_bit(0, &nlk->state)) {
skb_set_owner_r(skb, sk);
__netlink_sendskb(sk, skb);
return atomic_read(&sk->sk_rmem_alloc) > (sk->sk_rcvbuf >> 1);
}
return -1;
}
struct netlink_broadcast_data {
struct sock *exclude_sk;
struct net *net;
u32 pid;
u32 group;
int failure;
int delivery_failure;
int congested;
int delivered;
gfp_t allocation;
struct sk_buff *skb, *skb2;
int (*tx_filter)(struct sock *dsk, struct sk_buff *skb, void *data);
void *tx_data;
};
static int do_one_broadcast(struct sock *sk,
struct netlink_broadcast_data *p)
{
struct netlink_sock *nlk = nlk_sk(sk);
int val;
if (p->exclude_sk == sk)
goto out;
if (nlk->pid == p->pid || p->group - 1 >= nlk->ngroups ||
!test_bit(p->group - 1, nlk->groups))
goto out;
if (!net_eq(sock_net(sk), p->net))
goto out;
if (p->failure) {
netlink_overrun(sk);
goto out;
}
sock_hold(sk);
if (p->skb2 == NULL) {
if (skb_shared(p->skb)) {
p->skb2 = skb_clone(p->skb, p->allocation);
} else {
p->skb2 = skb_get(p->skb);
/*
* skb ownership may have been set when
* delivered to a previous socket.
*/
skb_orphan(p->skb2);
}
}
if (p->skb2 == NULL) {
netlink_overrun(sk);
/* Clone failed. Notify ALL listeners. */
p->failure = 1;
if (nlk->flags & NETLINK_BROADCAST_SEND_ERROR)
p->delivery_failure = 1;
} else if (p->tx_filter && p->tx_filter(sk, p->skb2, p->tx_data)) {
kfree_skb(p->skb2);
p->skb2 = NULL;
} else if (sk_filter(sk, p->skb2)) {
kfree_skb(p->skb2);
p->skb2 = NULL;
} else if ((val = netlink_broadcast_deliver(sk, p->skb2)) < 0) {
netlink_overrun(sk);
if (nlk->flags & NETLINK_BROADCAST_SEND_ERROR)
p->delivery_failure = 1;
} else {
p->congested |= val;
p->delivered = 1;
p->skb2 = NULL;
}
sock_put(sk);
out:
return 0;
}
int netlink_broadcast_filtered(struct sock *ssk, struct sk_buff *skb, u32 pid,
u32 group, gfp_t allocation,
int (*filter)(struct sock *dsk, struct sk_buff *skb, void *data),
void *filter_data)
{
struct net *net = sock_net(ssk);
struct netlink_broadcast_data info;
struct hlist_node *node;
struct sock *sk;
skb = netlink_trim(skb, allocation);
info.exclude_sk = ssk;
info.net = net;
info.pid = pid;
info.group = group;
info.failure = 0;
info.delivery_failure = 0;
info.congested = 0;
info.delivered = 0;
info.allocation = allocation;
info.skb = skb;
info.skb2 = NULL;
info.tx_filter = filter;
info.tx_data = filter_data;
/* While we sleep in clone, do not allow to change socket list */
netlink_lock_table();
sk_for_each_bound(sk, node, &nl_table[ssk->sk_protocol].mc_list)
do_one_broadcast(sk, &info);
consume_skb(skb);
netlink_unlock_table();
if (info.delivery_failure) {
kfree_skb(info.skb2);
return -ENOBUFS;
}
consume_skb(info.skb2);
if (info.delivered) {
if (info.congested && (allocation & __GFP_WAIT))
yield();
return 0;
}
return -ESRCH;
}
EXPORT_SYMBOL(netlink_broadcast_filtered);
int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 pid,
u32 group, gfp_t allocation)
{
return netlink_broadcast_filtered(ssk, skb, pid, group, allocation,
NULL, NULL);
}
EXPORT_SYMBOL(netlink_broadcast);
struct netlink_set_err_data {
struct sock *exclude_sk;
u32 pid;
u32 group;
int code;
};
static int do_one_set_err(struct sock *sk, struct netlink_set_err_data *p)
{
struct netlink_sock *nlk = nlk_sk(sk);
int ret = 0;
if (sk == p->exclude_sk)
goto out;
if (!net_eq(sock_net(sk), sock_net(p->exclude_sk)))
goto out;
if (nlk->pid == p->pid || p->group - 1 >= nlk->ngroups ||
!test_bit(p->group - 1, nlk->groups))
goto out;
if (p->code == ENOBUFS && nlk->flags & NETLINK_RECV_NO_ENOBUFS) {
ret = 1;
goto out;
}
sk->sk_err = p->code;
sk->sk_error_report(sk);
out:
return ret;
}
/**
* netlink_set_err - report error to broadcast listeners
* @ssk: the kernel netlink socket, as returned by netlink_kernel_create()
* @pid: the PID of a process that we want to skip (if any)
* @groups: the broadcast group that will notice the error
* @code: error code, must be negative (as usual in kernelspace)
*
* This function returns the number of broadcast listeners that have set the
* NETLINK_RECV_NO_ENOBUFS socket option.
*/
int netlink_set_err(struct sock *ssk, u32 pid, u32 group, int code)
{
struct netlink_set_err_data info;
struct hlist_node *node;
struct sock *sk;
int ret = 0;
info.exclude_sk = ssk;
info.pid = pid;
info.group = group;
/* sk->sk_err wants a positive error value */
info.code = -code;
read_lock(&nl_table_lock);
sk_for_each_bound(sk, node, &nl_table[ssk->sk_protocol].mc_list)
ret += do_one_set_err(sk, &info);
read_unlock(&nl_table_lock);
return ret;
}
EXPORT_SYMBOL(netlink_set_err);
/* must be called with netlink table grabbed */
static void netlink_update_socket_mc(struct netlink_sock *nlk,
unsigned int group,
int is_new)
{
int old, new = !!is_new, subscriptions;
old = test_bit(group - 1, nlk->groups);
subscriptions = nlk->subscriptions - old + new;
if (new)
__set_bit(group - 1, nlk->groups);
else
__clear_bit(group - 1, nlk->groups);
netlink_update_subscriptions(&nlk->sk, subscriptions);
netlink_update_listeners(&nlk->sk);
}
static int netlink_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
unsigned int val = 0;
int err;
if (level != SOL_NETLINK)
return -ENOPROTOOPT;
if (optlen >= sizeof(int) &&
get_user(val, (unsigned int __user *)optval))
return -EFAULT;
switch (optname) {
case NETLINK_PKTINFO:
if (val)
nlk->flags |= NETLINK_RECV_PKTINFO;
else
nlk->flags &= ~NETLINK_RECV_PKTINFO;
err = 0;
break;
case NETLINK_ADD_MEMBERSHIP:
case NETLINK_DROP_MEMBERSHIP: {
if (!netlink_capable(sock, NL_NONROOT_RECV))
return -EPERM;
err = netlink_realloc_groups(sk);
if (err)
return err;
if (!val || val - 1 >= nlk->ngroups)
return -EINVAL;
netlink_table_grab();
netlink_update_socket_mc(nlk, val,
optname == NETLINK_ADD_MEMBERSHIP);
netlink_table_ungrab();
if (nlk->netlink_bind)
nlk->netlink_bind(val);
err = 0;
break;
}
case NETLINK_BROADCAST_ERROR:
if (val)
nlk->flags |= NETLINK_BROADCAST_SEND_ERROR;
else
nlk->flags &= ~NETLINK_BROADCAST_SEND_ERROR;
err = 0;
break;
case NETLINK_NO_ENOBUFS:
if (val) {
nlk->flags |= NETLINK_RECV_NO_ENOBUFS;
clear_bit(0, &nlk->state);
wake_up_interruptible(&nlk->wait);
} else {
nlk->flags &= ~NETLINK_RECV_NO_ENOBUFS;
}
err = 0;
break;
default:
err = -ENOPROTOOPT;
}
return err;
}
static int netlink_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
int len, val, err;
if (level != SOL_NETLINK)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
switch (optname) {
case NETLINK_PKTINFO:
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = nlk->flags & NETLINK_RECV_PKTINFO ? 1 : 0;
if (put_user(len, optlen) ||
put_user(val, optval))
return -EFAULT;
err = 0;
break;
case NETLINK_BROADCAST_ERROR:
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = nlk->flags & NETLINK_BROADCAST_SEND_ERROR ? 1 : 0;
if (put_user(len, optlen) ||
put_user(val, optval))
return -EFAULT;
err = 0;
break;
case NETLINK_NO_ENOBUFS:
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = nlk->flags & NETLINK_RECV_NO_ENOBUFS ? 1 : 0;
if (put_user(len, optlen) ||
put_user(val, optval))
return -EFAULT;
err = 0;
break;
default:
err = -ENOPROTOOPT;
}
return err;
}
static void netlink_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb)
{
struct nl_pktinfo info;
info.group = NETLINK_CB(skb).dst_group;
put_cmsg(msg, SOL_NETLINK, NETLINK_PKTINFO, sizeof(info), &info);
}
static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
struct sockaddr_nl *addr = msg->msg_name;
u32 dst_pid;
u32 dst_group;
struct sk_buff *skb;
int err;
struct scm_cookie scm;
if (msg->msg_flags&MSG_OOB)
return -EOPNOTSUPP;
if (NULL == siocb->scm)
siocb->scm = &scm;
err = scm_send(sock, msg, siocb->scm, true);
if (err < 0)
return err;
if (msg->msg_namelen) {
err = -EINVAL;
if (addr->nl_family != AF_NETLINK)
goto out;
dst_pid = addr->nl_pid;
dst_group = ffs(addr->nl_groups);
err = -EPERM;
if (dst_group && !netlink_capable(sock, NL_NONROOT_SEND))
goto out;
} else {
dst_pid = nlk->dst_pid;
dst_group = nlk->dst_group;
}
if (!nlk->pid) {
err = netlink_autobind(sock);
if (err)
goto out;
}
err = -EMSGSIZE;
if (len > sk->sk_sndbuf - 32)
goto out;
err = -ENOBUFS;
skb = alloc_skb(len, GFP_KERNEL);
if (skb == NULL)
goto out;
NETLINK_CB(skb).pid = nlk->pid;
NETLINK_CB(skb).dst_group = dst_group;
memcpy(NETLINK_CREDS(skb), &siocb->scm->creds, sizeof(struct ucred));
err = -EFAULT;
if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {
kfree_skb(skb);
goto out;
}
err = security_netlink_send(sk, skb);
if (err) {
kfree_skb(skb);
goto out;
}
if (dst_group) {
atomic_inc(&skb->users);
netlink_broadcast(sk, skb, dst_pid, dst_group, GFP_KERNEL);
}
err = netlink_unicast(sk, skb, dst_pid, msg->msg_flags&MSG_DONTWAIT);
out:
scm_destroy(siocb->scm);
return err;
}
static int netlink_recvmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len,
int flags)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct scm_cookie scm;
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
int noblock = flags&MSG_DONTWAIT;
size_t copied;
struct sk_buff *skb, *data_skb;
int err, ret;
if (flags&MSG_OOB)
return -EOPNOTSUPP;
copied = 0;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (skb == NULL)
goto out;
data_skb = skb;
#ifdef CONFIG_COMPAT_NETLINK_MESSAGES
if (unlikely(skb_shinfo(skb)->frag_list)) {
/*
* If this skb has a frag_list, then here that means that we
* will have to use the frag_list skb's data for compat tasks
* and the regular skb's data for normal (non-compat) tasks.
*
* If we need to send the compat skb, assign it to the
* 'data_skb' variable so that it will be used below for data
* copying. We keep 'skb' for everything else, including
* freeing both later.
*/
if (flags & MSG_CMSG_COMPAT)
data_skb = skb_shinfo(skb)->frag_list;
}
#endif
msg->msg_namelen = 0;
copied = data_skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
skb_reset_transport_header(data_skb);
err = skb_copy_datagram_iovec(data_skb, 0, msg->msg_iov, copied);
if (msg->msg_name) {
struct sockaddr_nl *addr = (struct sockaddr_nl *)msg->msg_name;
addr->nl_family = AF_NETLINK;
addr->nl_pad = 0;
addr->nl_pid = NETLINK_CB(skb).pid;
addr->nl_groups = netlink_group_mask(NETLINK_CB(skb).dst_group);
msg->msg_namelen = sizeof(*addr);
}
if (nlk->flags & NETLINK_RECV_PKTINFO)
netlink_cmsg_recv_pktinfo(msg, skb);
if (NULL == siocb->scm) {
memset(&scm, 0, sizeof(scm));
siocb->scm = &scm;
}
siocb->scm->creds = *NETLINK_CREDS(skb);
if (flags & MSG_TRUNC)
copied = data_skb->len;
skb_free_datagram(sk, skb);
if (nlk->cb && atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) {
ret = netlink_dump(sk);
if (ret) {
sk->sk_err = ret;
sk->sk_error_report(sk);
}
}
scm_recv(sock, msg, siocb->scm, flags);
out:
netlink_rcv_wake(sk);
return err ? : copied;
}
static void netlink_data_ready(struct sock *sk, int len)
{
BUG();
}
/*
* We export these functions to other modules. They provide a
* complete set of kernel non-blocking support for message
* queueing.
*/
struct sock *
netlink_kernel_create(struct net *net, int unit,
struct module *module,
struct netlink_kernel_cfg *cfg)
{
struct socket *sock;
struct sock *sk;
struct netlink_sock *nlk;
struct listeners *listeners = NULL;
struct mutex *cb_mutex = cfg ? cfg->cb_mutex : NULL;
unsigned int groups;
BUG_ON(!nl_table);
if (unit < 0 || unit >= MAX_LINKS)
return NULL;
if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
return NULL;
/*
* We have to just have a reference on the net from sk, but don't
* get_net it. Besides, we cannot get and then put the net here.
* So we create one inside init_net and the move it to net.
*/
if (__netlink_create(&init_net, sock, cb_mutex, unit) < 0)
goto out_sock_release_nosk;
sk = sock->sk;
sk_change_net(sk, net);
if (!cfg || cfg->groups < 32)
groups = 32;
else
groups = cfg->groups;
listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
if (!listeners)
goto out_sock_release;
sk->sk_data_ready = netlink_data_ready;
if (cfg && cfg->input)
nlk_sk(sk)->netlink_rcv = cfg->input;
if (netlink_insert(sk, net, 0))
goto out_sock_release;
nlk = nlk_sk(sk);
nlk->flags |= NETLINK_KERNEL_SOCKET;
netlink_table_grab();
if (!nl_table[unit].registered) {
nl_table[unit].groups = groups;
rcu_assign_pointer(nl_table[unit].listeners, listeners);
nl_table[unit].cb_mutex = cb_mutex;
nl_table[unit].module = module;
nl_table[unit].bind = cfg ? cfg->bind : NULL;
nl_table[unit].registered = 1;
} else {
kfree(listeners);
nl_table[unit].registered++;
}
netlink_table_ungrab();
return sk;
out_sock_release:
kfree(listeners);
netlink_kernel_release(sk);
return NULL;
out_sock_release_nosk:
sock_release(sock);
return NULL;
}
EXPORT_SYMBOL(netlink_kernel_create);
void
netlink_kernel_release(struct sock *sk)
{
sk_release_kernel(sk);
}
EXPORT_SYMBOL(netlink_kernel_release);
int __netlink_change_ngroups(struct sock *sk, unsigned int groups)
{
struct listeners *new, *old;
struct netlink_table *tbl = &nl_table[sk->sk_protocol];
if (groups < 32)
groups = 32;
if (NLGRPSZ(tbl->groups) < NLGRPSZ(groups)) {
new = kzalloc(sizeof(*new) + NLGRPSZ(groups), GFP_ATOMIC);
if (!new)
return -ENOMEM;
old = rcu_dereference_protected(tbl->listeners, 1);
memcpy(new->masks, old->masks, NLGRPSZ(tbl->groups));
rcu_assign_pointer(tbl->listeners, new);
kfree_rcu(old, rcu);
}
tbl->groups = groups;
return 0;
}
/**
* netlink_change_ngroups - change number of multicast groups
*
* This changes the number of multicast groups that are available
* on a certain netlink family. Note that it is not possible to
* change the number of groups to below 32. Also note that it does
* not implicitly call netlink_clear_multicast_users() when the
* number of groups is reduced.
*
* @sk: The kernel netlink socket, as returned by netlink_kernel_create().
* @groups: The new number of groups.
*/
int netlink_change_ngroups(struct sock *sk, unsigned int groups)
{
int err;
netlink_table_grab();
err = __netlink_change_ngroups(sk, groups);
netlink_table_ungrab();
return err;
}
void __netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
{
struct sock *sk;
struct hlist_node *node;
struct netlink_table *tbl = &nl_table[ksk->sk_protocol];
sk_for_each_bound(sk, node, &tbl->mc_list)
netlink_update_socket_mc(nlk_sk(sk), group, 0);
}
/**
* netlink_clear_multicast_users - kick off multicast listeners
*
* This function removes all listeners from the given group.
* @ksk: The kernel netlink socket, as returned by
* netlink_kernel_create().
* @group: The multicast group to clear.
*/
void netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
{
netlink_table_grab();
__netlink_clear_multicast_users(ksk, group);
netlink_table_ungrab();
}
void netlink_set_nonroot(int protocol, unsigned int flags)
{
if ((unsigned int)protocol < MAX_LINKS)
nl_table[protocol].nl_nonroot = flags;
}
EXPORT_SYMBOL(netlink_set_nonroot);
struct nlmsghdr *
__nlmsg_put(struct sk_buff *skb, u32 pid, u32 seq, int type, int len, int flags)
{
struct nlmsghdr *nlh;
int size = NLMSG_LENGTH(len);
nlh = (struct nlmsghdr*)skb_put(skb, NLMSG_ALIGN(size));
nlh->nlmsg_type = type;
nlh->nlmsg_len = size;
nlh->nlmsg_flags = flags;
nlh->nlmsg_pid = pid;
nlh->nlmsg_seq = seq;
if (!__builtin_constant_p(size) || NLMSG_ALIGN(size) - size != 0)
memset(NLMSG_DATA(nlh) + len, 0, NLMSG_ALIGN(size) - size);
return nlh;
}
EXPORT_SYMBOL(__nlmsg_put);
/*
* It looks a bit ugly.
* It would be better to create kernel thread.
*/
static int netlink_dump(struct sock *sk)
{
struct netlink_sock *nlk = nlk_sk(sk);
struct netlink_callback *cb;
struct sk_buff *skb = NULL;
struct nlmsghdr *nlh;
int len, err = -ENOBUFS;
int alloc_size;
mutex_lock(nlk->cb_mutex);
cb = nlk->cb;
if (cb == NULL) {
err = -EINVAL;
goto errout_skb;
}
alloc_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE);
skb = sock_rmalloc(sk, alloc_size, 0, GFP_KERNEL);
if (!skb)
goto errout_skb;
len = cb->dump(skb, cb);
if (len > 0) {
mutex_unlock(nlk->cb_mutex);
if (sk_filter(sk, skb))
kfree_skb(skb);
else
__netlink_sendskb(sk, skb);
return 0;
}
nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE, sizeof(len), NLM_F_MULTI);
if (!nlh)
goto errout_skb;
nl_dump_check_consistent(cb, nlh);
memcpy(nlmsg_data(nlh), &len, sizeof(len));
if (sk_filter(sk, skb))
kfree_skb(skb);
else
__netlink_sendskb(sk, skb);
if (cb->done)
cb->done(cb);
nlk->cb = NULL;
mutex_unlock(nlk->cb_mutex);
netlink_consume_callback(cb);
return 0;
errout_skb:
mutex_unlock(nlk->cb_mutex);
kfree_skb(skb);
return err;
}
int netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
const struct nlmsghdr *nlh,
struct netlink_dump_control *control)
{
struct netlink_callback *cb;
struct sock *sk;
struct netlink_sock *nlk;
int ret;
cb = kzalloc(sizeof(*cb), GFP_KERNEL);
if (cb == NULL)
return -ENOBUFS;
cb->dump = control->dump;
cb->done = control->done;
cb->nlh = nlh;
cb->data = control->data;
cb->min_dump_alloc = control->min_dump_alloc;
atomic_inc(&skb->users);
cb->skb = skb;
sk = netlink_lookup(sock_net(ssk), ssk->sk_protocol, NETLINK_CB(skb).pid);
if (sk == NULL) {
netlink_destroy_callback(cb);
return -ECONNREFUSED;
}
nlk = nlk_sk(sk);
/* A dump is in progress... */
mutex_lock(nlk->cb_mutex);
if (nlk->cb) {
mutex_unlock(nlk->cb_mutex);
netlink_destroy_callback(cb);
sock_put(sk);
return -EBUSY;
}
nlk->cb = cb;
mutex_unlock(nlk->cb_mutex);
ret = netlink_dump(sk);
sock_put(sk);
if (ret)
return ret;
/* We successfully started a dump, by returning -EINTR we
* signal not to send ACK even if it was requested.
*/
return -EINTR;
}
EXPORT_SYMBOL(netlink_dump_start);
void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err)
{
struct sk_buff *skb;
struct nlmsghdr *rep;
struct nlmsgerr *errmsg;
size_t payload = sizeof(*errmsg);
/* error messages get the original request appened */
if (err)
payload += nlmsg_len(nlh);
skb = nlmsg_new(payload, GFP_KERNEL);
if (!skb) {
struct sock *sk;
sk = netlink_lookup(sock_net(in_skb->sk),
in_skb->sk->sk_protocol,
NETLINK_CB(in_skb).pid);
if (sk) {
sk->sk_err = ENOBUFS;
sk->sk_error_report(sk);
sock_put(sk);
}
return;
}
rep = __nlmsg_put(skb, NETLINK_CB(in_skb).pid, nlh->nlmsg_seq,
NLMSG_ERROR, payload, 0);
errmsg = nlmsg_data(rep);
errmsg->error = err;
memcpy(&errmsg->msg, nlh, err ? nlh->nlmsg_len : sizeof(*nlh));
netlink_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).pid, MSG_DONTWAIT);
}
EXPORT_SYMBOL(netlink_ack);
int netlink_rcv_skb(struct sk_buff *skb, int (*cb)(struct sk_buff *,
struct nlmsghdr *))
{
struct nlmsghdr *nlh;
int err;
while (skb->len >= nlmsg_total_size(0)) {
int msglen;
nlh = nlmsg_hdr(skb);
err = 0;
if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len)
return 0;
/* Only requests are handled by the kernel */
if (!(nlh->nlmsg_flags & NLM_F_REQUEST))
goto ack;
/* Skip control messages */
if (nlh->nlmsg_type < NLMSG_MIN_TYPE)
goto ack;
err = cb(skb, nlh);
if (err == -EINTR)
goto skip;
ack:
if (nlh->nlmsg_flags & NLM_F_ACK || err)
netlink_ack(skb, nlh, err);
skip:
msglen = NLMSG_ALIGN(nlh->nlmsg_len);
if (msglen > skb->len)
msglen = skb->len;
skb_pull(skb, msglen);
}
return 0;
}
EXPORT_SYMBOL(netlink_rcv_skb);
/**
* nlmsg_notify - send a notification netlink message
* @sk: netlink socket to use
* @skb: notification message
* @pid: destination netlink pid for reports or 0
* @group: destination multicast group or 0
* @report: 1 to report back, 0 to disable
* @flags: allocation flags
*/
int nlmsg_notify(struct sock *sk, struct sk_buff *skb, u32 pid,
unsigned int group, int report, gfp_t flags)
{
int err = 0;
if (group) {
int exclude_pid = 0;
if (report) {
atomic_inc(&skb->users);
exclude_pid = pid;
}
/* errors reported via destination sk->sk_err, but propagate
* delivery errors if NETLINK_BROADCAST_ERROR flag is set */
err = nlmsg_multicast(sk, skb, exclude_pid, group, flags);
}
if (report) {
int err2;
err2 = nlmsg_unicast(sk, skb, pid);
if (!err || err == -ESRCH)
err = err2;
}
return err;
}
EXPORT_SYMBOL(nlmsg_notify);
#ifdef CONFIG_PROC_FS
struct nl_seq_iter {
struct seq_net_private p;
int link;
int hash_idx;
};
static struct sock *netlink_seq_socket_idx(struct seq_file *seq, loff_t pos)
{
struct nl_seq_iter *iter = seq->private;
int i, j;
struct sock *s;
struct hlist_node *node;
loff_t off = 0;
for (i = 0; i < MAX_LINKS; i++) {
struct nl_pid_hash *hash = &nl_table[i].hash;
for (j = 0; j <= hash->mask; j++) {
sk_for_each(s, node, &hash->table[j]) {
if (sock_net(s) != seq_file_net(seq))
continue;
if (off == pos) {
iter->link = i;
iter->hash_idx = j;
return s;
}
++off;
}
}
}
return NULL;
}
static void *netlink_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(nl_table_lock)
{
read_lock(&nl_table_lock);
return *pos ? netlink_seq_socket_idx(seq, *pos - 1) : SEQ_START_TOKEN;
}
static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct sock *s;
struct nl_seq_iter *iter;
int i, j;
++*pos;
if (v == SEQ_START_TOKEN)
return netlink_seq_socket_idx(seq, 0);
iter = seq->private;
s = v;
do {
s = sk_next(s);
} while (s && sock_net(s) != seq_file_net(seq));
if (s)
return s;
i = iter->link;
j = iter->hash_idx + 1;
do {
struct nl_pid_hash *hash = &nl_table[i].hash;
for (; j <= hash->mask; j++) {
s = sk_head(&hash->table[j]);
while (s && sock_net(s) != seq_file_net(seq))
s = sk_next(s);
if (s) {
iter->link = i;
iter->hash_idx = j;
return s;
}
}
j = 0;
} while (++i < MAX_LINKS);
return NULL;
}
static void netlink_seq_stop(struct seq_file *seq, void *v)
__releases(nl_table_lock)
{
read_unlock(&nl_table_lock);
}
static int netlink_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN) {
seq_puts(seq,
"sk Eth Pid Groups "
"Rmem Wmem Dump Locks Drops Inode\n");
} else {
struct sock *s = v;
struct netlink_sock *nlk = nlk_sk(s);
seq_printf(seq, "%pK %-3d %-6d %08x %-8d %-8d %pK %-8d %-8d %-8lu\n",
s,
s->sk_protocol,
nlk->pid,
nlk->groups ? (u32)nlk->groups[0] : 0,
sk_rmem_alloc_get(s),
sk_wmem_alloc_get(s),
nlk->cb,
atomic_read(&s->sk_refcnt),
atomic_read(&s->sk_drops),
sock_i_ino(s)
);
}
return 0;
}
static const struct seq_operations netlink_seq_ops = {
.start = netlink_seq_start,
.next = netlink_seq_next,
.stop = netlink_seq_stop,
.show = netlink_seq_show,
};
static int netlink_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &netlink_seq_ops,
sizeof(struct nl_seq_iter));
}
static const struct file_operations netlink_seq_fops = {
.owner = THIS_MODULE,
.open = netlink_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
int netlink_register_notifier(struct notifier_block *nb)
{
return atomic_notifier_chain_register(&netlink_chain, nb);
}
EXPORT_SYMBOL(netlink_register_notifier);
int netlink_unregister_notifier(struct notifier_block *nb)
{
return atomic_notifier_chain_unregister(&netlink_chain, nb);
}
EXPORT_SYMBOL(netlink_unregister_notifier);
static const struct proto_ops netlink_ops = {
.family = PF_NETLINK,
.owner = THIS_MODULE,
.release = netlink_release,
.bind = netlink_bind,
.connect = netlink_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = netlink_getname,
.poll = datagram_poll,
.ioctl = sock_no_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = netlink_setsockopt,
.getsockopt = netlink_getsockopt,
.sendmsg = netlink_sendmsg,
.recvmsg = netlink_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static const struct net_proto_family netlink_family_ops = {
.family = PF_NETLINK,
.create = netlink_create,
.owner = THIS_MODULE, /* for consistency 8) */
};
static int __net_init netlink_net_init(struct net *net)
{
#ifdef CONFIG_PROC_FS
if (!proc_net_fops_create(net, "netlink", 0, &netlink_seq_fops))
return -ENOMEM;
#endif
return 0;
}
static void __net_exit netlink_net_exit(struct net *net)
{
#ifdef CONFIG_PROC_FS
proc_net_remove(net, "netlink");
#endif
}
static void __init netlink_add_usersock_entry(void)
{
struct listeners *listeners;
int groups = 32;
listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
if (!listeners)
panic("netlink_add_usersock_entry: Cannot allocate listeners\n");
netlink_table_grab();
nl_table[NETLINK_USERSOCK].groups = groups;
rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners);
nl_table[NETLINK_USERSOCK].module = THIS_MODULE;
nl_table[NETLINK_USERSOCK].registered = 1;
netlink_table_ungrab();
}
static struct pernet_operations __net_initdata netlink_net_ops = {
.init = netlink_net_init,
.exit = netlink_net_exit,
};
static int __init netlink_proto_init(void)
{
struct sk_buff *dummy_skb;
int i;
unsigned long limit;
unsigned int order;
int err = proto_register(&netlink_proto, 0);
if (err != 0)
goto out;
BUILD_BUG_ON(sizeof(struct netlink_skb_parms) > sizeof(dummy_skb->cb));
nl_table = kcalloc(MAX_LINKS, sizeof(*nl_table), GFP_KERNEL);
if (!nl_table)
goto panic;
if (totalram_pages >= (128 * 1024))
limit = totalram_pages >> (21 - PAGE_SHIFT);
else
limit = totalram_pages >> (23 - PAGE_SHIFT);
order = get_bitmask_order(limit) - 1 + PAGE_SHIFT;
limit = (1UL << order) / sizeof(struct hlist_head);
order = get_bitmask_order(min(limit, (unsigned long)UINT_MAX)) - 1;
for (i = 0; i < MAX_LINKS; i++) {
struct nl_pid_hash *hash = &nl_table[i].hash;
hash->table = nl_pid_hash_zalloc(1 * sizeof(*hash->table));
if (!hash->table) {
while (i-- > 0)
nl_pid_hash_free(nl_table[i].hash.table,
1 * sizeof(*hash->table));
kfree(nl_table);
goto panic;
}
hash->max_shift = order;
hash->shift = 0;
hash->mask = 0;
hash->rehash_time = jiffies;
}
netlink_add_usersock_entry();
sock_register(&netlink_family_ops);
register_pernet_subsys(&netlink_net_ops);
/* The netlink device handler may be needed early. */
rtnetlink_init();
out:
return err;
panic:
panic("netlink_init: Cannot allocate nl_table\n");
}
core_initcall(netlink_proto_init);
| ./CrossVul/dataset_final_sorted/CWE-287/c/good_3721_1 |
crossvul-cpp_data_bad_3721_1 | /*
* NETLINK Kernel-user communication protocol.
*
* Authors: Alan Cox <alan@lxorguk.ukuu.org.uk>
* Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
*
* 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.
*
* Tue Jun 26 14:36:48 MEST 2001 Herbert "herp" Rosmanith
* added netlink_proto_exit
* Tue Jan 22 18:32:44 BRST 2002 Arnaldo C. de Melo <acme@conectiva.com.br>
* use nlk_sk, as sk->protinfo is on a diet 8)
* Fri Jul 22 19:51:12 MEST 2005 Harald Welte <laforge@gnumonks.org>
* - inc module use count of module that owns
* the kernel socket in case userspace opens
* socket of same protocol
* - remove all module support, since netlink is
* mandatory if CONFIG_NET=y these days
*/
#include <linux/module.h>
#include <linux/capability.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/stat.h>
#include <linux/socket.h>
#include <linux/un.h>
#include <linux/fcntl.h>
#include <linux/termios.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/rtnetlink.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/notifier.h>
#include <linux/security.h>
#include <linux/jhash.h>
#include <linux/jiffies.h>
#include <linux/random.h>
#include <linux/bitops.h>
#include <linux/mm.h>
#include <linux/types.h>
#include <linux/audit.h>
#include <linux/mutex.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <net/scm.h>
#include <net/netlink.h>
#define NLGRPSZ(x) (ALIGN(x, sizeof(unsigned long) * 8) / 8)
#define NLGRPLONGS(x) (NLGRPSZ(x)/sizeof(unsigned long))
struct netlink_sock {
/* struct sock has to be the first member of netlink_sock */
struct sock sk;
u32 pid;
u32 dst_pid;
u32 dst_group;
u32 flags;
u32 subscriptions;
u32 ngroups;
unsigned long *groups;
unsigned long state;
wait_queue_head_t wait;
struct netlink_callback *cb;
struct mutex *cb_mutex;
struct mutex cb_def_mutex;
void (*netlink_rcv)(struct sk_buff *skb);
void (*netlink_bind)(int group);
struct module *module;
};
struct listeners {
struct rcu_head rcu;
unsigned long masks[0];
};
#define NETLINK_KERNEL_SOCKET 0x1
#define NETLINK_RECV_PKTINFO 0x2
#define NETLINK_BROADCAST_SEND_ERROR 0x4
#define NETLINK_RECV_NO_ENOBUFS 0x8
static inline struct netlink_sock *nlk_sk(struct sock *sk)
{
return container_of(sk, struct netlink_sock, sk);
}
static inline int netlink_is_kernel(struct sock *sk)
{
return nlk_sk(sk)->flags & NETLINK_KERNEL_SOCKET;
}
struct nl_pid_hash {
struct hlist_head *table;
unsigned long rehash_time;
unsigned int mask;
unsigned int shift;
unsigned int entries;
unsigned int max_shift;
u32 rnd;
};
struct netlink_table {
struct nl_pid_hash hash;
struct hlist_head mc_list;
struct listeners __rcu *listeners;
unsigned int nl_nonroot;
unsigned int groups;
struct mutex *cb_mutex;
struct module *module;
void (*bind)(int group);
int registered;
};
static struct netlink_table *nl_table;
static DECLARE_WAIT_QUEUE_HEAD(nl_table_wait);
static int netlink_dump(struct sock *sk);
static DEFINE_RWLOCK(nl_table_lock);
static atomic_t nl_table_users = ATOMIC_INIT(0);
static ATOMIC_NOTIFIER_HEAD(netlink_chain);
static inline u32 netlink_group_mask(u32 group)
{
return group ? 1 << (group - 1) : 0;
}
static inline struct hlist_head *nl_pid_hashfn(struct nl_pid_hash *hash, u32 pid)
{
return &hash->table[jhash_1word(pid, hash->rnd) & hash->mask];
}
static void netlink_destroy_callback(struct netlink_callback *cb)
{
kfree_skb(cb->skb);
kfree(cb);
}
static void netlink_consume_callback(struct netlink_callback *cb)
{
consume_skb(cb->skb);
kfree(cb);
}
static void netlink_sock_destruct(struct sock *sk)
{
struct netlink_sock *nlk = nlk_sk(sk);
if (nlk->cb) {
if (nlk->cb->done)
nlk->cb->done(nlk->cb);
netlink_destroy_callback(nlk->cb);
}
skb_queue_purge(&sk->sk_receive_queue);
if (!sock_flag(sk, SOCK_DEAD)) {
printk(KERN_ERR "Freeing alive netlink socket %p\n", sk);
return;
}
WARN_ON(atomic_read(&sk->sk_rmem_alloc));
WARN_ON(atomic_read(&sk->sk_wmem_alloc));
WARN_ON(nlk_sk(sk)->groups);
}
/* This lock without WQ_FLAG_EXCLUSIVE is good on UP and it is _very_ bad on
* SMP. Look, when several writers sleep and reader wakes them up, all but one
* immediately hit write lock and grab all the cpus. Exclusive sleep solves
* this, _but_ remember, it adds useless work on UP machines.
*/
void netlink_table_grab(void)
__acquires(nl_table_lock)
{
might_sleep();
write_lock_irq(&nl_table_lock);
if (atomic_read(&nl_table_users)) {
DECLARE_WAITQUEUE(wait, current);
add_wait_queue_exclusive(&nl_table_wait, &wait);
for (;;) {
set_current_state(TASK_UNINTERRUPTIBLE);
if (atomic_read(&nl_table_users) == 0)
break;
write_unlock_irq(&nl_table_lock);
schedule();
write_lock_irq(&nl_table_lock);
}
__set_current_state(TASK_RUNNING);
remove_wait_queue(&nl_table_wait, &wait);
}
}
void netlink_table_ungrab(void)
__releases(nl_table_lock)
{
write_unlock_irq(&nl_table_lock);
wake_up(&nl_table_wait);
}
static inline void
netlink_lock_table(void)
{
/* read_lock() synchronizes us to netlink_table_grab */
read_lock(&nl_table_lock);
atomic_inc(&nl_table_users);
read_unlock(&nl_table_lock);
}
static inline void
netlink_unlock_table(void)
{
if (atomic_dec_and_test(&nl_table_users))
wake_up(&nl_table_wait);
}
static struct sock *netlink_lookup(struct net *net, int protocol, u32 pid)
{
struct nl_pid_hash *hash = &nl_table[protocol].hash;
struct hlist_head *head;
struct sock *sk;
struct hlist_node *node;
read_lock(&nl_table_lock);
head = nl_pid_hashfn(hash, pid);
sk_for_each(sk, node, head) {
if (net_eq(sock_net(sk), net) && (nlk_sk(sk)->pid == pid)) {
sock_hold(sk);
goto found;
}
}
sk = NULL;
found:
read_unlock(&nl_table_lock);
return sk;
}
static struct hlist_head *nl_pid_hash_zalloc(size_t size)
{
if (size <= PAGE_SIZE)
return kzalloc(size, GFP_ATOMIC);
else
return (struct hlist_head *)
__get_free_pages(GFP_ATOMIC | __GFP_ZERO,
get_order(size));
}
static void nl_pid_hash_free(struct hlist_head *table, size_t size)
{
if (size <= PAGE_SIZE)
kfree(table);
else
free_pages((unsigned long)table, get_order(size));
}
static int nl_pid_hash_rehash(struct nl_pid_hash *hash, int grow)
{
unsigned int omask, mask, shift;
size_t osize, size;
struct hlist_head *otable, *table;
int i;
omask = mask = hash->mask;
osize = size = (mask + 1) * sizeof(*table);
shift = hash->shift;
if (grow) {
if (++shift > hash->max_shift)
return 0;
mask = mask * 2 + 1;
size *= 2;
}
table = nl_pid_hash_zalloc(size);
if (!table)
return 0;
otable = hash->table;
hash->table = table;
hash->mask = mask;
hash->shift = shift;
get_random_bytes(&hash->rnd, sizeof(hash->rnd));
for (i = 0; i <= omask; i++) {
struct sock *sk;
struct hlist_node *node, *tmp;
sk_for_each_safe(sk, node, tmp, &otable[i])
__sk_add_node(sk, nl_pid_hashfn(hash, nlk_sk(sk)->pid));
}
nl_pid_hash_free(otable, osize);
hash->rehash_time = jiffies + 10 * 60 * HZ;
return 1;
}
static inline int nl_pid_hash_dilute(struct nl_pid_hash *hash, int len)
{
int avg = hash->entries >> hash->shift;
if (unlikely(avg > 1) && nl_pid_hash_rehash(hash, 1))
return 1;
if (unlikely(len > avg) && time_after(jiffies, hash->rehash_time)) {
nl_pid_hash_rehash(hash, 0);
return 1;
}
return 0;
}
static const struct proto_ops netlink_ops;
static void
netlink_update_listeners(struct sock *sk)
{
struct netlink_table *tbl = &nl_table[sk->sk_protocol];
struct hlist_node *node;
unsigned long mask;
unsigned int i;
for (i = 0; i < NLGRPLONGS(tbl->groups); i++) {
mask = 0;
sk_for_each_bound(sk, node, &tbl->mc_list) {
if (i < NLGRPLONGS(nlk_sk(sk)->ngroups))
mask |= nlk_sk(sk)->groups[i];
}
tbl->listeners->masks[i] = mask;
}
/* this function is only called with the netlink table "grabbed", which
* makes sure updates are visible before bind or setsockopt return. */
}
static int netlink_insert(struct sock *sk, struct net *net, u32 pid)
{
struct nl_pid_hash *hash = &nl_table[sk->sk_protocol].hash;
struct hlist_head *head;
int err = -EADDRINUSE;
struct sock *osk;
struct hlist_node *node;
int len;
netlink_table_grab();
head = nl_pid_hashfn(hash, pid);
len = 0;
sk_for_each(osk, node, head) {
if (net_eq(sock_net(osk), net) && (nlk_sk(osk)->pid == pid))
break;
len++;
}
if (node)
goto err;
err = -EBUSY;
if (nlk_sk(sk)->pid)
goto err;
err = -ENOMEM;
if (BITS_PER_LONG > 32 && unlikely(hash->entries >= UINT_MAX))
goto err;
if (len && nl_pid_hash_dilute(hash, len))
head = nl_pid_hashfn(hash, pid);
hash->entries++;
nlk_sk(sk)->pid = pid;
sk_add_node(sk, head);
err = 0;
err:
netlink_table_ungrab();
return err;
}
static void netlink_remove(struct sock *sk)
{
netlink_table_grab();
if (sk_del_node_init(sk))
nl_table[sk->sk_protocol].hash.entries--;
if (nlk_sk(sk)->subscriptions)
__sk_del_bind_node(sk);
netlink_table_ungrab();
}
static struct proto netlink_proto = {
.name = "NETLINK",
.owner = THIS_MODULE,
.obj_size = sizeof(struct netlink_sock),
};
static int __netlink_create(struct net *net, struct socket *sock,
struct mutex *cb_mutex, int protocol)
{
struct sock *sk;
struct netlink_sock *nlk;
sock->ops = &netlink_ops;
sk = sk_alloc(net, PF_NETLINK, GFP_KERNEL, &netlink_proto);
if (!sk)
return -ENOMEM;
sock_init_data(sock, sk);
nlk = nlk_sk(sk);
if (cb_mutex) {
nlk->cb_mutex = cb_mutex;
} else {
nlk->cb_mutex = &nlk->cb_def_mutex;
mutex_init(nlk->cb_mutex);
}
init_waitqueue_head(&nlk->wait);
sk->sk_destruct = netlink_sock_destruct;
sk->sk_protocol = protocol;
return 0;
}
static int netlink_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct module *module = NULL;
struct mutex *cb_mutex;
struct netlink_sock *nlk;
void (*bind)(int group);
int err = 0;
sock->state = SS_UNCONNECTED;
if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
return -ESOCKTNOSUPPORT;
if (protocol < 0 || protocol >= MAX_LINKS)
return -EPROTONOSUPPORT;
netlink_lock_table();
#ifdef CONFIG_MODULES
if (!nl_table[protocol].registered) {
netlink_unlock_table();
request_module("net-pf-%d-proto-%d", PF_NETLINK, protocol);
netlink_lock_table();
}
#endif
if (nl_table[protocol].registered &&
try_module_get(nl_table[protocol].module))
module = nl_table[protocol].module;
else
err = -EPROTONOSUPPORT;
cb_mutex = nl_table[protocol].cb_mutex;
bind = nl_table[protocol].bind;
netlink_unlock_table();
if (err < 0)
goto out;
err = __netlink_create(net, sock, cb_mutex, protocol);
if (err < 0)
goto out_module;
local_bh_disable();
sock_prot_inuse_add(net, &netlink_proto, 1);
local_bh_enable();
nlk = nlk_sk(sock->sk);
nlk->module = module;
nlk->netlink_bind = bind;
out:
return err;
out_module:
module_put(module);
goto out;
}
static int netlink_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct netlink_sock *nlk;
if (!sk)
return 0;
netlink_remove(sk);
sock_orphan(sk);
nlk = nlk_sk(sk);
/*
* OK. Socket is unlinked, any packets that arrive now
* will be purged.
*/
sock->sk = NULL;
wake_up_interruptible_all(&nlk->wait);
skb_queue_purge(&sk->sk_write_queue);
if (nlk->pid) {
struct netlink_notify n = {
.net = sock_net(sk),
.protocol = sk->sk_protocol,
.pid = nlk->pid,
};
atomic_notifier_call_chain(&netlink_chain,
NETLINK_URELEASE, &n);
}
module_put(nlk->module);
netlink_table_grab();
if (netlink_is_kernel(sk)) {
BUG_ON(nl_table[sk->sk_protocol].registered == 0);
if (--nl_table[sk->sk_protocol].registered == 0) {
kfree(nl_table[sk->sk_protocol].listeners);
nl_table[sk->sk_protocol].module = NULL;
nl_table[sk->sk_protocol].registered = 0;
}
} else if (nlk->subscriptions) {
netlink_update_listeners(sk);
}
netlink_table_ungrab();
kfree(nlk->groups);
nlk->groups = NULL;
local_bh_disable();
sock_prot_inuse_add(sock_net(sk), &netlink_proto, -1);
local_bh_enable();
sock_put(sk);
return 0;
}
static int netlink_autobind(struct socket *sock)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct nl_pid_hash *hash = &nl_table[sk->sk_protocol].hash;
struct hlist_head *head;
struct sock *osk;
struct hlist_node *node;
s32 pid = task_tgid_vnr(current);
int err;
static s32 rover = -4097;
retry:
cond_resched();
netlink_table_grab();
head = nl_pid_hashfn(hash, pid);
sk_for_each(osk, node, head) {
if (!net_eq(sock_net(osk), net))
continue;
if (nlk_sk(osk)->pid == pid) {
/* Bind collision, search negative pid values. */
pid = rover--;
if (rover > -4097)
rover = -4097;
netlink_table_ungrab();
goto retry;
}
}
netlink_table_ungrab();
err = netlink_insert(sk, net, pid);
if (err == -EADDRINUSE)
goto retry;
/* If 2 threads race to autobind, that is fine. */
if (err == -EBUSY)
err = 0;
return err;
}
static inline int netlink_capable(const struct socket *sock, unsigned int flag)
{
return (nl_table[sock->sk->sk_protocol].nl_nonroot & flag) ||
capable(CAP_NET_ADMIN);
}
static void
netlink_update_subscriptions(struct sock *sk, unsigned int subscriptions)
{
struct netlink_sock *nlk = nlk_sk(sk);
if (nlk->subscriptions && !subscriptions)
__sk_del_bind_node(sk);
else if (!nlk->subscriptions && subscriptions)
sk_add_bind_node(sk, &nl_table[sk->sk_protocol].mc_list);
nlk->subscriptions = subscriptions;
}
static int netlink_realloc_groups(struct sock *sk)
{
struct netlink_sock *nlk = nlk_sk(sk);
unsigned int groups;
unsigned long *new_groups;
int err = 0;
netlink_table_grab();
groups = nl_table[sk->sk_protocol].groups;
if (!nl_table[sk->sk_protocol].registered) {
err = -ENOENT;
goto out_unlock;
}
if (nlk->ngroups >= groups)
goto out_unlock;
new_groups = krealloc(nlk->groups, NLGRPSZ(groups), GFP_ATOMIC);
if (new_groups == NULL) {
err = -ENOMEM;
goto out_unlock;
}
memset((char *)new_groups + NLGRPSZ(nlk->ngroups), 0,
NLGRPSZ(groups) - NLGRPSZ(nlk->ngroups));
nlk->groups = new_groups;
nlk->ngroups = groups;
out_unlock:
netlink_table_ungrab();
return err;
}
static int netlink_bind(struct socket *sock, struct sockaddr *addr,
int addr_len)
{
struct sock *sk = sock->sk;
struct net *net = sock_net(sk);
struct netlink_sock *nlk = nlk_sk(sk);
struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
int err;
if (nladdr->nl_family != AF_NETLINK)
return -EINVAL;
/* Only superuser is allowed to listen multicasts */
if (nladdr->nl_groups) {
if (!netlink_capable(sock, NL_NONROOT_RECV))
return -EPERM;
err = netlink_realloc_groups(sk);
if (err)
return err;
}
if (nlk->pid) {
if (nladdr->nl_pid != nlk->pid)
return -EINVAL;
} else {
err = nladdr->nl_pid ?
netlink_insert(sk, net, nladdr->nl_pid) :
netlink_autobind(sock);
if (err)
return err;
}
if (!nladdr->nl_groups && (nlk->groups == NULL || !(u32)nlk->groups[0]))
return 0;
netlink_table_grab();
netlink_update_subscriptions(sk, nlk->subscriptions +
hweight32(nladdr->nl_groups) -
hweight32(nlk->groups[0]));
nlk->groups[0] = (nlk->groups[0] & ~0xffffffffUL) | nladdr->nl_groups;
netlink_update_listeners(sk);
netlink_table_ungrab();
if (nlk->netlink_bind && nlk->groups[0]) {
int i;
for (i=0; i<nlk->ngroups; i++) {
if (test_bit(i, nlk->groups))
nlk->netlink_bind(i);
}
}
return 0;
}
static int netlink_connect(struct socket *sock, struct sockaddr *addr,
int alen, int flags)
{
int err = 0;
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
if (alen < sizeof(addr->sa_family))
return -EINVAL;
if (addr->sa_family == AF_UNSPEC) {
sk->sk_state = NETLINK_UNCONNECTED;
nlk->dst_pid = 0;
nlk->dst_group = 0;
return 0;
}
if (addr->sa_family != AF_NETLINK)
return -EINVAL;
/* Only superuser is allowed to send multicasts */
if (nladdr->nl_groups && !netlink_capable(sock, NL_NONROOT_SEND))
return -EPERM;
if (!nlk->pid)
err = netlink_autobind(sock);
if (err == 0) {
sk->sk_state = NETLINK_CONNECTED;
nlk->dst_pid = nladdr->nl_pid;
nlk->dst_group = ffs(nladdr->nl_groups);
}
return err;
}
static int netlink_getname(struct socket *sock, struct sockaddr *addr,
int *addr_len, int peer)
{
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_nl *, nladdr, addr);
nladdr->nl_family = AF_NETLINK;
nladdr->nl_pad = 0;
*addr_len = sizeof(*nladdr);
if (peer) {
nladdr->nl_pid = nlk->dst_pid;
nladdr->nl_groups = netlink_group_mask(nlk->dst_group);
} else {
nladdr->nl_pid = nlk->pid;
nladdr->nl_groups = nlk->groups ? nlk->groups[0] : 0;
}
return 0;
}
static void netlink_overrun(struct sock *sk)
{
struct netlink_sock *nlk = nlk_sk(sk);
if (!(nlk->flags & NETLINK_RECV_NO_ENOBUFS)) {
if (!test_and_set_bit(0, &nlk_sk(sk)->state)) {
sk->sk_err = ENOBUFS;
sk->sk_error_report(sk);
}
}
atomic_inc(&sk->sk_drops);
}
static struct sock *netlink_getsockbypid(struct sock *ssk, u32 pid)
{
struct sock *sock;
struct netlink_sock *nlk;
sock = netlink_lookup(sock_net(ssk), ssk->sk_protocol, pid);
if (!sock)
return ERR_PTR(-ECONNREFUSED);
/* Don't bother queuing skb if kernel socket has no input function */
nlk = nlk_sk(sock);
if (sock->sk_state == NETLINK_CONNECTED &&
nlk->dst_pid != nlk_sk(ssk)->pid) {
sock_put(sock);
return ERR_PTR(-ECONNREFUSED);
}
return sock;
}
struct sock *netlink_getsockbyfilp(struct file *filp)
{
struct inode *inode = filp->f_path.dentry->d_inode;
struct sock *sock;
if (!S_ISSOCK(inode->i_mode))
return ERR_PTR(-ENOTSOCK);
sock = SOCKET_I(inode)->sk;
if (sock->sk_family != AF_NETLINK)
return ERR_PTR(-EINVAL);
sock_hold(sock);
return sock;
}
/*
* Attach a skb to a netlink socket.
* The caller must hold a reference to the destination socket. On error, the
* reference is dropped. The skb is not send to the destination, just all
* all error checks are performed and memory in the queue is reserved.
* Return values:
* < 0: error. skb freed, reference to sock dropped.
* 0: continue
* 1: repeat lookup - reference dropped while waiting for socket memory.
*/
int netlink_attachskb(struct sock *sk, struct sk_buff *skb,
long *timeo, struct sock *ssk)
{
struct netlink_sock *nlk;
nlk = nlk_sk(sk);
if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
test_bit(0, &nlk->state)) {
DECLARE_WAITQUEUE(wait, current);
if (!*timeo) {
if (!ssk || netlink_is_kernel(ssk))
netlink_overrun(sk);
sock_put(sk);
kfree_skb(skb);
return -EAGAIN;
}
__set_current_state(TASK_INTERRUPTIBLE);
add_wait_queue(&nlk->wait, &wait);
if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
test_bit(0, &nlk->state)) &&
!sock_flag(sk, SOCK_DEAD))
*timeo = schedule_timeout(*timeo);
__set_current_state(TASK_RUNNING);
remove_wait_queue(&nlk->wait, &wait);
sock_put(sk);
if (signal_pending(current)) {
kfree_skb(skb);
return sock_intr_errno(*timeo);
}
return 1;
}
skb_set_owner_r(skb, sk);
return 0;
}
static int __netlink_sendskb(struct sock *sk, struct sk_buff *skb)
{
int len = skb->len;
skb_queue_tail(&sk->sk_receive_queue, skb);
sk->sk_data_ready(sk, len);
return len;
}
int netlink_sendskb(struct sock *sk, struct sk_buff *skb)
{
int len = __netlink_sendskb(sk, skb);
sock_put(sk);
return len;
}
void netlink_detachskb(struct sock *sk, struct sk_buff *skb)
{
kfree_skb(skb);
sock_put(sk);
}
static struct sk_buff *netlink_trim(struct sk_buff *skb, gfp_t allocation)
{
int delta;
skb_orphan(skb);
delta = skb->end - skb->tail;
if (delta * 2 < skb->truesize)
return skb;
if (skb_shared(skb)) {
struct sk_buff *nskb = skb_clone(skb, allocation);
if (!nskb)
return skb;
consume_skb(skb);
skb = nskb;
}
if (!pskb_expand_head(skb, 0, -delta, allocation))
skb->truesize -= delta;
return skb;
}
static void netlink_rcv_wake(struct sock *sk)
{
struct netlink_sock *nlk = nlk_sk(sk);
if (skb_queue_empty(&sk->sk_receive_queue))
clear_bit(0, &nlk->state);
if (!test_bit(0, &nlk->state))
wake_up_interruptible(&nlk->wait);
}
static int netlink_unicast_kernel(struct sock *sk, struct sk_buff *skb)
{
int ret;
struct netlink_sock *nlk = nlk_sk(sk);
ret = -ECONNREFUSED;
if (nlk->netlink_rcv != NULL) {
ret = skb->len;
skb_set_owner_r(skb, sk);
nlk->netlink_rcv(skb);
consume_skb(skb);
} else {
kfree_skb(skb);
}
sock_put(sk);
return ret;
}
int netlink_unicast(struct sock *ssk, struct sk_buff *skb,
u32 pid, int nonblock)
{
struct sock *sk;
int err;
long timeo;
skb = netlink_trim(skb, gfp_any());
timeo = sock_sndtimeo(ssk, nonblock);
retry:
sk = netlink_getsockbypid(ssk, pid);
if (IS_ERR(sk)) {
kfree_skb(skb);
return PTR_ERR(sk);
}
if (netlink_is_kernel(sk))
return netlink_unicast_kernel(sk, skb);
if (sk_filter(sk, skb)) {
err = skb->len;
kfree_skb(skb);
sock_put(sk);
return err;
}
err = netlink_attachskb(sk, skb, &timeo, ssk);
if (err == 1)
goto retry;
if (err)
return err;
return netlink_sendskb(sk, skb);
}
EXPORT_SYMBOL(netlink_unicast);
int netlink_has_listeners(struct sock *sk, unsigned int group)
{
int res = 0;
struct listeners *listeners;
BUG_ON(!netlink_is_kernel(sk));
rcu_read_lock();
listeners = rcu_dereference(nl_table[sk->sk_protocol].listeners);
if (group - 1 < nl_table[sk->sk_protocol].groups)
res = test_bit(group - 1, listeners->masks);
rcu_read_unlock();
return res;
}
EXPORT_SYMBOL_GPL(netlink_has_listeners);
static int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
{
struct netlink_sock *nlk = nlk_sk(sk);
if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
!test_bit(0, &nlk->state)) {
skb_set_owner_r(skb, sk);
__netlink_sendskb(sk, skb);
return atomic_read(&sk->sk_rmem_alloc) > (sk->sk_rcvbuf >> 1);
}
return -1;
}
struct netlink_broadcast_data {
struct sock *exclude_sk;
struct net *net;
u32 pid;
u32 group;
int failure;
int delivery_failure;
int congested;
int delivered;
gfp_t allocation;
struct sk_buff *skb, *skb2;
int (*tx_filter)(struct sock *dsk, struct sk_buff *skb, void *data);
void *tx_data;
};
static int do_one_broadcast(struct sock *sk,
struct netlink_broadcast_data *p)
{
struct netlink_sock *nlk = nlk_sk(sk);
int val;
if (p->exclude_sk == sk)
goto out;
if (nlk->pid == p->pid || p->group - 1 >= nlk->ngroups ||
!test_bit(p->group - 1, nlk->groups))
goto out;
if (!net_eq(sock_net(sk), p->net))
goto out;
if (p->failure) {
netlink_overrun(sk);
goto out;
}
sock_hold(sk);
if (p->skb2 == NULL) {
if (skb_shared(p->skb)) {
p->skb2 = skb_clone(p->skb, p->allocation);
} else {
p->skb2 = skb_get(p->skb);
/*
* skb ownership may have been set when
* delivered to a previous socket.
*/
skb_orphan(p->skb2);
}
}
if (p->skb2 == NULL) {
netlink_overrun(sk);
/* Clone failed. Notify ALL listeners. */
p->failure = 1;
if (nlk->flags & NETLINK_BROADCAST_SEND_ERROR)
p->delivery_failure = 1;
} else if (p->tx_filter && p->tx_filter(sk, p->skb2, p->tx_data)) {
kfree_skb(p->skb2);
p->skb2 = NULL;
} else if (sk_filter(sk, p->skb2)) {
kfree_skb(p->skb2);
p->skb2 = NULL;
} else if ((val = netlink_broadcast_deliver(sk, p->skb2)) < 0) {
netlink_overrun(sk);
if (nlk->flags & NETLINK_BROADCAST_SEND_ERROR)
p->delivery_failure = 1;
} else {
p->congested |= val;
p->delivered = 1;
p->skb2 = NULL;
}
sock_put(sk);
out:
return 0;
}
int netlink_broadcast_filtered(struct sock *ssk, struct sk_buff *skb, u32 pid,
u32 group, gfp_t allocation,
int (*filter)(struct sock *dsk, struct sk_buff *skb, void *data),
void *filter_data)
{
struct net *net = sock_net(ssk);
struct netlink_broadcast_data info;
struct hlist_node *node;
struct sock *sk;
skb = netlink_trim(skb, allocation);
info.exclude_sk = ssk;
info.net = net;
info.pid = pid;
info.group = group;
info.failure = 0;
info.delivery_failure = 0;
info.congested = 0;
info.delivered = 0;
info.allocation = allocation;
info.skb = skb;
info.skb2 = NULL;
info.tx_filter = filter;
info.tx_data = filter_data;
/* While we sleep in clone, do not allow to change socket list */
netlink_lock_table();
sk_for_each_bound(sk, node, &nl_table[ssk->sk_protocol].mc_list)
do_one_broadcast(sk, &info);
consume_skb(skb);
netlink_unlock_table();
if (info.delivery_failure) {
kfree_skb(info.skb2);
return -ENOBUFS;
}
consume_skb(info.skb2);
if (info.delivered) {
if (info.congested && (allocation & __GFP_WAIT))
yield();
return 0;
}
return -ESRCH;
}
EXPORT_SYMBOL(netlink_broadcast_filtered);
int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 pid,
u32 group, gfp_t allocation)
{
return netlink_broadcast_filtered(ssk, skb, pid, group, allocation,
NULL, NULL);
}
EXPORT_SYMBOL(netlink_broadcast);
struct netlink_set_err_data {
struct sock *exclude_sk;
u32 pid;
u32 group;
int code;
};
static int do_one_set_err(struct sock *sk, struct netlink_set_err_data *p)
{
struct netlink_sock *nlk = nlk_sk(sk);
int ret = 0;
if (sk == p->exclude_sk)
goto out;
if (!net_eq(sock_net(sk), sock_net(p->exclude_sk)))
goto out;
if (nlk->pid == p->pid || p->group - 1 >= nlk->ngroups ||
!test_bit(p->group - 1, nlk->groups))
goto out;
if (p->code == ENOBUFS && nlk->flags & NETLINK_RECV_NO_ENOBUFS) {
ret = 1;
goto out;
}
sk->sk_err = p->code;
sk->sk_error_report(sk);
out:
return ret;
}
/**
* netlink_set_err - report error to broadcast listeners
* @ssk: the kernel netlink socket, as returned by netlink_kernel_create()
* @pid: the PID of a process that we want to skip (if any)
* @groups: the broadcast group that will notice the error
* @code: error code, must be negative (as usual in kernelspace)
*
* This function returns the number of broadcast listeners that have set the
* NETLINK_RECV_NO_ENOBUFS socket option.
*/
int netlink_set_err(struct sock *ssk, u32 pid, u32 group, int code)
{
struct netlink_set_err_data info;
struct hlist_node *node;
struct sock *sk;
int ret = 0;
info.exclude_sk = ssk;
info.pid = pid;
info.group = group;
/* sk->sk_err wants a positive error value */
info.code = -code;
read_lock(&nl_table_lock);
sk_for_each_bound(sk, node, &nl_table[ssk->sk_protocol].mc_list)
ret += do_one_set_err(sk, &info);
read_unlock(&nl_table_lock);
return ret;
}
EXPORT_SYMBOL(netlink_set_err);
/* must be called with netlink table grabbed */
static void netlink_update_socket_mc(struct netlink_sock *nlk,
unsigned int group,
int is_new)
{
int old, new = !!is_new, subscriptions;
old = test_bit(group - 1, nlk->groups);
subscriptions = nlk->subscriptions - old + new;
if (new)
__set_bit(group - 1, nlk->groups);
else
__clear_bit(group - 1, nlk->groups);
netlink_update_subscriptions(&nlk->sk, subscriptions);
netlink_update_listeners(&nlk->sk);
}
static int netlink_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
unsigned int val = 0;
int err;
if (level != SOL_NETLINK)
return -ENOPROTOOPT;
if (optlen >= sizeof(int) &&
get_user(val, (unsigned int __user *)optval))
return -EFAULT;
switch (optname) {
case NETLINK_PKTINFO:
if (val)
nlk->flags |= NETLINK_RECV_PKTINFO;
else
nlk->flags &= ~NETLINK_RECV_PKTINFO;
err = 0;
break;
case NETLINK_ADD_MEMBERSHIP:
case NETLINK_DROP_MEMBERSHIP: {
if (!netlink_capable(sock, NL_NONROOT_RECV))
return -EPERM;
err = netlink_realloc_groups(sk);
if (err)
return err;
if (!val || val - 1 >= nlk->ngroups)
return -EINVAL;
netlink_table_grab();
netlink_update_socket_mc(nlk, val,
optname == NETLINK_ADD_MEMBERSHIP);
netlink_table_ungrab();
if (nlk->netlink_bind)
nlk->netlink_bind(val);
err = 0;
break;
}
case NETLINK_BROADCAST_ERROR:
if (val)
nlk->flags |= NETLINK_BROADCAST_SEND_ERROR;
else
nlk->flags &= ~NETLINK_BROADCAST_SEND_ERROR;
err = 0;
break;
case NETLINK_NO_ENOBUFS:
if (val) {
nlk->flags |= NETLINK_RECV_NO_ENOBUFS;
clear_bit(0, &nlk->state);
wake_up_interruptible(&nlk->wait);
} else {
nlk->flags &= ~NETLINK_RECV_NO_ENOBUFS;
}
err = 0;
break;
default:
err = -ENOPROTOOPT;
}
return err;
}
static int netlink_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
int len, val, err;
if (level != SOL_NETLINK)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
switch (optname) {
case NETLINK_PKTINFO:
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = nlk->flags & NETLINK_RECV_PKTINFO ? 1 : 0;
if (put_user(len, optlen) ||
put_user(val, optval))
return -EFAULT;
err = 0;
break;
case NETLINK_BROADCAST_ERROR:
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = nlk->flags & NETLINK_BROADCAST_SEND_ERROR ? 1 : 0;
if (put_user(len, optlen) ||
put_user(val, optval))
return -EFAULT;
err = 0;
break;
case NETLINK_NO_ENOBUFS:
if (len < sizeof(int))
return -EINVAL;
len = sizeof(int);
val = nlk->flags & NETLINK_RECV_NO_ENOBUFS ? 1 : 0;
if (put_user(len, optlen) ||
put_user(val, optval))
return -EFAULT;
err = 0;
break;
default:
err = -ENOPROTOOPT;
}
return err;
}
static void netlink_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb)
{
struct nl_pktinfo info;
info.group = NETLINK_CB(skb).dst_group;
put_cmsg(msg, SOL_NETLINK, NETLINK_PKTINFO, sizeof(info), &info);
}
static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
struct sockaddr_nl *addr = msg->msg_name;
u32 dst_pid;
u32 dst_group;
struct sk_buff *skb;
int err;
struct scm_cookie scm;
if (msg->msg_flags&MSG_OOB)
return -EOPNOTSUPP;
if (NULL == siocb->scm)
siocb->scm = &scm;
err = scm_send(sock, msg, siocb->scm);
if (err < 0)
return err;
if (msg->msg_namelen) {
err = -EINVAL;
if (addr->nl_family != AF_NETLINK)
goto out;
dst_pid = addr->nl_pid;
dst_group = ffs(addr->nl_groups);
err = -EPERM;
if (dst_group && !netlink_capable(sock, NL_NONROOT_SEND))
goto out;
} else {
dst_pid = nlk->dst_pid;
dst_group = nlk->dst_group;
}
if (!nlk->pid) {
err = netlink_autobind(sock);
if (err)
goto out;
}
err = -EMSGSIZE;
if (len > sk->sk_sndbuf - 32)
goto out;
err = -ENOBUFS;
skb = alloc_skb(len, GFP_KERNEL);
if (skb == NULL)
goto out;
NETLINK_CB(skb).pid = nlk->pid;
NETLINK_CB(skb).dst_group = dst_group;
memcpy(NETLINK_CREDS(skb), &siocb->scm->creds, sizeof(struct ucred));
err = -EFAULT;
if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {
kfree_skb(skb);
goto out;
}
err = security_netlink_send(sk, skb);
if (err) {
kfree_skb(skb);
goto out;
}
if (dst_group) {
atomic_inc(&skb->users);
netlink_broadcast(sk, skb, dst_pid, dst_group, GFP_KERNEL);
}
err = netlink_unicast(sk, skb, dst_pid, msg->msg_flags&MSG_DONTWAIT);
out:
scm_destroy(siocb->scm);
return err;
}
static int netlink_recvmsg(struct kiocb *kiocb, struct socket *sock,
struct msghdr *msg, size_t len,
int flags)
{
struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
struct scm_cookie scm;
struct sock *sk = sock->sk;
struct netlink_sock *nlk = nlk_sk(sk);
int noblock = flags&MSG_DONTWAIT;
size_t copied;
struct sk_buff *skb, *data_skb;
int err, ret;
if (flags&MSG_OOB)
return -EOPNOTSUPP;
copied = 0;
skb = skb_recv_datagram(sk, flags, noblock, &err);
if (skb == NULL)
goto out;
data_skb = skb;
#ifdef CONFIG_COMPAT_NETLINK_MESSAGES
if (unlikely(skb_shinfo(skb)->frag_list)) {
/*
* If this skb has a frag_list, then here that means that we
* will have to use the frag_list skb's data for compat tasks
* and the regular skb's data for normal (non-compat) tasks.
*
* If we need to send the compat skb, assign it to the
* 'data_skb' variable so that it will be used below for data
* copying. We keep 'skb' for everything else, including
* freeing both later.
*/
if (flags & MSG_CMSG_COMPAT)
data_skb = skb_shinfo(skb)->frag_list;
}
#endif
msg->msg_namelen = 0;
copied = data_skb->len;
if (len < copied) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
skb_reset_transport_header(data_skb);
err = skb_copy_datagram_iovec(data_skb, 0, msg->msg_iov, copied);
if (msg->msg_name) {
struct sockaddr_nl *addr = (struct sockaddr_nl *)msg->msg_name;
addr->nl_family = AF_NETLINK;
addr->nl_pad = 0;
addr->nl_pid = NETLINK_CB(skb).pid;
addr->nl_groups = netlink_group_mask(NETLINK_CB(skb).dst_group);
msg->msg_namelen = sizeof(*addr);
}
if (nlk->flags & NETLINK_RECV_PKTINFO)
netlink_cmsg_recv_pktinfo(msg, skb);
if (NULL == siocb->scm) {
memset(&scm, 0, sizeof(scm));
siocb->scm = &scm;
}
siocb->scm->creds = *NETLINK_CREDS(skb);
if (flags & MSG_TRUNC)
copied = data_skb->len;
skb_free_datagram(sk, skb);
if (nlk->cb && atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) {
ret = netlink_dump(sk);
if (ret) {
sk->sk_err = ret;
sk->sk_error_report(sk);
}
}
scm_recv(sock, msg, siocb->scm, flags);
out:
netlink_rcv_wake(sk);
return err ? : copied;
}
static void netlink_data_ready(struct sock *sk, int len)
{
BUG();
}
/*
* We export these functions to other modules. They provide a
* complete set of kernel non-blocking support for message
* queueing.
*/
struct sock *
netlink_kernel_create(struct net *net, int unit,
struct module *module,
struct netlink_kernel_cfg *cfg)
{
struct socket *sock;
struct sock *sk;
struct netlink_sock *nlk;
struct listeners *listeners = NULL;
struct mutex *cb_mutex = cfg ? cfg->cb_mutex : NULL;
unsigned int groups;
BUG_ON(!nl_table);
if (unit < 0 || unit >= MAX_LINKS)
return NULL;
if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
return NULL;
/*
* We have to just have a reference on the net from sk, but don't
* get_net it. Besides, we cannot get and then put the net here.
* So we create one inside init_net and the move it to net.
*/
if (__netlink_create(&init_net, sock, cb_mutex, unit) < 0)
goto out_sock_release_nosk;
sk = sock->sk;
sk_change_net(sk, net);
if (!cfg || cfg->groups < 32)
groups = 32;
else
groups = cfg->groups;
listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
if (!listeners)
goto out_sock_release;
sk->sk_data_ready = netlink_data_ready;
if (cfg && cfg->input)
nlk_sk(sk)->netlink_rcv = cfg->input;
if (netlink_insert(sk, net, 0))
goto out_sock_release;
nlk = nlk_sk(sk);
nlk->flags |= NETLINK_KERNEL_SOCKET;
netlink_table_grab();
if (!nl_table[unit].registered) {
nl_table[unit].groups = groups;
rcu_assign_pointer(nl_table[unit].listeners, listeners);
nl_table[unit].cb_mutex = cb_mutex;
nl_table[unit].module = module;
nl_table[unit].bind = cfg ? cfg->bind : NULL;
nl_table[unit].registered = 1;
} else {
kfree(listeners);
nl_table[unit].registered++;
}
netlink_table_ungrab();
return sk;
out_sock_release:
kfree(listeners);
netlink_kernel_release(sk);
return NULL;
out_sock_release_nosk:
sock_release(sock);
return NULL;
}
EXPORT_SYMBOL(netlink_kernel_create);
void
netlink_kernel_release(struct sock *sk)
{
sk_release_kernel(sk);
}
EXPORT_SYMBOL(netlink_kernel_release);
int __netlink_change_ngroups(struct sock *sk, unsigned int groups)
{
struct listeners *new, *old;
struct netlink_table *tbl = &nl_table[sk->sk_protocol];
if (groups < 32)
groups = 32;
if (NLGRPSZ(tbl->groups) < NLGRPSZ(groups)) {
new = kzalloc(sizeof(*new) + NLGRPSZ(groups), GFP_ATOMIC);
if (!new)
return -ENOMEM;
old = rcu_dereference_protected(tbl->listeners, 1);
memcpy(new->masks, old->masks, NLGRPSZ(tbl->groups));
rcu_assign_pointer(tbl->listeners, new);
kfree_rcu(old, rcu);
}
tbl->groups = groups;
return 0;
}
/**
* netlink_change_ngroups - change number of multicast groups
*
* This changes the number of multicast groups that are available
* on a certain netlink family. Note that it is not possible to
* change the number of groups to below 32. Also note that it does
* not implicitly call netlink_clear_multicast_users() when the
* number of groups is reduced.
*
* @sk: The kernel netlink socket, as returned by netlink_kernel_create().
* @groups: The new number of groups.
*/
int netlink_change_ngroups(struct sock *sk, unsigned int groups)
{
int err;
netlink_table_grab();
err = __netlink_change_ngroups(sk, groups);
netlink_table_ungrab();
return err;
}
void __netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
{
struct sock *sk;
struct hlist_node *node;
struct netlink_table *tbl = &nl_table[ksk->sk_protocol];
sk_for_each_bound(sk, node, &tbl->mc_list)
netlink_update_socket_mc(nlk_sk(sk), group, 0);
}
/**
* netlink_clear_multicast_users - kick off multicast listeners
*
* This function removes all listeners from the given group.
* @ksk: The kernel netlink socket, as returned by
* netlink_kernel_create().
* @group: The multicast group to clear.
*/
void netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
{
netlink_table_grab();
__netlink_clear_multicast_users(ksk, group);
netlink_table_ungrab();
}
void netlink_set_nonroot(int protocol, unsigned int flags)
{
if ((unsigned int)protocol < MAX_LINKS)
nl_table[protocol].nl_nonroot = flags;
}
EXPORT_SYMBOL(netlink_set_nonroot);
struct nlmsghdr *
__nlmsg_put(struct sk_buff *skb, u32 pid, u32 seq, int type, int len, int flags)
{
struct nlmsghdr *nlh;
int size = NLMSG_LENGTH(len);
nlh = (struct nlmsghdr*)skb_put(skb, NLMSG_ALIGN(size));
nlh->nlmsg_type = type;
nlh->nlmsg_len = size;
nlh->nlmsg_flags = flags;
nlh->nlmsg_pid = pid;
nlh->nlmsg_seq = seq;
if (!__builtin_constant_p(size) || NLMSG_ALIGN(size) - size != 0)
memset(NLMSG_DATA(nlh) + len, 0, NLMSG_ALIGN(size) - size);
return nlh;
}
EXPORT_SYMBOL(__nlmsg_put);
/*
* It looks a bit ugly.
* It would be better to create kernel thread.
*/
static int netlink_dump(struct sock *sk)
{
struct netlink_sock *nlk = nlk_sk(sk);
struct netlink_callback *cb;
struct sk_buff *skb = NULL;
struct nlmsghdr *nlh;
int len, err = -ENOBUFS;
int alloc_size;
mutex_lock(nlk->cb_mutex);
cb = nlk->cb;
if (cb == NULL) {
err = -EINVAL;
goto errout_skb;
}
alloc_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE);
skb = sock_rmalloc(sk, alloc_size, 0, GFP_KERNEL);
if (!skb)
goto errout_skb;
len = cb->dump(skb, cb);
if (len > 0) {
mutex_unlock(nlk->cb_mutex);
if (sk_filter(sk, skb))
kfree_skb(skb);
else
__netlink_sendskb(sk, skb);
return 0;
}
nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE, sizeof(len), NLM_F_MULTI);
if (!nlh)
goto errout_skb;
nl_dump_check_consistent(cb, nlh);
memcpy(nlmsg_data(nlh), &len, sizeof(len));
if (sk_filter(sk, skb))
kfree_skb(skb);
else
__netlink_sendskb(sk, skb);
if (cb->done)
cb->done(cb);
nlk->cb = NULL;
mutex_unlock(nlk->cb_mutex);
netlink_consume_callback(cb);
return 0;
errout_skb:
mutex_unlock(nlk->cb_mutex);
kfree_skb(skb);
return err;
}
int netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
const struct nlmsghdr *nlh,
struct netlink_dump_control *control)
{
struct netlink_callback *cb;
struct sock *sk;
struct netlink_sock *nlk;
int ret;
cb = kzalloc(sizeof(*cb), GFP_KERNEL);
if (cb == NULL)
return -ENOBUFS;
cb->dump = control->dump;
cb->done = control->done;
cb->nlh = nlh;
cb->data = control->data;
cb->min_dump_alloc = control->min_dump_alloc;
atomic_inc(&skb->users);
cb->skb = skb;
sk = netlink_lookup(sock_net(ssk), ssk->sk_protocol, NETLINK_CB(skb).pid);
if (sk == NULL) {
netlink_destroy_callback(cb);
return -ECONNREFUSED;
}
nlk = nlk_sk(sk);
/* A dump is in progress... */
mutex_lock(nlk->cb_mutex);
if (nlk->cb) {
mutex_unlock(nlk->cb_mutex);
netlink_destroy_callback(cb);
sock_put(sk);
return -EBUSY;
}
nlk->cb = cb;
mutex_unlock(nlk->cb_mutex);
ret = netlink_dump(sk);
sock_put(sk);
if (ret)
return ret;
/* We successfully started a dump, by returning -EINTR we
* signal not to send ACK even if it was requested.
*/
return -EINTR;
}
EXPORT_SYMBOL(netlink_dump_start);
void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err)
{
struct sk_buff *skb;
struct nlmsghdr *rep;
struct nlmsgerr *errmsg;
size_t payload = sizeof(*errmsg);
/* error messages get the original request appened */
if (err)
payload += nlmsg_len(nlh);
skb = nlmsg_new(payload, GFP_KERNEL);
if (!skb) {
struct sock *sk;
sk = netlink_lookup(sock_net(in_skb->sk),
in_skb->sk->sk_protocol,
NETLINK_CB(in_skb).pid);
if (sk) {
sk->sk_err = ENOBUFS;
sk->sk_error_report(sk);
sock_put(sk);
}
return;
}
rep = __nlmsg_put(skb, NETLINK_CB(in_skb).pid, nlh->nlmsg_seq,
NLMSG_ERROR, payload, 0);
errmsg = nlmsg_data(rep);
errmsg->error = err;
memcpy(&errmsg->msg, nlh, err ? nlh->nlmsg_len : sizeof(*nlh));
netlink_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).pid, MSG_DONTWAIT);
}
EXPORT_SYMBOL(netlink_ack);
int netlink_rcv_skb(struct sk_buff *skb, int (*cb)(struct sk_buff *,
struct nlmsghdr *))
{
struct nlmsghdr *nlh;
int err;
while (skb->len >= nlmsg_total_size(0)) {
int msglen;
nlh = nlmsg_hdr(skb);
err = 0;
if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len)
return 0;
/* Only requests are handled by the kernel */
if (!(nlh->nlmsg_flags & NLM_F_REQUEST))
goto ack;
/* Skip control messages */
if (nlh->nlmsg_type < NLMSG_MIN_TYPE)
goto ack;
err = cb(skb, nlh);
if (err == -EINTR)
goto skip;
ack:
if (nlh->nlmsg_flags & NLM_F_ACK || err)
netlink_ack(skb, nlh, err);
skip:
msglen = NLMSG_ALIGN(nlh->nlmsg_len);
if (msglen > skb->len)
msglen = skb->len;
skb_pull(skb, msglen);
}
return 0;
}
EXPORT_SYMBOL(netlink_rcv_skb);
/**
* nlmsg_notify - send a notification netlink message
* @sk: netlink socket to use
* @skb: notification message
* @pid: destination netlink pid for reports or 0
* @group: destination multicast group or 0
* @report: 1 to report back, 0 to disable
* @flags: allocation flags
*/
int nlmsg_notify(struct sock *sk, struct sk_buff *skb, u32 pid,
unsigned int group, int report, gfp_t flags)
{
int err = 0;
if (group) {
int exclude_pid = 0;
if (report) {
atomic_inc(&skb->users);
exclude_pid = pid;
}
/* errors reported via destination sk->sk_err, but propagate
* delivery errors if NETLINK_BROADCAST_ERROR flag is set */
err = nlmsg_multicast(sk, skb, exclude_pid, group, flags);
}
if (report) {
int err2;
err2 = nlmsg_unicast(sk, skb, pid);
if (!err || err == -ESRCH)
err = err2;
}
return err;
}
EXPORT_SYMBOL(nlmsg_notify);
#ifdef CONFIG_PROC_FS
struct nl_seq_iter {
struct seq_net_private p;
int link;
int hash_idx;
};
static struct sock *netlink_seq_socket_idx(struct seq_file *seq, loff_t pos)
{
struct nl_seq_iter *iter = seq->private;
int i, j;
struct sock *s;
struct hlist_node *node;
loff_t off = 0;
for (i = 0; i < MAX_LINKS; i++) {
struct nl_pid_hash *hash = &nl_table[i].hash;
for (j = 0; j <= hash->mask; j++) {
sk_for_each(s, node, &hash->table[j]) {
if (sock_net(s) != seq_file_net(seq))
continue;
if (off == pos) {
iter->link = i;
iter->hash_idx = j;
return s;
}
++off;
}
}
}
return NULL;
}
static void *netlink_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(nl_table_lock)
{
read_lock(&nl_table_lock);
return *pos ? netlink_seq_socket_idx(seq, *pos - 1) : SEQ_START_TOKEN;
}
static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct sock *s;
struct nl_seq_iter *iter;
int i, j;
++*pos;
if (v == SEQ_START_TOKEN)
return netlink_seq_socket_idx(seq, 0);
iter = seq->private;
s = v;
do {
s = sk_next(s);
} while (s && sock_net(s) != seq_file_net(seq));
if (s)
return s;
i = iter->link;
j = iter->hash_idx + 1;
do {
struct nl_pid_hash *hash = &nl_table[i].hash;
for (; j <= hash->mask; j++) {
s = sk_head(&hash->table[j]);
while (s && sock_net(s) != seq_file_net(seq))
s = sk_next(s);
if (s) {
iter->link = i;
iter->hash_idx = j;
return s;
}
}
j = 0;
} while (++i < MAX_LINKS);
return NULL;
}
static void netlink_seq_stop(struct seq_file *seq, void *v)
__releases(nl_table_lock)
{
read_unlock(&nl_table_lock);
}
static int netlink_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN) {
seq_puts(seq,
"sk Eth Pid Groups "
"Rmem Wmem Dump Locks Drops Inode\n");
} else {
struct sock *s = v;
struct netlink_sock *nlk = nlk_sk(s);
seq_printf(seq, "%pK %-3d %-6d %08x %-8d %-8d %pK %-8d %-8d %-8lu\n",
s,
s->sk_protocol,
nlk->pid,
nlk->groups ? (u32)nlk->groups[0] : 0,
sk_rmem_alloc_get(s),
sk_wmem_alloc_get(s),
nlk->cb,
atomic_read(&s->sk_refcnt),
atomic_read(&s->sk_drops),
sock_i_ino(s)
);
}
return 0;
}
static const struct seq_operations netlink_seq_ops = {
.start = netlink_seq_start,
.next = netlink_seq_next,
.stop = netlink_seq_stop,
.show = netlink_seq_show,
};
static int netlink_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &netlink_seq_ops,
sizeof(struct nl_seq_iter));
}
static const struct file_operations netlink_seq_fops = {
.owner = THIS_MODULE,
.open = netlink_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
int netlink_register_notifier(struct notifier_block *nb)
{
return atomic_notifier_chain_register(&netlink_chain, nb);
}
EXPORT_SYMBOL(netlink_register_notifier);
int netlink_unregister_notifier(struct notifier_block *nb)
{
return atomic_notifier_chain_unregister(&netlink_chain, nb);
}
EXPORT_SYMBOL(netlink_unregister_notifier);
static const struct proto_ops netlink_ops = {
.family = PF_NETLINK,
.owner = THIS_MODULE,
.release = netlink_release,
.bind = netlink_bind,
.connect = netlink_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = netlink_getname,
.poll = datagram_poll,
.ioctl = sock_no_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = netlink_setsockopt,
.getsockopt = netlink_getsockopt,
.sendmsg = netlink_sendmsg,
.recvmsg = netlink_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static const struct net_proto_family netlink_family_ops = {
.family = PF_NETLINK,
.create = netlink_create,
.owner = THIS_MODULE, /* for consistency 8) */
};
static int __net_init netlink_net_init(struct net *net)
{
#ifdef CONFIG_PROC_FS
if (!proc_net_fops_create(net, "netlink", 0, &netlink_seq_fops))
return -ENOMEM;
#endif
return 0;
}
static void __net_exit netlink_net_exit(struct net *net)
{
#ifdef CONFIG_PROC_FS
proc_net_remove(net, "netlink");
#endif
}
static void __init netlink_add_usersock_entry(void)
{
struct listeners *listeners;
int groups = 32;
listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
if (!listeners)
panic("netlink_add_usersock_entry: Cannot allocate listeners\n");
netlink_table_grab();
nl_table[NETLINK_USERSOCK].groups = groups;
rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners);
nl_table[NETLINK_USERSOCK].module = THIS_MODULE;
nl_table[NETLINK_USERSOCK].registered = 1;
netlink_table_ungrab();
}
static struct pernet_operations __net_initdata netlink_net_ops = {
.init = netlink_net_init,
.exit = netlink_net_exit,
};
static int __init netlink_proto_init(void)
{
struct sk_buff *dummy_skb;
int i;
unsigned long limit;
unsigned int order;
int err = proto_register(&netlink_proto, 0);
if (err != 0)
goto out;
BUILD_BUG_ON(sizeof(struct netlink_skb_parms) > sizeof(dummy_skb->cb));
nl_table = kcalloc(MAX_LINKS, sizeof(*nl_table), GFP_KERNEL);
if (!nl_table)
goto panic;
if (totalram_pages >= (128 * 1024))
limit = totalram_pages >> (21 - PAGE_SHIFT);
else
limit = totalram_pages >> (23 - PAGE_SHIFT);
order = get_bitmask_order(limit) - 1 + PAGE_SHIFT;
limit = (1UL << order) / sizeof(struct hlist_head);
order = get_bitmask_order(min(limit, (unsigned long)UINT_MAX)) - 1;
for (i = 0; i < MAX_LINKS; i++) {
struct nl_pid_hash *hash = &nl_table[i].hash;
hash->table = nl_pid_hash_zalloc(1 * sizeof(*hash->table));
if (!hash->table) {
while (i-- > 0)
nl_pid_hash_free(nl_table[i].hash.table,
1 * sizeof(*hash->table));
kfree(nl_table);
goto panic;
}
hash->max_shift = order;
hash->shift = 0;
hash->mask = 0;
hash->rehash_time = jiffies;
}
netlink_add_usersock_entry();
sock_register(&netlink_family_ops);
register_pernet_subsys(&netlink_net_ops);
/* The netlink device handler may be needed early. */
rtnetlink_init();
out:
return err;
panic:
panic("netlink_init: Cannot allocate nl_table\n");
}
core_initcall(netlink_proto_init);
| ./CrossVul/dataset_final_sorted/CWE-287/c/bad_3721_1 |
crossvul-cpp_data_good_2757_1 | /*
* X.509 certificate parsing and verification
*
* 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)
*/
/*
* The ITU-T X.509 standard defines a certificate format for PKI.
*
* http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs)
* http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs)
* http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10)
*
* http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf
* http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_X509_CRT_PARSE_C)
#include "mbedtls/x509_crt.h"
#include "mbedtls/oid.h"
#include <stdio.h>
#include <string.h>
#if defined(MBEDTLS_PEM_PARSE_C)
#include "mbedtls/pem.h"
#endif
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#define mbedtls_free free
#define mbedtls_calloc calloc
#define mbedtls_snprintf snprintf
#endif
#if defined(MBEDTLS_THREADING_C)
#include "mbedtls/threading.h"
#endif
#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
#include <windows.h>
#else
#include <time.h>
#endif
#if defined(MBEDTLS_FS_IO)
#include <stdio.h>
#if !defined(_WIN32) || defined(EFIX64) || defined(EFI32)
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#endif /* !_WIN32 || EFIX64 || EFI32 */
#endif
/* 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;
}
/*
* Default profile
*/
const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default =
{
#if defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES)
/* Allow SHA-1 (weak, but still safe in controlled environments) */
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA1 ) |
#endif
/* Only SHA-2 hashes */
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
0xFFFFFFF, /* Any PK alg */
0xFFFFFFF, /* Any curve */
2048,
};
/*
* Next-default profile
*/
const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next =
{
/* Hashes from SHA-256 and above */
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA512 ),
0xFFFFFFF, /* Any PK alg */
#if defined(MBEDTLS_ECP_C)
/* Curves at or above 128-bit security level */
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP521R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP256R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP384R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_BP512R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256K1 ),
#else
0,
#endif
2048,
};
/*
* NSA Suite B Profile
*/
const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb =
{
/* Only SHA-256 and 384 */
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ),
/* Only ECDSA */
MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECDSA ),
#if defined(MBEDTLS_ECP_C)
/* Only NIST P-256 and P-384 */
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP384R1 ),
#else
0,
#endif
0,
};
/*
* Check md_alg against profile
* Return 0 if md_alg acceptable for this profile, -1 otherwise
*/
static int x509_profile_check_md_alg( const mbedtls_x509_crt_profile *profile,
mbedtls_md_type_t md_alg )
{
if( ( profile->allowed_mds & MBEDTLS_X509_ID_FLAG( md_alg ) ) != 0 )
return( 0 );
return( -1 );
}
/*
* Check pk_alg against profile
* Return 0 if pk_alg acceptable for this profile, -1 otherwise
*/
static int x509_profile_check_pk_alg( const mbedtls_x509_crt_profile *profile,
mbedtls_pk_type_t pk_alg )
{
if( ( profile->allowed_pks & MBEDTLS_X509_ID_FLAG( pk_alg ) ) != 0 )
return( 0 );
return( -1 );
}
/*
* Check key against profile
* Return 0 if pk_alg acceptable for this profile, -1 otherwise
*/
static int x509_profile_check_key( const mbedtls_x509_crt_profile *profile,
mbedtls_pk_type_t pk_alg,
const mbedtls_pk_context *pk )
{
#if defined(MBEDTLS_RSA_C)
if( pk_alg == MBEDTLS_PK_RSA || pk_alg == MBEDTLS_PK_RSASSA_PSS )
{
if( mbedtls_pk_get_bitlen( pk ) >= profile->rsa_min_bitlen )
return( 0 );
return( -1 );
}
#endif
#if defined(MBEDTLS_ECP_C)
if( pk_alg == MBEDTLS_PK_ECDSA ||
pk_alg == MBEDTLS_PK_ECKEY ||
pk_alg == MBEDTLS_PK_ECKEY_DH )
{
mbedtls_ecp_group_id gid = mbedtls_pk_ec( *pk )->grp.id;
if( ( profile->allowed_curves & MBEDTLS_X509_ID_FLAG( gid ) ) != 0 )
return( 0 );
return( -1 );
}
#endif
return( -1 );
}
/*
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
*/
static int x509_get_version( unsigned char **p,
const unsigned char *end,
int *ver )
{
int ret;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
{
*ver = 0;
return( 0 );
}
return( ret );
}
end = *p + len;
if( ( ret = mbedtls_asn1_get_int( p, end, ver ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_VERSION + ret );
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_VERSION +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
/*
* Validity ::= SEQUENCE {
* notBefore Time,
* notAfter Time }
*/
static int x509_get_dates( unsigned char **p,
const unsigned char *end,
mbedtls_x509_time *from,
mbedtls_x509_time *to )
{
int ret;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_DATE + ret );
end = *p + len;
if( ( ret = mbedtls_x509_get_time( p, end, from ) ) != 0 )
return( ret );
if( ( ret = mbedtls_x509_get_time( p, end, to ) ) != 0 )
return( ret );
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_DATE +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
/*
* X.509 v2/v3 unique identifier (not parsed)
*/
static int x509_get_uid( unsigned char **p,
const unsigned char *end,
mbedtls_x509_buf *uid, int n )
{
int ret;
if( *p == end )
return( 0 );
uid->tag = **p;
if( ( ret = mbedtls_asn1_get_tag( p, end, &uid->len,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | n ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
return( 0 );
return( ret );
}
uid->p = *p;
*p += uid->len;
return( 0 );
}
static int x509_get_basic_constraints( unsigned char **p,
const unsigned char *end,
int *ca_istrue,
int *max_pathlen )
{
int ret;
size_t len;
/*
* BasicConstraints ::= SEQUENCE {
* cA BOOLEAN DEFAULT FALSE,
* pathLenConstraint INTEGER (0..MAX) OPTIONAL }
*/
*ca_istrue = 0; /* DEFAULT FALSE */
*max_pathlen = 0; /* endless */
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( *p == end )
return( 0 );
if( ( ret = mbedtls_asn1_get_bool( p, end, ca_istrue ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
ret = mbedtls_asn1_get_int( p, end, ca_istrue );
if( ret != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( *ca_istrue != 0 )
*ca_istrue = 1;
}
if( *p == end )
return( 0 );
if( ( ret = mbedtls_asn1_get_int( p, end, max_pathlen ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
(*max_pathlen)++;
return( 0 );
}
static int x509_get_ns_cert_type( unsigned char **p,
const unsigned char *end,
unsigned char *ns_cert_type)
{
int ret;
mbedtls_x509_bitstring bs = { 0, 0, NULL };
if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( bs.len != 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_INVALID_LENGTH );
/* Get actual bitstring */
*ns_cert_type = *bs.p;
return( 0 );
}
static int x509_get_key_usage( unsigned char **p,
const unsigned char *end,
unsigned int *key_usage)
{
int ret;
size_t i;
mbedtls_x509_bitstring bs = { 0, 0, NULL };
if( ( ret = mbedtls_asn1_get_bitstring( p, end, &bs ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( bs.len < 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_INVALID_LENGTH );
/* Get actual bitstring */
*key_usage = 0;
for( i = 0; i < bs.len && i < sizeof( unsigned int ); i++ )
{
*key_usage |= (unsigned int) bs.p[i] << (8*i);
}
return( 0 );
}
/*
* ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
*
* KeyPurposeId ::= OBJECT IDENTIFIER
*/
static int x509_get_ext_key_usage( unsigned char **p,
const unsigned char *end,
mbedtls_x509_sequence *ext_key_usage)
{
int ret;
if( ( ret = mbedtls_asn1_get_sequence_of( p, end, ext_key_usage, MBEDTLS_ASN1_OID ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
/* Sequence length must be >= 1 */
if( ext_key_usage->buf.p == NULL )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_INVALID_LENGTH );
return( 0 );
}
/*
* SubjectAltName ::= GeneralNames
*
* GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
*
* GeneralName ::= CHOICE {
* otherName [0] OtherName,
* rfc822Name [1] IA5String,
* dNSName [2] IA5String,
* x400Address [3] ORAddress,
* directoryName [4] Name,
* ediPartyName [5] EDIPartyName,
* uniformResourceIdentifier [6] IA5String,
* iPAddress [7] OCTET STRING,
* registeredID [8] OBJECT IDENTIFIER }
*
* OtherName ::= SEQUENCE {
* type-id OBJECT IDENTIFIER,
* value [0] EXPLICIT ANY DEFINED BY type-id }
*
* EDIPartyName ::= SEQUENCE {
* nameAssigner [0] DirectoryString OPTIONAL,
* partyName [1] DirectoryString }
*
* NOTE: we only parse and use dNSName at this point.
*/
static int x509_get_subject_alt_name( unsigned char **p,
const unsigned char *end,
mbedtls_x509_sequence *subject_alt_name )
{
int ret;
size_t len, tag_len;
mbedtls_asn1_buf *buf;
unsigned char tag;
mbedtls_asn1_sequence *cur = subject_alt_name;
/* Get main sequence tag */
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( *p + len != end )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
while( *p < end )
{
if( ( end - *p ) < 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_OUT_OF_DATA );
tag = **p;
(*p)++;
if( ( ret = mbedtls_asn1_get_len( p, end, &tag_len ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( ( tag & MBEDTLS_ASN1_CONTEXT_SPECIFIC ) != MBEDTLS_ASN1_CONTEXT_SPECIFIC )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
/* Skip everything but DNS name */
if( tag != ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2 ) )
{
*p += tag_len;
continue;
}
/* Allocate and assign next pointer */
if( cur->buf.p != NULL )
{
if( cur->next != NULL )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
cur->next = mbedtls_calloc( 1, sizeof( mbedtls_asn1_sequence ) );
if( cur->next == NULL )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_ALLOC_FAILED );
cur = cur->next;
}
buf = &(cur->buf);
buf->tag = tag;
buf->p = *p;
buf->len = tag_len;
*p += buf->len;
}
/* Set final sequence entry's next pointer to NULL */
cur->next = NULL;
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
/*
* X.509 v3 extensions
*
*/
static int x509_get_crt_ext( unsigned char **p,
const unsigned char *end,
mbedtls_x509_crt *crt )
{
int ret;
size_t len;
unsigned char *end_ext_data, *end_ext_octet;
if( ( ret = mbedtls_x509_get_ext( p, end, &crt->v3_ext, 3 ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
return( 0 );
return( ret );
}
while( *p < end )
{
/*
* Extension ::= SEQUENCE {
* extnID OBJECT IDENTIFIER,
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING }
*/
mbedtls_x509_buf extn_oid = {0, 0, NULL};
int is_critical = 0; /* DEFAULT FALSE */
int ext_type = 0;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
end_ext_data = *p + len;
/* Get extension ID */
extn_oid.tag = **p;
if( ( ret = mbedtls_asn1_get_tag( p, end, &extn_oid.len, MBEDTLS_ASN1_OID ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
extn_oid.p = *p;
*p += extn_oid.len;
if( ( end - *p ) < 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_OUT_OF_DATA );
/* Get optional critical */
if( ( ret = mbedtls_asn1_get_bool( p, end_ext_data, &is_critical ) ) != 0 &&
( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
/* Data should be octet string type */
if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len,
MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
end_ext_octet = *p + len;
if( end_ext_octet != end_ext_data )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
/*
* Detect supported extensions
*/
ret = mbedtls_oid_get_x509_ext_type( &extn_oid, &ext_type );
if( ret != 0 )
{
/* No parser found, skip extension */
*p = end_ext_octet;
#if !defined(MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION)
if( is_critical )
{
/* Data is marked as critical: fail */
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
}
#endif
continue;
}
/* Forbid repeated extensions */
if( ( crt->ext_types & ext_type ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS );
crt->ext_types |= ext_type;
switch( ext_type )
{
case MBEDTLS_X509_EXT_BASIC_CONSTRAINTS:
/* Parse basic constraints */
if( ( ret = x509_get_basic_constraints( p, end_ext_octet,
&crt->ca_istrue, &crt->max_pathlen ) ) != 0 )
return( ret );
break;
case MBEDTLS_X509_EXT_KEY_USAGE:
/* Parse key usage */
if( ( ret = x509_get_key_usage( p, end_ext_octet,
&crt->key_usage ) ) != 0 )
return( ret );
break;
case MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE:
/* Parse extended key usage */
if( ( ret = x509_get_ext_key_usage( p, end_ext_octet,
&crt->ext_key_usage ) ) != 0 )
return( ret );
break;
case MBEDTLS_X509_EXT_SUBJECT_ALT_NAME:
/* Parse subject alt name */
if( ( ret = x509_get_subject_alt_name( p, end_ext_octet,
&crt->subject_alt_names ) ) != 0 )
return( ret );
break;
case MBEDTLS_X509_EXT_NS_CERT_TYPE:
/* Parse netscape certificate type */
if( ( ret = x509_get_ns_cert_type( p, end_ext_octet,
&crt->ns_cert_type ) ) != 0 )
return( ret );
break;
default:
return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE );
}
}
if( *p != end )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
return( 0 );
}
/*
* Parse and fill a single X.509 certificate in DER format
*/
static int x509_crt_parse_der_core( mbedtls_x509_crt *crt, const unsigned char *buf,
size_t buflen )
{
int ret;
size_t len;
unsigned char *p, *end, *crt_end;
mbedtls_x509_buf sig_params1, sig_params2, sig_oid2;
memset( &sig_params1, 0, sizeof( mbedtls_x509_buf ) );
memset( &sig_params2, 0, sizeof( mbedtls_x509_buf ) );
memset( &sig_oid2, 0, sizeof( mbedtls_x509_buf ) );
/*
* Check for valid input
*/
if( crt == NULL || buf == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
// Use the original buffer until we figure out actual length
p = (unsigned char*) buf;
len = buflen;
end = p + len;
/*
* Certificate ::= SEQUENCE {
* tbsCertificate TBSCertificate,
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING }
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT );
}
if( len > (size_t) ( end - p ) )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
}
crt_end = p + len;
// Create and populate a new buffer for the raw field
crt->raw.len = crt_end - buf;
crt->raw.p = p = mbedtls_calloc( 1, crt->raw.len );
if( p == NULL )
return( MBEDTLS_ERR_X509_ALLOC_FAILED );
memcpy( p, buf, crt->raw.len );
// Direct pointers to the new buffer
p += crt->raw.len - len;
end = crt_end = p + len;
/*
* TBSCertificate ::= SEQUENCE {
*/
crt->tbs.p = p;
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
}
end = p + len;
crt->tbs.len = end - crt->tbs.p;
/*
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
*
* CertificateSerialNumber ::= INTEGER
*
* signature AlgorithmIdentifier
*/
if( ( ret = x509_get_version( &p, end, &crt->version ) ) != 0 ||
( ret = mbedtls_x509_get_serial( &p, end, &crt->serial ) ) != 0 ||
( ret = mbedtls_x509_get_alg( &p, end, &crt->sig_oid,
&sig_params1 ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
crt->version++;
if( crt->version > 3 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_UNKNOWN_VERSION );
}
if( ( ret = mbedtls_x509_get_sig_alg( &crt->sig_oid, &sig_params1,
&crt->sig_md, &crt->sig_pk,
&crt->sig_opts ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
/*
* issuer Name
*/
crt->issuer_raw.p = p;
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
}
if( ( ret = mbedtls_x509_get_name( &p, p + len, &crt->issuer ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
crt->issuer_raw.len = p - crt->issuer_raw.p;
/*
* Validity ::= SEQUENCE {
* notBefore Time,
* notAfter Time }
*
*/
if( ( ret = x509_get_dates( &p, end, &crt->valid_from,
&crt->valid_to ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
/*
* subject Name
*/
crt->subject_raw.p = p;
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT + ret );
}
if( len && ( ret = mbedtls_x509_get_name( &p, p + len, &crt->subject ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
crt->subject_raw.len = p - crt->subject_raw.p;
/*
* SubjectPublicKeyInfo
*/
if( ( ret = mbedtls_pk_parse_subpubkey( &p, end, &crt->pk ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
/*
* issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version shall be v2 or v3
* subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
* -- If present, version shall be v2 or v3
* extensions [3] EXPLICIT Extensions OPTIONAL
* -- If present, version shall be v3
*/
if( crt->version == 2 || crt->version == 3 )
{
ret = x509_get_uid( &p, end, &crt->issuer_id, 1 );
if( ret != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
}
if( crt->version == 2 || crt->version == 3 )
{
ret = x509_get_uid( &p, end, &crt->subject_id, 2 );
if( ret != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
}
#if !defined(MBEDTLS_X509_ALLOW_EXTENSIONS_NON_V3)
if( crt->version == 3 )
#endif
{
ret = x509_get_crt_ext( &p, end, crt );
if( ret != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
}
if( p != end )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
}
end = crt_end;
/*
* }
* -- end of TBSCertificate
*
* signatureAlgorithm AlgorithmIdentifier,
* signatureValue BIT STRING
*/
if( ( ret = mbedtls_x509_get_alg( &p, end, &sig_oid2, &sig_params2 ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
if( crt->sig_oid.len != sig_oid2.len ||
memcmp( crt->sig_oid.p, sig_oid2.p, crt->sig_oid.len ) != 0 ||
sig_params1.len != sig_params2.len ||
( sig_params1.len != 0 &&
memcmp( sig_params1.p, sig_params2.p, sig_params1.len ) != 0 ) )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_SIG_MISMATCH );
}
if( ( ret = mbedtls_x509_get_sig( &p, end, &crt->sig ) ) != 0 )
{
mbedtls_x509_crt_free( crt );
return( ret );
}
if( p != end )
{
mbedtls_x509_crt_free( crt );
return( MBEDTLS_ERR_X509_INVALID_FORMAT +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
}
return( 0 );
}
/*
* Parse one X.509 certificate in DER format from a buffer and add them to a
* chained list
*/
int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf,
size_t buflen )
{
int ret;
mbedtls_x509_crt *crt = chain, *prev = NULL;
/*
* Check for valid input
*/
if( crt == NULL || buf == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
while( crt->version != 0 && crt->next != NULL )
{
prev = crt;
crt = crt->next;
}
/*
* Add new certificate on the end of the chain if needed.
*/
if( crt->version != 0 && crt->next == NULL )
{
crt->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );
if( crt->next == NULL )
return( MBEDTLS_ERR_X509_ALLOC_FAILED );
prev = crt;
mbedtls_x509_crt_init( crt->next );
crt = crt->next;
}
if( ( ret = x509_crt_parse_der_core( crt, buf, buflen ) ) != 0 )
{
if( prev )
prev->next = NULL;
if( crt != chain )
mbedtls_free( crt );
return( ret );
}
return( 0 );
}
/*
* Parse one or more PEM certificates from a buffer and add them to the chained
* list
*/
int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen )
{
#if defined(MBEDTLS_PEM_PARSE_C)
int success = 0, first_error = 0, total_failed = 0;
int buf_format = MBEDTLS_X509_FORMAT_DER;
#endif
/*
* Check for valid input
*/
if( chain == NULL || buf == NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
/*
* Determine buffer content. Buffer contains either one DER certificate or
* one or more PEM certificates.
*/
#if defined(MBEDTLS_PEM_PARSE_C)
if( buflen != 0 && buf[buflen - 1] == '\0' &&
strstr( (const char *) buf, "-----BEGIN CERTIFICATE-----" ) != NULL )
{
buf_format = MBEDTLS_X509_FORMAT_PEM;
}
if( buf_format == MBEDTLS_X509_FORMAT_DER )
return mbedtls_x509_crt_parse_der( chain, buf, buflen );
#else
return mbedtls_x509_crt_parse_der( chain, buf, buflen );
#endif
#if defined(MBEDTLS_PEM_PARSE_C)
if( buf_format == MBEDTLS_X509_FORMAT_PEM )
{
int ret;
mbedtls_pem_context pem;
/* 1 rather than 0 since the terminating NULL byte is counted in */
while( buflen > 1 )
{
size_t use_len;
mbedtls_pem_init( &pem );
/* If we get there, we know the string is null-terminated */
ret = mbedtls_pem_read_buffer( &pem,
"-----BEGIN CERTIFICATE-----",
"-----END CERTIFICATE-----",
buf, NULL, 0, &use_len );
if( ret == 0 )
{
/*
* Was PEM encoded
*/
buflen -= use_len;
buf += use_len;
}
else if( ret == MBEDTLS_ERR_PEM_BAD_INPUT_DATA )
{
return( ret );
}
else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
{
mbedtls_pem_free( &pem );
/*
* PEM header and footer were found
*/
buflen -= use_len;
buf += use_len;
if( first_error == 0 )
first_error = ret;
total_failed++;
continue;
}
else
break;
ret = mbedtls_x509_crt_parse_der( chain, pem.buf, pem.buflen );
mbedtls_pem_free( &pem );
if( ret != 0 )
{
/*
* Quit parsing on a memory error
*/
if( ret == MBEDTLS_ERR_X509_ALLOC_FAILED )
return( ret );
if( first_error == 0 )
first_error = ret;
total_failed++;
continue;
}
success = 1;
}
}
if( success )
return( total_failed );
else if( first_error )
return( first_error );
else
return( MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT );
#endif /* MBEDTLS_PEM_PARSE_C */
}
#if defined(MBEDTLS_FS_IO)
/*
* Load one or more certificates and add them to the chained list
*/
int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path )
{
int ret;
size_t n;
unsigned char *buf;
if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )
return( ret );
ret = mbedtls_x509_crt_parse( chain, buf, n );
mbedtls_zeroize( buf, n );
mbedtls_free( buf );
return( ret );
}
int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path )
{
int ret = 0;
#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
int w_ret;
WCHAR szDir[MAX_PATH];
char filename[MAX_PATH];
char *p;
size_t len = strlen( path );
WIN32_FIND_DATAW file_data;
HANDLE hFind;
if( len > MAX_PATH - 3 )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
memset( szDir, 0, sizeof(szDir) );
memset( filename, 0, MAX_PATH );
memcpy( filename, path, len );
filename[len++] = '\\';
p = filename + len;
filename[len++] = '*';
w_ret = MultiByteToWideChar( CP_ACP, 0, filename, (int)len, szDir,
MAX_PATH - 3 );
if( w_ret == 0 )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
hFind = FindFirstFileW( szDir, &file_data );
if( hFind == INVALID_HANDLE_VALUE )
return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
len = MAX_PATH - len;
do
{
memset( p, 0, len );
if( file_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
continue;
w_ret = WideCharToMultiByte( CP_ACP, 0, file_data.cFileName,
lstrlenW( file_data.cFileName ),
p, (int) len - 1,
NULL, NULL );
if( w_ret == 0 )
return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
w_ret = mbedtls_x509_crt_parse_file( chain, filename );
if( w_ret < 0 )
ret++;
else
ret += w_ret;
}
while( FindNextFileW( hFind, &file_data ) != 0 );
if( GetLastError() != ERROR_NO_MORE_FILES )
ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
FindClose( hFind );
#else /* _WIN32 */
int t_ret;
int snp_ret;
struct stat sb;
struct dirent *entry;
char entry_name[MBEDTLS_X509_MAX_FILE_PATH_LEN];
DIR *dir = opendir( path );
if( dir == NULL )
return( MBEDTLS_ERR_X509_FILE_IO_ERROR );
#if defined(MBEDTLS_THREADING_PTHREAD)
if( ( ret = mbedtls_mutex_lock( &mbedtls_threading_readdir_mutex ) ) != 0 )
{
closedir( dir );
return( ret );
}
#endif
while( ( entry = readdir( dir ) ) != NULL )
{
snp_ret = mbedtls_snprintf( entry_name, sizeof entry_name,
"%s/%s", path, entry->d_name );
if( snp_ret < 0 || (size_t)snp_ret >= sizeof entry_name )
{
ret = MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
goto cleanup;
}
else if( stat( entry_name, &sb ) == -1 )
{
ret = MBEDTLS_ERR_X509_FILE_IO_ERROR;
goto cleanup;
}
if( !S_ISREG( sb.st_mode ) )
continue;
// Ignore parse errors
//
t_ret = mbedtls_x509_crt_parse_file( chain, entry_name );
if( t_ret < 0 )
ret++;
else
ret += t_ret;
}
cleanup:
closedir( dir );
#if defined(MBEDTLS_THREADING_PTHREAD)
if( mbedtls_mutex_unlock( &mbedtls_threading_readdir_mutex ) != 0 )
ret = MBEDTLS_ERR_THREADING_MUTEX_ERROR;
#endif
#endif /* _WIN32 */
return( ret );
}
#endif /* MBEDTLS_FS_IO */
static int x509_info_subject_alt_name( char **buf, size_t *size,
const mbedtls_x509_sequence *subject_alt_name )
{
size_t i;
size_t n = *size;
char *p = *buf;
const mbedtls_x509_sequence *cur = subject_alt_name;
const char *sep = "";
size_t sep_len = 0;
while( cur != NULL )
{
if( cur->buf.len + sep_len >= n )
{
*p = '\0';
return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL );
}
n -= cur->buf.len + sep_len;
for( i = 0; i < sep_len; i++ )
*p++ = sep[i];
for( i = 0; i < cur->buf.len; i++ )
*p++ = cur->buf.p[i];
sep = ", ";
sep_len = 2;
cur = cur->next;
}
*p = '\0';
*size = n;
*buf = p;
return( 0 );
}
#define PRINT_ITEM(i) \
{ \
ret = mbedtls_snprintf( p, n, "%s" i, sep ); \
MBEDTLS_X509_SAFE_SNPRINTF; \
sep = ", "; \
}
#define CERT_TYPE(type,name) \
if( ns_cert_type & type ) \
PRINT_ITEM( name );
static int x509_info_cert_type( char **buf, size_t *size,
unsigned char ns_cert_type )
{
int ret;
size_t n = *size;
char *p = *buf;
const char *sep = "";
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT, "SSL Client" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER, "SSL Server" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL, "Email" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING, "Object Signing" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_RESERVED, "Reserved" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_SSL_CA, "SSL CA" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA, "Email CA" );
CERT_TYPE( MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA, "Object Signing CA" );
*size = n;
*buf = p;
return( 0 );
}
#define KEY_USAGE(code,name) \
if( key_usage & code ) \
PRINT_ITEM( name );
static int x509_info_key_usage( char **buf, size_t *size,
unsigned int key_usage )
{
int ret;
size_t n = *size;
char *p = *buf;
const char *sep = "";
KEY_USAGE( MBEDTLS_X509_KU_DIGITAL_SIGNATURE, "Digital Signature" );
KEY_USAGE( MBEDTLS_X509_KU_NON_REPUDIATION, "Non Repudiation" );
KEY_USAGE( MBEDTLS_X509_KU_KEY_ENCIPHERMENT, "Key Encipherment" );
KEY_USAGE( MBEDTLS_X509_KU_DATA_ENCIPHERMENT, "Data Encipherment" );
KEY_USAGE( MBEDTLS_X509_KU_KEY_AGREEMENT, "Key Agreement" );
KEY_USAGE( MBEDTLS_X509_KU_KEY_CERT_SIGN, "Key Cert Sign" );
KEY_USAGE( MBEDTLS_X509_KU_CRL_SIGN, "CRL Sign" );
KEY_USAGE( MBEDTLS_X509_KU_ENCIPHER_ONLY, "Encipher Only" );
KEY_USAGE( MBEDTLS_X509_KU_DECIPHER_ONLY, "Decipher Only" );
*size = n;
*buf = p;
return( 0 );
}
static int x509_info_ext_key_usage( char **buf, size_t *size,
const mbedtls_x509_sequence *extended_key_usage )
{
int ret;
const char *desc;
size_t n = *size;
char *p = *buf;
const mbedtls_x509_sequence *cur = extended_key_usage;
const char *sep = "";
while( cur != NULL )
{
if( mbedtls_oid_get_extended_key_usage( &cur->buf, &desc ) != 0 )
desc = "???";
ret = mbedtls_snprintf( p, n, "%s%s", sep, desc );
MBEDTLS_X509_SAFE_SNPRINTF;
sep = ", ";
cur = cur->next;
}
*size = n;
*buf = p;
return( 0 );
}
/*
* Return an informational string about the certificate.
*/
#define BEFORE_COLON 18
#define BC "18"
int mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix,
const mbedtls_x509_crt *crt )
{
int ret;
size_t n;
char *p;
char key_size_str[BEFORE_COLON];
p = buf;
n = size;
if( NULL == crt )
{
ret = mbedtls_snprintf( p, n, "\nCertificate is uninitialised!\n" );
MBEDTLS_X509_SAFE_SNPRINTF;
return( (int) ( size - n ) );
}
ret = mbedtls_snprintf( p, n, "%scert. version : %d\n",
prefix, crt->version );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "%sserial number : ",
prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_serial_gets( p, n, &crt->serial );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%sissuer name : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_dn_gets( p, n, &crt->issuer );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%ssubject name : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_dn_gets( p, n, &crt->subject );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%sissued on : " \
"%04d-%02d-%02d %02d:%02d:%02d", prefix,
crt->valid_from.year, crt->valid_from.mon,
crt->valid_from.day, crt->valid_from.hour,
crt->valid_from.min, crt->valid_from.sec );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%sexpires on : " \
"%04d-%02d-%02d %02d:%02d:%02d", prefix,
crt->valid_to.year, crt->valid_to.mon,
crt->valid_to.day, crt->valid_to.hour,
crt->valid_to.min, crt->valid_to.sec );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_snprintf( p, n, "\n%ssigned using : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
ret = mbedtls_x509_sig_alg_gets( p, n, &crt->sig_oid, crt->sig_pk,
crt->sig_md, crt->sig_opts );
MBEDTLS_X509_SAFE_SNPRINTF;
/* Key size */
if( ( ret = mbedtls_x509_key_size_helper( key_size_str, BEFORE_COLON,
mbedtls_pk_get_name( &crt->pk ) ) ) != 0 )
{
return( ret );
}
ret = mbedtls_snprintf( p, n, "\n%s%-" BC "s: %d bits", prefix, key_size_str,
(int) mbedtls_pk_get_bitlen( &crt->pk ) );
MBEDTLS_X509_SAFE_SNPRINTF;
/*
* Optional extensions
*/
if( crt->ext_types & MBEDTLS_X509_EXT_BASIC_CONSTRAINTS )
{
ret = mbedtls_snprintf( p, n, "\n%sbasic constraints : CA=%s", prefix,
crt->ca_istrue ? "true" : "false" );
MBEDTLS_X509_SAFE_SNPRINTF;
if( crt->max_pathlen > 0 )
{
ret = mbedtls_snprintf( p, n, ", max_pathlen=%d", crt->max_pathlen - 1 );
MBEDTLS_X509_SAFE_SNPRINTF;
}
}
if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
{
ret = mbedtls_snprintf( p, n, "\n%ssubject alt name : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
if( ( ret = x509_info_subject_alt_name( &p, &n,
&crt->subject_alt_names ) ) != 0 )
return( ret );
}
if( crt->ext_types & MBEDTLS_X509_EXT_NS_CERT_TYPE )
{
ret = mbedtls_snprintf( p, n, "\n%scert. type : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
if( ( ret = x509_info_cert_type( &p, &n, crt->ns_cert_type ) ) != 0 )
return( ret );
}
if( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE )
{
ret = mbedtls_snprintf( p, n, "\n%skey usage : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
if( ( ret = x509_info_key_usage( &p, &n, crt->key_usage ) ) != 0 )
return( ret );
}
if( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE )
{
ret = mbedtls_snprintf( p, n, "\n%sext key usage : ", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
if( ( ret = x509_info_ext_key_usage( &p, &n,
&crt->ext_key_usage ) ) != 0 )
return( ret );
}
ret = mbedtls_snprintf( p, n, "\n" );
MBEDTLS_X509_SAFE_SNPRINTF;
return( (int) ( size - n ) );
}
struct x509_crt_verify_string {
int code;
const char *string;
};
static const struct x509_crt_verify_string x509_crt_verify_strings[] = {
{ MBEDTLS_X509_BADCERT_EXPIRED, "The certificate validity has expired" },
{ MBEDTLS_X509_BADCERT_REVOKED, "The certificate has been revoked (is on a CRL)" },
{ MBEDTLS_X509_BADCERT_CN_MISMATCH, "The certificate Common Name (CN) does not match with the expected CN" },
{ MBEDTLS_X509_BADCERT_NOT_TRUSTED, "The certificate is not correctly signed by the trusted CA" },
{ MBEDTLS_X509_BADCRL_NOT_TRUSTED, "The CRL is not correctly signed by the trusted CA" },
{ MBEDTLS_X509_BADCRL_EXPIRED, "The CRL is expired" },
{ MBEDTLS_X509_BADCERT_MISSING, "Certificate was missing" },
{ MBEDTLS_X509_BADCERT_SKIP_VERIFY, "Certificate verification was skipped" },
{ MBEDTLS_X509_BADCERT_OTHER, "Other reason (can be used by verify callback)" },
{ MBEDTLS_X509_BADCERT_FUTURE, "The certificate validity starts in the future" },
{ MBEDTLS_X509_BADCRL_FUTURE, "The CRL is from the future" },
{ MBEDTLS_X509_BADCERT_KEY_USAGE, "Usage does not match the keyUsage extension" },
{ MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, "Usage does not match the extendedKeyUsage extension" },
{ MBEDTLS_X509_BADCERT_NS_CERT_TYPE, "Usage does not match the nsCertType extension" },
{ MBEDTLS_X509_BADCERT_BAD_MD, "The certificate is signed with an unacceptable hash." },
{ MBEDTLS_X509_BADCERT_BAD_PK, "The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA)." },
{ MBEDTLS_X509_BADCERT_BAD_KEY, "The certificate is signed with an unacceptable key (eg bad curve, RSA too short)." },
{ MBEDTLS_X509_BADCRL_BAD_MD, "The CRL is signed with an unacceptable hash." },
{ MBEDTLS_X509_BADCRL_BAD_PK, "The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA)." },
{ MBEDTLS_X509_BADCRL_BAD_KEY, "The CRL is signed with an unacceptable key (eg bad curve, RSA too short)." },
{ 0, NULL }
};
int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
uint32_t flags )
{
int ret;
const struct x509_crt_verify_string *cur;
char *p = buf;
size_t n = size;
for( cur = x509_crt_verify_strings; cur->string != NULL ; cur++ )
{
if( ( flags & cur->code ) == 0 )
continue;
ret = mbedtls_snprintf( p, n, "%s%s\n", prefix, cur->string );
MBEDTLS_X509_SAFE_SNPRINTF;
flags ^= cur->code;
}
if( flags != 0 )
{
ret = mbedtls_snprintf( p, n, "%sUnknown reason "
"(this should not happen)\n", prefix );
MBEDTLS_X509_SAFE_SNPRINTF;
}
return( (int) ( size - n ) );
}
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
unsigned int usage )
{
unsigned int usage_must, usage_may;
unsigned int may_mask = MBEDTLS_X509_KU_ENCIPHER_ONLY
| MBEDTLS_X509_KU_DECIPHER_ONLY;
if( ( crt->ext_types & MBEDTLS_X509_EXT_KEY_USAGE ) == 0 )
return( 0 );
usage_must = usage & ~may_mask;
if( ( ( crt->key_usage & ~may_mask ) & usage_must ) != usage_must )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
usage_may = usage & may_mask;
if( ( ( crt->key_usage & may_mask ) | usage_may ) != usage_may )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
return( 0 );
}
#endif
#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,
const char *usage_oid,
size_t usage_len )
{
const mbedtls_x509_sequence *cur;
/* Extension is not mandatory, absent means no restriction */
if( ( crt->ext_types & MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE ) == 0 )
return( 0 );
/*
* Look for the requested usage (or wildcard ANY) in our list
*/
for( cur = &crt->ext_key_usage; cur != NULL; cur = cur->next )
{
const mbedtls_x509_buf *cur_oid = &cur->buf;
if( cur_oid->len == usage_len &&
memcmp( cur_oid->p, usage_oid, usage_len ) == 0 )
{
return( 0 );
}
if( MBEDTLS_OID_CMP( MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE, cur_oid ) == 0 )
return( 0 );
}
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
}
#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
#if defined(MBEDTLS_X509_CRL_PARSE_C)
/*
* Return 1 if the certificate is revoked, or 0 otherwise.
*/
int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl )
{
const mbedtls_x509_crl_entry *cur = &crl->entry;
while( cur != NULL && cur->serial.len != 0 )
{
if( crt->serial.len == cur->serial.len &&
memcmp( crt->serial.p, cur->serial.p, crt->serial.len ) == 0 )
{
if( mbedtls_x509_time_is_past( &cur->revocation_date ) )
return( 1 );
}
cur = cur->next;
}
return( 0 );
}
/*
* Check that the given certificate is not revoked according to the CRL.
* Skip validation is no CRL for the given CA is present.
*/
static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca,
mbedtls_x509_crl *crl_list,
const mbedtls_x509_crt_profile *profile )
{
int flags = 0;
unsigned char hash[MBEDTLS_MD_MAX_SIZE];
const mbedtls_md_info_t *md_info;
if( ca == NULL )
return( flags );
while( crl_list != NULL )
{
if( crl_list->version == 0 ||
crl_list->issuer_raw.len != ca->subject_raw.len ||
memcmp( crl_list->issuer_raw.p, ca->subject_raw.p,
crl_list->issuer_raw.len ) != 0 )
{
crl_list = crl_list->next;
continue;
}
/*
* Check if the CA is configured to sign CRLs
*/
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
if( mbedtls_x509_crt_check_key_usage( ca, MBEDTLS_X509_KU_CRL_SIGN ) != 0 )
{
flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
break;
}
#endif
/*
* Check if CRL is correctly signed by the trusted CA
*/
if( x509_profile_check_md_alg( profile, crl_list->sig_md ) != 0 )
flags |= MBEDTLS_X509_BADCRL_BAD_MD;
if( x509_profile_check_pk_alg( profile, crl_list->sig_pk ) != 0 )
flags |= MBEDTLS_X509_BADCRL_BAD_PK;
md_info = mbedtls_md_info_from_type( crl_list->sig_md );
if( md_info == NULL )
{
/*
* Cannot check 'unknown' hash
*/
flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
break;
}
mbedtls_md( md_info, crl_list->tbs.p, crl_list->tbs.len, hash );
if( x509_profile_check_key( profile, crl_list->sig_pk, &ca->pk ) != 0 )
flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
if( mbedtls_pk_verify_ext( crl_list->sig_pk, crl_list->sig_opts, &ca->pk,
crl_list->sig_md, hash, mbedtls_md_get_size( md_info ),
crl_list->sig.p, crl_list->sig.len ) != 0 )
{
flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
break;
}
/*
* Check for validity of CRL (Do not drop out)
*/
if( mbedtls_x509_time_is_past( &crl_list->next_update ) )
flags |= MBEDTLS_X509_BADCRL_EXPIRED;
if( mbedtls_x509_time_is_future( &crl_list->this_update ) )
flags |= MBEDTLS_X509_BADCRL_FUTURE;
/*
* Check if certificate is revoked
*/
if( mbedtls_x509_crt_is_revoked( crt, crl_list ) )
{
flags |= MBEDTLS_X509_BADCERT_REVOKED;
break;
}
crl_list = crl_list->next;
}
return( flags );
}
#endif /* MBEDTLS_X509_CRL_PARSE_C */
/*
* Like memcmp, but case-insensitive and always returns -1 if different
*/
static int x509_memcasecmp( const void *s1, const void *s2, size_t len )
{
size_t i;
unsigned char diff;
const unsigned char *n1 = s1, *n2 = s2;
for( i = 0; i < len; i++ )
{
diff = n1[i] ^ n2[i];
if( diff == 0 )
continue;
if( diff == 32 &&
( ( n1[i] >= 'a' && n1[i] <= 'z' ) ||
( n1[i] >= 'A' && n1[i] <= 'Z' ) ) )
{
continue;
}
return( -1 );
}
return( 0 );
}
/*
* Return 0 if name matches wildcard, -1 otherwise
*/
static int x509_check_wildcard( const char *cn, mbedtls_x509_buf *name )
{
size_t i;
size_t cn_idx = 0, cn_len = strlen( cn );
if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' )
return( 0 );
for( i = 0; i < cn_len; ++i )
{
if( cn[i] == '.' )
{
cn_idx = i;
break;
}
}
if( cn_idx == 0 )
return( -1 );
if( cn_len - cn_idx == name->len - 1 &&
x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )
{
return( 0 );
}
return( -1 );
}
/*
* Compare two X.509 strings, case-insensitive, and allowing for some encoding
* variations (but not all).
*
* Return 0 if equal, -1 otherwise.
*/
static int x509_string_cmp( const mbedtls_x509_buf *a, const mbedtls_x509_buf *b )
{
if( a->tag == b->tag &&
a->len == b->len &&
memcmp( a->p, b->p, b->len ) == 0 )
{
return( 0 );
}
if( ( a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
( b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
a->len == b->len &&
x509_memcasecmp( a->p, b->p, b->len ) == 0 )
{
return( 0 );
}
return( -1 );
}
/*
* Compare two X.509 Names (aka rdnSequence).
*
* See RFC 5280 section 7.1, though we don't implement the whole algorithm:
* we sometimes return unequal when the full algorithm would return equal,
* but never the other way. (In particular, we don't do Unicode normalisation
* or space folding.)
*
* Return 0 if equal, -1 otherwise.
*/
static int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b )
{
/* Avoid recursion, it might not be optimised by the compiler */
while( a != NULL || b != NULL )
{
if( a == NULL || b == NULL )
return( -1 );
/* type */
if( a->oid.tag != b->oid.tag ||
a->oid.len != b->oid.len ||
memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 )
{
return( -1 );
}
/* value */
if( x509_string_cmp( &a->val, &b->val ) != 0 )
return( -1 );
/* structure of the list of sets */
if( a->next_merged != b->next_merged )
return( -1 );
a = a->next;
b = b->next;
}
/* a == NULL == b */
return( 0 );
}
/*
* Check if 'parent' is a suitable parent (signing CA) for 'child'.
* Return 0 if yes, -1 if not.
*
* top means parent is a locally-trusted certificate
* bottom means child is the end entity cert
*/
static int x509_crt_check_parent( const mbedtls_x509_crt *child,
const mbedtls_x509_crt *parent,
int top, int bottom )
{
int need_ca_bit;
/* Parent must be the issuer */
if( x509_name_cmp( &child->issuer, &parent->subject ) != 0 )
return( -1 );
/* Parent must have the basicConstraints CA bit set as a general rule */
need_ca_bit = 1;
/* Exception: v1/v2 certificates that are locally trusted. */
if( top && parent->version < 3 )
need_ca_bit = 0;
/* Exception: self-signed end-entity certs that are locally trusted. */
if( top && bottom &&
child->raw.len == parent->raw.len &&
memcmp( child->raw.p, parent->raw.p, child->raw.len ) == 0 )
{
need_ca_bit = 0;
}
if( need_ca_bit && ! parent->ca_istrue )
return( -1 );
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
if( need_ca_bit &&
mbedtls_x509_crt_check_key_usage( parent, MBEDTLS_X509_KU_KEY_CERT_SIGN ) != 0 )
{
return( -1 );
}
#endif
return( 0 );
}
static int x509_crt_verify_top(
mbedtls_x509_crt *child, mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
int path_cnt, int self_cnt, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
int ret;
uint32_t ca_flags = 0;
int check_path_cnt;
unsigned char hash[MBEDTLS_MD_MAX_SIZE];
const mbedtls_md_info_t *md_info;
mbedtls_x509_crt *future_past_ca = NULL;
if( mbedtls_x509_time_is_past( &child->valid_to ) )
*flags |= MBEDTLS_X509_BADCERT_EXPIRED;
if( mbedtls_x509_time_is_future( &child->valid_from ) )
*flags |= MBEDTLS_X509_BADCERT_FUTURE;
if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_MD;
if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
/*
* Child is the top of the chain. Check against the trust_ca list.
*/
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
md_info = mbedtls_md_info_from_type( child->sig_md );
if( md_info == NULL )
{
/*
* Cannot check 'unknown', no need to try any CA
*/
trust_ca = NULL;
}
else
mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash );
for( /* trust_ca */ ; trust_ca != NULL; trust_ca = trust_ca->next )
{
if( x509_crt_check_parent( child, trust_ca, 1, path_cnt == 0 ) != 0 )
continue;
check_path_cnt = path_cnt + 1;
/*
* Reduce check_path_cnt to check against if top of the chain is
* the same as the trusted CA
*/
if( child->subject_raw.len == trust_ca->subject_raw.len &&
memcmp( child->subject_raw.p, trust_ca->subject_raw.p,
child->issuer_raw.len ) == 0 )
{
check_path_cnt--;
}
/* Self signed certificates do not count towards the limit */
if( trust_ca->max_pathlen > 0 &&
trust_ca->max_pathlen < check_path_cnt - self_cnt )
{
continue;
}
if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &trust_ca->pk,
child->sig_md, hash, mbedtls_md_get_size( md_info ),
child->sig.p, child->sig.len ) != 0 )
{
continue;
}
if( mbedtls_x509_time_is_past( &trust_ca->valid_to ) ||
mbedtls_x509_time_is_future( &trust_ca->valid_from ) )
{
if ( future_past_ca == NULL )
future_past_ca = trust_ca;
continue;
}
break;
}
if( trust_ca != NULL || ( trust_ca = future_past_ca ) != NULL )
{
/*
* Top of chain is signed by a trusted CA
*/
*flags &= ~MBEDTLS_X509_BADCERT_NOT_TRUSTED;
if( x509_profile_check_key( profile, child->sig_pk, &trust_ca->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
}
/*
* If top of chain is not the same as the trusted CA send a verify request
* to the callback for any issues with validity and CRL presence for the
* trusted CA certificate.
*/
if( trust_ca != NULL &&
( child->subject_raw.len != trust_ca->subject_raw.len ||
memcmp( child->subject_raw.p, trust_ca->subject_raw.p,
child->issuer_raw.len ) != 0 ) )
{
#if defined(MBEDTLS_X509_CRL_PARSE_C)
/* Check trusted CA's CRL for the chain's top crt */
*flags |= x509_crt_verifycrl( child, trust_ca, ca_crl, profile );
#else
((void) ca_crl);
#endif
if( mbedtls_x509_time_is_past( &trust_ca->valid_to ) )
ca_flags |= MBEDTLS_X509_BADCERT_EXPIRED;
if( mbedtls_x509_time_is_future( &trust_ca->valid_from ) )
ca_flags |= MBEDTLS_X509_BADCERT_FUTURE;
if( NULL != f_vrfy )
{
if( ( ret = f_vrfy( p_vrfy, trust_ca, path_cnt + 1,
&ca_flags ) ) != 0 )
{
return( ret );
}
}
}
/* Call callback on top cert */
if( NULL != f_vrfy )
{
if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 )
return( ret );
}
*flags |= ca_flags;
return( 0 );
}
static int x509_crt_verify_child(
mbedtls_x509_crt *child, mbedtls_x509_crt *parent,
mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
int path_cnt, int self_cnt, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
int ret;
uint32_t parent_flags = 0;
unsigned char hash[MBEDTLS_MD_MAX_SIZE];
mbedtls_x509_crt *grandparent;
const mbedtls_md_info_t *md_info;
/* Counting intermediate self signed certificates */
if( ( path_cnt != 0 ) && x509_name_cmp( &child->issuer, &child->subject ) == 0 )
self_cnt++;
/* path_cnt is 0 for the first intermediate CA */
if( 1 + path_cnt > MBEDTLS_X509_MAX_INTERMEDIATE_CA )
{
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
}
if( mbedtls_x509_time_is_past( &child->valid_to ) )
*flags |= MBEDTLS_X509_BADCERT_EXPIRED;
if( mbedtls_x509_time_is_future( &child->valid_from ) )
*flags |= MBEDTLS_X509_BADCERT_FUTURE;
if( x509_profile_check_md_alg( profile, child->sig_md ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_MD;
if( x509_profile_check_pk_alg( profile, child->sig_pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
md_info = mbedtls_md_info_from_type( child->sig_md );
if( md_info == NULL )
{
/*
* Cannot check 'unknown' hash
*/
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
}
else
{
mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash );
if( x509_profile_check_key( profile, child->sig_pk, &parent->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
if( mbedtls_pk_verify_ext( child->sig_pk, child->sig_opts, &parent->pk,
child->sig_md, hash, mbedtls_md_get_size( md_info ),
child->sig.p, child->sig.len ) != 0 )
{
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
}
}
#if defined(MBEDTLS_X509_CRL_PARSE_C)
/* Check trusted CA's CRL for the given crt */
*flags |= x509_crt_verifycrl(child, parent, ca_crl, profile );
#endif
/* Look for a grandparent in trusted CAs */
for( grandparent = trust_ca;
grandparent != NULL;
grandparent = grandparent->next )
{
if( x509_crt_check_parent( parent, grandparent,
0, path_cnt == 0 ) == 0 )
break;
}
if( grandparent != NULL )
{
ret = x509_crt_verify_top( parent, grandparent, ca_crl, profile,
path_cnt + 1, self_cnt, &parent_flags, f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
else
{
/* Look for a grandparent upwards the chain */
for( grandparent = parent->next;
grandparent != NULL;
grandparent = grandparent->next )
{
/* +2 because the current step is not yet accounted for
* and because max_pathlen is one higher than it should be.
* Also self signed certificates do not count to the limit. */
if( grandparent->max_pathlen > 0 &&
grandparent->max_pathlen < 2 + path_cnt - self_cnt )
{
continue;
}
if( x509_crt_check_parent( parent, grandparent,
0, path_cnt == 0 ) == 0 )
break;
}
/* Is our parent part of the chain or at the top? */
if( grandparent != NULL )
{
ret = x509_crt_verify_child( parent, grandparent, trust_ca, ca_crl,
profile, path_cnt + 1, self_cnt, &parent_flags,
f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
else
{
ret = x509_crt_verify_top( parent, trust_ca, ca_crl, profile,
path_cnt + 1, self_cnt, &parent_flags,
f_vrfy, p_vrfy );
if( ret != 0 )
return( ret );
}
}
/* child is verified to be a child of the parent, call verify callback */
if( NULL != f_vrfy )
if( ( ret = f_vrfy( p_vrfy, child, path_cnt, flags ) ) != 0 )
return( ret );
*flags |= parent_flags;
return( 0 );
}
/*
* Verify the certificate validity
*/
int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
return( mbedtls_x509_crt_verify_with_profile( crt, trust_ca, ca_crl,
&mbedtls_x509_crt_profile_default, cn, flags, f_vrfy, p_vrfy ) );
}
/*
* Verify the certificate validity, with profile
*/
int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
const mbedtls_x509_crt_profile *profile,
const char *cn, uint32_t *flags,
int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
void *p_vrfy )
{
size_t cn_len;
int ret;
int pathlen = 0, selfsigned = 0;
mbedtls_x509_crt *parent;
mbedtls_x509_name *name;
mbedtls_x509_sequence *cur = NULL;
mbedtls_pk_type_t pk_type;
*flags = 0;
if( profile == NULL )
{
ret = MBEDTLS_ERR_X509_BAD_INPUT_DATA;
goto exit;
}
if( cn != NULL )
{
name = &crt->subject;
cn_len = strlen( cn );
if( crt->ext_types & MBEDTLS_X509_EXT_SUBJECT_ALT_NAME )
{
cur = &crt->subject_alt_names;
while( cur != NULL )
{
if( cur->buf.len == cn_len &&
x509_memcasecmp( cn, cur->buf.p, cn_len ) == 0 )
break;
if( cur->buf.len > 2 &&
memcmp( cur->buf.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &cur->buf ) == 0 )
{
break;
}
cur = cur->next;
}
if( cur == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
else
{
while( name != NULL )
{
if( MBEDTLS_OID_CMP( MBEDTLS_OID_AT_CN, &name->oid ) == 0 )
{
if( name->val.len == cn_len &&
x509_memcasecmp( name->val.p, cn, cn_len ) == 0 )
break;
if( name->val.len > 2 &&
memcmp( name->val.p, "*.", 2 ) == 0 &&
x509_check_wildcard( cn, &name->val ) == 0 )
break;
}
name = name->next;
}
if( name == NULL )
*flags |= MBEDTLS_X509_BADCERT_CN_MISMATCH;
}
}
/* Check the type and size of the key */
pk_type = mbedtls_pk_get_type( &crt->pk );
if( x509_profile_check_pk_alg( profile, pk_type ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
if( x509_profile_check_key( profile, pk_type, &crt->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
/* Look for a parent in trusted CAs */
for( parent = trust_ca; parent != NULL; parent = parent->next )
{
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
}
if( parent != NULL )
{
ret = x509_crt_verify_top( crt, parent, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
else
{
/* Look for a parent upwards the chain */
for( parent = crt->next; parent != NULL; parent = parent->next )
if( x509_crt_check_parent( crt, parent, 0, pathlen == 0 ) == 0 )
break;
/* Are we part of the chain or at the top? */
if( parent != NULL )
{
ret = x509_crt_verify_child( crt, parent, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
else
{
ret = x509_crt_verify_top( crt, trust_ca, ca_crl, profile,
pathlen, selfsigned, flags, f_vrfy, p_vrfy );
if( ret != 0 )
goto exit;
}
}
exit:
if( ret != 0 )
{
*flags = (uint32_t) -1;
return( ret );
}
if( *flags != 0 )
return( MBEDTLS_ERR_X509_CERT_VERIFY_FAILED );
return( 0 );
}
/*
* Initialize a certificate chain
*/
void mbedtls_x509_crt_init( mbedtls_x509_crt *crt )
{
memset( crt, 0, sizeof(mbedtls_x509_crt) );
}
/*
* Unallocate all certificate data
*/
void mbedtls_x509_crt_free( mbedtls_x509_crt *crt )
{
mbedtls_x509_crt *cert_cur = crt;
mbedtls_x509_crt *cert_prv;
mbedtls_x509_name *name_cur;
mbedtls_x509_name *name_prv;
mbedtls_x509_sequence *seq_cur;
mbedtls_x509_sequence *seq_prv;
if( crt == NULL )
return;
do
{
mbedtls_pk_free( &cert_cur->pk );
#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
mbedtls_free( cert_cur->sig_opts );
#endif
name_cur = cert_cur->issuer.next;
while( name_cur != NULL )
{
name_prv = name_cur;
name_cur = name_cur->next;
mbedtls_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
mbedtls_free( name_prv );
}
name_cur = cert_cur->subject.next;
while( name_cur != NULL )
{
name_prv = name_cur;
name_cur = name_cur->next;
mbedtls_zeroize( name_prv, sizeof( mbedtls_x509_name ) );
mbedtls_free( name_prv );
}
seq_cur = cert_cur->ext_key_usage.next;
while( seq_cur != NULL )
{
seq_prv = seq_cur;
seq_cur = seq_cur->next;
mbedtls_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) );
mbedtls_free( seq_prv );
}
seq_cur = cert_cur->subject_alt_names.next;
while( seq_cur != NULL )
{
seq_prv = seq_cur;
seq_cur = seq_cur->next;
mbedtls_zeroize( seq_prv, sizeof( mbedtls_x509_sequence ) );
mbedtls_free( seq_prv );
}
if( cert_cur->raw.p != NULL )
{
mbedtls_zeroize( cert_cur->raw.p, cert_cur->raw.len );
mbedtls_free( cert_cur->raw.p );
}
cert_cur = cert_cur->next;
}
while( cert_cur != NULL );
cert_cur = crt;
do
{
cert_prv = cert_cur;
cert_cur = cert_cur->next;
mbedtls_zeroize( cert_prv, sizeof( mbedtls_x509_crt ) );
if( cert_prv != crt )
mbedtls_free( cert_prv );
}
while( cert_cur != NULL );
}
#endif /* MBEDTLS_X509_CRT_PARSE_C */
| ./CrossVul/dataset_final_sorted/CWE-287/c/good_2757_1 |
crossvul-cpp_data_good_5267_0 | /*
* IRC - Internet Relay Chat, src/modules/m_sasl.c
* (C) 2012 The UnrealIRCd Team
*
* See file AUTHORS in IRC package for additional names of
* the programmers.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 1, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "unrealircd.h"
#define MSG_AUTHENTICATE "AUTHENTICATE"
#define MSG_SASL "SASL"
#define MSG_SVSLOGIN "SVSLOGIN"
/* returns a server identifier given agent_p */
#define AGENT_SID(agent_p) (agent_p->user != NULL ? agent_p->user->server : agent_p->name)
ModuleHeader MOD_HEADER(m_sasl)
= {
"m_sasl",
"4.0",
"SASL",
"3.2-b8-1",
NULL
};
/*
* This is a "lightweight" SASL implementation/stack which uses psuedo-identifiers
* to identify connecting clients. In Unreal 3.3, we should use real identifiers
* so that SASL sessions can be correlated.
*
* The following people were involved in making the current iteration of SASL over
* IRC which allowed psuedo-identifiers:
*
* danieldg, Daniel de Graff <danieldg@inspircd.org>
* jilles, Jilles Tjoelker <jilles@stack.nl>
* Jobe, Matthew Beeching <jobe@mdbnet.co.uk>
* gxti, Michael Tharp <gxti@partiallystapled.com>
* nenolod, William Pitcock <nenolod@dereferenced.org>
*
* Thanks also to all of the client authors which have implemented SASL in their
* clients. With the backwards-compatibility layer allowing "lightweight" SASL
* implementations, we now truly have a universal authentication mechanism for
* IRC.
*/
/*
* decode_puid
*
* Decode PUID sent from a SASL agent. If the servername in the PUID doesn't match
* ours, we reject the PUID (by returning NULL).
*/
static aClient *decode_puid(char *puid)
{
aClient *cptr;
char *it, *it2;
int cookie = 0;
if ((it = strrchr(puid, '!')) == NULL)
return NULL;
*it++ = '\0';
if ((it2 = strrchr(it, '.')) != NULL)
{
*it2++ = '\0';
cookie = atoi(it2);
}
if (stricmp(me.name, puid))
return NULL;
list_for_each_entry(cptr, &unknown_list, lclient_node)
if (cptr->local->sasl_cookie == cookie)
return cptr;
return NULL;
}
/*
* encode_puid
*
* Encode PUID based on aClient.
*/
static const char *encode_puid(aClient *client)
{
static char buf[HOSTLEN + 20];
/* create a cookie if necessary (and in case getrandom16 returns 0, then run again) */
while (!client->local->sasl_cookie)
client->local->sasl_cookie = getrandom16();
snprintf(buf, sizeof buf, "%s!0.%d", me.name, client->local->sasl_cookie);
return buf;
}
/*
* SVSLOGIN message
*
* parv[1]: propagation mask
* parv[2]: target PUID
* parv[3]: ESVID
*/
CMD_FUNC(m_svslogin)
{
if (!SASL_SERVER || MyClient(sptr) || (parc < 3) || !parv[3])
return 0;
if (!stricmp(parv[1], me.name))
{
aClient *target_p;
/* is the PUID valid? */
if ((target_p = decode_puid(parv[2])) == NULL)
return 0;
if (target_p->user == NULL)
make_user(target_p);
strlcpy(target_p->user->svid, parv[3], sizeof(target_p->user->svid));
sendto_one(target_p, err_str(RPL_LOGGEDIN), me.name,
BadPtr(target_p->name) ? "*" : target_p->name,
BadPtr(target_p->name) ? "*" : target_p->name,
BadPtr(target_p->user->username) ? "*" : target_p->user->username,
BadPtr(target_p->user->realhost) ? "*" : target_p->user->realhost,
target_p->user->svid, target_p->user->svid);
return 0;
}
/* not for us; propagate. */
sendto_server(cptr, 0, 0, ":%s SVSLOGIN %s %s %s",
sptr->name, parv[1], parv[2], parv[3]);
return 0;
}
/*
* SASL message
*
* parv[1]: distribution mask
* parv[2]: target PUID
* parv[3]: mode/state
* parv[4]: data
* parv[5]: out-of-bound data
*/
CMD_FUNC(m_sasl)
{
if (!SASL_SERVER || MyClient(sptr) || (parc < 4) || !parv[4])
return 0;
if (!stricmp(parv[1], me.name))
{
aClient *target_p;
/* is the PUID valid? */
if ((target_p = decode_puid(parv[2])) == NULL)
return 0;
if (target_p->user == NULL)
make_user(target_p);
/* reject if another SASL agent is answering */
if (*target_p->local->sasl_agent && stricmp(sptr->name, target_p->local->sasl_agent))
return 0;
else
strlcpy(target_p->local->sasl_agent, sptr->name, sizeof(target_p->local->sasl_agent));
if (*parv[3] == 'C')
sendto_one(target_p, "AUTHENTICATE %s", parv[4]);
else if (*parv[3] == 'D')
{
if (*parv[4] == 'F')
sendto_one(target_p, err_str(ERR_SASLFAIL), me.name, BadPtr(target_p->name) ? "*" : target_p->name);
else if (*parv[4] == 'S')
{
target_p->local->sasl_complete++;
sendto_one(target_p, err_str(RPL_SASLSUCCESS), me.name, BadPtr(target_p->name) ? "*" : target_p->name);
}
*target_p->local->sasl_agent = '\0';
}
else if (*parv[3] == 'M')
sendto_one(target_p, err_str(RPL_SASLMECHS), me.name, BadPtr(target_p->name) ? "*" : target_p->name, parv[4]);
return 0;
}
/* not for us; propagate. */
sendto_server(cptr, 0, 0, ":%s SASL %s %s %c %s %s",
sptr->name, parv[1], parv[2], *parv[3], parv[4], parc > 5 ? parv[5] : "");
return 0;
}
/*
* AUTHENTICATE message
*
* parv[1]: data
*/
CMD_FUNC(m_authenticate)
{
aClient *agent_p = NULL;
/* Failing to use CAP REQ for sasl is a protocol violation. */
if (!SASL_SERVER || !MyConnect(sptr) || BadPtr(parv[1]) || !CHECKPROTO(sptr, PROTO_SASL))
return 0;
if (sptr->local->sasl_complete)
{
sendto_one(sptr, err_str(ERR_SASLALREADY), me.name, BadPtr(sptr->name) ? "*" : sptr->name);
return 0;
}
if ((parv[1][0] == ':') || strchr(parv[1], ' '))
{
sendto_one(sptr, err_str(ERR_CANNOTDOCOMMAND), me.name, "*", "AUTHENTICATE", "Invalid parameter");
return 0;
}
if (strlen(parv[1]) > 400)
{
sendto_one(sptr, err_str(ERR_SASLTOOLONG), me.name, BadPtr(sptr->name) ? "*" : sptr->name);
return 0;
}
if (*sptr->local->sasl_agent)
agent_p = find_client(sptr->local->sasl_agent, NULL);
if (agent_p == NULL)
{
char *addr = BadPtr(sptr->ip) ? "0" : sptr->ip;
char *certfp = moddata_client_get(sptr, "certfp");
sendto_server(NULL, 0, 0, ":%s SASL %s %s H %s %s",
me.name, SASL_SERVER, encode_puid(sptr), addr, addr);
if (certfp)
sendto_server(NULL, 0, 0, ":%s SASL %s %s S %s %s",
me.name, SASL_SERVER, encode_puid(sptr), parv[1], certfp);
else
sendto_server(NULL, 0, 0, ":%s SASL %s %s S %s",
me.name, SASL_SERVER, encode_puid(sptr), parv[1]);
}
else
sendto_server(NULL, 0, 0, ":%s SASL %s %s C %s",
me.name, AGENT_SID(agent_p), encode_puid(sptr), parv[1]);
sptr->local->sasl_out++;
return 0;
}
static int abort_sasl(aClient *cptr)
{
if (cptr->local->sasl_out == 0 || cptr->local->sasl_complete)
return 0;
cptr->local->sasl_out = cptr->local->sasl_complete = 0;
sendto_one(cptr, err_str(ERR_SASLABORTED), me.name, BadPtr(cptr->name) ? "*" : cptr->name);
if (*cptr->local->sasl_agent)
{
aClient *agent_p = find_client(cptr->local->sasl_agent, NULL);
if (agent_p != NULL)
{
sendto_server(NULL, 0, 0, ":%s SASL %s %s D A",
me.name, AGENT_SID(agent_p), encode_puid(cptr));
return 0;
}
}
sendto_server(NULL, 0, 0, ":%s SASL * %s D A", me.name, encode_puid(cptr));
return 0;
}
int sasl_capability_visible(void)
{
if (!SASL_SERVER || !find_server(SASL_SERVER, NULL))
return 0;
return 1;
}
int sasl_connect(aClient *sptr)
{
return abort_sasl(sptr);
}
int sasl_quit(aClient *sptr, char *comment)
{
return abort_sasl(sptr);
}
MOD_INIT(m_sasl)
{
ClientCapability cap;
MARK_AS_OFFICIAL_MODULE(modinfo);
CommandAdd(modinfo->handle, MSG_SASL, m_sasl, MAXPARA, M_USER|M_SERVER);
CommandAdd(modinfo->handle, MSG_SVSLOGIN, m_svslogin, MAXPARA, M_USER|M_SERVER);
CommandAdd(modinfo->handle, MSG_AUTHENTICATE, m_authenticate, MAXPARA, M_UNREGISTERED);
HookAdd(modinfo->handle, HOOKTYPE_LOCAL_CONNECT, 0, sasl_connect);
HookAdd(modinfo->handle, HOOKTYPE_LOCAL_QUIT, 0, sasl_quit);
memset(&cap, 0, sizeof(cap));
cap.name = "sasl";
cap.cap = PROTO_SASL;
cap.visible = sasl_capability_visible;
ClientCapabilityAdd(modinfo->handle, &cap);
return MOD_SUCCESS;
}
MOD_LOAD(m_sasl)
{
return MOD_SUCCESS;
}
MOD_UNLOAD(m_sasl)
{
return MOD_SUCCESS;
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/good_5267_0 |
crossvul-cpp_data_good_2756_5 | /*
* Error message information
*
* 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_ERROR_C) || defined(MBEDTLS_ERROR_STRERROR_DUMMY)
#include "mbedtls/error.h"
#include <string.h>
#endif
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#define mbedtls_snprintf snprintf
#define mbedtls_time_t time_t
#endif
#if defined(MBEDTLS_ERROR_C)
#include <stdio.h>
#if defined(MBEDTLS_AES_C)
#include "mbedtls/aes.h"
#endif
#if defined(MBEDTLS_BASE64_C)
#include "mbedtls/base64.h"
#endif
#if defined(MBEDTLS_BIGNUM_C)
#include "mbedtls/bignum.h"
#endif
#if defined(MBEDTLS_BLOWFISH_C)
#include "mbedtls/blowfish.h"
#endif
#if defined(MBEDTLS_CAMELLIA_C)
#include "mbedtls/camellia.h"
#endif
#if defined(MBEDTLS_CCM_C)
#include "mbedtls/ccm.h"
#endif
#if defined(MBEDTLS_CIPHER_C)
#include "mbedtls/cipher.h"
#endif
#if defined(MBEDTLS_CTR_DRBG_C)
#include "mbedtls/ctr_drbg.h"
#endif
#if defined(MBEDTLS_DES_C)
#include "mbedtls/des.h"
#endif
#if defined(MBEDTLS_DHM_C)
#include "mbedtls/dhm.h"
#endif
#if defined(MBEDTLS_ECP_C)
#include "mbedtls/ecp.h"
#endif
#if defined(MBEDTLS_ENTROPY_C)
#include "mbedtls/entropy.h"
#endif
#if defined(MBEDTLS_GCM_C)
#include "mbedtls/gcm.h"
#endif
#if defined(MBEDTLS_HMAC_DRBG_C)
#include "mbedtls/hmac_drbg.h"
#endif
#if defined(MBEDTLS_MD_C)
#include "mbedtls/md.h"
#endif
#if defined(MBEDTLS_NET_C)
#include "mbedtls/net_sockets.h"
#endif
#if defined(MBEDTLS_OID_C)
#include "mbedtls/oid.h"
#endif
#if defined(MBEDTLS_PADLOCK_C)
#include "mbedtls/padlock.h"
#endif
#if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C)
#include "mbedtls/pem.h"
#endif
#if defined(MBEDTLS_PK_C)
#include "mbedtls/pk.h"
#endif
#if defined(MBEDTLS_PKCS12_C)
#include "mbedtls/pkcs12.h"
#endif
#if defined(MBEDTLS_PKCS5_C)
#include "mbedtls/pkcs5.h"
#endif
#if defined(MBEDTLS_RSA_C)
#include "mbedtls/rsa.h"
#endif
#if defined(MBEDTLS_SSL_TLS_C)
#include "mbedtls/ssl.h"
#endif
#if defined(MBEDTLS_THREADING_C)
#include "mbedtls/threading.h"
#endif
#if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C)
#include "mbedtls/x509.h"
#endif
#if defined(MBEDTLS_XTEA_C)
#include "mbedtls/xtea.h"
#endif
void mbedtls_strerror( int ret, char *buf, size_t buflen )
{
size_t len;
int use_ret;
if( buflen == 0 )
return;
memset( buf, 0x00, buflen );
if( ret < 0 )
ret = -ret;
if( ret & 0xFF80 )
{
use_ret = ret & 0xFF80;
// High level error codes
//
// BEGIN generated code
#if defined(MBEDTLS_CIPHER_C)
if( use_ret == -(MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "CIPHER - The selected feature is not available" );
if( use_ret == -(MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "CIPHER - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_CIPHER_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "CIPHER - Failed to allocate memory" );
if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_PADDING) )
mbedtls_snprintf( buf, buflen, "CIPHER - Input data contains invalid padding and is rejected" );
if( use_ret == -(MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED) )
mbedtls_snprintf( buf, buflen, "CIPHER - Decryption of block requires a full block" );
if( use_ret == -(MBEDTLS_ERR_CIPHER_AUTH_FAILED) )
mbedtls_snprintf( buf, buflen, "CIPHER - Authentication failed (for AEAD modes)" );
if( use_ret == -(MBEDTLS_ERR_CIPHER_INVALID_CONTEXT) )
mbedtls_snprintf( buf, buflen, "CIPHER - The context is invalid, eg because it was free()ed" );
#endif /* MBEDTLS_CIPHER_C */
#if defined(MBEDTLS_DHM_C)
if( use_ret == -(MBEDTLS_ERR_DHM_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "DHM - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_DHM_READ_PARAMS_FAILED) )
mbedtls_snprintf( buf, buflen, "DHM - Reading of the DHM parameters failed" );
if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED) )
mbedtls_snprintf( buf, buflen, "DHM - Making of the DHM parameters failed" );
if( use_ret == -(MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED) )
mbedtls_snprintf( buf, buflen, "DHM - Reading of the public values failed" );
if( use_ret == -(MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED) )
mbedtls_snprintf( buf, buflen, "DHM - Making of the public value failed" );
if( use_ret == -(MBEDTLS_ERR_DHM_CALC_SECRET_FAILED) )
mbedtls_snprintf( buf, buflen, "DHM - Calculation of the DHM secret failed" );
if( use_ret == -(MBEDTLS_ERR_DHM_INVALID_FORMAT) )
mbedtls_snprintf( buf, buflen, "DHM - The ASN.1 data is not formatted correctly" );
if( use_ret == -(MBEDTLS_ERR_DHM_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "DHM - Allocation of memory failed" );
if( use_ret == -(MBEDTLS_ERR_DHM_FILE_IO_ERROR) )
mbedtls_snprintf( buf, buflen, "DHM - Read/write of file failed" );
#endif /* MBEDTLS_DHM_C */
#if defined(MBEDTLS_ECP_C)
if( use_ret == -(MBEDTLS_ERR_ECP_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "ECP - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "ECP - The buffer is too small to write to" );
if( use_ret == -(MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "ECP - Requested curve not available" );
if( use_ret == -(MBEDTLS_ERR_ECP_VERIFY_FAILED) )
mbedtls_snprintf( buf, buflen, "ECP - The signature is not valid" );
if( use_ret == -(MBEDTLS_ERR_ECP_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "ECP - Memory allocation failed" );
if( use_ret == -(MBEDTLS_ERR_ECP_RANDOM_FAILED) )
mbedtls_snprintf( buf, buflen, "ECP - Generation of random value, such as (ephemeral) key, failed" );
if( use_ret == -(MBEDTLS_ERR_ECP_INVALID_KEY) )
mbedtls_snprintf( buf, buflen, "ECP - Invalid private or public key" );
if( use_ret == -(MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH) )
mbedtls_snprintf( buf, buflen, "ECP - Signature is valid but shorter than the user-supplied length" );
#endif /* MBEDTLS_ECP_C */
#if defined(MBEDTLS_MD_C)
if( use_ret == -(MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "MD - The selected feature is not available" );
if( use_ret == -(MBEDTLS_ERR_MD_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "MD - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_MD_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "MD - Failed to allocate memory" );
if( use_ret == -(MBEDTLS_ERR_MD_FILE_IO_ERROR) )
mbedtls_snprintf( buf, buflen, "MD - Opening or reading of file failed" );
#endif /* MBEDTLS_MD_C */
#if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C)
if( use_ret == -(MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT) )
mbedtls_snprintf( buf, buflen, "PEM - No PEM header or footer found" );
if( use_ret == -(MBEDTLS_ERR_PEM_INVALID_DATA) )
mbedtls_snprintf( buf, buflen, "PEM - PEM string is not as expected" );
if( use_ret == -(MBEDTLS_ERR_PEM_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "PEM - Failed to allocate memory" );
if( use_ret == -(MBEDTLS_ERR_PEM_INVALID_ENC_IV) )
mbedtls_snprintf( buf, buflen, "PEM - RSA IV is not in hex-format" );
if( use_ret == -(MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG) )
mbedtls_snprintf( buf, buflen, "PEM - Unsupported key encryption algorithm" );
if( use_ret == -(MBEDTLS_ERR_PEM_PASSWORD_REQUIRED) )
mbedtls_snprintf( buf, buflen, "PEM - Private key password can't be empty" );
if( use_ret == -(MBEDTLS_ERR_PEM_PASSWORD_MISMATCH) )
mbedtls_snprintf( buf, buflen, "PEM - Given private key password does not allow for correct decryption" );
if( use_ret == -(MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "PEM - Unavailable feature, e.g. hashing/encryption combination" );
if( use_ret == -(MBEDTLS_ERR_PEM_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "PEM - Bad input parameters to function" );
#endif /* MBEDTLS_PEM_PARSE_C || MBEDTLS_PEM_WRITE_C */
#if defined(MBEDTLS_PK_C)
if( use_ret == -(MBEDTLS_ERR_PK_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "PK - Memory allocation failed" );
if( use_ret == -(MBEDTLS_ERR_PK_TYPE_MISMATCH) )
mbedtls_snprintf( buf, buflen, "PK - Type mismatch, eg attempt to encrypt with an ECDSA key" );
if( use_ret == -(MBEDTLS_ERR_PK_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "PK - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_PK_FILE_IO_ERROR) )
mbedtls_snprintf( buf, buflen, "PK - Read/write of file failed" );
if( use_ret == -(MBEDTLS_ERR_PK_KEY_INVALID_VERSION) )
mbedtls_snprintf( buf, buflen, "PK - Unsupported key version" );
if( use_ret == -(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT) )
mbedtls_snprintf( buf, buflen, "PK - Invalid key tag or value" );
if( use_ret == -(MBEDTLS_ERR_PK_UNKNOWN_PK_ALG) )
mbedtls_snprintf( buf, buflen, "PK - Key algorithm is unsupported (only RSA and EC are supported)" );
if( use_ret == -(MBEDTLS_ERR_PK_PASSWORD_REQUIRED) )
mbedtls_snprintf( buf, buflen, "PK - Private key password can't be empty" );
if( use_ret == -(MBEDTLS_ERR_PK_PASSWORD_MISMATCH) )
mbedtls_snprintf( buf, buflen, "PK - Given private key password does not allow for correct decryption" );
if( use_ret == -(MBEDTLS_ERR_PK_INVALID_PUBKEY) )
mbedtls_snprintf( buf, buflen, "PK - The pubkey tag or value is invalid (only RSA and EC are supported)" );
if( use_ret == -(MBEDTLS_ERR_PK_INVALID_ALG) )
mbedtls_snprintf( buf, buflen, "PK - The algorithm tag or value is invalid" );
if( use_ret == -(MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE) )
mbedtls_snprintf( buf, buflen, "PK - Elliptic curve is unsupported (only NIST curves are supported)" );
if( use_ret == -(MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "PK - Unavailable feature, e.g. RSA disabled for RSA key" );
if( use_ret == -(MBEDTLS_ERR_PK_SIG_LEN_MISMATCH) )
mbedtls_snprintf( buf, buflen, "PK - The signature is valid but its length is less than expected" );
#endif /* MBEDTLS_PK_C */
#if defined(MBEDTLS_PKCS12_C)
if( use_ret == -(MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "PKCS12 - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "PKCS12 - Feature not available, e.g. unsupported encryption scheme" );
if( use_ret == -(MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT) )
mbedtls_snprintf( buf, buflen, "PKCS12 - PBE ASN.1 data not as expected" );
if( use_ret == -(MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH) )
mbedtls_snprintf( buf, buflen, "PKCS12 - Given private key password does not allow for correct decryption" );
#endif /* MBEDTLS_PKCS12_C */
#if defined(MBEDTLS_PKCS5_C)
if( use_ret == -(MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "PKCS5 - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_PKCS5_INVALID_FORMAT) )
mbedtls_snprintf( buf, buflen, "PKCS5 - Unexpected ASN.1 data" );
if( use_ret == -(MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "PKCS5 - Requested encryption or digest alg not available" );
if( use_ret == -(MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH) )
mbedtls_snprintf( buf, buflen, "PKCS5 - Given private key password does not allow for correct decryption" );
#endif /* MBEDTLS_PKCS5_C */
#if defined(MBEDTLS_RSA_C)
if( use_ret == -(MBEDTLS_ERR_RSA_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "RSA - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_RSA_INVALID_PADDING) )
mbedtls_snprintf( buf, buflen, "RSA - Input data contains invalid padding and is rejected" );
if( use_ret == -(MBEDTLS_ERR_RSA_KEY_GEN_FAILED) )
mbedtls_snprintf( buf, buflen, "RSA - Something failed during generation of a key" );
if( use_ret == -(MBEDTLS_ERR_RSA_KEY_CHECK_FAILED) )
mbedtls_snprintf( buf, buflen, "RSA - Key failed to pass the library's validity check" );
if( use_ret == -(MBEDTLS_ERR_RSA_PUBLIC_FAILED) )
mbedtls_snprintf( buf, buflen, "RSA - The public key operation failed" );
if( use_ret == -(MBEDTLS_ERR_RSA_PRIVATE_FAILED) )
mbedtls_snprintf( buf, buflen, "RSA - The private key operation failed" );
if( use_ret == -(MBEDTLS_ERR_RSA_VERIFY_FAILED) )
mbedtls_snprintf( buf, buflen, "RSA - The PKCS#1 verification failed" );
if( use_ret == -(MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE) )
mbedtls_snprintf( buf, buflen, "RSA - The output buffer for decryption is not large enough" );
if( use_ret == -(MBEDTLS_ERR_RSA_RNG_FAILED) )
mbedtls_snprintf( buf, buflen, "RSA - The random generator failed to generate non-zeros" );
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_SSL_TLS_C)
if( use_ret == -(MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "SSL - The requested feature is not available" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "SSL - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_MAC) )
mbedtls_snprintf( buf, buflen, "SSL - Verification of the message MAC failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_RECORD) )
mbedtls_snprintf( buf, buflen, "SSL - An invalid SSL record was received" );
if( use_ret == -(MBEDTLS_ERR_SSL_CONN_EOF) )
mbedtls_snprintf( buf, buflen, "SSL - The connection indicated an EOF" );
if( use_ret == -(MBEDTLS_ERR_SSL_UNKNOWN_CIPHER) )
mbedtls_snprintf( buf, buflen, "SSL - An unknown cipher was received" );
if( use_ret == -(MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN) )
mbedtls_snprintf( buf, buflen, "SSL - The server has no ciphersuites in common with the client" );
if( use_ret == -(MBEDTLS_ERR_SSL_NO_RNG) )
mbedtls_snprintf( buf, buflen, "SSL - No RNG was provided to the SSL module" );
if( use_ret == -(MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE) )
mbedtls_snprintf( buf, buflen, "SSL - No client certification received from the client, but required by the authentication mode" );
if( use_ret == -(MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE) )
mbedtls_snprintf( buf, buflen, "SSL - Our own certificate(s) is/are too large to send in an SSL message" );
if( use_ret == -(MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED) )
mbedtls_snprintf( buf, buflen, "SSL - The own certificate is not set, but needed by the server" );
if( use_ret == -(MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED) )
mbedtls_snprintf( buf, buflen, "SSL - The own private key or pre-shared key is not set, but needed" );
if( use_ret == -(MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED) )
mbedtls_snprintf( buf, buflen, "SSL - No CA Chain is set, but required to operate" );
if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE) )
mbedtls_snprintf( buf, buflen, "SSL - An unexpected message was received from our peer" );
if( use_ret == -(MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE) )
{
mbedtls_snprintf( buf, buflen, "SSL - A fatal alert message was received from our peer" );
return;
}
if( use_ret == -(MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED) )
mbedtls_snprintf( buf, buflen, "SSL - Verification of our peer failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY) )
mbedtls_snprintf( buf, buflen, "SSL - The peer notified us that the connection is going to be closed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientHello handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerHello handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the Certificate handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the CertificateRequest handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerKeyExchange handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the ServerHelloDone handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Read Public" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the ClientKeyExchange handshake message failed in DHM / ECDH Calculate Secret" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the CertificateVerify handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the ChangeCipherSpec handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_FINISHED) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the Finished handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "SSL - Memory allocation failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_HW_ACCEL_FAILED) )
mbedtls_snprintf( buf, buflen, "SSL - Hardware acceleration function returned with error" );
if( use_ret == -(MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH) )
mbedtls_snprintf( buf, buflen, "SSL - Hardware acceleration function skipped / left alone data" );
if( use_ret == -(MBEDTLS_ERR_SSL_COMPRESSION_FAILED) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the compression / decompression failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION) )
mbedtls_snprintf( buf, buflen, "SSL - Handshake protocol not within min/max boundaries" );
if( use_ret == -(MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET) )
mbedtls_snprintf( buf, buflen, "SSL - Processing of the NewSessionTicket handshake message failed" );
if( use_ret == -(MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED) )
mbedtls_snprintf( buf, buflen, "SSL - Session ticket has expired" );
if( use_ret == -(MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH) )
mbedtls_snprintf( buf, buflen, "SSL - Public key type mismatch (eg, asked for RSA key exchange and presented EC key)" );
if( use_ret == -(MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY) )
mbedtls_snprintf( buf, buflen, "SSL - Unknown identity received (eg, PSK identity)" );
if( use_ret == -(MBEDTLS_ERR_SSL_INTERNAL_ERROR) )
mbedtls_snprintf( buf, buflen, "SSL - Internal error (eg, unexpected failure in lower-level module)" );
if( use_ret == -(MBEDTLS_ERR_SSL_COUNTER_WRAPPING) )
mbedtls_snprintf( buf, buflen, "SSL - A counter would wrap (eg, too many messages exchanged)" );
if( use_ret == -(MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO) )
mbedtls_snprintf( buf, buflen, "SSL - Unexpected message at ServerHello in renegotiation" );
if( use_ret == -(MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED) )
mbedtls_snprintf( buf, buflen, "SSL - DTLS client must retry for hello verification" );
if( use_ret == -(MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "SSL - A buffer is too small to receive or write a message" );
if( use_ret == -(MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE) )
mbedtls_snprintf( buf, buflen, "SSL - None of the common ciphersuites is usable (eg, no suitable certificate, see debug messages)" );
if( use_ret == -(MBEDTLS_ERR_SSL_WANT_READ) )
mbedtls_snprintf( buf, buflen, "SSL - Connection requires a read call" );
if( use_ret == -(MBEDTLS_ERR_SSL_WANT_WRITE) )
mbedtls_snprintf( buf, buflen, "SSL - Connection requires a write call" );
if( use_ret == -(MBEDTLS_ERR_SSL_TIMEOUT) )
mbedtls_snprintf( buf, buflen, "SSL - The operation timed out" );
if( use_ret == -(MBEDTLS_ERR_SSL_CLIENT_RECONNECT) )
mbedtls_snprintf( buf, buflen, "SSL - The client initiated a reconnect from the same port" );
if( use_ret == -(MBEDTLS_ERR_SSL_UNEXPECTED_RECORD) )
mbedtls_snprintf( buf, buflen, "SSL - Record header looks valid but is not expected" );
if( use_ret == -(MBEDTLS_ERR_SSL_NON_FATAL) )
mbedtls_snprintf( buf, buflen, "SSL - The alert message received indicates a non-fatal error" );
if( use_ret == -(MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH) )
mbedtls_snprintf( buf, buflen, "SSL - Couldn't set the hash for verifying CertificateVerify" );
#endif /* MBEDTLS_SSL_TLS_C */
#if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C)
if( use_ret == -(MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "X509 - Unavailable feature, e.g. RSA hashing/encryption combination" );
if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_OID) )
mbedtls_snprintf( buf, buflen, "X509 - Requested OID is unknown" );
if( use_ret == -(MBEDTLS_ERR_X509_INVALID_FORMAT) )
mbedtls_snprintf( buf, buflen, "X509 - The CRT/CRL/CSR format is invalid, e.g. different type expected" );
if( use_ret == -(MBEDTLS_ERR_X509_INVALID_VERSION) )
mbedtls_snprintf( buf, buflen, "X509 - The CRT/CRL/CSR version element is invalid" );
if( use_ret == -(MBEDTLS_ERR_X509_INVALID_SERIAL) )
mbedtls_snprintf( buf, buflen, "X509 - The serial tag or value is invalid" );
if( use_ret == -(MBEDTLS_ERR_X509_INVALID_ALG) )
mbedtls_snprintf( buf, buflen, "X509 - The algorithm tag or value is invalid" );
if( use_ret == -(MBEDTLS_ERR_X509_INVALID_NAME) )
mbedtls_snprintf( buf, buflen, "X509 - The name tag or value is invalid" );
if( use_ret == -(MBEDTLS_ERR_X509_INVALID_DATE) )
mbedtls_snprintf( buf, buflen, "X509 - The date tag or value is invalid" );
if( use_ret == -(MBEDTLS_ERR_X509_INVALID_SIGNATURE) )
mbedtls_snprintf( buf, buflen, "X509 - The signature tag or value invalid" );
if( use_ret == -(MBEDTLS_ERR_X509_INVALID_EXTENSIONS) )
mbedtls_snprintf( buf, buflen, "X509 - The extension tag or value is invalid" );
if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_VERSION) )
mbedtls_snprintf( buf, buflen, "X509 - CRT/CRL/CSR has an unsupported version number" );
if( use_ret == -(MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG) )
mbedtls_snprintf( buf, buflen, "X509 - Signature algorithm (oid) is unsupported" );
if( use_ret == -(MBEDTLS_ERR_X509_SIG_MISMATCH) )
mbedtls_snprintf( buf, buflen, "X509 - Signature algorithms do not match. (see \\c ::mbedtls_x509_crt sig_oid)" );
if( use_ret == -(MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) )
mbedtls_snprintf( buf, buflen, "X509 - Certificate verification failed, e.g. CRL, CA or signature check failed" );
if( use_ret == -(MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT) )
mbedtls_snprintf( buf, buflen, "X509 - Format not recognized as DER or PEM" );
if( use_ret == -(MBEDTLS_ERR_X509_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "X509 - Input invalid" );
if( use_ret == -(MBEDTLS_ERR_X509_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "X509 - Allocation of memory failed" );
if( use_ret == -(MBEDTLS_ERR_X509_FILE_IO_ERROR) )
mbedtls_snprintf( buf, buflen, "X509 - Read/write of file failed" );
if( use_ret == -(MBEDTLS_ERR_X509_BUFFER_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "X509 - Destination buffer is too small" );
if( use_ret == -(MBEDTLS_ERR_X509_FATAL_ERROR) )
mbedtls_snprintf( buf, buflen, "X509 - A fatal error occured, eg the chain is too long or the vrfy callback failed" );
#endif /* MBEDTLS_X509_USE_C || MBEDTLS_X509_CREATE_C */
// END generated code
if( strlen( buf ) == 0 )
mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret );
}
use_ret = ret & ~0xFF80;
if( use_ret == 0 )
return;
// If high level code is present, make a concatenation between both
// error strings.
//
len = strlen( buf );
if( len > 0 )
{
if( buflen - len < 5 )
return;
mbedtls_snprintf( buf + len, buflen - len, " : " );
buf += len + 3;
buflen -= len + 3;
}
// Low level error codes
//
// BEGIN generated code
#if defined(MBEDTLS_AES_C)
if( use_ret == -(MBEDTLS_ERR_AES_INVALID_KEY_LENGTH) )
mbedtls_snprintf( buf, buflen, "AES - Invalid key length" );
if( use_ret == -(MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH) )
mbedtls_snprintf( buf, buflen, "AES - Invalid data input length" );
#endif /* MBEDTLS_AES_C */
#if defined(MBEDTLS_ASN1_PARSE_C)
if( use_ret == -(MBEDTLS_ERR_ASN1_OUT_OF_DATA) )
mbedtls_snprintf( buf, buflen, "ASN1 - Out of data when parsing an ASN1 data structure" );
if( use_ret == -(MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) )
mbedtls_snprintf( buf, buflen, "ASN1 - ASN1 tag was of an unexpected value" );
if( use_ret == -(MBEDTLS_ERR_ASN1_INVALID_LENGTH) )
mbedtls_snprintf( buf, buflen, "ASN1 - Error when trying to determine the length or invalid length" );
if( use_ret == -(MBEDTLS_ERR_ASN1_LENGTH_MISMATCH) )
mbedtls_snprintf( buf, buflen, "ASN1 - Actual length differs from expected length" );
if( use_ret == -(MBEDTLS_ERR_ASN1_INVALID_DATA) )
mbedtls_snprintf( buf, buflen, "ASN1 - Data is invalid. (not used)" );
if( use_ret == -(MBEDTLS_ERR_ASN1_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "ASN1 - Memory allocation failed" );
if( use_ret == -(MBEDTLS_ERR_ASN1_BUF_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "ASN1 - Buffer too small when writing ASN.1 data structure" );
#endif /* MBEDTLS_ASN1_PARSE_C */
#if defined(MBEDTLS_BASE64_C)
if( use_ret == -(MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "BASE64 - Output buffer too small" );
if( use_ret == -(MBEDTLS_ERR_BASE64_INVALID_CHARACTER) )
mbedtls_snprintf( buf, buflen, "BASE64 - Invalid character in input" );
#endif /* MBEDTLS_BASE64_C */
#if defined(MBEDTLS_BIGNUM_C)
if( use_ret == -(MBEDTLS_ERR_MPI_FILE_IO_ERROR) )
mbedtls_snprintf( buf, buflen, "BIGNUM - An error occurred while reading from or writing to a file" );
if( use_ret == -(MBEDTLS_ERR_MPI_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "BIGNUM - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_MPI_INVALID_CHARACTER) )
mbedtls_snprintf( buf, buflen, "BIGNUM - There is an invalid character in the digit string" );
if( use_ret == -(MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "BIGNUM - The buffer is too small to write to" );
if( use_ret == -(MBEDTLS_ERR_MPI_NEGATIVE_VALUE) )
mbedtls_snprintf( buf, buflen, "BIGNUM - The input arguments are negative or result in illegal output" );
if( use_ret == -(MBEDTLS_ERR_MPI_DIVISION_BY_ZERO) )
mbedtls_snprintf( buf, buflen, "BIGNUM - The input argument for division is zero, which is not allowed" );
if( use_ret == -(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) )
mbedtls_snprintf( buf, buflen, "BIGNUM - The input arguments are not acceptable" );
if( use_ret == -(MBEDTLS_ERR_MPI_ALLOC_FAILED) )
mbedtls_snprintf( buf, buflen, "BIGNUM - Memory allocation failed" );
#endif /* MBEDTLS_BIGNUM_C */
#if defined(MBEDTLS_BLOWFISH_C)
if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH) )
mbedtls_snprintf( buf, buflen, "BLOWFISH - Invalid key length" );
if( use_ret == -(MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH) )
mbedtls_snprintf( buf, buflen, "BLOWFISH - Invalid data input length" );
#endif /* MBEDTLS_BLOWFISH_C */
#if defined(MBEDTLS_CAMELLIA_C)
if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH) )
mbedtls_snprintf( buf, buflen, "CAMELLIA - Invalid key length" );
if( use_ret == -(MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH) )
mbedtls_snprintf( buf, buflen, "CAMELLIA - Invalid data input length" );
#endif /* MBEDTLS_CAMELLIA_C */
#if defined(MBEDTLS_CCM_C)
if( use_ret == -(MBEDTLS_ERR_CCM_BAD_INPUT) )
mbedtls_snprintf( buf, buflen, "CCM - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_CCM_AUTH_FAILED) )
mbedtls_snprintf( buf, buflen, "CCM - Authenticated decryption failed" );
#endif /* MBEDTLS_CCM_C */
#if defined(MBEDTLS_CTR_DRBG_C)
if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED) )
mbedtls_snprintf( buf, buflen, "CTR_DRBG - The entropy source failed" );
if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG) )
mbedtls_snprintf( buf, buflen, "CTR_DRBG - Too many random requested in single call" );
if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG) )
mbedtls_snprintf( buf, buflen, "CTR_DRBG - Input too large (Entropy + additional)" );
if( use_ret == -(MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR) )
mbedtls_snprintf( buf, buflen, "CTR_DRBG - Read/write error in file" );
#endif /* MBEDTLS_CTR_DRBG_C */
#if defined(MBEDTLS_DES_C)
if( use_ret == -(MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH) )
mbedtls_snprintf( buf, buflen, "DES - The data input has an invalid length" );
#endif /* MBEDTLS_DES_C */
#if defined(MBEDTLS_ENTROPY_C)
if( use_ret == -(MBEDTLS_ERR_ENTROPY_SOURCE_FAILED) )
mbedtls_snprintf( buf, buflen, "ENTROPY - Critical entropy source failure" );
if( use_ret == -(MBEDTLS_ERR_ENTROPY_MAX_SOURCES) )
mbedtls_snprintf( buf, buflen, "ENTROPY - No more sources can be added" );
if( use_ret == -(MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED) )
mbedtls_snprintf( buf, buflen, "ENTROPY - No sources have been added to poll" );
if( use_ret == -(MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE) )
mbedtls_snprintf( buf, buflen, "ENTROPY - No strong sources have been added to poll" );
if( use_ret == -(MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR) )
mbedtls_snprintf( buf, buflen, "ENTROPY - Read/write error in file" );
#endif /* MBEDTLS_ENTROPY_C */
#if defined(MBEDTLS_GCM_C)
if( use_ret == -(MBEDTLS_ERR_GCM_AUTH_FAILED) )
mbedtls_snprintf( buf, buflen, "GCM - Authenticated decryption failed" );
if( use_ret == -(MBEDTLS_ERR_GCM_BAD_INPUT) )
mbedtls_snprintf( buf, buflen, "GCM - Bad input parameters to function" );
#endif /* MBEDTLS_GCM_C */
#if defined(MBEDTLS_HMAC_DRBG_C)
if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG) )
mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Too many random requested in single call" );
if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG) )
mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Input too large (Entropy + additional)" );
if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR) )
mbedtls_snprintf( buf, buflen, "HMAC_DRBG - Read/write error in file" );
if( use_ret == -(MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED) )
mbedtls_snprintf( buf, buflen, "HMAC_DRBG - The entropy source failed" );
#endif /* MBEDTLS_HMAC_DRBG_C */
#if defined(MBEDTLS_NET_C)
if( use_ret == -(MBEDTLS_ERR_NET_SOCKET_FAILED) )
mbedtls_snprintf( buf, buflen, "NET - Failed to open a socket" );
if( use_ret == -(MBEDTLS_ERR_NET_CONNECT_FAILED) )
mbedtls_snprintf( buf, buflen, "NET - The connection to the given server / port failed" );
if( use_ret == -(MBEDTLS_ERR_NET_BIND_FAILED) )
mbedtls_snprintf( buf, buflen, "NET - Binding of the socket failed" );
if( use_ret == -(MBEDTLS_ERR_NET_LISTEN_FAILED) )
mbedtls_snprintf( buf, buflen, "NET - Could not listen on the socket" );
if( use_ret == -(MBEDTLS_ERR_NET_ACCEPT_FAILED) )
mbedtls_snprintf( buf, buflen, "NET - Could not accept the incoming connection" );
if( use_ret == -(MBEDTLS_ERR_NET_RECV_FAILED) )
mbedtls_snprintf( buf, buflen, "NET - Reading information from the socket failed" );
if( use_ret == -(MBEDTLS_ERR_NET_SEND_FAILED) )
mbedtls_snprintf( buf, buflen, "NET - Sending information through the socket failed" );
if( use_ret == -(MBEDTLS_ERR_NET_CONN_RESET) )
mbedtls_snprintf( buf, buflen, "NET - Connection was reset by peer" );
if( use_ret == -(MBEDTLS_ERR_NET_UNKNOWN_HOST) )
mbedtls_snprintf( buf, buflen, "NET - Failed to get an IP address for the given hostname" );
if( use_ret == -(MBEDTLS_ERR_NET_BUFFER_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "NET - Buffer is too small to hold the data" );
if( use_ret == -(MBEDTLS_ERR_NET_INVALID_CONTEXT) )
mbedtls_snprintf( buf, buflen, "NET - The context is invalid, eg because it was free()ed" );
#endif /* MBEDTLS_NET_C */
#if defined(MBEDTLS_OID_C)
if( use_ret == -(MBEDTLS_ERR_OID_NOT_FOUND) )
mbedtls_snprintf( buf, buflen, "OID - OID is not found" );
if( use_ret == -(MBEDTLS_ERR_OID_BUF_TOO_SMALL) )
mbedtls_snprintf( buf, buflen, "OID - output buffer is too small" );
#endif /* MBEDTLS_OID_C */
#if defined(MBEDTLS_PADLOCK_C)
if( use_ret == -(MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED) )
mbedtls_snprintf( buf, buflen, "PADLOCK - Input data should be aligned" );
#endif /* MBEDTLS_PADLOCK_C */
#if defined(MBEDTLS_THREADING_C)
if( use_ret == -(MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE) )
mbedtls_snprintf( buf, buflen, "THREADING - The selected feature is not available" );
if( use_ret == -(MBEDTLS_ERR_THREADING_BAD_INPUT_DATA) )
mbedtls_snprintf( buf, buflen, "THREADING - Bad input parameters to function" );
if( use_ret == -(MBEDTLS_ERR_THREADING_MUTEX_ERROR) )
mbedtls_snprintf( buf, buflen, "THREADING - Locking / unlocking / free failed with error code" );
#endif /* MBEDTLS_THREADING_C */
#if defined(MBEDTLS_XTEA_C)
if( use_ret == -(MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH) )
mbedtls_snprintf( buf, buflen, "XTEA - The data input has an invalid length" );
#endif /* MBEDTLS_XTEA_C */
// END generated code
if( strlen( buf ) != 0 )
return;
mbedtls_snprintf( buf, buflen, "UNKNOWN ERROR CODE (%04X)", use_ret );
}
#else /* MBEDTLS_ERROR_C */
#if defined(MBEDTLS_ERROR_STRERROR_DUMMY)
/*
* Provide an non-function in case MBEDTLS_ERROR_C is not defined
*/
void mbedtls_strerror( int ret, char *buf, size_t buflen )
{
((void) ret);
if( buflen > 0 )
buf[0] = '\0';
}
#endif /* MBEDTLS_ERROR_STRERROR_DUMMY */
#endif /* MBEDTLS_ERROR_C */
| ./CrossVul/dataset_final_sorted/CWE-287/c/good_2756_5 |
crossvul-cpp_data_good_3184_2 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/***************************************************************************
* Copyright (C) 2013-2017 Ping Identity Corporation
* All rights reserved.
*
* For further information please contact:
*
* Ping Identity Corporation
* 1099 18th St Suite 2950
* Denver, CO 80202
* 303.468.2900
* http://www.pingidentity.com
*
* DISCLAIMER OF WARRANTIES:
*
* THE SOFTWARE PROVIDED HEREUNDER IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
* ANY WARRANTIES OR REPRESENTATIONS EXPRESS, IMPLIED OR STATUTORY; INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF QUALITY, PERFORMANCE, NONINFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. NOR ARE THERE ANY
* WARRANTIES CREATED BY A COURSE OR DEALING, COURSE OF PERFORMANCE OR TRADE
* USAGE. FURTHERMORE, THERE ARE NO WARRANTIES THAT THE SOFTWARE WILL MEET
* YOUR NEEDS OR BE FREE FROM ERRORS, OR THAT THE OPERATION OF THE SOFTWARE
* WILL BE UNINTERRUPTED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES 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.
*
* Initially based on mod_auth_cas.c:
* https://github.com/Jasig/mod_auth_cas
*
* Other code copied/borrowed/adapted:
* shared memory caching: mod_auth_mellon
*
* @Author: Hans Zandbelt - hans.zandbelt@zmartzone.eu
*
**************************************************************************/
#include "apr_hash.h"
#include "apr_strings.h"
#include "ap_config.h"
#include "ap_provider.h"
#include "apr_lib.h"
#include "apr_file_io.h"
#include "apr_sha1.h"
#include "apr_base64.h"
#include "httpd.h"
#include "http_core.h"
#include "http_config.h"
#include "http_log.h"
#include "http_protocol.h"
#include "http_request.h"
#include "mod_auth_openidc.h"
// TODO:
// - sort out oidc_cfg vs. oidc_dir_cfg stuff
// - rigid input checking on discovery responses
// - check self-issued support
// - README.quickstart
// - refresh metadata once-per too? (for non-signing key changes)
extern module AP_MODULE_DECLARE_DATA auth_openidc_module;
/*
* clean any suspicious headers in the HTTP request sent by the user agent
*/
static void oidc_scrub_request_headers(request_rec *r, const char *claim_prefix,
const char *authn_header) {
const int prefix_len = claim_prefix ? strlen(claim_prefix) : 0;
/* get an array representation of the incoming HTTP headers */
const apr_array_header_t * const h = apr_table_elts(r->headers_in);
/* table to keep the non-suspicious headers */
apr_table_t *clean_headers = apr_table_make(r->pool, h->nelts);
/* loop over the incoming HTTP headers */
const apr_table_entry_t * const e = (const apr_table_entry_t *) h->elts;
int i;
for (i = 0; i < h->nelts; i++) {
const char * const k = e[i].key;
/* is this header's name equivalent to the header that mod_auth_openidc would set for the authenticated user? */
const int authn_header_matches = (k != NULL) && authn_header
&& (oidc_strnenvcmp(k, authn_header, -1) == 0);
/*
* would this header be interpreted as a mod_auth_openidc attribute? Note
* that prefix_len will be zero if no attr_prefix is defined,
* so this will always be false. Also note that we do not
* scrub headers if the prefix is empty because every header
* would match.
*/
const int prefix_matches = (k != NULL) && prefix_len
&& (oidc_strnenvcmp(k, claim_prefix, prefix_len) == 0);
/* add to the clean_headers if non-suspicious, skip and report otherwise */
if (!prefix_matches && !authn_header_matches) {
apr_table_addn(clean_headers, k, e[i].val);
} else {
oidc_warn(r, "scrubbed suspicious request header (%s: %.32s)", k,
e[i].val);
}
}
/* overwrite the incoming headers with the cleaned result */
r->headers_in = clean_headers;
}
/*
* scrub all mod_auth_openidc related headers
*/
void oidc_scrub_headers(request_rec *r) {
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
if (cfg->scrub_request_headers != 0) {
/* scrub all headers starting with OIDC_ first */
oidc_scrub_request_headers(r, OIDC_DEFAULT_HEADER_PREFIX,
oidc_cfg_dir_authn_header(r));
/*
* then see if the claim headers need to be removed on top of that
* (i.e. the prefix does not start with the default OIDC_)
*/
if ((strstr(cfg->claim_prefix, OIDC_DEFAULT_HEADER_PREFIX)
!= cfg->claim_prefix)) {
oidc_scrub_request_headers(r, cfg->claim_prefix, NULL);
}
}
}
/*
* strip the session cookie from the headers sent to the application/backend
*/
static void oidc_strip_cookies(request_rec *r) {
char *cookie, *ctx, *result = NULL;
const char *name = NULL;
int i;
apr_array_header_t *strip = oidc_dir_cfg_strip_cookies(r);
char *cookies = apr_pstrdup(r->pool,
(char *) apr_table_get(r->headers_in, "Cookie"));
if ((cookies != NULL) && (strip != NULL)) {
oidc_debug(r,
"looking for the following cookies to strip from cookie header: %s",
apr_array_pstrcat(r->pool, strip, ','));
cookie = apr_strtok(cookies, ";", &ctx);
do {
while (cookie != NULL && *cookie == ' ')
cookie++;
for (i = 0; i < strip->nelts; i++) {
name = ((const char**) strip->elts)[i];
if ((strncmp(cookie, name, strlen(name)) == 0)
&& (cookie[strlen(name)] == '=')) {
oidc_debug(r, "stripping: %s", name);
break;
}
}
if (i == strip->nelts) {
result =
result ?
apr_psprintf(r->pool, "%s;%s", result, cookie) :
cookie;
}
cookie = apr_strtok(NULL, ";", &ctx);
} while (cookie != NULL);
if (result != NULL) {
oidc_debug(r, "set cookie to backend to: %s",
result ?
apr_psprintf(r->pool, "\"%s\"", result) : "<null>");
apr_table_set(r->headers_in, "Cookie", result);
} else {
oidc_debug(r, "unsetting all cookies to backend");
apr_table_unset(r->headers_in, "Cookie");
}
}
}
#define OIDC_SHA1_LEN 20
/*
* calculates a hash value based on request fingerprint plus a provided nonce string.
*/
static char *oidc_get_browser_state_hash(request_rec *r, const char *nonce) {
oidc_debug(r, "enter");
/* helper to hold to header values */
const char *value = NULL;
/* the hash context */
apr_sha1_ctx_t sha1;
/* Initialize the hash context */
apr_sha1_init(&sha1);
/* get the X_FORWARDED_FOR header value */
value = (char *) apr_table_get(r->headers_in, "X_FORWARDED_FOR");
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, strlen(value));
/* get the USER_AGENT header value */
value = (char *) apr_table_get(r->headers_in, "USER_AGENT");
/* if we have a value for this header, concat it to the hash input */
if (value != NULL)
apr_sha1_update(&sha1, value, strlen(value));
/* get the remote client IP address or host name */
/*
int remotehost_is_ip;
value = ap_get_remote_host(r->connection, r->per_dir_config,
REMOTE_NOLOOKUP, &remotehost_is_ip);
apr_sha1_update(&sha1, value, strlen(value));
*/
/* concat the nonce parameter to the hash input */
apr_sha1_update(&sha1, nonce, strlen(nonce));
/* finalize the hash input and calculate the resulting hash output */
unsigned char hash[OIDC_SHA1_LEN];
apr_sha1_final(hash, &sha1);
/* base64url-encode the resulting hash and return it */
char *result = NULL;
oidc_base64url_encode(r, &result, (const char *) hash, OIDC_SHA1_LEN, TRUE);
return result;
}
/*
* return the name for the state cookie
*/
static char *oidc_get_state_cookie_name(request_rec *r, const char *state) {
return apr_psprintf(r->pool, "%s%s", OIDCStateCookiePrefix, state);
}
/*
* return the static provider configuration, i.e. from a metadata URL or configuration primitives
*/
static apr_byte_t oidc_provider_static_config(request_rec *r, oidc_cfg *c,
oidc_provider_t **provider) {
json_t *j_provider = NULL;
const char *s_json = NULL;
/* see if we should configure a static provider based on external (cached) metadata */
if ((c->metadata_dir != NULL) || (c->provider.metadata_url == NULL)) {
*provider = &c->provider;
return TRUE;
}
c->cache->get(r, OIDC_CACHE_SECTION_PROVIDER,
oidc_util_escape_string(r, c->provider.metadata_url), &s_json);
if (s_json == NULL) {
if (oidc_metadata_provider_retrieve(r, c, NULL,
c->provider.metadata_url, &j_provider, &s_json) == FALSE) {
oidc_error(r, "could not retrieve metadata from url: %s",
c->provider.metadata_url);
return FALSE;
}
c->cache->set(r, OIDC_CACHE_SECTION_PROVIDER,
oidc_util_escape_string(r, c->provider.metadata_url), s_json,
apr_time_now()
+ (c->provider_metadata_refresh_interval <= 0 ?
apr_time_from_sec(
OIDC_CACHE_PROVIDER_METADATA_EXPIRY_DEFAULT) :
c->provider_metadata_refresh_interval));
} else {
/* correct parsing and validation was already done when it was put in the cache */
j_provider = json_loads(s_json, 0, 0);
}
*provider = apr_pcalloc(r->pool, sizeof(oidc_provider_t));
memcpy(*provider, &c->provider, sizeof(oidc_provider_t));
if (oidc_metadata_provider_parse(r, c, j_provider, *provider) == FALSE) {
oidc_error(r, "could not parse metadata from url: %s",
c->provider.metadata_url);
if (j_provider)
json_decref(j_provider);
return FALSE;
}
json_decref(j_provider);
return TRUE;
}
/*
* return the oidc_provider_t struct for the specified issuer
*/
static oidc_provider_t *oidc_get_provider_for_issuer(request_rec *r,
oidc_cfg *c, const char *issuer, apr_byte_t allow_discovery) {
/* by default we'll assume that we're dealing with a single statically configured OP */
oidc_provider_t *provider = NULL;
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return NULL;
/* unless a metadata directory was configured, so we'll try and get the provider settings from there */
if (c->metadata_dir != NULL) {
/* try and get metadata from the metadata directory for the OP that sent this response */
if ((oidc_metadata_get(r, c, issuer, &provider, allow_discovery)
== FALSE) || (provider == NULL)) {
/* don't know nothing about this OP/issuer */
oidc_error(r, "no provider metadata found for issuer \"%s\"",
issuer);
return NULL;
}
}
return provider;
}
/*
* find out whether the request is a response from an IDP discovery page
*/
static apr_byte_t oidc_is_discovery_response(request_rec *r, oidc_cfg *cfg) {
/*
* prereq: this is a call to the configured redirect_uri, now see if:
* the OIDC_DISC_OP_PARAM is present
*/
return oidc_util_request_has_parameter(r, OIDC_DISC_OP_PARAM)
|| oidc_util_request_has_parameter(r, OIDC_DISC_USER_PARAM);
}
/*
* return the HTTP method being called: only for POST data persistence purposes
*/
static const char *oidc_original_request_method(request_rec *r, oidc_cfg *cfg,
apr_byte_t handle_discovery_response) {
const char *method = OIDC_METHOD_GET;
char *m = NULL;
if ((handle_discovery_response == TRUE)
&& (oidc_util_request_matches_url(r, cfg->redirect_uri))
&& (oidc_is_discovery_response(r, cfg))) {
oidc_util_get_request_parameter(r, OIDC_DISC_RM_PARAM, &m);
if (m != NULL)
method = apr_pstrdup(r->pool, m);
} else {
/*
* if POST preserve is not enabled for this location, there's no point in preserving
* the method either which would result in POSTing empty data on return;
* so we revert to legacy behavior
*/
if (oidc_cfg_dir_preserve_post(r) == 0)
return OIDC_METHOD_GET;
const char *content_type = apr_table_get(r->headers_in, "Content-Type");
if ((r->method_number == M_POST)
&& (apr_strnatcmp(content_type,
"application/x-www-form-urlencoded") == 0))
method = OIDC_METHOD_FORM_POST;
}
oidc_debug(r, "return: %s", method);
return method;
}
/*
* send an OpenID Connect authorization request to the specified provider preserving POST parameters using HTML5 storage
*/
apr_byte_t oidc_post_preserve_javascript(request_rec *r, const char *location,
char **javascript, char **javascript_method) {
if (oidc_cfg_dir_preserve_post(r) == 0)
return FALSE;
oidc_debug(r, "enter");
oidc_cfg *cfg = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
const char *method = oidc_original_request_method(r, cfg, FALSE);
if (apr_strnatcmp(method, OIDC_METHOD_FORM_POST) != 0)
return FALSE;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return FALSE;
}
const apr_array_header_t *arr = apr_table_elts(params);
const apr_table_entry_t *elts = (const apr_table_entry_t*) arr->elts;
int i;
char *json = "";
for (i = 0; i < arr->nelts; i++) {
json = apr_psprintf(r->pool, "%s'%s': '%s'%s", json,
oidc_util_escape_string(r, elts[i].key),
oidc_util_escape_string(r, elts[i].val),
i < arr->nelts - 1 ? "," : "");
}
json = apr_psprintf(r->pool, "{ %s }", json);
const char *jmethod = "preserveOnLoad";
const char *jscript =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function %s() {\n"
" localStorage.setItem('mod_auth_openidc_preserve_post_params', JSON.stringify(%s));\n"
" %s"
" }\n"
" </script>\n", jmethod, json,
location ?
apr_psprintf(r->pool, "window.location='%s';\n",
location) :
"");
if (location == NULL) {
if (javascript_method)
*javascript_method = apr_pstrdup(r->pool, jmethod);
if (javascript)
*javascript = apr_pstrdup(r->pool, jscript);
} else {
oidc_util_html_send(r, "Preserving...", jscript, jmethod,
"<p>Preserving...</p>", DONE);
}
return TRUE;
}
/*
* restore POST parameters on original_url from HTML5 local storage
*/
static int oidc_request_post_preserved_restore(request_rec *r,
const char *original_url) {
oidc_debug(r, "enter: original_url=%s", original_url);
const char *method = "postOnLoad";
const char *script =
apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" function %s() {\n"
" var mod_auth_openidc_preserve_post_params = JSON.parse(localStorage.getItem('mod_auth_openidc_preserve_post_params'));\n"
" localStorage.removeItem('mod_auth_openidc_preserve_post_params');\n"
" for (var key in mod_auth_openidc_preserve_post_params) {\n"
" var input = document.createElement(\"input\");\n"
" input.name = decodeURIComponent(key);\n"
" input.value = decodeURIComponent(mod_auth_openidc_preserve_post_params[key]);\n"
" input.type = \"hidden\";\n"
" document.forms[0].appendChild(input);\n"
" }\n"
" document.forms[0].action = '%s';\n"
" document.forms[0].submit();\n"
" }\n"
" </script>\n", method, original_url);
const char *body = " <p>Restoring...</p>\n"
" <form method=\"post\"></form>\n";
return oidc_util_html_send(r, "Restoring...", script, method, body,
DONE);
}
/*
* parse state that was sent to us by the issuer
*/
static apr_byte_t oidc_unsolicited_proto_state(request_rec *r, oidc_cfg *c,
const char *state, json_t **proto_state) {
char *alg = NULL;
oidc_debug(r, "enter: state header=%s",
oidc_proto_peek_jwt_header(r, state, &alg));
oidc_jose_error_t err;
oidc_jwk_t *jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret,
oidc_alg2keysize(alg), "sha256",
TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwt_t *jwt = NULL;
if (oidc_jwt_parse(r->pool, state, &jwt,
oidc_util_merge_symmetric_key(r->pool, c->private_keys, jwk),
&err) == FALSE) {
oidc_error(r,
"could not parse JWT from state: invalid unsolicited response: %s",
oidc_jose_e2s(r->pool, err));
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully parsed JWT from state");
if (jwt->payload.iss == NULL) {
oidc_error(r, "no \"iss\" could be retrieved from JWT state, aborting");
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_provider_t *provider = oidc_get_provider_for_issuer(r, c,
jwt->payload.iss, FALSE);
if (provider == NULL) {
oidc_jwt_destroy(jwt);
return FALSE;
}
/* validate the state JWT, validating optional exp + iat */
if (oidc_proto_validate_jwt(r, jwt, provider->issuer, FALSE, FALSE,
provider->idtoken_iat_slack) == FALSE) {
oidc_jwt_destroy(jwt);
return FALSE;
}
char *rfp = NULL;
if (oidc_jose_get_string(r->pool, jwt->payload.value.json, "rfp", TRUE,
&rfp, &err) == FALSE) {
oidc_error(r,
"no \"rfp\" claim could be retrieved from JWT state, aborting: %s",
oidc_jose_e2s(r->pool, err));
oidc_jwt_destroy(jwt);
return FALSE;
}
if (apr_strnatcmp(rfp, "iss") != 0) {
oidc_error(r, "\"rfp\" (%s) does not match \"iss\", aborting", rfp);
oidc_jwt_destroy(jwt);
return FALSE;
}
char *target_link_uri = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json, "target_link_uri",
FALSE, &target_link_uri, NULL);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
oidc_error(r,
"no \"target_link_uri\" claim could be retrieved from JWT state and no OIDCDefaultURL is set, aborting");
oidc_jwt_destroy(jwt);
return FALSE;
}
target_link_uri = c->default_sso_url;
}
if (c->metadata_dir != NULL) {
if ((oidc_metadata_get(r, c, jwt->payload.iss, &provider, FALSE)
== FALSE) || (provider == NULL)) {
oidc_error(r, "no provider metadata found for provider \"%s\"",
jwt->payload.iss);
oidc_jwt_destroy(jwt);
return FALSE;
}
}
char *jti = NULL;
oidc_jose_get_string(r->pool, jwt->payload.value.json, "jti", FALSE, &jti,
NULL);
if (jti == NULL) {
char *cser = oidc_jwt_serialize(r->pool, jwt, &err);
if (cser == NULL)
return FALSE;
if (oidc_util_hash_string_and_base64url_encode(r, "sha256", cser,
&jti) == FALSE) {
oidc_error(r,
"oidc_util_hash_string_and_base64url_encode returned an error");
return FALSE;
}
}
const char *replay = NULL;
c->cache->get(r, OIDC_CACHE_SECTION_JTI, jti, &replay);
if (replay != NULL) {
oidc_error(r,
"the jti value (%s) passed in the browser state was found in the cache already; possible replay attack!?",
jti);
oidc_jwt_destroy(jwt);
return FALSE;
}
/* jti cache duration is the configured replay prevention window for token issuance plus 10 seconds for safety */
apr_time_t jti_cache_duration = apr_time_from_sec(
provider->idtoken_iat_slack * 2 + 10);
/* store it in the cache for the calculated duration */
c->cache->set(r, OIDC_CACHE_SECTION_JTI, jti, jti,
apr_time_now() + jti_cache_duration);
oidc_debug(r,
"jti \"%s\" validated successfully and is now cached for %" APR_TIME_T_FMT " seconds",
jti, apr_time_sec(jti_cache_duration));
jwk = NULL;
if (oidc_util_create_symmetric_key(r, c->provider.client_secret, 0,
NULL, TRUE, &jwk) == FALSE)
return FALSE;
oidc_jwks_uri_t jwks_uri = { provider->jwks_uri,
provider->jwks_refresh_interval, provider->ssl_validate_server };
if (oidc_proto_jwt_verify(r, c, jwt, &jwks_uri,
oidc_util_merge_symmetric_key(r->pool, NULL, jwk)) == FALSE) {
oidc_error(r, "state JWT could not be validated, aborting");
oidc_jwt_destroy(jwt);
return FALSE;
}
oidc_jwk_destroy(jwk);
oidc_debug(r, "successfully verified state JWT");
*proto_state = json_object();
json_object_set_new(*proto_state, "issuer", json_string(jwt->payload.iss));
json_object_set_new(*proto_state, "original_url",
json_string(target_link_uri));
json_object_set_new(*proto_state, "original_method", json_string("get"));
json_object_set_new(*proto_state, "response_mode",
json_string(provider->response_mode));
json_object_set_new(*proto_state, "response_type",
json_string(provider->response_type));
json_object_set_new(*proto_state, "timestamp",
json_integer(apr_time_sec(apr_time_now())));
oidc_jwt_destroy(jwt);
return TRUE;
}
/* obtain the state from the cookie value */
static json_t * oidc_get_state_from_cookie(request_rec *r, oidc_cfg *c,
const char *cookieValue) {
json_t *result = NULL;
oidc_util_jwt_verify(r, c->crypto_passphrase, cookieValue, &result);
return result;
}
static void oidc_clean_expired_state_cookies(request_rec *r, oidc_cfg *c) {
char *cookie, *tokenizerCtx;
char *cookies = apr_pstrdup(r->pool,
(char *) apr_table_get(r->headers_in, "Cookie"));
if (cookies != NULL) {
cookie = apr_strtok(cookies, ";", &tokenizerCtx);
do {
while (cookie != NULL && *cookie == ' ')
cookie++;
if (strstr(cookie, OIDCStateCookiePrefix) == cookie) {
char *cookieName = cookie;
while (cookie != NULL && *cookie != '=')
cookie++;
if (*cookie == '=') {
*cookie = '\0';
cookie++;
json_t *state = oidc_get_state_from_cookie(r, c, cookie);
if (state != NULL) {
json_t *v = json_object_get(state, "timestamp");
apr_time_t now = apr_time_sec(apr_time_now());
if (now > json_integer_value(v) + c->state_timeout) {
oidc_error(r, "state has expired");
oidc_util_set_cookie(r, cookieName, "", 0);
}
json_decref(state);
}
}
}
cookie = apr_strtok(NULL, ";", &tokenizerCtx);
} while (cookie != NULL);
}
}
/*
* restore the state that was maintained between authorization request and response in an encrypted cookie
*/
static apr_byte_t oidc_restore_proto_state(request_rec *r, oidc_cfg *c,
const char *state, json_t **proto_state) {
oidc_debug(r, "enter");
/* clean expired state cookies to avoid pollution */
oidc_clean_expired_state_cookies(r, c);
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* get the state cookie value first */
char *cookieValue = oidc_util_get_cookie(r, cookieName);
if (cookieValue == NULL) {
oidc_error(r, "no \"%s\" state cookie found", cookieName);
return oidc_unsolicited_proto_state(r, c, state, proto_state);
}
/* clear state cookie because we don't need it anymore */
oidc_util_set_cookie(r, cookieName, "", 0);
*proto_state = oidc_get_state_from_cookie(r, c, cookieValue);
if (*proto_state == NULL)
return FALSE;
json_t *v = json_object_get(*proto_state, "nonce");
/* calculate the hash of the browser fingerprint concatenated with the nonce */
char *calc = oidc_get_browser_state_hash(r, json_string_value(v));
/* compare the calculated hash with the value provided in the authorization response */
if (apr_strnatcmp(calc, state) != 0) {
oidc_error(r,
"calculated state from cookie does not match state parameter passed back in URL: \"%s\" != \"%s\"",
state, calc);
json_decref(*proto_state);
return FALSE;
}
v = json_object_get(*proto_state, "timestamp");
apr_time_t now = apr_time_sec(apr_time_now());
/* check that the timestamp is not beyond the valid interval */
if (now > json_integer_value(v) + c->state_timeout) {
oidc_error(r, "state has expired");
oidc_util_html_send_error(r, c->error_template,
"Invalid Authentication Response",
apr_psprintf(r->pool,
"This is due to a timeout; please restart your authentication session by re-entering the URL/bookmark you originally wanted to access: %s",
json_string_value(
json_object_get(*proto_state, "original_url"))),
DONE);
json_decref(*proto_state);
return FALSE;
}
/* add the state */
json_object_set_new(*proto_state, "state", json_string(state));
char *s_value = json_dumps(*proto_state, JSON_ENCODE_ANY);
oidc_debug(r, "restored state: %s", s_value);
free(s_value);
/* we've made it */
return TRUE;
}
/*
* set the state that is maintained between an authorization request and an authorization response
* in a cookie in the browser that is cryptographically bound to that state
*/
static apr_byte_t oidc_authorization_request_set_cookie(request_rec *r,
oidc_cfg *c, const char *state, json_t *proto_state) {
/*
* create a cookie consisting of 8 elements:
* random value, original URL, original method, issuer, response_type, response_mod, prompt and timestamp
* encoded as JSON
*/
/* encrypt the resulting JSON value */
char *cookieValue = NULL;
if (oidc_util_jwt_create(r, c->crypto_passphrase, proto_state,
&cookieValue) == FALSE)
return FALSE;
/* clean expired state cookies to avoid pollution */
oidc_clean_expired_state_cookies(r, c);
/* assemble the cookie name for the state cookie */
const char *cookieName = oidc_get_state_cookie_name(r, state);
/* set it as a cookie */
oidc_util_set_cookie(r, cookieName, cookieValue, -1);
//free(s_value);
return TRUE;
}
/*
* get the mod_auth_openidc related context from the (userdata in the) request
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
static apr_table_t *oidc_request_state(request_rec *rr) {
/* our state is always stored in the main request */
request_rec *r = (rr->main != NULL) ? rr->main : rr;
/* our state is a table, get it */
apr_table_t *state = NULL;
apr_pool_userdata_get((void **) &state, OIDC_USERDATA_KEY, r->pool);
/* if it does not exist, we'll create a new table */
if (state == NULL) {
state = apr_table_make(r->pool, 5);
apr_pool_userdata_set(state, OIDC_USERDATA_KEY, NULL, r->pool);
}
/* return the resulting table, always non-null now */
return state;
}
/*
* set a name/value pair in the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
void oidc_request_state_set(request_rec *r, const char *key, const char *value) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* put the name/value pair in that table */
apr_table_setn(state, key, value);
}
/*
* get a name/value pair from the mod_auth_openidc-specific request context
* (used for passing state between various Apache request processing stages and hook callbacks)
*/
const char*oidc_request_state_get(request_rec *r, const char *key) {
/* get a handle to the global state, which is a table */
apr_table_t *state = oidc_request_state(r);
/* return the value from the table */
return apr_table_get(state, key);
}
/*
* set the claims from a JSON object (c.q. id_token or user_info response) stored
* in the session in to HTTP headers passed on to the application
*/
static apr_byte_t oidc_set_app_claims(request_rec *r,
const oidc_cfg * const cfg, oidc_session_t *session,
const char *s_claims) {
json_t *j_claims = NULL;
/* decode the string-encoded attributes in to a JSON structure */
if (s_claims != NULL) {
json_error_t json_error;
j_claims = json_loads(s_claims, 0, &json_error);
if (j_claims == NULL) {
/* whoops, JSON has been corrupted */
oidc_error(r,
"unable to parse \"%s\" JSON stored in the session: %s",
s_claims, json_error.text);
return FALSE;
}
}
/* set the resolved claims a HTTP headers for the application */
if (j_claims != NULL) {
oidc_util_set_app_infos(r, j_claims, cfg->claim_prefix,
cfg->claim_delimiter, oidc_cfg_dir_pass_info_in_headers(r),
oidc_cfg_dir_pass_info_in_envvars(r));
/* release resources */
json_decref(j_claims);
}
return TRUE;
}
static int oidc_authenticate_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, const char *original_url,
const char *login_hint, const char *id_token_hint, const char *prompt,
const char *auth_request_params);
/*
* log message about max session duration
*/
static void oidc_log_session_expires(request_rec *r, const char *msg,
apr_time_t session_expires) {
char buf[APR_RFC822_DATE_LEN + 1];
apr_rfc822_date(buf, session_expires);
oidc_debug(r, "%s: %s (in %" APR_TIME_T_FMT " secs from now)", msg, buf,
apr_time_sec(session_expires - apr_time_now()));
}
/*
* find out which action we need to take when encountering an unauthenticated request
*/
static int oidc_handle_unauthenticated_user(request_rec *r, oidc_cfg *c) {
/* see if we've configured OIDCUnAuthAction for this path */
switch (oidc_dir_cfg_unauth_action(r)) {
case OIDC_UNAUTH_RETURN410:
return HTTP_GONE;
case OIDC_UNAUTH_RETURN401:
return HTTP_UNAUTHORIZED;
case OIDC_UNAUTH_PASS:
r->user = "";
/*
* we're not going to pass information about an authenticated user to the application,
* but we do need to scrub the headers that mod_auth_openidc would set for security reasons
*/
oidc_scrub_headers(r);
return OK;
case OIDC_UNAUTH_AUTHENTICATE:
/*
* exception handling: if this looks like a XMLHttpRequest call we
* won't redirect the user and thus avoid creating a state cookie
* for a non-browser (= Javascript) call that will never return from the OP
*/
if ((apr_table_get(r->headers_in, "X-Requested-With") != NULL) && (apr_strnatcasecmp(apr_table_get(r->headers_in, "X-Requested-With"), "XMLHttpRequest") == 0))
return HTTP_UNAUTHORIZED;
}
/*
* else: no session (regardless of whether it is main or sub-request),
* and we need to authenticate the user
*/
return oidc_authenticate_user(r, c, NULL, oidc_get_current_url(r), NULL,
NULL, NULL, NULL);
}
/*
* check if maximum session duration was exceeded
*/
static int oidc_check_max_session_duration(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
const char *s_session_expires = NULL;
apr_time_t session_expires;
/* get the session expiry from the session data */
oidc_session_get(r, session, OIDC_SESSION_EXPIRES_SESSION_KEY,
&s_session_expires);
/* convert the string to a timestamp */
sscanf(s_session_expires, "%" APR_TIME_T_FMT, &session_expires);
/* check the expire timestamp against the current time */
if (apr_time_now() > session_expires) {
oidc_warn(r, "maximum session duration exceeded for user: %s",
session->remote_user);
oidc_session_kill(r, session);
return oidc_handle_unauthenticated_user(r, cfg);
}
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
return OK;
}
/*
* validate received session cookie against the domain it was issued for:
*
* this handles the case where the cache configured is a the same single memcache, Redis, or file
* backend for different (virtual) hosts, or a client-side cookie protected with the same secret
*
* it also handles the case that a cookie is unexpectedly shared across multiple hosts in
* name-based virtual hosting even though the OP(s) would be the same
*/
static apr_byte_t oidc_check_cookie_domain(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
const char *c_cookie_domain =
cfg->cookie_domain ?
cfg->cookie_domain : oidc_get_current_url_host(r);
const char *s_cookie_domain = NULL;
oidc_session_get(r, session, OIDC_COOKIE_DOMAIN_SESSION_KEY,
&s_cookie_domain);
if ((s_cookie_domain == NULL)
|| (apr_strnatcmp(c_cookie_domain, s_cookie_domain) != 0)) {
oidc_warn(r,
"aborting: detected attempt to play cookie against a different domain/host than issued for! (issued=%s, current=%s)",
s_cookie_domain, c_cookie_domain);
return FALSE;
}
return TRUE;
}
/*
* get a handle to the provider configuration via the "issuer" stored in the session
*/
apr_byte_t oidc_get_provider_from_session(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t **provider) {
oidc_debug(r, "enter");
/* get the issuer value from the session state */
const char *issuer = NULL;
oidc_session_get(r, session, OIDC_ISSUER_SESSION_KEY, &issuer);
if (issuer == NULL) {
oidc_error(r, "session corrupted: no issuer found in session");
return FALSE;
}
/* get the provider info associated with the issuer value */
oidc_provider_t *p = oidc_get_provider_for_issuer(r, c, issuer, FALSE);
if (p == NULL) {
oidc_error(r, "session corrupted: no provider found for issuer: %s",
issuer);
return FALSE;
}
*provider = p;
return TRUE;
}
/*
* store the access token expiry timestamp in the session, based on the expires_in
*/
static void oidc_store_access_token_expiry(request_rec *r,
oidc_session_t *session, int expires_in) {
if (expires_in != -1) {
oidc_session_set(r, session, OIDC_ACCESSTOKEN_EXPIRES_SESSION_KEY,
apr_psprintf(r->pool, "%" APR_TIME_T_FMT,
apr_time_sec(apr_time_now()) + expires_in));
}
}
/*
* store claims resolved from the userinfo endpoint in the session
*/
static void oidc_store_userinfo_claims(request_rec *r, oidc_session_t *session,
oidc_provider_t *provider, const char *claims) {
oidc_debug(r, "enter");
/* see if we've resolved any claims */
if (claims != NULL) {
/*
* Successfully decoded a set claims from the response so we can store them
* (well actually the stringified representation in the response)
* in the session context safely now
*/
oidc_session_set(r, session, OIDC_CLAIMS_SESSION_KEY, claims);
} else {
/*
* clear the existing claims because we could not refresh them
*/
oidc_session_set(r, session, OIDC_CLAIMS_SESSION_KEY, NULL);
}
/* store the last refresh time if we've configured a userinfo refresh interval */
if (provider->userinfo_refresh_interval > 0)
oidc_session_set(r, session, OIDC_USERINFO_LAST_REFRESH_SESSION_KEY,
apr_psprintf(r->pool, "%" APR_TIME_T_FMT, apr_time_now()));
}
/*
* execute refresh token grant to refresh the existing access token
*/
static apr_byte_t oidc_refresh_access_token(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider,
char **new_access_token) {
oidc_debug(r, "enter");
/* get the refresh token that was stored in the session */
const char *refresh_token = NULL;
oidc_session_get(r, session, OIDC_REFRESHTOKEN_SESSION_KEY, &refresh_token);
if (refresh_token == NULL) {
oidc_warn(r,
"refresh token routine called but no refresh_token found in the session");
return FALSE;
}
/* elements returned in the refresh response */
char *s_id_token = NULL;
int expires_in = -1;
char *s_token_type = NULL;
char *s_access_token = NULL;
char *s_refresh_token = NULL;
/* refresh the tokens by calling the token endpoint */
if (oidc_proto_refresh_request(r, c, provider, refresh_token, &s_id_token,
&s_access_token, &s_token_type, &expires_in,
&s_refresh_token) == FALSE) {
oidc_error(r, "access_token could not be refreshed");
return FALSE;
}
/* store the new access_token in the session and discard the old one */
oidc_session_set(r, session, OIDC_ACCESSTOKEN_SESSION_KEY, s_access_token);
oidc_store_access_token_expiry(r, session, expires_in);
/* see if we need to return it as a parameter */
if (new_access_token != NULL)
*new_access_token = s_access_token;
/* if we have a new refresh token (rolling refresh), store it in the session and overwrite the old one */
if (s_refresh_token != NULL)
oidc_session_set(r, session, OIDC_REFRESHTOKEN_SESSION_KEY,
s_refresh_token);
return TRUE;
}
/*
* retrieve claims from the userinfo endpoint and return the stringified response
*/
static const char *oidc_retrieve_claims_from_userinfo_endpoint(request_rec *r,
oidc_cfg *c, oidc_provider_t *provider, const char *access_token,
oidc_session_t *session, char *id_token_sub) {
oidc_debug(r, "enter");
/* see if a userinfo endpoint is set, otherwise there's nothing to do for us */
if (provider->userinfo_endpoint_url == NULL) {
oidc_debug(r,
"not retrieving userinfo claims because userinfo_endpoint is not set");
return NULL;
}
/* see if there's an access token, otherwise we can't call the userinfo endpoint at all */
if (access_token == NULL) {
oidc_debug(r,
"not retrieving userinfo claims because access_token is not provided");
return NULL;
}
if ((id_token_sub == NULL) && (session != NULL)) {
// when refreshing claims from the userinfo endpoint
const char *s_id_token_claims = NULL;
oidc_session_get(r, session, OIDC_IDTOKEN_CLAIMS_SESSION_KEY,
&s_id_token_claims);
if (s_id_token_claims == NULL) {
oidc_error(r, "no id_token claims provided");
return NULL;
}
json_error_t json_error;
json_t *id_token_claims = json_loads(s_id_token_claims, 0, &json_error);
if (id_token_claims == NULL) {
oidc_error(r, "JSON parsing (json_loads) failed: %s (%s)",
json_error.text, s_id_token_claims);
return NULL;
}
oidc_jose_get_string(r->pool, id_token_claims, "sub", FALSE, &id_token_sub, NULL);
}
// TODO: return code should indicate whether the token expired or some other error occurred
// TODO: long-term: session storage should be JSON (with explicit types and less conversion, using standard routines)
/* try to get claims from the userinfo endpoint using the provided access token */
const char *result = NULL;
if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub, access_token,
&result) == FALSE) {
/* see if we have an existing session and we are refreshing the user info claims */
if (session != NULL) {
/* first call to user info endpoint failed, but the access token may have just expired, so refresh it */
char *access_token = NULL;
if (oidc_refresh_access_token(r, c, session, provider,
&access_token) == TRUE) {
/* try again with the new access token */
if (oidc_proto_resolve_userinfo(r, c, provider, id_token_sub, access_token,
&result) == FALSE) {
oidc_error(r,
"resolving user info claims with the refreshed access token failed, nothing will be stored in the session");
result = NULL;
}
} else {
oidc_warn(r,
"refreshing access token failed, claims will not be retrieved/refreshed from the userinfo endpoint");
result = NULL;
}
} else {
oidc_error(r,
"resolving user info claims with the existing/provided access token failed, nothing will be stored in the session");
result = NULL;
}
}
return result;
}
/*
* get (new) claims from the userinfo endpoint
*/
static apr_byte_t oidc_refresh_claims_from_userinfo_endpoint(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session) {
oidc_provider_t *provider = NULL;
const char *claims = NULL;
char *access_token = NULL;
/* get the current provider info */
if (oidc_get_provider_from_session(r, cfg, session, &provider) == FALSE)
return FALSE;
/* see if we can do anything here, i.e. we have a userinfo endpoint and a refresh interval is configured */
apr_time_t interval = apr_time_from_sec(
provider->userinfo_refresh_interval);
oidc_debug(r, "userinfo_endpoint=%s, interval=%d",
provider->userinfo_endpoint_url,
provider->userinfo_refresh_interval);
if ((provider->userinfo_endpoint_url != NULL) && (interval > 0)) {
/* get the last refresh timestamp from the session info */
apr_time_t last_refresh = 0;
const char *s_last_refresh = NULL;
oidc_session_get(r, session, OIDC_USERINFO_LAST_REFRESH_SESSION_KEY,
&s_last_refresh);
if (s_last_refresh != NULL) {
sscanf(s_last_refresh, "%" APR_TIME_T_FMT, &last_refresh);
}
oidc_debug(r, "refresh needed in: %" APR_TIME_T_FMT " seconds",
apr_time_sec(last_refresh + interval - apr_time_now()));
/* see if we need to refresh again */
if (last_refresh + interval < apr_time_now()) {
/* get the current access token */
oidc_session_get(r, session, OIDC_ACCESSTOKEN_SESSION_KEY,
(const char **) &access_token);
/* retrieve the current claims */
claims = oidc_retrieve_claims_from_userinfo_endpoint(r, cfg,
provider, access_token, session, NULL);
/* store claims resolved from userinfo endpoint */
oidc_store_userinfo_claims(r, session, provider, claims);
/* indicated something changed */
return TRUE;
}
}
return FALSE;
}
/*
* copy the claims and id_token from the session to the request state and optionally return them
*/
static void oidc_copy_tokens_to_request_state(request_rec *r,
oidc_session_t *session, const char **s_id_token, const char **s_claims) {
const char *id_token = NULL, *claims = NULL;
oidc_session_get(r, session, OIDC_IDTOKEN_CLAIMS_SESSION_KEY, &id_token);
oidc_session_get(r, session, OIDC_CLAIMS_SESSION_KEY, &claims);
oidc_debug(r, "id_token=%s claims=%s", id_token, claims);
if (id_token != NULL) {
oidc_request_state_set(r, OIDC_IDTOKEN_CLAIMS_SESSION_KEY, id_token);
if (s_id_token != NULL)
*s_id_token = id_token;
}
if (claims != NULL) {
oidc_request_state_set(r, OIDC_CLAIMS_SESSION_KEY, claims);
if (s_claims != NULL)
*s_claims = claims;
}
}
/*
* pass refresh_token, access_token and access_token_expires as headers/environment variables to the application
*/
static apr_byte_t oidc_session_pass_tokens_and_save(request_rec *r,
oidc_cfg *cfg, oidc_session_t *session, apr_byte_t needs_save) {
int pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
int pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
/* set the refresh_token in the app headers/variables, if enabled for this location/directory */
const char *refresh_token = NULL;
oidc_session_get(r, session, OIDC_REFRESHTOKEN_SESSION_KEY, &refresh_token);
if ((oidc_cfg_dir_pass_refresh_token(r) != 0) && (refresh_token != NULL)) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, "refresh_token", refresh_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* set the access_token in the app headers/variables */
const char *access_token = NULL;
oidc_session_get(r, session, OIDC_ACCESSTOKEN_SESSION_KEY, &access_token);
if (access_token != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, "access_token", access_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/* set the expiry timestamp in the app headers/variables */
const char *access_token_expires = NULL;
oidc_session_get(r, session, OIDC_ACCESSTOKEN_EXPIRES_SESSION_KEY,
&access_token_expires);
if (access_token_expires != NULL) {
/* pass it to the app in a header or environment variable */
oidc_util_set_app_info(r, "access_token_expires", access_token_expires,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
/*
* reset the session inactivity timer
* but only do this once per 10% of the inactivity timeout interval (with a max to 60 seconds)
* for performance reasons
*
* now there's a small chance that the session ends 10% (or a minute) earlier than configured/expected
* cq. when there's a request after a recent save (so no update) and then no activity happens until
* a request comes in just before the session should expire
* ("recent" and "just before" refer to 10%-with-a-max-of-60-seconds of the inactivity interval after
* the start/last-update and before the expiry of the session respectively)
*
* this is be deemed acceptable here because of performance gain
*/
apr_time_t interval = apr_time_from_sec(cfg->session_inactivity_timeout);
apr_time_t now = apr_time_now();
apr_time_t slack = interval / 10;
if (slack > apr_time_from_sec(60))
slack = apr_time_from_sec(60);
if (session->expiry - now < interval - slack) {
session->expiry = now + interval;
needs_save = TRUE;
}
/* log message about session expiry */
oidc_log_session_expires(r, "session inactivity timeout", session->expiry);
/* check if something was updated in the session and we need to save it again */
if (needs_save)
if (oidc_session_save(r, session) == FALSE)
return FALSE;
return TRUE;
}
/*
* handle the case where we have identified an existing authentication session for a user
*/
static int oidc_handle_existing_session(request_rec *r, oidc_cfg *cfg,
oidc_session_t *session) {
oidc_debug(r, "enter");
/* get the header name in which the remote user name needs to be passed */
char *authn_header = oidc_cfg_dir_authn_header(r);
int pass_headers = oidc_cfg_dir_pass_info_in_headers(r);
int pass_envvars = oidc_cfg_dir_pass_info_in_envvars(r);
/* verify current cookie domain against issued cookie domain */
if (oidc_check_cookie_domain(r, cfg, session) == FALSE)
return HTTP_UNAUTHORIZED;
/* check if the maximum session duration was exceeded */
int rc = oidc_check_max_session_duration(r, cfg, session);
if (rc != OK)
return rc;
/* if needed, refresh claims from the user info endpoint */
apr_byte_t needs_save = oidc_refresh_claims_from_userinfo_endpoint(r, cfg,
session);
/*
* we're going to pass the information that we have to the application,
* but first we need to scrub the headers that we're going to use for security reasons
*/
oidc_scrub_headers(r);
/* set the user authentication HTTP header if set and required */
if ((r->user != NULL) && (authn_header != NULL))
oidc_util_set_header(r, authn_header, r->user);
const char *s_claims = NULL;
const char *s_id_token = NULL;
/* copy id_token and claims from session to request state and obtain their values */
oidc_copy_tokens_to_request_state(r, session, &s_id_token, &s_claims);
/* set the claims in the app headers */
if (oidc_set_app_claims(r, cfg, session, s_claims) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_CLAIMS)) {
/* set the id_token in the app headers */
if (oidc_set_app_claims(r, cfg, session, s_id_token) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_PAYLOAD)) {
/* pass the id_token JSON object to the app in a header or environment variable */
oidc_util_set_app_info(r, "id_token_payload", s_id_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
}
if ((cfg->pass_idtoken_as & OIDC_PASS_IDTOKEN_AS_SERIALIZED)) {
if (cfg->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
const char *s_id_token = NULL;
/* get the compact serialized JWT from the session */
oidc_session_get(r, session, OIDC_IDTOKEN_SESSION_KEY, &s_id_token);
/* pass the compact serialized JWT to the app in a header or environment variable */
oidc_util_set_app_info(r, "id_token", s_id_token,
OIDC_DEFAULT_HEADER_PREFIX, pass_headers, pass_envvars);
} else {
oidc_error(r,
"session type \"client-cookie\" does not allow storing/passing the id_token; use \"OIDCSessionType server-cache\" for that");
}
}
/* pass the at, rt and at expiry to the application, possibly update the session expiry and save the session */
if (oidc_session_pass_tokens_and_save(r, cfg, session, needs_save) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* return "user authenticated" status */
return OK;
}
/*
* helper function for basic/implicit client flows upon receiving an authorization response:
* check that it matches the state stored in the browser and return the variables associated
* with the state, such as original_url and OP oidc_provider_t pointer.
*/
static apr_byte_t oidc_authorization_response_match_state(request_rec *r,
oidc_cfg *c, const char *state, struct oidc_provider_t **provider,
json_t **proto_state) {
oidc_debug(r, "enter (state=%s)", state);
if ((state == NULL) || (apr_strnatcmp(state, "") == 0)) {
oidc_error(r, "state parameter is not set");
return FALSE;
}
/* check the state parameter against what we stored in a cookie */
if (oidc_restore_proto_state(r, c, state, proto_state) == FALSE) {
oidc_error(r, "unable to restore state");
return FALSE;
}
*provider = oidc_get_provider_for_issuer(r, c,
json_string_value(json_object_get(*proto_state, "issuer")), FALSE);
return (*provider != NULL);
}
/*
* redirect the browser to the session logout endpoint
*/
static int oidc_session_redirect_parent_window_to_logout(request_rec *r,
oidc_cfg *c) {
oidc_debug(r, "enter");
char *java_script = apr_psprintf(r->pool,
" <script type=\"text/javascript\">\n"
" window.top.location.href = '%s?session=logout';\n"
" </script>\n", c->redirect_uri);
return oidc_util_html_send(r, "Redirecting...", java_script, NULL, NULL,
DONE);
}
/*
* handle an error returned by the OP
*/
static int oidc_authorization_response_error(request_rec *r, oidc_cfg *c,
json_t *proto_state, const char *error, const char *error_description) {
const char *prompt =
json_object_get(proto_state, "prompt") ?
apr_pstrdup(r->pool,
json_string_value(
json_object_get(proto_state, "prompt"))) :
NULL;
json_decref(proto_state);
if ((prompt != NULL) && (apr_strnatcmp(prompt, "none") == 0)) {
return oidc_session_redirect_parent_window_to_logout(r, c);
}
return oidc_util_html_send_error(r, c->error_template,
apr_psprintf(r->pool, "OpenID Connect Provider error: %s", error),
error_description, DONE);
}
/*
* set the unique user identifier that will be propagated in the Apache r->user and REMOTE_USER variables
*/
static apr_byte_t oidc_get_remote_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, oidc_jwt_t *jwt, char **user,
const char *s_claims) {
char *issuer = provider->issuer;
char *claim_name = apr_pstrdup(r->pool, c->remote_user_claim.claim_name);
int n = strlen(claim_name);
int post_fix_with_issuer = (claim_name[n - 1] == '@');
if (post_fix_with_issuer) {
claim_name[n - 1] = '\0';
issuer =
(strstr(issuer, "https://") == NULL) ?
apr_pstrdup(r->pool, issuer) :
apr_pstrdup(r->pool, issuer + strlen("https://"));
}
/* extract the username claim (default: "sub") from the id_token payload or user claims */
char *username = NULL;
json_error_t json_error;
json_t *claims = json_loads(s_claims, 0, &json_error);
if (claims == NULL) {
username = apr_pstrdup(r->pool,
json_string_value(
json_object_get(jwt->payload.value.json, claim_name)));
} else {
oidc_util_json_merge(jwt->payload.value.json, claims);
username = apr_pstrdup(r->pool,
json_string_value(json_object_get(claims, claim_name)));
json_decref(claims);
}
if (username == NULL) {
oidc_error(r,
"OIDCRemoteUserClaim is set to \"%s\", but the id_token JSON payload and user claims did not contain a \"%s\" string",
c->remote_user_claim.claim_name, claim_name);
*user = NULL;
return FALSE;
}
/* set the unique username in the session (will propagate to r->user/REMOTE_USER) */
*user = post_fix_with_issuer ?
apr_psprintf(r->pool, "%s@%s", username, issuer) : username;
if (c->remote_user_claim.reg_exp != NULL) {
char *error_str = NULL;
if (oidc_util_regexp_first_match(r->pool, *user,
c->remote_user_claim.reg_exp, user, &error_str) == FALSE) {
oidc_error(r, "oidc_util_regexp_first_match failed: %s", error_str);
*user = NULL;
return FALSE;
}
}
oidc_debug(r, "set user to \"%s\"", *user);
return TRUE;
}
/*
* store resolved information in the session
*/
static apr_byte_t oidc_save_in_session(request_rec *r, oidc_cfg *c,
oidc_session_t *session, oidc_provider_t *provider,
const char *remoteUser, const char *id_token, oidc_jwt_t *id_token_jwt,
const char *claims, const char *access_token, const int expires_in,
const char *refresh_token, const char *session_state, const char *state,
const char *original_url) {
/* store the user in the session */
session->remote_user = remoteUser;
/* set the session expiry to the inactivity timeout */
session->expiry =
apr_time_now() + apr_time_from_sec(c->session_inactivity_timeout);
/* store the claims payload in the id_token for later reference */
oidc_session_set(r, session, OIDC_IDTOKEN_CLAIMS_SESSION_KEY,
id_token_jwt->payload.value.str);
if (c->session_type != OIDC_SESSION_TYPE_CLIENT_COOKIE) {
/* store the compact serialized representation of the id_token for later reference */
oidc_session_set(r, session, OIDC_IDTOKEN_SESSION_KEY, id_token);
}
/* store the issuer in the session (at least needed for session mgmt and token refresh */
oidc_session_set(r, session, OIDC_ISSUER_SESSION_KEY, provider->issuer);
/* store the state and original URL in the session for handling browser-back more elegantly */
oidc_session_set(r, session, OIDC_REQUEST_STATE_SESSION_KEY, state);
oidc_session_set(r, session, OIDC_REQUEST_ORIGINAL_URL, original_url);
if ((session_state != NULL) && (provider->check_session_iframe != NULL)) {
/* store the session state and required parameters session management */
oidc_session_set(r, session, OIDC_SESSION_STATE_SESSION_KEY,
session_state);
oidc_session_set(r, session, OIDC_CHECK_IFRAME_SESSION_KEY,
provider->check_session_iframe);
oidc_session_set(r, session, OIDC_CLIENTID_SESSION_KEY,
provider->client_id);
oidc_debug(r,
"session management enabled: stored session_state (%s), check_session_iframe (%s) and client_id (%s) in the session",
session_state, provider->check_session_iframe,
provider->client_id);
} else if (provider->check_session_iframe == NULL) {
oidc_debug(r,
"session management disabled: \"check_session_iframe\" is not set in provider configuration");
} else {
oidc_warn(r,
"session management disabled: no \"session_state\" value is provided in the authentication response even though \"check_session_iframe\" (%s) is set in the provider configuration",
provider->check_session_iframe);
}
if (provider->end_session_endpoint != NULL)
oidc_session_set(r, session, OIDC_LOGOUT_ENDPOINT_SESSION_KEY,
provider->end_session_endpoint);
/* store claims resolved from userinfo endpoint */
oidc_store_userinfo_claims(r, session, provider, claims);
/* see if we have an access_token */
if (access_token != NULL) {
/* store the access_token in the session context */
oidc_session_set(r, session, OIDC_ACCESSTOKEN_SESSION_KEY,
access_token);
/* store the associated expires_in value */
oidc_store_access_token_expiry(r, session, expires_in);
}
/* see if we have a refresh_token */
if (refresh_token != NULL) {
/* store the refresh_token in the session context */
oidc_session_set(r, session, OIDC_REFRESHTOKEN_SESSION_KEY,
refresh_token);
}
/* store max session duration in the session as a hard cut-off expiry timestamp */
apr_time_t session_expires =
(provider->session_max_duration == 0) ?
apr_time_from_sec(id_token_jwt->payload.exp) :
(apr_time_now()
+ apr_time_from_sec(provider->session_max_duration));
oidc_session_set(r, session, OIDC_SESSION_EXPIRES_SESSION_KEY,
apr_psprintf(r->pool, "%" APR_TIME_T_FMT, session_expires));
/* log message about max session duration */
oidc_log_session_expires(r, "session max lifetime", session_expires);
/* store the domain for which this session is valid */
oidc_session_set(r, session, OIDC_COOKIE_DOMAIN_SESSION_KEY,
c->cookie_domain ? c->cookie_domain : oidc_get_current_url_host(r));
/* store the session */
return oidc_session_save(r, session);
}
/*
* parse the expiry for the access token
*/
static int oidc_parse_expires_in(request_rec *r, const char *expires_in) {
if (expires_in != NULL) {
char *ptr = NULL;
long number = strtol(expires_in, &ptr, 10);
if (number <= 0) {
oidc_warn(r,
"could not convert \"expires_in\" value (%s) to a number",
expires_in);
return -1;
}
return number;
}
return -1;
}
/*
* handle the different flows (hybrid, implicit, Authorization Code)
*/
static apr_byte_t oidc_handle_flows(request_rec *r, oidc_cfg *c,
json_t *proto_state, oidc_provider_t *provider, apr_table_t *params,
const char *response_mode, oidc_jwt_t **jwt) {
apr_byte_t rc = FALSE;
const char *requested_response_type = json_string_value(
json_object_get(proto_state, "response_type"));
/* handle the requested response type/mode */
if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
"code id_token token")) {
rc = oidc_proto_authorization_response_code_idtoken_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
"code id_token")) {
rc = oidc_proto_authorization_response_code_idtoken(r, c, proto_state,
provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
"code token")) {
rc = oidc_proto_handle_authorization_response_code_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
"code")) {
rc = oidc_proto_handle_authorization_response_code(r, c, proto_state,
provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
"id_token token")) {
rc = oidc_proto_handle_authorization_response_idtoken_token(r, c,
proto_state, provider, params, response_mode, jwt);
} else if (oidc_util_spaced_string_equals(r->pool, requested_response_type,
"id_token")) {
rc = oidc_proto_handle_authorization_response_idtoken(r, c, proto_state,
provider, params, response_mode, jwt);
} else {
oidc_error(r, "unsupported response type: \"%s\"",
requested_response_type);
}
if ((rc == FALSE) && (*jwt != NULL)) {
oidc_jwt_destroy(*jwt);
*jwt = NULL;
}
return rc;
}
/* handle the browser back on an authorization response */
static apr_byte_t oidc_handle_browser_back(request_rec *r, const char *r_state,
oidc_session_t *session) {
/* see if we have an existing session and browser-back was used */
const char *s_state = NULL, *o_url = NULL;
if (session->remote_user != NULL) {
oidc_session_get(r, session, OIDC_REQUEST_STATE_SESSION_KEY, &s_state);
oidc_session_get(r, session, OIDC_REQUEST_ORIGINAL_URL, &o_url);
if ((r_state != NULL) && (s_state != NULL)
&& (apr_strnatcmp(r_state, s_state) == 0)) {
/* log the browser back event detection */
oidc_warn(r,
"browser back detected, redirecting to original URL: %s",
o_url);
/* go back to the URL that he originally tried to access */
apr_table_add(r->headers_out, "Location", o_url);
return TRUE;
}
}
return FALSE;
}
/*
* complete the handling of an authorization response by obtaining, parsing and verifying the
* id_token and storing the authenticated user state in the session
*/
static int oidc_handle_authorization_response(request_rec *r, oidc_cfg *c,
oidc_session_t *session, apr_table_t *params, const char *response_mode) {
oidc_debug(r, "enter, response_mode=%s", response_mode);
oidc_provider_t *provider = NULL;
json_t *proto_state = NULL;
oidc_jwt_t *jwt = NULL;
/* see if this response came from a browser-back event */
if (oidc_handle_browser_back(r, apr_table_get(params, "state"),
session) == TRUE)
return HTTP_MOVED_TEMPORARILY;
/* match the returned state parameter against the state stored in the browser */
if (oidc_authorization_response_match_state(r, c,
apr_table_get(params, "state"), &provider, &proto_state) == FALSE) {
if (c->default_sso_url != NULL) {
oidc_warn(r,
"invalid authorization response state; a default SSO URL is set, sending the user there: %s",
c->default_sso_url);
apr_table_add(r->headers_out, "Location", c->default_sso_url);
return HTTP_MOVED_TEMPORARILY;
}
oidc_error(r,
"invalid authorization response state and no default SSO URL is set, sending an error...");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if the response is an error response */
if (apr_table_get(params, "error") != NULL)
return oidc_authorization_response_error(r, c, proto_state,
apr_table_get(params, "error"),
apr_table_get(params, "error_description"));
/* handle the code, implicit or hybrid flow */
if (oidc_handle_flows(r, c, proto_state, provider, params, response_mode,
&jwt) == FALSE)
return oidc_authorization_response_error(r, c, proto_state,
"Error in handling response type.", NULL);
if (jwt == NULL) {
oidc_error(r, "no id_token was provided");
return oidc_authorization_response_error(r, c, proto_state,
"No id_token was provided.", NULL);
}
int expires_in = oidc_parse_expires_in(r,
apr_table_get(params, "expires_in"));
/*
* optionally resolve additional claims against the userinfo endpoint
* parsed claims are not actually used here but need to be parsed anyway for error checking purposes
*/
const char *claims = oidc_retrieve_claims_from_userinfo_endpoint(r, c,
provider, apr_table_get(params, "access_token"), NULL, jwt->payload.sub);
/* restore the original protected URL that the user was trying to access */
const char *original_url = apr_pstrdup(r->pool,
json_string_value(json_object_get(proto_state, "original_url")));
const char *original_method = apr_pstrdup(r->pool,
json_string_value(json_object_get(proto_state, "original_method")));
/* set the user */
if (oidc_get_remote_user(r, c, provider, jwt, &r->user, claims) == TRUE) {
/* session management: if the user in the new response is not equal to the old one, error out */
if ((json_object_get(proto_state, "prompt") != NULL)
&& (apr_strnatcmp(
json_string_value(
json_object_get(proto_state, "prompt")), "none")
== 0)) {
// TOOD: actually need to compare sub? (need to store it in the session separately then
//const char *sub = NULL;
//oidc_session_get(r, session, "sub", &sub);
//if (apr_strnatcmp(sub, jwt->payload.sub) != 0) {
if (apr_strnatcmp(session->remote_user, r->user) != 0) {
oidc_warn(r,
"user set from new id_token is different from current one");
oidc_jwt_destroy(jwt);
return oidc_authorization_response_error(r, c, proto_state,
"User changed!", NULL);
}
}
/* store resolved information in the session */
if (oidc_save_in_session(r, c, session, provider, r->user,
apr_table_get(params, "id_token"), jwt, claims,
apr_table_get(params, "access_token"), expires_in,
apr_table_get(params, "refresh_token"),
apr_table_get(params, "session_state"),
apr_table_get(params, "state"), original_url) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
} else {
oidc_error(r, "remote user could not be set");
return oidc_authorization_response_error(r, c, proto_state,
"Remote user could not be set: contact the website administrator",
NULL);
}
/* cleanup */
json_decref(proto_state);
oidc_jwt_destroy(jwt);
/* check that we've actually authenticated a user; functions as error handling for oidc_get_remote_user */
if (r->user == NULL)
return HTTP_UNAUTHORIZED;
/* log the successful response */
oidc_debug(r,
"session created and stored, returning to original URL: %s, original method: %s",
original_url, original_method);
/* check whether form post data was preserved; if so restore it */
if (apr_strnatcmp(original_method, OIDC_METHOD_FORM_POST) == 0) {
return oidc_request_post_preserved_restore(r, original_url);
}
/* now we've authenticated the user so go back to the URL that he originally tried to access */
apr_table_add(r->headers_out, "Location", original_url);
/* do the actual redirect to the original URL */
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle an OpenID Connect Authorization Response using the POST (+fragment->POST) response_mode
*/
static int oidc_handle_post_authorization_response(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
oidc_debug(r, "enter");
/* initialize local variables */
char *response_mode = NULL;
/* read the parameters that are POST-ed to us */
apr_table_t *params = apr_table_make(r->pool, 8);
if (oidc_util_read_post_params(r, params) == FALSE) {
oidc_error(r, "something went wrong when reading the POST parameters");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if we've got any POST-ed data at all */
if ((apr_table_elts(params)->nelts < 1)
|| ((apr_table_elts(params)->nelts == 1)
&& apr_table_get(params, "response_mode")
&& (apr_strnatcmp(apr_table_get(params, "response_mode"),
"fragment") == 0))) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"You've hit an OpenID Connect Redirect URI with no parameters, this is an invalid request; you should not open this URL in your browser directly, or have the server administrator use a different OIDCRedirectURI setting.",
HTTP_INTERNAL_SERVER_ERROR);
}
/* get the parameters */
response_mode = (char *) apr_table_get(params, "response_mode");
/* do the actual implicit work */
return oidc_handle_authorization_response(r, c, session, params,
response_mode ? response_mode : "form_post");
}
/*
* handle an OpenID Connect Authorization Response using the redirect response_mode
*/
static int oidc_handle_redirect_authorization_response(request_rec *r,
oidc_cfg *c, oidc_session_t *session) {
oidc_debug(r, "enter");
/* read the parameters from the query string */
apr_table_t *params = apr_table_make(r->pool, 8);
oidc_util_read_form_encoded_params(r, params, r->args);
/* do the actual work */
return oidc_handle_authorization_response(r, c, session, params, "query");
}
/*
* present the user with an OP selection screen
*/
static int oidc_discovery(request_rec *r, oidc_cfg *cfg) {
oidc_debug(r, "enter");
/* obtain the URL we're currently accessing, to be stored in the state/session */
char *current_url = oidc_get_current_url(r);
const char *method = oidc_original_request_method(r, cfg, FALSE);
/* generate CSRF token */
char *csrf = NULL;
if (oidc_proto_generate_nonce(r, &csrf, 8) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
char *discover_url = oidc_cfg_dir_discover_url(r);
/* see if there's an external discovery page configured */
if (discover_url != NULL) {
/* yes, assemble the parameters for external discovery */
char *url = apr_psprintf(r->pool, "%s%s%s=%s&%s=%s&%s=%s&%s=%s",
discover_url, strchr(discover_url, '?') != NULL ? "&" : "?",
OIDC_DISC_RT_PARAM, oidc_util_escape_string(r, current_url),
OIDC_DISC_RM_PARAM, method,
OIDC_DISC_CB_PARAM,
oidc_util_escape_string(r, cfg->redirect_uri),
OIDC_CSRF_NAME, oidc_util_escape_string(r, csrf));
/* log what we're about to do */
oidc_debug(r, "redirecting to external discovery page: %s", url);
/* set CSRF cookie */
oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1);
/* see if we need to preserve POST parameters through Javascript/HTML5 storage */
if (oidc_post_preserve_javascript(r, url, NULL, NULL) == TRUE)
return DONE;
/* do the actual redirect to an external discovery page */
apr_table_add(r->headers_out, "Location", url);
return HTTP_MOVED_TEMPORARILY;
}
/* get a list of all providers configured in the metadata directory */
apr_array_header_t *arr = NULL;
if (oidc_metadata_list(r, cfg, &arr) == FALSE)
return oidc_util_html_send_error(r, cfg->error_template,
"Configuration Error",
"No configured providers found, contact your administrator",
HTTP_UNAUTHORIZED);
/* assemble a where-are-you-from IDP discovery HTML page */
const char *s = " <h3>Select your OpenID Connect Identity Provider</h3>\n";
/* list all configured providers in there */
int i;
for (i = 0; i < arr->nelts; i++) {
const char *issuer = ((const char**) arr->elts)[i];
// TODO: html escape (especially & character)
char *display =
(strstr(issuer, "https://") == NULL) ?
apr_pstrdup(r->pool, issuer) :
apr_pstrdup(r->pool, issuer + strlen("https://"));
/* strip port number */
//char *p = strstr(display, ":");
//if (p != NULL) *p = '\0';
/* point back to the redirect_uri, where the selection is handled, with an IDP selection and return_to URL */
s =
apr_psprintf(r->pool,
"%s<p><a href=\"%s?%s=%s&%s=%s&%s=%s&%s=%s\">%s</a></p>\n",
s, cfg->redirect_uri, OIDC_DISC_OP_PARAM,
oidc_util_escape_string(r, issuer),
OIDC_DISC_RT_PARAM,
oidc_util_escape_string(r, current_url),
OIDC_DISC_RM_PARAM, method,
OIDC_CSRF_NAME, csrf, display);
}
/* add an option to enter an account or issuer name for dynamic OP discovery */
s = apr_psprintf(r->pool, "%s<form method=\"get\" action=\"%s\">\n", s,
cfg->redirect_uri);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_RT_PARAM, current_url);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_DISC_RM_PARAM, method);
s = apr_psprintf(r->pool,
"%s<p><input type=\"hidden\" name=\"%s\" value=\"%s\"><p>\n", s,
OIDC_CSRF_NAME, csrf);
s =
apr_psprintf(r->pool,
"%s<p>Or enter your account name (eg. "mike@seed.gluu.org", or an IDP identifier (eg. "mitreid.org"):</p>\n",
s);
s = apr_psprintf(r->pool,
"%s<p><input type=\"text\" name=\"%s\" value=\"%s\"></p>\n", s,
OIDC_DISC_OP_PARAM, "");
s = apr_psprintf(r->pool,
"%s<p><input type=\"submit\" value=\"Submit\"></p>\n", s);
s = apr_psprintf(r->pool, "%s</form>\n", s);
oidc_util_set_cookie(r, OIDC_CSRF_NAME, csrf, -1);
char *javascript = NULL, *javascript_method = NULL;
char *html_head =
"<style type=\"text/css\">body {text-align: center}</style>";
if (oidc_post_preserve_javascript(r, NULL, &javascript,
&javascript_method) == TRUE)
html_head = apr_psprintf(r->pool, "%s%s", html_head, javascript);
/* now send the HTML contents to the user agent */
return oidc_util_html_send(r, "OpenID Connect Provider Discovery",
html_head, javascript_method, s, DONE);
}
/*
* authenticate the user to the selected OP, if the OP is not selected yet perform discovery first
*/
static int oidc_authenticate_user(request_rec *r, oidc_cfg *c,
oidc_provider_t *provider, const char *original_url,
const char *login_hint, const char *id_token_hint, const char *prompt,
const char *auth_request_params) {
oidc_debug(r, "enter");
if (provider == NULL) {
// TODO: should we use an explicit redirect to the discovery endpoint (maybe a "discovery" param to the redirect_uri)?
if (c->metadata_dir != NULL)
return oidc_discovery(r, c);
/* we're not using multiple OP's configured in a metadata directory, pick the statically configured OP */
if (oidc_provider_static_config(r, c, &provider) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
/* generate the random nonce value that correlates requests and responses */
char *nonce = NULL;
if (oidc_proto_generate_nonce(r, &nonce, OIDC_PROTO_NONCE_LENGTH) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
char *code_verifier = NULL;
char *code_challenge = NULL;
if ((oidc_util_spaced_string_contains(r->pool, provider->response_type,
"code") == TRUE) && (provider->pkce_method != NULL)) {
/* generate the code verifier value that correlates authorization requests and code exchange requests */
if (oidc_proto_generate_code_verifier(r, &code_verifier,
OIDC_PROTO_CODE_VERIFIER_LENGTH) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/* generate the PKCE code challenge */
if (oidc_proto_generate_code_challenge(r, code_verifier,
&code_challenge, provider->pkce_method) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
}
/* create the state between request/response */
json_t *proto_state = json_object();
json_object_set_new(proto_state, "original_url", json_string(original_url));
json_object_set_new(proto_state, "original_method",
json_string(oidc_original_request_method(r, c, TRUE)));
json_object_set_new(proto_state, "issuer", json_string(provider->issuer));
json_object_set_new(proto_state, "response_type",
json_string(provider->response_type));
json_object_set_new(proto_state, "nonce", json_string(nonce));
json_object_set_new(proto_state, "timestamp",
json_integer(apr_time_sec(apr_time_now())));
if (provider->response_mode)
json_object_set_new(proto_state, "response_mode",
json_string(provider->response_mode));
if (prompt)
json_object_set_new(proto_state, "prompt", json_string(prompt));
if (code_verifier)
json_object_set_new(proto_state, "code_verifier",
json_string(code_verifier));
/* get a hash value that fingerprints the browser concatenated with the random input */
char *state = oidc_get_browser_state_hash(r, nonce);
/* create state that restores the context when the authorization response comes in; cryptographically bind it to the browser */
if (oidc_authorization_request_set_cookie(r, c, state, proto_state) == FALSE)
return HTTP_INTERNAL_SERVER_ERROR;
/*
* printout errors if Cookie settings are not going to work
*/
apr_uri_t o_uri;
memset(&o_uri, 0, sizeof(apr_uri_t));
apr_uri_t r_uri;
memset(&r_uri, 0, sizeof(apr_uri_t));
apr_uri_parse(r->pool, original_url, &o_uri);
apr_uri_parse(r->pool, c->redirect_uri, &r_uri);
if ((apr_strnatcmp(o_uri.scheme, r_uri.scheme) != 0)
&& (apr_strnatcmp(r_uri.scheme, "https") == 0)) {
oidc_error(r,
"the URL scheme (%s) of the configured OIDCRedirectURI does not match the URL scheme of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!",
r_uri.scheme, o_uri.scheme);
return HTTP_INTERNAL_SERVER_ERROR;
}
if (c->cookie_domain == NULL) {
if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
char *p = strstr(o_uri.hostname, r_uri.hostname);
if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
oidc_error(r,
"the URL hostname (%s) of the configured OIDCRedirectURI does not match the URL hostname of the URL being accessed (%s): the \"state\" and \"session\" cookies will not be shared between the two!",
r_uri.hostname, o_uri.hostname);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
} else {
if (!oidc_util_cookie_domain_valid(r_uri.hostname, c->cookie_domain)) {
oidc_error(r,
"the domain (%s) configured in OIDCCookieDomain does not match the URL hostname (%s) of the URL being accessed (%s): setting \"state\" and \"session\" cookies will not work!!",
c->cookie_domain, o_uri.hostname, original_url);
return HTTP_INTERNAL_SERVER_ERROR;
}
}
/* send off to the OpenID Connect Provider */
// TODO: maybe show intermediate/progress screen "redirecting to"
return oidc_proto_authorization_request(r, provider, login_hint,
c->redirect_uri, state, proto_state, id_token_hint, code_challenge,
auth_request_params);
}
/*
* check if the target_link_uri matches to configuration settings to prevent an open redirect
*/
static int oidc_target_link_uri_matches_configuration(request_rec *r,
oidc_cfg *cfg, const char *target_link_uri) {
apr_uri_t o_uri;
apr_uri_parse(r->pool, target_link_uri, &o_uri);
if (o_uri.hostname == NULL) {
oidc_error(r,
"could not parse the \"target_link_uri\" (%s) in to a valid URL: aborting.",
target_link_uri);
return FALSE;
}
apr_uri_t r_uri;
apr_uri_parse(r->pool, cfg->redirect_uri, &r_uri);
if (cfg->cookie_domain == NULL) {
/* cookie_domain set: see if the target_link_uri matches the redirect_uri host (because the session cookie will be set host-wide) */
if (apr_strnatcmp(o_uri.hostname, r_uri.hostname) != 0) {
char *p = strstr(o_uri.hostname, r_uri.hostname);
if ((p == NULL) || (apr_strnatcmp(r_uri.hostname, p) != 0)) {
oidc_error(r,
"the URL hostname (%s) of the configured OIDCRedirectURI does not match the URL hostname of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
r_uri.hostname, o_uri.hostname);
return FALSE;
}
}
} else {
/* cookie_domain set: see if the target_link_uri is within the cookie_domain */
char *p = strstr(o_uri.hostname, cfg->cookie_domain);
if ((p == NULL) || (apr_strnatcmp(cfg->cookie_domain, p) != 0)) {
oidc_error(r,
"the domain (%s) configured in OIDCCookieDomain does not match the URL hostname (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.hostname, target_link_uri);
return FALSE;
}
}
/* see if the cookie_path setting matches the target_link_uri path */
char *cookie_path = oidc_cfg_dir_cookie_path(r);
if (cookie_path != NULL) {
char *p = (o_uri.path != NULL) ? strstr(o_uri.path, cookie_path) : NULL;
if ((p == NULL) || (p != o_uri.path)) {
oidc_error(r,
"the path (%s) configured in OIDCCookiePath does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.path, target_link_uri);
return FALSE;
} else if (strlen(o_uri.path) > strlen(cookie_path)) {
int n = strlen(cookie_path);
if (cookie_path[n - 1] == '/')
n--;
if (o_uri.path[n] != '/') {
oidc_error(r,
"the path (%s) configured in OIDCCookiePath does not match the URL path (%s) of the \"target_link_uri\" (%s): aborting to prevent an open redirect.",
cfg->cookie_domain, o_uri.path, target_link_uri);
return FALSE;
}
}
}
return TRUE;
}
/*
* handle a response from an IDP discovery page and/or handle 3rd-party initiated SSO
*/
static int oidc_handle_discovery_response(request_rec *r, oidc_cfg *c) {
/* variables to hold the values returned in the response */
char *issuer = NULL, *target_link_uri = NULL, *login_hint = NULL,
*auth_request_params = NULL, *csrf_cookie, *csrf_query = NULL,
*user = NULL;
oidc_provider_t *provider = NULL;
oidc_util_get_request_parameter(r, OIDC_DISC_OP_PARAM, &issuer);
oidc_util_get_request_parameter(r, OIDC_DISC_USER_PARAM, &user);
oidc_util_get_request_parameter(r, OIDC_DISC_RT_PARAM, &target_link_uri);
oidc_util_get_request_parameter(r, OIDC_DISC_LH_PARAM, &login_hint);
oidc_util_get_request_parameter(r, OIDC_DISC_AR_PARAM,
&auth_request_params);
oidc_util_get_request_parameter(r, OIDC_CSRF_NAME, &csrf_query);
csrf_cookie = oidc_util_get_cookie(r, OIDC_CSRF_NAME);
/* do CSRF protection if not 3rd party initiated SSO */
if (csrf_cookie) {
/* clean CSRF cookie */
oidc_util_set_cookie(r, OIDC_CSRF_NAME, "", 0);
/* compare CSRF cookie value with query parameter value */
if ((csrf_query == NULL)
|| apr_strnatcmp(csrf_query, csrf_cookie) != 0) {
oidc_warn(r,
"CSRF protection failed, no Discovery and dynamic client registration will be allowed");
csrf_cookie = NULL;
}
}
// TODO: trim issuer/accountname/domain input and do more input validation
oidc_debug(r,
"issuer=\"%s\", target_link_uri=\"%s\", login_hint=\"%s\", user=\"%s\"",
issuer, target_link_uri, login_hint, user);
if (target_link_uri == NULL) {
if (c->default_sso_url == NULL) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"SSO to this module without specifying a \"target_link_uri\" parameter is not possible because OIDCDefaultURL is not set.",
HTTP_INTERNAL_SERVER_ERROR);
}
target_link_uri = c->default_sso_url;
}
/* do open redirect prevention */
if (oidc_target_link_uri_matches_configuration(r, c,
target_link_uri) == FALSE) {
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"\"target_link_uri\" parameter does not match configuration settings, aborting to prevent an open redirect.",
HTTP_UNAUTHORIZED);
}
/* find out if the user entered an account name or selected an OP manually */
if (user != NULL) {
if (login_hint == NULL)
login_hint = apr_pstrdup(r->pool, user);
/* normalize the user identifier */
if (strstr(user, "https://") != user)
user = apr_psprintf(r->pool, "https://%s", user);
/* got an user identifier as input, perform OP discovery with that */
if (oidc_proto_url_based_discovery(r, c, user, &issuer) == FALSE) {
/* something did not work out, show a user facing error */
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"Could not resolve the provided user identifier to an OpenID Connect provider; check your syntax.",
HTTP_NOT_FOUND);
}
/* issuer is set now, so let's continue as planned */
} else if (strstr(issuer, "@") != NULL) {
if (login_hint == NULL) {
login_hint = apr_pstrdup(r->pool, issuer);
//char *p = strstr(issuer, "@");
//*p = '\0';
}
/* got an account name as input, perform OP discovery with that */
if (oidc_proto_account_based_discovery(r, c, issuer, &issuer) == FALSE) {
/* something did not work out, show a user facing error */
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request",
"Could not resolve the provided account name to an OpenID Connect provider; check your syntax.",
HTTP_NOT_FOUND);
}
/* issuer is set now, so let's continue as planned */
}
/* strip trailing '/' */
int n = strlen(issuer);
if (issuer[n - 1] == '/')
issuer[n - 1] = '\0';
/* try and get metadata from the metadata directories for the selected OP */
if ((oidc_metadata_get(r, c, issuer, &provider, csrf_cookie != NULL) == TRUE)
&& (provider != NULL)) {
/* now we've got a selected OP, send the user there to authenticate */
return oidc_authenticate_user(r, c, provider, target_link_uri,
login_hint, NULL, NULL, auth_request_params);
}
/* something went wrong */
return oidc_util_html_send_error(r, c->error_template, "Invalid Request",
"Could not find valid provider metadata for the selected OpenID Connect provider; contact the administrator",
HTTP_NOT_FOUND);
}
static apr_uint32_t oidc_transparent_pixel[17] = { 0x474e5089, 0x0a1a0a0d,
0x0d000000, 0x52444849, 0x01000000, 0x01000000, 0x00000408, 0x0c1cb500,
0x00000002, 0x4144490b, 0x639c7854, 0x0000cffa, 0x02010702, 0x71311c9a,
0x00000000, 0x444e4549, 0x826042ae };
static apr_byte_t oidc_is_front_channel_logout(const char *logout_param_value) {
return ((logout_param_value != NULL)
&& ((apr_strnatcmp(logout_param_value,
OIDC_GET_STYLE_LOGOUT_PARAM_VALUE) == 0)
|| (apr_strnatcmp(logout_param_value,
OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0)));
}
/*
* handle a local logout
*/
static int oidc_handle_logout_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *url) {
oidc_debug(r, "enter (url=%s)", url);
/* if there's no remote_user then there's no (stored) session to kill */
if (session->remote_user != NULL) {
/* remove session state (cq. cache entry and cookie) */
oidc_session_kill(r, session);
}
/* see if this is the OP calling us */
if (oidc_is_front_channel_logout(url)) {
/* set recommended cache control headers */
apr_table_add(r->err_headers_out, "Cache-Control",
"no-cache, no-store");
apr_table_add(r->err_headers_out, "Pragma", "no-cache");
apr_table_add(r->err_headers_out, "P3P", "CAO PSA OUR");
apr_table_add(r->err_headers_out, "Expires", "0");
apr_table_add(r->err_headers_out, "X-Frame-Options", "DENY");
/* see if this is PF-PA style logout in which case we return a transparent pixel */
const char *accept = apr_table_get(r->headers_in, "Accept");
if ((apr_strnatcmp(url, OIDC_IMG_STYLE_LOGOUT_PARAM_VALUE) == 0)
|| ((accept) && strstr(accept, "image/png"))) {
return oidc_util_http_send(r,
(const char *) &oidc_transparent_pixel,
sizeof(oidc_transparent_pixel), "image/png", DONE);
}
/* standard HTTP based logout: should be called in an iframe from the OP */
return oidc_util_html_send(r, "Logged Out", NULL, NULL,
"<p>Logged Out</p>", DONE);
}
/* see if we don't need to go somewhere special after killing the session locally */
if (url == NULL)
return oidc_util_html_send(r, "Logged Out", NULL, NULL,
"<p>Logged Out</p>", DONE);
/* send the user to the specified where-to-go-after-logout URL */
apr_table_add(r->headers_out, "Location", url);
return HTTP_MOVED_TEMPORARILY;
}
/*
* perform (single) logout
*/
static int oidc_handle_logout(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
/* pickup the command or URL where the user wants to go after logout */
char *url = NULL;
oidc_util_get_request_parameter(r, "logout", &url);
oidc_debug(r, "enter (url=%s)", url);
if (oidc_is_front_channel_logout(url)) {
return oidc_handle_logout_request(r, c, session, url);
}
if ((url == NULL) || (apr_strnatcmp(url, "") == 0)) {
url = c->default_slo_url;
} else {
/* do input validation on the logout parameter value */
const char *error_description = NULL;
apr_uri_t uri;
if (apr_uri_parse(r->pool, url, &uri) != APR_SUCCESS) {
const char *error_description = apr_psprintf(r->pool,
"Logout URL malformed: %s", url);
oidc_error(r, "%s", error_description);
return oidc_util_html_send_error(r, c->error_template,
"Malformed URL", error_description,
HTTP_INTERNAL_SERVER_ERROR);
}
if ((strstr(r->hostname, uri.hostname) == NULL)
|| (strstr(uri.hostname, r->hostname) == NULL)) {
error_description =
apr_psprintf(r->pool,
"logout value \"%s\" does not match the hostname of the current request \"%s\"",
apr_uri_unparse(r->pool, &uri, 0), r->hostname);
oidc_error(r, "%s", error_description);
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request", error_description,
HTTP_INTERNAL_SERVER_ERROR);
}
/* validate the URL to prevent HTTP header splitting */
if (((strstr(url, "\n") != NULL) || strstr(url, "\r") != NULL)) {
error_description =
apr_psprintf(r->pool,
"logout value \"%s\" contains illegal \"\n\" or \"\r\" character(s)",
url);
oidc_error(r, "%s", error_description);
return oidc_util_html_send_error(r, c->error_template,
"Invalid Request", error_description,
HTTP_INTERNAL_SERVER_ERROR);
}
}
const char *end_session_endpoint = NULL;
oidc_session_get(r, session, OIDC_LOGOUT_ENDPOINT_SESSION_KEY,
&end_session_endpoint);
if (end_session_endpoint != NULL) {
const char *id_token_hint = NULL;
oidc_session_get(r, session, OIDC_IDTOKEN_SESSION_KEY, &id_token_hint);
char *logout_request = apr_pstrdup(r->pool, end_session_endpoint);
if (id_token_hint != NULL) {
logout_request = apr_psprintf(r->pool, "%s%sid_token_hint=%s",
logout_request,
strchr(logout_request, '?') != NULL ? "&" : "?",
oidc_util_escape_string(r, id_token_hint));
}
if (url != NULL) {
logout_request = apr_psprintf(r->pool,
"%s%spost_logout_redirect_uri=%s", logout_request,
strchr(logout_request, '?') != NULL ? "&" : "?",
oidc_util_escape_string(r, url));
}
url = logout_request;
}
return oidc_handle_logout_request(r, c, session, url);
}
/*
* handle request for JWKs
*/
int oidc_handle_jwks(request_rec *r, oidc_cfg *c) {
/* pickup requested JWKs type */
// char *jwks_type = NULL;
// oidc_util_get_request_parameter(r, "jwks", &jwks_type);
char *jwks = apr_pstrdup(r->pool, "{ \"keys\" : [");
apr_hash_index_t *hi = NULL;
apr_byte_t first = TRUE;
oidc_jose_error_t err;
if (c->public_keys != NULL) {
/* loop over the RSA public keys */
for (hi = apr_hash_first(r->pool, c->public_keys); hi; hi =
apr_hash_next(hi)) {
const char *s_kid = NULL;
oidc_jwk_t *jwk = NULL;
char *s_json = NULL;
apr_hash_this(hi, (const void**) &s_kid, NULL, (void**) &jwk);
if (oidc_jwk_to_json(r->pool, jwk, &s_json, &err) == TRUE) {
jwks = apr_psprintf(r->pool, "%s%s %s ", jwks, first ? "" : ",",
s_json);
first = FALSE;
} else {
oidc_error(r,
"could not convert RSA JWK to JSON using oidc_jwk_to_json: %s",
oidc_jose_e2s(r->pool, err));
}
}
}
// TODO: send stuff if first == FALSE?
jwks = apr_psprintf(r->pool, "%s ] }", jwks);
return oidc_util_http_send(r, jwks, strlen(jwks), "application/json", DONE);
}
static int oidc_handle_session_management_iframe_op(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *check_session_iframe) {
oidc_debug(r, "enter");
apr_table_add(r->headers_out, "Location", check_session_iframe);
return HTTP_MOVED_TEMPORARILY;
}
static int oidc_handle_session_management_iframe_rp(request_rec *r, oidc_cfg *c,
oidc_session_t *session, const char *client_id,
const char *check_session_iframe) {
oidc_debug(r, "enter");
const char *java_script =
" <script type=\"text/javascript\">\n"
" var targetOrigin = '%s';\n"
" var message = '%s' + ' ' + '%s';\n"
" var timerID;\n"
"\n"
" function checkSession() {\n"
" console.log('checkSession: posting ' + message + ' to ' + targetOrigin);\n"
" var win = window.parent.document.getElementById('%s').contentWindow;\n"
" win.postMessage( message, targetOrigin);\n"
" }\n"
"\n"
" function setTimer() {\n"
" checkSession();\n"
" timerID = setInterval('checkSession()', %s);\n"
" }\n"
"\n"
" function receiveMessage(e) {\n"
" console.log('receiveMessage: ' + e.data + ' from ' + e.origin);\n"
" if (e.origin !== targetOrigin ) {\n"
" console.log('receiveMessage: cross-site scripting attack?');\n"
" return;\n"
" }\n"
" if (e.data != 'unchanged') {\n"
" clearInterval(timerID);\n"
" if (e.data == 'changed') {\n"
" window.location.href = '%s?session=check';\n"
" } else {\n"
" window.location.href = '%s?session=logout';\n"
" }\n"
" }\n"
" }\n"
"\n"
" window.addEventListener('message', receiveMessage, false);\n"
"\n"
" </script>\n";
/* determine the origin for the check_session_iframe endpoint */
char *origin = apr_pstrdup(r->pool, check_session_iframe);
apr_uri_t uri;
apr_uri_parse(r->pool, check_session_iframe, &uri);
char *p = strstr(origin, uri.path);
*p = '\0';
/* the element identifier for the OP iframe */
const char *op_iframe_id = "openidc-op";
/* restore the OP session_state from the session */
const char *session_state = NULL;
oidc_session_get(r, session, OIDC_SESSION_STATE_SESSION_KEY,
&session_state);
if (session_state == NULL) {
oidc_warn(r,
"no session_state found in the session; the OP does probably not support session management!?");
return DONE;
}
char *s_poll_interval = NULL;
oidc_util_get_request_parameter(r, "poll", &s_poll_interval);
if (s_poll_interval == NULL)
s_poll_interval = "3000";
java_script = apr_psprintf(r->pool, java_script, origin, client_id,
session_state, op_iframe_id, s_poll_interval, c->redirect_uri,
c->redirect_uri);
return oidc_util_html_send(r, NULL, java_script, "setTimer", NULL, DONE);
}
/*
* handle session management request
*/
static int oidc_handle_session_management(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *cmd = NULL;
const char *id_token_hint = NULL, *client_id = NULL, *check_session_iframe =
NULL;
oidc_provider_t *provider = NULL;
/* get the command passed to the session management handler */
oidc_util_get_request_parameter(r, "session", &cmd);
if (cmd == NULL) {
oidc_error(r, "session management handler called with no command");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* see if this is a local logout during session management */
if (apr_strnatcmp("logout", cmd) == 0) {
oidc_debug(r,
"[session=logout] calling oidc_handle_logout_request because of session mgmt local logout call.");
return oidc_handle_logout_request(r, c, session, c->default_slo_url);
}
/* see if this is a request for the OP iframe */
if (apr_strnatcmp("iframe_op", cmd) == 0) {
oidc_session_get(r, session, OIDC_CHECK_IFRAME_SESSION_KEY,
&check_session_iframe);
if (check_session_iframe != NULL) {
return oidc_handle_session_management_iframe_op(r, c, session,
check_session_iframe);
}
return HTTP_NOT_FOUND;
}
/* see if this is a request for the RP iframe */
if (apr_strnatcmp("iframe_rp", cmd) == 0) {
oidc_session_get(r, session, OIDC_CLIENTID_SESSION_KEY, &client_id);
oidc_session_get(r, session, OIDC_CHECK_IFRAME_SESSION_KEY,
&check_session_iframe);
if ((client_id != NULL) && (check_session_iframe != NULL)) {
return oidc_handle_session_management_iframe_rp(r, c, session,
client_id, check_session_iframe);
}
oidc_debug(r,
"iframe_rp command issued but no client (%s) and/or no check_session_iframe (%s) set",
client_id, check_session_iframe);
return HTTP_NOT_FOUND;
}
/* see if this is a request check the login state with the OP */
if (apr_strnatcmp("check", cmd) == 0) {
oidc_session_get(r, session, OIDC_IDTOKEN_SESSION_KEY, &id_token_hint);
oidc_get_provider_from_session(r, c, session, &provider);
if ((session->remote_user != NULL) && (provider != NULL)) {
return oidc_authenticate_user(r, c, provider,
apr_psprintf(r->pool, "%s?session=iframe_rp",
c->redirect_uri), NULL, id_token_hint, "none", NULL);
}
oidc_debug(r,
"[session=check] calling oidc_handle_logout_request because no session found.");
return oidc_session_redirect_parent_window_to_logout(r, c);
}
/* handle failure in fallthrough */
oidc_error(r, "unknown command: %s", cmd);
return HTTP_INTERNAL_SERVER_ERROR;
}
/*
* handle refresh token request
*/
static int oidc_handle_refresh_token_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
char *return_to = NULL;
char *r_access_token = NULL;
char *error_code = NULL;
/* get the command passed to the session management handler */
oidc_util_get_request_parameter(r, "refresh", &return_to);
oidc_util_get_request_parameter(r, "access_token", &r_access_token);
/* check the input parameters */
if (return_to == NULL) {
oidc_error(r,
"refresh token request handler called with no URL to return to");
return HTTP_INTERNAL_SERVER_ERROR;
}
if (r_access_token == NULL) {
oidc_error(r,
"refresh token request handler called with no access_token parameter");
error_code = "no_access_token";
goto end;
}
char *s_access_token = NULL;
oidc_session_get(r, session, OIDC_ACCESSTOKEN_SESSION_KEY,
(const char **) &s_access_token);
if (s_access_token == NULL) {
oidc_error(r,
"no existing access_token found in the session, nothing to refresh");
error_code = "no_access_token_exists";
goto end;
}
/* compare the access_token parameter used for XSRF protection */
if (apr_strnatcmp(s_access_token, r_access_token) != 0) {
oidc_error(r,
"access_token passed in refresh request does not match the one stored in the session");
error_code = "no_access_token_match";
goto end;
}
/* get a handle to the provider configuration */
oidc_provider_t *provider = NULL;
if (oidc_get_provider_from_session(r, c, session, &provider) == FALSE) {
error_code = "session_corruption";
goto end;
}
/* execute the actual refresh grant */
if (oidc_refresh_access_token(r, c, session, provider, NULL) == FALSE) {
oidc_error(r, "access_token could not be refreshed");
error_code = "refresh_failed";
goto end;
}
/* pass the tokens to the application and save the session, possibly updating the expiry */
if (oidc_session_pass_tokens_and_save(r, c, session, TRUE) == FALSE) {
error_code = "session_corruption";
goto end;
}
end:
/* pass optional error message to the return URL */
if (error_code != NULL)
return_to = apr_psprintf(r->pool, "%s%serror_code=%s", return_to,
strchr(return_to, '?') ? "&" : "?",
oidc_util_escape_string(r, error_code));
/* add the redirect location header */
apr_table_add(r->headers_out, "Location", return_to);
return HTTP_MOVED_TEMPORARILY;
}
/*
* handle request object by reference request
*/
static int oidc_handle_request_uri(request_rec *r, oidc_cfg *c) {
char *request_ref = NULL;
oidc_util_get_request_parameter(r, "request_uri", &request_ref);
if (request_ref == NULL) {
oidc_error(r, "no \"request_uri\" parameter found");
return HTTP_BAD_REQUEST;
}
const char *jwt = NULL;
c->cache->get(r, OIDC_CACHE_SECTION_REQUEST_URI, request_ref, &jwt);
if (jwt == NULL) {
oidc_error(r, "no cached JWT found for request_uri reference: %s",
request_ref);
return HTTP_NOT_FOUND;
}
c->cache->set(r, OIDC_CACHE_SECTION_REQUEST_URI, request_ref, NULL, 0);
return oidc_util_http_send(r, jwt, strlen(jwt), " application/jwt", DONE);
}
/*
* handle a request to invalidate a cached access token introspection result
*/
static int oidc_handle_remove_at_cache(request_rec *r, oidc_cfg *c) {
char *access_token = NULL;
oidc_util_get_request_parameter(r, "remove_at_cache", &access_token);
const char *cache_entry = NULL;
c->cache->get(r, OIDC_CACHE_SECTION_ACCESS_TOKEN, access_token, &cache_entry);
if (cache_entry == NULL) {
oidc_error(r, "no cached access token found for value: %s", access_token);
return HTTP_NOT_FOUND;
}
c->cache->set(r, OIDC_CACHE_SECTION_ACCESS_TOKEN, access_token, NULL, 0);
return DONE;
}
/*
* handle all requests to the redirect_uri
*/
int oidc_handle_redirect_uri_request(request_rec *r, oidc_cfg *c,
oidc_session_t *session) {
if (oidc_proto_is_redirect_authorization_response(r, c)) {
/* this is an authorization response from the OP using the Basic Client profile or a Hybrid flow*/
return oidc_handle_redirect_authorization_response(r, c, session);
} else if (oidc_proto_is_post_authorization_response(r, c)) {
/* this is an authorization response using the fragment(+POST) response_mode with the Implicit Client profile */
return oidc_handle_post_authorization_response(r, c, session);
} else if (oidc_is_discovery_response(r, c)) {
/* this is response from the OP discovery page */
return oidc_handle_discovery_response(r, c);
} else if (oidc_util_request_has_parameter(r, "logout")) {
/* handle logout */
return oidc_handle_logout(r, c, session);
} else if (oidc_util_request_has_parameter(r, "jwks")) {
/* handle JWKs request */
return oidc_handle_jwks(r, c);
} else if (oidc_util_request_has_parameter(r, "session")) {
/* handle session management request */
return oidc_handle_session_management(r, c, session);
} else if (oidc_util_request_has_parameter(r, "refresh")) {
/* handle refresh token request */
return oidc_handle_refresh_token_request(r, c, session);
} else if (oidc_util_request_has_parameter(r, "request_uri")) {
/* handle request object by reference request */
return oidc_handle_request_uri(r, c);
} else if (oidc_util_request_has_parameter(r, "remove_at_cache")) {
/* handle request to invalidate access token cache */
return oidc_handle_remove_at_cache(r, c);
} else if ((r->args == NULL) || (apr_strnatcmp(r->args, "") == 0)) {
/* this is a "bare" request to the redirect URI, indicating implicit flow using the fragment response_mode */
return oidc_proto_javascript_implicit(r, c);
}
/* this is not an authorization response or logout request */
/* check for "error" response */
if (oidc_util_request_has_parameter(r, "error")) {
// char *error = NULL, *descr = NULL;
// oidc_util_get_request_parameter(r, "error", &error);
// oidc_util_get_request_parameter(r, "error_description", &descr);
//
// /* send user facing error to browser */
// return oidc_util_html_send_error(r, error, descr, DONE);
oidc_handle_redirect_authorization_response(r, c, session);
}
oidc_error(r,
"The OpenID Connect callback URL received an invalid request: %s; returning HTTP_INTERNAL_SERVER_ERROR",
r->args);
/* something went wrong */
return oidc_util_html_send_error(r, c->error_template, "Invalid Request",
apr_psprintf(r->pool,
"The OpenID Connect callback URL received an invalid request"),
HTTP_INTERNAL_SERVER_ERROR);
}
/*
* main routine: handle OpenID Connect authentication
*/
static int oidc_check_userid_openidc(request_rec *r, oidc_cfg *c) {
if (c->redirect_uri == NULL) {
oidc_error(r,
"configuration error: the authentication type is set to \"openid-connect\" but OIDCRedirectURI has not been set");
return HTTP_INTERNAL_SERVER_ERROR;
}
/* check if this is a sub-request or an initial request */
if (ap_is_initial_req(r)) {
int rc = OK;
/* load the session from the request state; this will be a new "empty" session if no state exists */
oidc_session_t *session = NULL;
oidc_session_load(r, &session);
/* see if the initial request is to the redirect URI; this handles potential logout too */
if (oidc_util_request_matches_url(r, c->redirect_uri)) {
/* handle request to the redirect_uri */
rc = oidc_handle_redirect_uri_request(r, c, session);
/* free resources allocated for the session */
oidc_session_free(r, session);
return rc;
/* initial request to non-redirect URI, check if we have an existing session */
} else if (session->remote_user != NULL) {
/* set the user in the main request for further (incl. sub-request) processing */
r->user = (char *) session->remote_user;
/* this is initial request and we already have a session */
rc = oidc_handle_existing_session(r, c, session);
/* free resources allocated for the session */
oidc_session_free(r, session);
/* strip any cookies that we need to */
oidc_strip_cookies(r);
return rc;
}
/* free resources allocated for the session */
oidc_session_free(r, session);
/*
* else: initial request, we have no session and it is not an authorization or
* discovery response: just hit the default flow for unauthenticated users
*/
} else {
/* not an initial request, try to recycle what we've already established in the main request */
if (r->main != NULL)
r->user = r->main->user;
else if (r->prev != NULL)
r->user = r->prev->user;
if (r->user != NULL) {
/* this is a sub-request and we have a session (headers will have been scrubbed and set already) */
oidc_debug(r,
"recycling user '%s' from initial request for sub-request",
r->user);
/*
* apparently request state can get lost in sub-requests, so let's see
* if we need to restore id_token and/or claims from the session cache
*/
const char *s_id_token = oidc_request_state_get(r,
OIDC_IDTOKEN_CLAIMS_SESSION_KEY);
if (s_id_token == NULL) {
oidc_session_t *session = NULL;
oidc_session_load(r, &session);
oidc_copy_tokens_to_request_state(r, session, NULL, NULL);
/* free resources allocated for the session */
oidc_session_free(r, session);
}
/* strip any cookies that we need to */
oidc_strip_cookies(r);
return OK;
}
/*
* else: not initial request, but we could not find a session, so:
* just hit the default flow for unauthenticated users
*/
}
return oidc_handle_unauthenticated_user(r, c);
}
/*
* generic Apache authentication hook for this module: dispatches to OpenID Connect or OAuth 2.0 specific routines
*/
int oidc_check_user_id(request_rec *r) {
oidc_cfg *c = ap_get_module_config(r->server->module_config,
&auth_openidc_module);
/* log some stuff about the incoming HTTP request */
oidc_debug(r, "incoming request: \"%s?%s\", ap_is_initial_req(r)=%d",
r->parsed_uri.path, r->args, ap_is_initial_req(r));
/* see if any authentication has been defined at all */
if (ap_auth_type(r) == NULL)
return DECLINED;
/* see if we've configured OpenID Connect user authentication for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r), "openid-connect")
== 0)
return oidc_check_userid_openidc(r, c);
/* see if we've configured OAuth 2.0 access control for this request */
if (apr_strnatcasecmp((const char *) ap_auth_type(r), "oauth20") == 0)
return oidc_oauth_check_userid(r, c);
/* this is not for us but for some other handler */
return DECLINED;
}
/*
* get the claims and id_token from request state
*/
static void oidc_authz_get_claims_and_idtoken(request_rec *r, json_t **claims,
json_t **id_token) {
const char *s_claims = oidc_request_state_get(r, OIDC_CLAIMS_SESSION_KEY);
const char *s_id_token = oidc_request_state_get(r,
OIDC_IDTOKEN_CLAIMS_SESSION_KEY);
json_error_t json_error;
if (s_claims != NULL) {
*claims = json_loads(s_claims, 0, &json_error);
if (*claims == NULL) {
oidc_error(r, "could not restore claims from request state: %s",
json_error.text);
}
}
if (s_id_token != NULL) {
*id_token = json_loads(s_id_token, 0, &json_error);
if (*id_token == NULL) {
oidc_error(r, "could not restore id_token from request state: %s",
json_error.text);
}
}
}
#if MODULE_MAGIC_NUMBER_MAJOR >= 20100714
/*
* generic Apache >=2.4 authorization hook for this module
* handles both OpenID Connect or OAuth 2.0 in the same way, based on the claims stored in the session
*/
authz_status oidc_authz_checker(request_rec *r, const char *require_args, const void *parsed_require_args) {
/* check for anonymous access and PASS mode */
if (r->user != NULL && strlen(r->user) == 0) {
r->user = NULL;
if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS) return AUTHZ_GRANTED;
}
/* get the set of claims from the request state (they've been set in the authentication part earlier */
json_t *claims = NULL, *id_token = NULL;
oidc_authz_get_claims_and_idtoken(r, &claims, &id_token);
/* merge id_token claims (e.g. "iss") in to claims json object */
if (claims)
oidc_util_json_merge(id_token, claims);
/* dispatch to the >=2.4 specific authz routine */
authz_status rc = oidc_authz_worker24(r, claims ? claims : id_token, require_args);
/* cleanup */
if (claims) json_decref(claims);
if (id_token) json_decref(id_token);
if ((rc == AUTHZ_DENIED) && ap_auth_type(r)
&& (apr_strnatcasecmp((const char *) ap_auth_type(r), "oauth20")
== 0))
oidc_oauth_return_www_authenticate(r, "insufficient_scope", "Different scope(s) or other claims required");
return rc;
}
#else
/*
* generic Apache <2.4 authorization hook for this module
* handles both OpenID Connect and OAuth 2.0 in the same way, based on the claims stored in the request context
*/
int oidc_auth_checker(request_rec *r) {
/* check for anonymous access and PASS mode */
if (r->user != NULL && strlen(r->user) == 0) {
r->user = NULL;
if (oidc_dir_cfg_unauth_action(r) == OIDC_UNAUTH_PASS)
return OK;
}
/* get the set of claims from the request state (they've been set in the authentication part earlier */
json_t *claims = NULL, *id_token = NULL;
oidc_authz_get_claims_and_idtoken(r, &claims, &id_token);
/* get the Require statements */
const apr_array_header_t * const reqs_arr = ap_requires(r);
/* see if we have any */
const require_line * const reqs =
reqs_arr ? (require_line *) reqs_arr->elts : NULL;
if (!reqs_arr) {
oidc_debug(r,
"no require statements found, so declining to perform authorization.");
return DECLINED;
}
/* merge id_token claims (e.g. "iss") in to claims json object */
if (claims)
oidc_util_json_merge(id_token, claims);
/* dispatch to the <2.4 specific authz routine */
int rc = oidc_authz_worker(r, claims ? claims : id_token, reqs,
reqs_arr->nelts);
/* cleanup */
if (claims)
json_decref(claims);
if (id_token)
json_decref(id_token);
if ((rc == HTTP_UNAUTHORIZED) && ap_auth_type(r)
&& (apr_strnatcasecmp((const char *) ap_auth_type(r), "oauth20")
== 0))
oidc_oauth_return_www_authenticate(r, "insufficient_scope",
"Different scope(s) or other claims required");
return rc;
}
#endif
extern const command_rec oidc_config_cmds[];
module AP_MODULE_DECLARE_DATA auth_openidc_module = {
STANDARD20_MODULE_STUFF,
oidc_create_dir_config,
oidc_merge_dir_config,
oidc_create_server_config,
oidc_merge_server_config,
oidc_config_cmds,
oidc_register_hooks
};
| ./CrossVul/dataset_final_sorted/CWE-287/c/good_3184_2 |
crossvul-cpp_data_good_1723_0 | /*
* PgBouncer - Lightweight connection pooler for PostgreSQL.
*
* Copyright (c) 2007-2009 Marko Kreen, Skype Technologies OÜ
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Client connection handling
*/
#include "bouncer.h"
#include <usual/pgutil.h>
static const char *hdr2hex(const struct MBuf *data, char *buf, unsigned buflen)
{
const uint8_t *bin = data->data + data->read_pos;
unsigned int dlen;
dlen = mbuf_avail_for_read(data);
return bin2hex(bin, dlen, buf, buflen);
}
static bool check_client_passwd(PgSocket *client, const char *passwd)
{
char md5[MD5_PASSWD_LEN + 1];
PgUser *user = client->auth_user;
int auth_type = client->client_auth_type;
/* disallow empty passwords */
if (!*passwd || !*user->passwd)
return false;
switch (auth_type) {
case AUTH_PLAIN:
return strcmp(user->passwd, passwd) == 0;
case AUTH_MD5:
if (strlen(passwd) != MD5_PASSWD_LEN)
return false;
if (!isMD5(user->passwd))
pg_md5_encrypt(user->passwd, user->name, strlen(user->name), user->passwd);
pg_md5_encrypt(user->passwd + 3, (char *)client->tmp_login_salt, 4, md5);
return strcmp(md5, passwd) == 0;
}
return false;
}
static bool send_client_authreq(PgSocket *client)
{
uint8_t saltlen = 0;
int res;
int auth_type = client->client_auth_type;
if (auth_type == AUTH_MD5) {
saltlen = 4;
get_random_bytes((void*)client->tmp_login_salt, saltlen);
} else if (auth_type == AUTH_PLAIN) {
/* nothing to do */
} else {
return false;
}
SEND_generic(res, client, 'R', "ib", auth_type, client->tmp_login_salt, saltlen);
if (!res)
disconnect_client(client, false, "failed to send auth req");
return res;
}
static void start_auth_request(PgSocket *client, const char *username)
{
int res;
PktBuf *buf;
/* have to fetch user info from db */
client->pool = get_pool(client->db, client->db->auth_user);
if (!find_server(client)) {
client->wait_for_user_conn = true;
return;
}
slog_noise(client, "Doing auth_conn query");
client->wait_for_user_conn = false;
client->wait_for_user = true;
if (!sbuf_pause(&client->sbuf)) {
release_server(client->link);
disconnect_client(client, true, "pause failed");
return;
}
client->link->ready = 0;
res = 0;
buf = pktbuf_dynamic(512);
if (buf) {
pktbuf_write_ExtQuery(buf, cf_auth_query, 1, username);
res = pktbuf_send_immediate(buf, client->link);
pktbuf_free(buf);
/*
* Should do instead:
* res = pktbuf_send_queued(buf, client->link);
* but that needs better integration with SBuf.
*/
}
if (!res)
disconnect_server(client->link, false, "unable to send login query");
}
static bool login_via_cert(PgSocket *client)
{
struct tls *tls = client->sbuf.tls;
struct tls_cert *cert;
struct tls_cert_dname *subj;
if (!tls) {
disconnect_client(client, true, "TLS connection required");
return false;
}
if (tls_get_peer_cert(client->sbuf.tls, &cert, NULL) < 0 || !cert) {
disconnect_client(client, true, "TLS client certificate required");
return false;
}
subj = &cert->subject;
log_debug("TLS cert login: CN=%s/C=%s/L=%s/ST=%s/O=%s/OU=%s",
subj->common_name ? subj->common_name : "(null)",
subj->country_name ? subj->country_name : "(null)",
subj->locality_name ? subj->locality_name : "(null)",
subj->state_or_province_name ? subj->state_or_province_name : "(null)",
subj->organization_name ? subj->organization_name : "(null)",
subj->organizational_unit_name ? subj->organizational_unit_name : "(null)");
if (!subj->common_name) {
disconnect_client(client, true, "Invalid TLS certificate");
goto fail;
}
if (strcmp(subj->common_name, client->auth_user->name) != 0) {
disconnect_client(client, true, "TLS certificate name mismatch");
goto fail;
}
tls_cert_free(cert);
/* login successful */
return finish_client_login(client);
fail:
tls_cert_free(cert);
return false;
}
static bool login_as_unix_peer(PgSocket *client)
{
if (!pga_is_unix(&client->remote_addr))
goto fail;
if (!check_unix_peer_name(sbuf_socket(&client->sbuf), client->auth_user->name))
goto fail;
return finish_client_login(client);
fail:
disconnect_client(client, true, "unix socket login rejected");
return false;
}
static bool finish_set_pool(PgSocket *client, bool takeover)
{
PgUser *user = client->auth_user;
bool ok = false;
int auth;
/* pool user may be forced */
if (client->db->forced_user) {
user = client->db->forced_user;
}
client->pool = get_pool(client->db, user);
if (!client->pool) {
disconnect_client(client, true, "no memory for pool");
return false;
}
if (cf_log_connections) {
if (client->sbuf.tls) {
char infobuf[96] = "";
tls_get_connection_info(client->sbuf.tls, infobuf, sizeof infobuf);
slog_info(client, "login attempt: db=%s user=%s tls=%s",
client->db->name, client->auth_user->name, infobuf);
} else {
slog_info(client, "login attempt: db=%s user=%s tls=no",
client->db->name, client->auth_user->name);
}
}
if (!check_fast_fail(client))
return false;
if (takeover)
return true;
if (client->pool->db->admin) {
if (!admin_post_login(client))
return false;
}
if (client->own_user)
return finish_client_login(client);
auth = cf_auth_type;
if (auth == AUTH_HBA) {
auth = hba_eval(parsed_hba, &client->remote_addr, !!client->sbuf.tls,
client->db->name, client->auth_user->name);
}
/* remember method */
client->client_auth_type = auth;
switch (auth) {
case AUTH_ANY:
case AUTH_TRUST:
ok = finish_client_login(client);
break;
case AUTH_PLAIN:
case AUTH_MD5:
ok = send_client_authreq(client);
break;
case AUTH_CERT:
ok = login_via_cert(client);
break;
case AUTH_PEER:
ok = login_as_unix_peer(client);
break;
default:
disconnect_client(client, true, "login rejected");
ok = false;
}
return ok;
}
bool set_pool(PgSocket *client, const char *dbname, const char *username, const char *password, bool takeover)
{
/* find database */
client->db = find_database(dbname);
if (!client->db) {
client->db = register_auto_database(dbname);
if (!client->db) {
disconnect_client(client, true, "No such database: %s", dbname);
if (cf_log_connections)
slog_info(client, "login failed: db=%s user=%s", dbname, username);
return false;
} else {
slog_info(client, "registered new auto-database: db = %s", dbname );
}
}
/* are new connections allowed? */
if (client->db->db_disabled) {
disconnect_client(client, true, "database does not allow connections: %s", dbname);
return false;
}
if (client->db->admin) {
if (admin_pre_login(client, username))
return finish_set_pool(client, takeover);
}
/* find user */
if (cf_auth_type == AUTH_ANY) {
/* ignore requested user */
if (client->db->forced_user == NULL) {
slog_error(client, "auth_type=any requires forced user");
disconnect_client(client, true, "bouncer config error");
return false;
}
client->auth_user = client->db->forced_user;
} else {
/* the user clients wants to log in as */
client->auth_user = find_user(username);
if (!client->auth_user && client->db->auth_user) {
if (takeover) {
client->auth_user = add_db_user(client->db, username, password);
return finish_set_pool(client, takeover);
}
start_auth_request(client, username);
return false;
}
if (!client->auth_user) {
disconnect_client(client, true, "No such user: %s", username);
if (cf_log_connections)
slog_info(client, "login failed: db=%s user=%s", dbname, username);
return false;
}
}
return finish_set_pool(client, takeover);
}
bool handle_auth_response(PgSocket *client, PktHdr *pkt) {
uint16_t columns;
uint32_t length;
const char *username, *password;
PgUser user;
PgSocket *server = client->link;
switch(pkt->type) {
case 'T': /* RowDescription */
if (!mbuf_get_uint16be(&pkt->data, &columns)) {
disconnect_server(server, false, "bad packet");
return false;
}
if (columns != 2u) {
disconnect_server(server, false, "expected 1 column from login query, not %hu", columns);
return false;
}
break;
case 'D': /* DataRow */
memset(&user, 0, sizeof(user));
if (!mbuf_get_uint16be(&pkt->data, &columns)) {
disconnect_server(server, false, "bad packet");
return false;
}
if (columns != 2u) {
disconnect_server(server, false, "expected 1 column from login query, not %hu", columns);
return false;
}
if (!mbuf_get_uint32be(&pkt->data, &length)) {
disconnect_server(server, false, "bad packet");
return false;
}
if (!mbuf_get_chars(&pkt->data, length, &username)) {
disconnect_server(server, false, "bad packet");
return false;
}
if (sizeof(user.name) - 1 < length)
length = sizeof(user.name) - 1;
memcpy(user.name, username, length);
if (!mbuf_get_uint32be(&pkt->data, &length)) {
disconnect_server(server, false, "bad packet");
return false;
}
if (length == (uint32_t)-1) {
/*
* NULL - set an md5 password with an impossible value,
* so that nothing will ever match
*/
password = "md5";
length = 3;
} else {
if (!mbuf_get_chars(&pkt->data, length, &password)) {
disconnect_server(server, false, "bad packet");
return false;
}
}
if (sizeof(user.passwd) - 1 < length)
length = sizeof(user.passwd) - 1;
memcpy(user.passwd, password, length);
client->auth_user = add_db_user(client->db, user.name, user.passwd);
if (!client->auth_user) {
disconnect_server(server, false, "unable to allocate new user for auth");
return false;
}
break;
case 'N': /* NoticeResponse */
break;
case 'C': /* CommandComplete */
break;
case '1': /* ParseComplete */
break;
case '2': /* BindComplete */
break;
case 'Z': /* ReadyForQuery */
sbuf_prepare_skip(&client->link->sbuf, pkt->len);
if (!client->auth_user) {
if (cf_log_connections)
slog_info(client, "login failed: db=%s", client->db->name);
disconnect_client(client, true, "No such user");
} else {
slog_noise(client, "auth query complete");
client->link->resetting = true;
sbuf_continue(&client->sbuf);
}
/*
* either sbuf_continue or disconnect_client could disconnect the server
* way down in their bowels of other callbacks. so check that, and
* return appropriately (similar to reuse_on_release)
*/
if (server->state == SV_FREE || server->state == SV_JUSTFREE)
return false;
return true;
default:
disconnect_server(server, false, "unexpected response from login query");
return false;
}
sbuf_prepare_skip(&server->sbuf, pkt->len);
return true;
}
static void set_appname(PgSocket *client, const char *app_name)
{
char buf[400], abuf[300];
const char *details;
if (cf_application_name_add_host) {
/* give app a name */
if (!app_name)
app_name = "app";
/* add details */
details = pga_details(&client->remote_addr, abuf, sizeof(abuf));
snprintf(buf, sizeof(buf), "%s - %s", app_name, details);
app_name = buf;
}
if (app_name) {
slog_debug(client, "using application_name: %s", app_name);
varcache_set(&client->vars, "application_name", app_name);
}
}
static bool decide_startup_pool(PgSocket *client, PktHdr *pkt)
{
const char *username = NULL, *dbname = NULL;
const char *key, *val;
bool ok;
bool appname_found = false;
while (1) {
ok = mbuf_get_string(&pkt->data, &key);
if (!ok || *key == 0)
break;
ok = mbuf_get_string(&pkt->data, &val);
if (!ok)
break;
if (strcmp(key, "database") == 0) {
slog_debug(client, "got var: %s=%s", key, val);
dbname = val;
} else if (strcmp(key, "user") == 0) {
slog_debug(client, "got var: %s=%s", key, val);
username = val;
} else if (strcmp(key, "application_name") == 0) {
set_appname(client, val);
appname_found = true;
} else if (varcache_set(&client->vars, key, val)) {
slog_debug(client, "got var: %s=%s", key, val);
} else if (strlist_contains(cf_ignore_startup_params, key)) {
slog_debug(client, "ignoring startup parameter: %s=%s", key, val);
} else {
slog_warning(client, "unsupported startup parameter: %s=%s", key, val);
disconnect_client(client, true, "Unsupported startup parameter: %s", key);
return false;
}
}
if (!username || !username[0]) {
disconnect_client(client, true, "No username supplied");
return false;
}
/* if missing dbname, default to username */
if (!dbname || !dbname[0])
dbname = username;
/* create application_name if requested */
if (!appname_found)
set_appname(client, NULL);
/* check if limit allows, don't limit admin db
nb: new incoming conn will be attached to PgSocket, thus
get_active_client_count() counts it */
if (get_active_client_count() > cf_max_client_conn) {
if (strcmp(dbname, "pgbouncer") != 0) {
disconnect_client(client, true, "no more connections allowed (max_client_conn)");
return false;
}
}
/* find pool */
return set_pool(client, dbname, username, "", false);
}
/* decide on packets of client in login phase */
static bool handle_client_startup(PgSocket *client, PktHdr *pkt)
{
const char *passwd;
const uint8_t *key;
bool ok;
SBuf *sbuf = &client->sbuf;
/* don't tolerate partial packets */
if (incomplete_pkt(pkt)) {
disconnect_client(client, true, "client sent partial pkt in startup phase");
return false;
}
if (client->wait_for_welcome) {
if (finish_client_login(client)) {
/* the packet was already parsed */
sbuf_prepare_skip(sbuf, pkt->len);
return true;
} else {
return false;
}
}
switch (pkt->type) {
case PKT_SSLREQ:
slog_noise(client, "C: req SSL");
if (client->sbuf.tls) {
disconnect_client(client, false, "SSL req inside SSL");
return false;
}
if (cf_client_tls_sslmode != SSLMODE_DISABLED) {
slog_noise(client, "P: SSL ack");
if (!sbuf_answer(&client->sbuf, "S", 1)) {
disconnect_client(client, false, "failed to ack SSL");
return false;
}
if (!sbuf_tls_accept(&client->sbuf)) {
disconnect_client(client, false, "failed to accept SSL");
return false;
}
break;
}
/* reject SSL attempt */
slog_noise(client, "P: nak");
if (!sbuf_answer(&client->sbuf, "N", 1)) {
disconnect_client(client, false, "failed to nak SSL");
return false;
}
break;
case PKT_STARTUP_V2:
disconnect_client(client, true, "Old V2 protocol not supported");
return false;
case PKT_STARTUP:
/* require SSL except on unix socket */
if (cf_client_tls_sslmode >= SSLMODE_REQUIRE && !client->sbuf.tls && !pga_is_unix(&client->remote_addr)) {
disconnect_client(client, true, "SSL required");
return false;
}
if (client->pool && !client->wait_for_user_conn && !client->wait_for_user) {
disconnect_client(client, true, "client re-sent startup pkt");
return false;
}
if (client->wait_for_user) {
client->wait_for_user = false;
if (!finish_set_pool(client, false))
return false;
} else if (!decide_startup_pool(client, pkt)) {
return false;
}
break;
case 'p': /* PasswordMessage */
/* too early */
if (!client->auth_user) {
disconnect_client(client, true, "client password pkt before startup packet");
return false;
}
ok = mbuf_get_string(&pkt->data, &passwd);
if (ok && check_client_passwd(client, passwd)) {
if (!finish_client_login(client))
return false;
} else {
disconnect_client(client, true, "Auth failed");
return false;
}
break;
case PKT_CANCEL:
if (mbuf_avail_for_read(&pkt->data) == BACKENDKEY_LEN
&& mbuf_get_bytes(&pkt->data, BACKENDKEY_LEN, &key))
{
memcpy(client->cancel_key, key, BACKENDKEY_LEN);
accept_cancel_request(client);
} else {
disconnect_client(client, false, "bad cancel request");
}
return false;
default:
disconnect_client(client, false, "bad packet");
return false;
}
sbuf_prepare_skip(sbuf, pkt->len);
client->request_time = get_cached_time();
return true;
}
/* decide on packets of logged-in client */
static bool handle_client_work(PgSocket *client, PktHdr *pkt)
{
SBuf *sbuf = &client->sbuf;
switch (pkt->type) {
/* one-packet queries */
case 'Q': /* Query */
if (cf_disable_pqexec) {
slog_error(client, "Client used 'Q' packet type.");
disconnect_client(client, true, "PQexec disallowed");
return false;
}
case 'F': /* FunctionCall */
/* request immediate response from server */
case 'S': /* Sync */
client->expect_rfq_count++;
break;
case 'H': /* Flush */
break;
/* copy end markers */
case 'c': /* CopyDone(F/B) */
case 'f': /* CopyFail(F/B) */
break;
/*
* extended protocol allows server (and thus pooler)
* to buffer packets until sync or flush is sent by client
*/
case 'P': /* Parse */
case 'E': /* Execute */
case 'C': /* Close */
case 'B': /* Bind */
case 'D': /* Describe */
case 'd': /* CopyData(F/B) */
break;
/* client wants to go away */
default:
slog_error(client, "unknown pkt from client: %d/0x%x", pkt->type, pkt->type);
disconnect_client(client, true, "unknown pkt");
return false;
case 'X': /* Terminate */
disconnect_client(client, false, "client close request");
return false;
}
/* update stats */
if (!client->query_start) {
client->pool->stats.request_count++;
client->query_start = get_cached_time();
}
if (client->pool->db->admin)
return admin_handle_client(client, pkt);
/* acquire server */
if (!find_server(client))
return false;
client->pool->stats.client_bytes += pkt->len;
/* tag the server as dirty */
client->link->ready = false;
client->link->idle_tx = false;
/* forward the packet */
sbuf_prepare_send(sbuf, &client->link->sbuf, pkt->len);
return true;
}
/* callback from SBuf */
bool client_proto(SBuf *sbuf, SBufEvent evtype, struct MBuf *data)
{
bool res = false;
PgSocket *client = container_of(sbuf, PgSocket, sbuf);
PktHdr pkt;
Assert(!is_server_socket(client));
Assert(client->sbuf.sock);
Assert(client->state != CL_FREE);
/* may happen if close failed */
if (client->state == CL_JUSTFREE)
return false;
switch (evtype) {
case SBUF_EV_CONNECT_OK:
case SBUF_EV_CONNECT_FAILED:
/* ^ those should not happen */
case SBUF_EV_RECV_FAILED:
disconnect_client(client, false, "client unexpected eof");
break;
case SBUF_EV_SEND_FAILED:
disconnect_server(client->link, false, "Server connection closed");
break;
case SBUF_EV_READ:
/* Wait until full packet headers is available. */
if (incomplete_header(data)) {
slog_noise(client, "C: got partial header, trying to wait a bit");
return false;
}
if (!get_header(data, &pkt)) {
char hex[8*2 + 1];
disconnect_client(client, true, "bad packet header: '%s'",
hdr2hex(data, hex, sizeof(hex)));
return false;
}
slog_noise(client, "pkt='%c' len=%d", pkt_desc(&pkt), pkt.len);
client->request_time = get_cached_time();
switch (client->state) {
case CL_LOGIN:
res = handle_client_startup(client, &pkt);
break;
case CL_ACTIVE:
if (client->wait_for_welcome)
res = handle_client_startup(client, &pkt);
else
res = handle_client_work(client, &pkt);
break;
case CL_WAITING:
fatal("why waiting client in client_proto()");
default:
fatal("bad client state: %d", client->state);
}
break;
case SBUF_EV_FLUSH:
/* client is not interested in it */
break;
case SBUF_EV_PKT_CALLBACK:
/* unused ATM */
break;
case SBUF_EV_TLS_READY:
sbuf_continue(&client->sbuf);
res = true;
break;
}
return res;
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/good_1723_0 |
crossvul-cpp_data_bad_2556_1 | /*
* jabberd - Jabber Open Source Server
* Copyright (c) 2002 Jeremie Miller, Thomas Muldowney,
* Ryan Eatmon, Robert Norris
*
* 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, MA02111-1307USA
*/
/* SASL authentication handler */
#include "sx.h"
#include "sasl.h"
#include <gsasl.h>
#include <gsasl-mech.h>
#include <string.h>
/** our sasl application context */
typedef struct _sx_sasl_st {
char *appname;
Gsasl *gsasl_ctx;
sx_sasl_callback_t cb;
void *cbarg;
char *ext_id[SX_CONN_EXTERNAL_ID_MAX_COUNT];
} *_sx_sasl_t;
/** our sasl per session context */
typedef struct _sx_sasl_sess_st {
sx_t s;
_sx_sasl_t ctx;
} *_sx_sasl_sess_t;
/** utility: generate a success nad */
static nad_t _sx_sasl_success(sx_t s, const char *data, int dlen) {
nad_t nad;
int ns;
nad = nad_new();
ns = nad_add_namespace(nad, uri_SASL, NULL);
nad_append_elem(nad, ns, "success", 0);
if(data != NULL)
nad_append_cdata(nad, data, dlen, 1);
return nad;
}
/** utility: generate a failure nad */
static nad_t _sx_sasl_failure(sx_t s, const char *err, const char *text) {
nad_t nad;
int ns;
nad = nad_new();
ns = nad_add_namespace(nad, uri_SASL, NULL);
nad_append_elem(nad, ns, "failure", 0);
if(err != NULL)
nad_append_elem(nad, ns, err, 1);
if(text != NULL) {
nad_append_elem(nad, ns, "text", 1);
nad_append_cdata(nad, text, strlen(text), 2);
}
return nad;
}
/** utility: generate a challenge nad */
static nad_t _sx_sasl_challenge(sx_t s, const char *data, int dlen) {
nad_t nad;
int ns;
nad = nad_new();
ns = nad_add_namespace(nad, uri_SASL, NULL);
nad_append_elem(nad, ns, "challenge", 0);
if(data != NULL)
nad_append_cdata(nad, data, dlen, 1);
return nad;
}
/** utility: generate a response nad */
static nad_t _sx_sasl_response(sx_t s, const char *data, int dlen) {
nad_t nad;
int ns;
nad = nad_new();
ns = nad_add_namespace(nad, uri_SASL, NULL);
nad_append_elem(nad, ns, "response", 0);
if(data != NULL)
nad_append_cdata(nad, data, dlen, 1);
return nad;
}
/** utility: generate an abort nad */
static nad_t _sx_sasl_abort(sx_t s) {
nad_t nad;
int ns;
nad = nad_new();
ns = nad_add_namespace(nad, uri_SASL, NULL);
nad_append_elem(nad, ns, "abort", 0);
return nad;
}
static int _sx_sasl_wio(sx_t s, sx_plugin_t p, sx_buf_t buf) {
sx_error_t sxe;
size_t len;
int ret;
char *out;
Gsasl_session *sd = (Gsasl_session *) s->plugin_data[p->index];
_sx_debug(ZONE, "doing sasl encode");
/* encode the output */
ret = gsasl_encode(sd, buf->data, buf->len, &out, &len);
if (ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_encode failed (%d): %s", ret, gsasl_strerror (ret));
/* Fatal error */
_sx_gen_error(sxe, SX_ERR_AUTH, "SASL Stream encoding failed", (char*) gsasl_strerror (ret));
_sx_event(s, event_ERROR, (void *) &sxe);
return -1;
}
/* replace the buffer */
_sx_buffer_set(buf, out, len, NULL);
free(out);
_sx_debug(ZONE, "%d bytes encoded for sasl channel", buf->len);
return 1;
}
static int _sx_sasl_rio(sx_t s, sx_plugin_t p, sx_buf_t buf) {
sx_error_t sxe;
size_t len;
int ret;
char *out;
Gsasl_session *sd = (Gsasl_session *) s->plugin_data[p->index];
_sx_debug(ZONE, "doing sasl decode");
/* decode the input */
ret = gsasl_decode(sd, buf->data, buf->len, &out, &len);
if (ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_decode failed (%d): %s", ret, gsasl_strerror (ret));
/* Fatal error */
_sx_gen_error(sxe, SX_ERR_AUTH, "SASL Stream decoding failed", (char*) gsasl_strerror (ret));
_sx_event(s, event_ERROR, (void *) &sxe);
return -1;
}
/* replace the buffer */
_sx_buffer_set(buf, out, len, NULL);
free(out);
_sx_debug(ZONE, "%d bytes decoded from sasl channel", len);
return 1;
}
/** move the stream to the auth state */
void _sx_sasl_open(sx_t s, Gsasl_session *sd) {
char *method, *authzid;
const char *realm = NULL;
struct sx_sasl_creds_st creds = {NULL, NULL, NULL, NULL};
_sx_sasl_sess_t sctx = gsasl_session_hook_get(sd);
_sx_sasl_t ctx = sctx->ctx;
const char *mechname = gsasl_mechanism_name (sd);
/* get the method */
method = (char *) malloc(sizeof(char) * (strlen(mechname) + 6));
sprintf(method, "SASL/%s", mechname);
/* and the authorization identifier */
creds.authzid = gsasl_property_fast(sd, GSASL_AUTHZID);
creds.authnid = gsasl_property_fast(sd, GSASL_AUTHID);
creds.realm = gsasl_property_fast(sd, GSASL_REALM);
if(0 && ctx && ctx->cb) { /* not supported yet */
if((ctx->cb)(sx_sasl_cb_CHECK_AUTHZID, &creds, NULL, s, ctx->cbarg)!=sx_sasl_ret_OK) {
_sx_debug(ZONE, "stream authzid: %s verification failed, not advancing to auth state", creds.authzid);
free(method);
return;
}
} else if (NULL != gsasl_property_fast(sd, GSASL_GSSAPI_DISPLAY_NAME)) {
creds.authzid = strdup(gsasl_property_fast(sd, GSASL_GSSAPI_DISPLAY_NAME));
authzid = NULL;
} else {
/* override unchecked arbitrary authzid */
if(creds.realm && creds.realm[0] != '\0') {
realm = creds.realm;
} else {
realm = s->req_to;
}
authzid = (char *) malloc(sizeof(char) * (strlen(creds.authnid) + strlen(realm) + 2));
sprintf(authzid, "%s@%s", creds.authnid, realm);
creds.authzid = authzid;
}
/* proceed stream to authenticated state */
sx_auth(s, method, creds.authzid);
free(method);
if(authzid) free(authzid);
}
/** make the stream authenticated second time round */
static void _sx_sasl_stream(sx_t s, sx_plugin_t p) {
Gsasl_session *sd = (Gsasl_session *) s->plugin_data[p->index];
/* do nothing the first time */
if(sd == NULL)
return;
/* are we auth'd? */
if(NULL == gsasl_property_fast(sd, GSASL_AUTHID)) {
_sx_debug(ZONE, "not auth'd, not advancing to auth'd state yet");
return;
}
/* otherwise, its auth time */
_sx_sasl_open(s, sd);
}
static void _sx_sasl_features(sx_t s, sx_plugin_t p, nad_t nad) {
_sx_sasl_t ctx = (_sx_sasl_t) p->private;
Gsasl_session *sd = (Gsasl_session *) s->plugin_data[p->index];
int nmechs, ret;
char *mechs, *mech, *c;
if(s->type != type_SERVER)
return;
if(sd != NULL) {
_sx_debug(ZONE, "already auth'd, not offering sasl mechanisms");
return;
}
if(!(s->flags & SX_SASL_OFFER)) {
_sx_debug(ZONE, "application didn't ask us to offer sasl, so we won't");
return;
}
#ifdef HAVE_SSL
if((s->flags & SX_SSL_STARTTLS_REQUIRE) && s->ssf == 0) {
_sx_debug(ZONE, "ssl not established yet but the app requires it, not offering mechanisms");
return;
}
#endif
_sx_debug(ZONE, "offering sasl mechanisms");
ret = gsasl_server_mechlist(ctx->gsasl_ctx, &mechs);
if(ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_server_mechlist failed (%d): %s, not offering sasl for this conn", ret, gsasl_strerror (ret));
return;
}
mech = mechs;
nmechs = 0;
while(mech != NULL) {
c = strchr(mech, ' ');
if(c != NULL)
*c = '\0';
if ((ctx->cb)(sx_sasl_cb_CHECK_MECH, mech, NULL, s, ctx->cbarg)==sx_sasl_ret_OK) {
if (nmechs == 0) {
int ns = nad_add_namespace(nad, uri_SASL, NULL);
nad_append_elem(nad, ns, "mechanisms", 1);
}
_sx_debug(ZONE, "offering mechanism: %s", mech);
nad_append_elem(nad, -1 /*ns*/, "mechanism", 2);
nad_append_cdata(nad, mech, strlen(mech), 3);
nmechs++;
}
if(c == NULL)
mech = NULL;
else
mech = ++c;
}
free(mechs);
}
/** auth done, restart the stream */
static void _sx_sasl_notify_success(sx_t s, void *arg) {
sx_plugin_t p = (sx_plugin_t) arg;
_sx_chain_io_plugin(s, p);
_sx_debug(ZONE, "auth completed, resetting");
_sx_reset(s);
sx_server_init(s, s->flags);
}
/** process handshake packets from the client */
static void _sx_sasl_client_process(sx_t s, sx_plugin_t p, Gsasl_session *sd, const char *mech, const char *in, int inlen) {
_sx_sasl_t ctx = (_sx_sasl_t) p->private;
_sx_sasl_sess_t sctx = NULL;
char *buf = NULL, *out = NULL, *realm = NULL, **ext_id;
char hostname[256];
int ret;
#ifdef HAVE_SSL
int i;
#endif
size_t buflen, outlen;
assert(ctx);
assert(ctx->cb);
if(mech != NULL) {
_sx_debug(ZONE, "auth request from client (mechanism=%s)", mech);
if(!gsasl_server_support_p(ctx->gsasl_ctx, mech)) {
_sx_debug(ZONE, "client requested mechanism (%s) that we didn't offer", mech);
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INVALID_MECHANISM, NULL), 0);
return;
}
/* startup */
ret = gsasl_server_start(ctx->gsasl_ctx, mech, &sd);
if(ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_server_start failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_TEMPORARY_FAILURE, gsasl_strerror(ret)), 0);
return;
}
/* get the realm */
(ctx->cb)(sx_sasl_cb_GET_REALM, NULL, (void **) &realm, s, ctx->cbarg);
/* cleanup any existing session context */
sctx = gsasl_session_hook_get(sd);
if (sctx != NULL) free(sctx);
/* allocate and initialize our per session context */
sctx = (_sx_sasl_sess_t) calloc(1, sizeof(struct _sx_sasl_sess_st));
sctx->s = s;
sctx->ctx = ctx;
gsasl_session_hook_set(sd, (void *) sctx);
gsasl_property_set(sd, GSASL_SERVICE, ctx->appname);
gsasl_property_set(sd, GSASL_REALM, realm);
/* get hostname */
hostname[0] = '\0';
gethostname(hostname, 256);
hostname[255] = '\0';
gsasl_property_set(sd, GSASL_HOSTNAME, hostname);
/* get EXTERNAL data from the ssl plugin */
ext_id = NULL;
#ifdef HAVE_SSL
for(i = 0; i < s->env->nplugins; i++)
if(s->env->plugins[i]->magic == SX_SSL_MAGIC && s->plugin_data[s->env->plugins[i]->index] != NULL)
ext_id = ((_sx_ssl_conn_t) s->plugin_data[s->env->plugins[i]->index])->external_id;
if (ext_id != NULL) {
//_sx_debug(ZONE, "sasl context ext id '%s'", ext_id);
/* if there is, store it for later */
for (i = 0; i < SX_CONN_EXTERNAL_ID_MAX_COUNT; i++)
if (ext_id[i] != NULL) {
ctx->ext_id[i] = strdup(ext_id[i]);
} else {
ctx->ext_id[i] = NULL;
break;
}
}
#endif
_sx_debug(ZONE, "sasl context initialised for %d", s->tag);
s->plugin_data[p->index] = (void *) sd;
if(strcmp(mech, "ANONYMOUS") == 0) {
/*
* special case for SASL ANONYMOUS: ignore the initial
* response provided by the client and generate a random
* authid to use as the jid node for the user, as
* specified in XEP-0175
*/
(ctx->cb)(sx_sasl_cb_GEN_AUTHZID, NULL, (void **)&out, s, ctx->cbarg);
buf = strdup(out);
buflen = strlen(buf);
} else if (strstr(in, "<") != NULL && strncmp(in, "=", strstr(in, "<") - in ) == 0) {
/* XXX The above check is hackish, but `in` is just weird */
/* This is a special case for SASL External c2s. See XEP-0178 */
_sx_debug(ZONE, "gsasl auth string is empty");
buf = strdup("");
buflen = strlen(buf);
} else {
/* decode and process */
ret = gsasl_base64_from(in, inlen, &buf, &buflen);
if (ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_base64_from failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0);
if(buf != NULL) free(buf);
return;
}
}
ret = gsasl_step(sd, buf, buflen, &out, &outlen);
}
else {
/* decode and process */
ret = gsasl_base64_from(in, inlen, &buf, &buflen);
if (ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_base64_from failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0);
return;
}
if(!sd) {
_sx_debug(ZONE, "response send before auth request enabling mechanism (decoded: %.*s)", buflen, buf);
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_MECH_TOO_WEAK, "response send before auth request enabling mechanism"), 0);
if(buf != NULL) free(buf);
return;
}
_sx_debug(ZONE, "response from client (decoded: %.*s)", buflen, buf);
ret = gsasl_step(sd, buf, buflen, &out, &outlen);
}
if(buf != NULL) free(buf);
/* auth completed */
if(ret == GSASL_OK) {
_sx_debug(ZONE, "sasl handshake completed");
/* encode the leftover response */
ret = gsasl_base64_to(out, outlen, &buf, &buflen);
if (ret == GSASL_OK) {
/* send success */
_sx_nad_write(s, _sx_sasl_success(s, buf, buflen), 0);
free(buf);
/* set a notify on the success nad buffer */
((sx_buf_t) s->wbufq->front->data)->notify = _sx_sasl_notify_success;
((sx_buf_t) s->wbufq->front->data)->notify_arg = (void *) p;
}
else {
_sx_debug(ZONE, "gsasl_base64_to failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0);
if(buf != NULL) free(buf);
}
if(out != NULL) free(out);
return;
}
/* in progress */
if(ret == GSASL_NEEDS_MORE) {
_sx_debug(ZONE, "sasl handshake in progress (challenge: %.*s)", outlen, out);
/* encode the challenge */
ret = gsasl_base64_to(out, outlen, &buf, &buflen);
if (ret == GSASL_OK) {
_sx_nad_write(s, _sx_sasl_challenge(s, buf, buflen), 0);
free(buf);
}
else {
_sx_debug(ZONE, "gsasl_base64_to failed, no sasl for this conn; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INCORRECT_ENCODING, gsasl_strerror(ret)), 0);
if(buf != NULL) free(buf);
}
if(out != NULL) free(out);
return;
}
if(out != NULL) free(out);
/* its over */
_sx_debug(ZONE, "sasl handshake failed; (%d): %s", ret, gsasl_strerror(ret));
switch (ret) {
case GSASL_AUTHENTICATION_ERROR:
case GSASL_NO_ANONYMOUS_TOKEN:
case GSASL_NO_AUTHID:
case GSASL_NO_AUTHZID:
case GSASL_NO_PASSWORD:
case GSASL_NO_PASSCODE:
case GSASL_NO_PIN:
case GSASL_NO_SERVICE:
case GSASL_NO_HOSTNAME:
out = _sasl_err_NOT_AUTHORIZED;
break;
case GSASL_UNKNOWN_MECHANISM:
case GSASL_MECHANISM_PARSE_ERROR:
out = _sasl_err_INVALID_MECHANISM;
break;
case GSASL_BASE64_ERROR:
out = _sasl_err_INCORRECT_ENCODING;
break;
default:
out = _sasl_err_MALFORMED_REQUEST;
}
_sx_nad_write(s, _sx_sasl_failure(s, out, gsasl_strerror(ret)), 0);
}
/** process handshake packets from the server */
static void _sx_sasl_server_process(sx_t s, sx_plugin_t p, Gsasl_session *sd, const char *in, int inlen) {
char *buf = NULL, *out = NULL;
size_t buflen, outlen;
int ret;
_sx_debug(ZONE, "data from client");
/* decode the response */
ret = gsasl_base64_from(in, inlen, &buf, &buflen);
if (ret == GSASL_OK) {
_sx_debug(ZONE, "decoded data: %.*s", buflen, buf);
/* process the data */
ret = gsasl_step(sd, buf, buflen, &out, &outlen);
if(buf != NULL) free(buf);
buf = NULL;
/* in progress */
if(ret == GSASL_OK || ret == GSASL_NEEDS_MORE) {
_sx_debug(ZONE, "sasl handshake in progress (response: %.*s)", outlen, out);
/* encode the response */
ret = gsasl_base64_to(out, outlen, &buf, &buflen);
if (ret == GSASL_OK) {
_sx_nad_write(s, _sx_sasl_response(s, buf, buflen), 0);
}
if(out != NULL) free(out);
if(buf != NULL) free(buf);
return;
}
}
if(out != NULL) free(out);
if(buf != NULL) free(buf);
/* its over */
_sx_debug(ZONE, "sasl handshake aborted; (%d): %s", ret, gsasl_strerror(ret));
_sx_nad_write(s, _sx_sasl_abort(s), 0);
}
/** main nad processor */
static int _sx_sasl_process(sx_t s, sx_plugin_t p, nad_t nad) {
Gsasl_session *sd = (Gsasl_session *) s->plugin_data[p->index];
int attr;
char mech[128];
sx_error_t sxe;
int flags;
char *ns = NULL, *to = NULL, *from = NULL, *version = NULL;
/* only want sasl packets */
if(NAD_ENS(nad, 0) < 0 || NAD_NURI_L(nad, NAD_ENS(nad, 0)) != strlen(uri_SASL) || strncmp(NAD_NURI(nad, NAD_ENS(nad, 0)), uri_SASL, strlen(uri_SASL)) != 0)
return 1;
/* quietly drop it if sasl is disabled, or if not ready */
if(s->state != state_STREAM) {
_sx_debug(ZONE, "not correct state for sasl, ignoring");
nad_free(nad);
return 0;
}
/* packets from the client */
if(s->type == type_SERVER) {
if(!(s->flags & SX_SASL_OFFER)) {
_sx_debug(ZONE, "they tried to do sasl, but we never offered it, ignoring");
nad_free(nad);
return 0;
}
#ifdef HAVE_SSL
if((s->flags & SX_SSL_STARTTLS_REQUIRE) && s->ssf == 0) {
_sx_debug(ZONE, "they tried to do sasl, but they have to do starttls first, ignoring");
nad_free(nad);
return 0;
}
#endif
/* auth */
if(NAD_ENAME_L(nad, 0) == 4 && strncmp("auth", NAD_ENAME(nad, 0), NAD_ENAME_L(nad, 0)) == 0) {
/* require mechanism */
if((attr = nad_find_attr(nad, 0, -1, "mechanism", NULL)) < 0) {
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_INVALID_MECHANISM, NULL), 0);
nad_free(nad);
return 0;
}
/* extract */
snprintf(mech, 127, "%.*s", NAD_AVAL_L(nad, attr), NAD_AVAL(nad, attr));
/* go */
_sx_sasl_client_process(s, p, sd, mech, NAD_CDATA(nad, 0), NAD_CDATA_L(nad, 0));
nad_free(nad);
return 0;
}
/* response */
else if(NAD_ENAME_L(nad, 0) == 8 && strncmp("response", NAD_ENAME(nad, 0), NAD_ENAME_L(nad, 0)) == 0) {
/* process it */
_sx_sasl_client_process(s, p, sd, NULL, NAD_CDATA(nad, 0), NAD_CDATA_L(nad, 0));
nad_free(nad);
return 0;
}
/* abort */
else if(NAD_ENAME_L(nad, 0) == 5 && strncmp("abort", NAD_ENAME(nad, 0), NAD_ENAME_L(nad, 0)) == 0) {
_sx_debug(ZONE, "sasl handshake aborted");
_sx_nad_write(s, _sx_sasl_failure(s, _sasl_err_ABORTED, NULL), 0);
nad_free(nad);
return 0;
}
}
/* packets from the server */
else if(s->type == type_CLIENT) {
if(sd == NULL) {
_sx_debug(ZONE, "got sasl client packets, but they never started sasl, ignoring");
nad_free(nad);
return 0;
}
/* challenge */
if(NAD_ENAME_L(nad, 0) == 9 && strncmp("challenge", NAD_ENAME(nad, 0), NAD_ENAME_L(nad, 0)) == 0) {
/* process it */
_sx_sasl_server_process(s, p, sd, NAD_CDATA(nad, 0), NAD_CDATA_L(nad, 0));
nad_free(nad);
return 0;
}
/* success */
else if(NAD_ENAME_L(nad, 0) == 7 && strncmp("success", NAD_ENAME(nad, 0), NAD_ENAME_L(nad, 0)) == 0) {
_sx_debug(ZONE, "sasl handshake completed, resetting");
nad_free(nad);
/* save interesting bits */
flags = s->flags;
if(s->ns != NULL) ns = strdup(s->ns);
if(s->req_to != NULL) to = strdup(s->req_to);
if(s->req_from != NULL) from = strdup(s->req_from);
if(s->req_version != NULL) version = strdup(s->req_version);
/* reset state */
_sx_reset(s);
_sx_debug(ZONE, "restarting stream with sasl layer established");
/* second time round */
sx_client_init(s, flags, ns, to, from, version);
/* free bits */
if(ns != NULL) free(ns);
if(to != NULL) free(to);
if(from != NULL) free(from);
if(version != NULL) free(version);
return 0;
}
/* failure */
else if(NAD_ENAME_L(nad, 0) == 7 && strncmp("failure", NAD_ENAME(nad, 0), NAD_ENAME_L(nad, 0)) == 0) {
/* fire the error */
_sx_gen_error(sxe, SX_ERR_AUTH, "Authentication failed", NULL);
_sx_event(s, event_ERROR, (void *) &sxe);
/* cleanup */
gsasl_finish(sd);
s->plugin_data[p->index] = NULL;
nad_free(nad);
return 0;
}
}
/* invalid sasl command, quietly drop it */
_sx_debug(ZONE, "unknown sasl command '%.*s', ignoring", NAD_ENAME_L(nad, 0), NAD_ENAME(nad, 0));
nad_free(nad);
return 0;
}
/** cleanup */
static void _sx_sasl_free(sx_t s, sx_plugin_t p) {
Gsasl_session *sd = (Gsasl_session *) s->plugin_data[p->index];
_sx_sasl_sess_t sctx;
if(sd == NULL)
return;
_sx_debug(ZONE, "cleaning up conn state");
/* we need to clean up our per session context but keep sasl ctx */
sctx = gsasl_session_hook_get(sd);
if (sctx != NULL){
free(sctx);
gsasl_session_hook_set(sd, (void *) NULL);
}
gsasl_finish(sd);
s->plugin_data[p->index] = NULL;
}
static int _sx_sasl_gsasl_callback(Gsasl *gsasl_ctx, Gsasl_session *sd, Gsasl_property prop) {
_sx_sasl_sess_t sctx = gsasl_session_hook_get(sd);
_sx_sasl_t ctx = NULL;
struct sx_sasl_creds_st creds = {NULL, NULL, NULL, NULL};
char *value, *node, *host;
int len, i;
/*
* session hook data is not always available while its being set up,
* also not needed in many of the cases below.
*/
if(sctx != NULL) {
ctx = sctx->ctx;
}
_sx_debug(ZONE, "in _sx_sasl_gsasl_callback, property: %d", prop);
switch(prop) {
case GSASL_PASSWORD:
/* GSASL_AUTHID, GSASL_AUTHZID, GSASL_REALM */
assert(ctx);
assert(ctx->cb);
creds.authnid = gsasl_property_fast(sd, GSASL_AUTHID);
creds.realm = gsasl_property_fast(sd, GSASL_REALM);
if(!creds.authnid) return GSASL_NO_AUTHID;
if(!creds.realm) return GSASL_NO_AUTHZID;
if((ctx->cb)(sx_sasl_cb_GET_PASS, &creds, (void **)&value, sctx->s, ctx->cbarg) == sx_sasl_ret_OK) {
gsasl_property_set(sd, GSASL_PASSWORD, value);
}
return GSASL_NEEDS_MORE;
case GSASL_SERVICE:
gsasl_property_set(sd, GSASL_SERVICE, "xmpp");
return GSASL_OK;
case GSASL_HOSTNAME:
{
char hostname[256];
/* get hostname */
hostname[0] = '\0';
gethostname(hostname, 256);
hostname[255] = '\0';
gsasl_property_set(sd, GSASL_HOSTNAME, hostname);
}
return GSASL_OK;
case GSASL_VALIDATE_SIMPLE:
/* GSASL_AUTHID, GSASL_AUTHZID, GSASL_PASSWORD */
assert(ctx);
assert(ctx->cb);
creds.authnid = gsasl_property_fast(sd, GSASL_AUTHID);
creds.realm = gsasl_property_fast(sd, GSASL_REALM);
creds.pass = gsasl_property_fast(sd, GSASL_PASSWORD);
if(!creds.authnid) return GSASL_NO_AUTHID;
if(!creds.realm) return GSASL_NO_AUTHZID;
if(!creds.pass) return GSASL_NO_PASSWORD;
if((ctx->cb)(sx_sasl_cb_CHECK_PASS, &creds, NULL, sctx->s, ctx->cbarg) == sx_sasl_ret_OK)
return GSASL_OK;
else
return GSASL_AUTHENTICATION_ERROR;
case GSASL_VALIDATE_GSSAPI:
/* GSASL_AUTHZID, GSASL_GSSAPI_DISPLAY_NAME */
creds.authnid = gsasl_property_fast(sd, GSASL_GSSAPI_DISPLAY_NAME);
if(!creds.authnid) return GSASL_NO_AUTHID;
creds.authzid = gsasl_property_fast(sd, GSASL_AUTHZID);
if(!creds.authzid) return GSASL_NO_AUTHZID;
gsasl_property_set(sd, GSASL_AUTHID, creds.authnid);
return GSASL_OK;
case GSASL_VALIDATE_ANONYMOUS:
/* GSASL_ANONYMOUS_TOKEN */
creds.authnid = gsasl_property_fast(sd, GSASL_ANONYMOUS_TOKEN);
if(!creds.authnid) return GSASL_NO_ANONYMOUS_TOKEN;
/* set token as authid for later use */
gsasl_property_set(sd, GSASL_AUTHID, creds.authnid);
return GSASL_OK;
case GSASL_VALIDATE_EXTERNAL:
/* GSASL_AUTHID */
assert(ctx);
assert(ctx->ext_id);
creds.authzid = gsasl_property_fast(sd, GSASL_AUTHZID);
_sx_debug(ZONE, "sasl external");
_sx_debug(ZONE, "sasl creds.authzid is '%s'", creds.authzid);
for (i = 0; i < SX_CONN_EXTERNAL_ID_MAX_COUNT; i++) {
if (ctx->ext_id[i] == NULL)
break;
_sx_debug(ZONE, "sasl ext_id(%d) is '%s'", i, ctx->ext_id[i]);
/* XXX hackish.. detect c2s by existance of @ */
value = strstr(ctx->ext_id[i], "@");
if(value == NULL && creds.authzid != NULL && strcmp(ctx->ext_id[i], creds.authzid) == 0) {
// s2s connection and it's valid
/* TODO Handle wildcards and other thigs from XEP-0178 */
_sx_debug(ZONE, "sasl ctx->ext_id doesn't have '@' in it. Assuming s2s");
return GSASL_OK;
}
if(value != NULL &&
((creds.authzid != NULL && strcmp(ctx->ext_id[i], creds.authzid) == 0) ||
(creds.authzid == NULL)) ) {
// c2s connection
// creds.authzid == NULL condition is from XEP-0178 '=' auth reply
// This should be freed by gsasl_finish() but I'm not sure
// node = authnid
len = value - ctx->ext_id[i];
node = (char *) malloc(sizeof(char) * (len + 1)); // + null termination
strncpy(node, ctx->ext_id[i], len);
node[len] = '\0'; // null terminate the string
// host = realm
len = strlen(value) - 1 + 1; // - the @ + null termination
host = (char *) malloc(sizeof(char) * (len));
strcpy(host, value + 1); // skip the @
gsasl_property_set(sd, GSASL_AUTHID, node);
gsasl_property_set(sd, GSASL_REALM, host);
return GSASL_OK;
}
}
return GSASL_AUTHENTICATION_ERROR;
default:
break;
}
return GSASL_NO_CALLBACK;
}
static void _sx_sasl_unload(sx_plugin_t p) {
_sx_sasl_t ctx = (_sx_sasl_t) p->private;
int i;
assert(ctx);
if (ctx->gsasl_ctx != NULL) gsasl_done (ctx->gsasl_ctx);
if (ctx->appname != NULL) free(ctx->appname);
for (i = 0; i < SX_CONN_EXTERNAL_ID_MAX_COUNT; i++)
if(ctx->ext_id[i] != NULL)
free(ctx->ext_id[i]);
else
break;
free(ctx);
}
/** args: appname, callback, cb arg */
int sx_sasl_init(sx_env_t env, sx_plugin_t p, va_list args) {
const char *appname;
sx_sasl_callback_t cb;
void *cbarg;
_sx_sasl_t ctx;
int ret, i;
_sx_debug(ZONE, "initialising sasl plugin");
appname = va_arg(args, const char *);
if(appname == NULL) {
_sx_debug(ZONE, "appname was NULL, failing");
return 1;
}
cb = va_arg(args, sx_sasl_callback_t);
cbarg = va_arg(args, void *);
ctx = (_sx_sasl_t) calloc(1, sizeof(struct _sx_sasl_st));
ctx->appname = strdup(appname);
ctx->cb = cb;
ctx->cbarg = cbarg;
for (i = 0; i < SX_CONN_EXTERNAL_ID_MAX_COUNT; i++)
ctx->ext_id[i] = NULL;
ret = gsasl_init(&ctx->gsasl_ctx);
if(ret != GSASL_OK) {
_sx_debug(ZONE, "couldn't initialize libgsasl (%d): %s", ret, gsasl_strerror (ret));
free(ctx);
return 1;
}
gsasl_callback_set (ctx->gsasl_ctx, &_sx_sasl_gsasl_callback);
_sx_debug(ZONE, "sasl context initialised");
p->private = (void *) ctx;
p->unload = _sx_sasl_unload;
p->wio = _sx_sasl_wio;
p->rio = _sx_sasl_rio;
p->stream = _sx_sasl_stream;
p->features = _sx_sasl_features;
p->process = _sx_sasl_process;
p->free = _sx_sasl_free;
return 0;
}
/** kick off the auth handshake */
int sx_sasl_auth(sx_plugin_t p, sx_t s, const char *appname, const char *mech, const char *user, const char *pass) {
_sx_sasl_t ctx = (_sx_sasl_t) p->private;
_sx_sasl_sess_t sctx = NULL;
Gsasl_session *sd;
char *buf = NULL, *out = NULL;
char hostname[256];
int ret, ns;
size_t buflen, outlen;
nad_t nad;
assert((p != NULL));
assert((s != NULL));
assert((appname != NULL));
assert((mech != NULL));
assert((user != NULL));
assert((pass != NULL));
if(s->type != type_CLIENT || s->state != state_STREAM) {
_sx_debug(ZONE, "need client in stream state for sasl auth");
return 1;
}
/* handshake start */
ret = gsasl_client_start(ctx->gsasl_ctx, mech, &sd);
if(ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_client_start failed, not authing; (%d): %s", ret, gsasl_strerror(ret));
return 1;
}
/* get hostname */
hostname[0] = '\0';
gethostname(hostname, 256);
hostname[255] = '\0';
/* cleanup any existing session context */
sctx = gsasl_session_hook_get(sd);
if (sctx != NULL) free(sctx);
/* allocate and initialize our per session context */
sctx = (_sx_sasl_sess_t) calloc(1, sizeof(struct _sx_sasl_sess_st));
sctx->s = s;
sctx->ctx = ctx;
/* set user data in session handle */
gsasl_session_hook_set(sd, (void *) sctx);
gsasl_property_set(sd, GSASL_AUTHID, user);
gsasl_property_set(sd, GSASL_PASSWORD, pass);
gsasl_property_set(sd, GSASL_SERVICE, appname);
gsasl_property_set(sd, GSASL_HOSTNAME, hostname);
/* handshake step */
ret = gsasl_step(sd, NULL, 0, &out, &outlen);
if(ret != GSASL_OK && ret != GSASL_NEEDS_MORE) {
_sx_debug(ZONE, "gsasl_step failed, not authing; (%d): %s", ret, gsasl_strerror(ret));
gsasl_finish(sd);
return 1;
}
/* save userdata */
s->plugin_data[p->index] = (void *) sd;
/* in progress */
_sx_debug(ZONE, "sending auth request to server, mech '%s': %.*s", mech, outlen, out);
/* encode the challenge */
ret = gsasl_base64_to(out, outlen, &buf, &buflen);
if(ret != GSASL_OK) {
_sx_debug(ZONE, "gsasl_base64_to failed, not authing; (%d): %s", ret, gsasl_strerror(ret));
gsasl_finish(sd);
if (out != NULL) free(out);
return 1;
}
free(out);
/* build the nad */
nad = nad_new();
ns = nad_add_namespace(nad, uri_SASL, NULL);
nad_append_elem(nad, ns, "auth", 0);
nad_append_attr(nad, -1, "mechanism", mech);
if(buf != NULL) {
nad_append_cdata(nad, buf, buflen, 1);
free(buf);
}
/* its away */
sx_nad_write(s, nad);
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-287/c/bad_2556_1 |
crossvul-cpp_data_good_333_0 | /*
* Copyright (C) 1999 WIDE Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Extensively modified by Hannes Gredler (hannes@gredler.at) for more
* complete BGP support.
*/
/* \summary: Border Gateway Protocol (BGP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "af.h"
#include "l2vpn.h"
static const char tstr[] = "[|BGP]";
struct bgp {
uint8_t bgp_marker[16];
uint16_t bgp_len;
uint8_t bgp_type;
};
#define BGP_SIZE 19 /* unaligned */
#define BGP_OPEN 1
#define BGP_UPDATE 2
#define BGP_NOTIFICATION 3
#define BGP_KEEPALIVE 4
#define BGP_ROUTE_REFRESH 5
static const struct tok bgp_msg_values[] = {
{ BGP_OPEN, "Open"},
{ BGP_UPDATE, "Update"},
{ BGP_NOTIFICATION, "Notification"},
{ BGP_KEEPALIVE, "Keepalive"},
{ BGP_ROUTE_REFRESH, "Route Refresh"},
{ 0, NULL}
};
struct bgp_open {
uint8_t bgpo_marker[16];
uint16_t bgpo_len;
uint8_t bgpo_type;
uint8_t bgpo_version;
uint16_t bgpo_myas;
uint16_t bgpo_holdtime;
uint32_t bgpo_id;
uint8_t bgpo_optlen;
/* options should follow */
};
#define BGP_OPEN_SIZE 29 /* unaligned */
struct bgp_opt {
uint8_t bgpopt_type;
uint8_t bgpopt_len;
/* variable length */
};
#define BGP_OPT_SIZE 2 /* some compilers may pad to 4 bytes */
#define BGP_CAP_HEADER_SIZE 2 /* some compilers may pad to 4 bytes */
struct bgp_notification {
uint8_t bgpn_marker[16];
uint16_t bgpn_len;
uint8_t bgpn_type;
uint8_t bgpn_major;
uint8_t bgpn_minor;
};
#define BGP_NOTIFICATION_SIZE 21 /* unaligned */
struct bgp_route_refresh {
uint8_t bgp_marker[16];
uint16_t len;
uint8_t type;
uint8_t afi[2]; /* the compiler messes this structure up */
uint8_t res; /* when doing misaligned sequences of int8 and int16 */
uint8_t safi; /* afi should be int16 - so we have to access it using */
}; /* EXTRACT_16BITS(&bgp_route_refresh->afi) (sigh) */
#define BGP_ROUTE_REFRESH_SIZE 23
#define bgp_attr_lenlen(flags, p) \
(((flags) & 0x10) ? 2 : 1)
#define bgp_attr_len(flags, p) \
(((flags) & 0x10) ? EXTRACT_16BITS(p) : *(p))
#define BGPTYPE_ORIGIN 1
#define BGPTYPE_AS_PATH 2
#define BGPTYPE_NEXT_HOP 3
#define BGPTYPE_MULTI_EXIT_DISC 4
#define BGPTYPE_LOCAL_PREF 5
#define BGPTYPE_ATOMIC_AGGREGATE 6
#define BGPTYPE_AGGREGATOR 7
#define BGPTYPE_COMMUNITIES 8 /* RFC1997 */
#define BGPTYPE_ORIGINATOR_ID 9 /* RFC4456 */
#define BGPTYPE_CLUSTER_LIST 10 /* RFC4456 */
#define BGPTYPE_DPA 11 /* deprecated, draft-ietf-idr-bgp-dpa */
#define BGPTYPE_ADVERTISERS 12 /* deprecated RFC1863 */
#define BGPTYPE_RCID_PATH 13 /* deprecated RFC1863 */
#define BGPTYPE_MP_REACH_NLRI 14 /* RFC4760 */
#define BGPTYPE_MP_UNREACH_NLRI 15 /* RFC4760 */
#define BGPTYPE_EXTD_COMMUNITIES 16 /* RFC4360 */
#define BGPTYPE_AS4_PATH 17 /* RFC6793 */
#define BGPTYPE_AGGREGATOR4 18 /* RFC6793 */
#define BGPTYPE_PMSI_TUNNEL 22 /* RFC6514 */
#define BGPTYPE_TUNNEL_ENCAP 23 /* RFC5512 */
#define BGPTYPE_TRAFFIC_ENG 24 /* RFC5543 */
#define BGPTYPE_IPV6_EXTD_COMMUNITIES 25 /* RFC5701 */
#define BGPTYPE_AIGP 26 /* RFC7311 */
#define BGPTYPE_PE_DISTINGUISHER_LABEL 27 /* RFC6514 */
#define BGPTYPE_ENTROPY_LABEL 28 /* RFC6790 */
#define BGPTYPE_LARGE_COMMUNITY 32 /* draft-ietf-idr-large-community-05 */
#define BGPTYPE_ATTR_SET 128 /* RFC6368 */
#define BGP_MP_NLRI_MINSIZE 3 /* End of RIB Marker detection */
static const struct tok bgp_attr_values[] = {
{ BGPTYPE_ORIGIN, "Origin"},
{ BGPTYPE_AS_PATH, "AS Path"},
{ BGPTYPE_AS4_PATH, "AS4 Path"},
{ BGPTYPE_NEXT_HOP, "Next Hop"},
{ BGPTYPE_MULTI_EXIT_DISC, "Multi Exit Discriminator"},
{ BGPTYPE_LOCAL_PREF, "Local Preference"},
{ BGPTYPE_ATOMIC_AGGREGATE, "Atomic Aggregate"},
{ BGPTYPE_AGGREGATOR, "Aggregator"},
{ BGPTYPE_AGGREGATOR4, "Aggregator4"},
{ BGPTYPE_COMMUNITIES, "Community"},
{ BGPTYPE_ORIGINATOR_ID, "Originator ID"},
{ BGPTYPE_CLUSTER_LIST, "Cluster List"},
{ BGPTYPE_DPA, "DPA"},
{ BGPTYPE_ADVERTISERS, "Advertisers"},
{ BGPTYPE_RCID_PATH, "RCID Path / Cluster ID"},
{ BGPTYPE_MP_REACH_NLRI, "Multi-Protocol Reach NLRI"},
{ BGPTYPE_MP_UNREACH_NLRI, "Multi-Protocol Unreach NLRI"},
{ BGPTYPE_EXTD_COMMUNITIES, "Extended Community"},
{ BGPTYPE_PMSI_TUNNEL, "PMSI Tunnel"},
{ BGPTYPE_TUNNEL_ENCAP, "Tunnel Encapsulation"},
{ BGPTYPE_TRAFFIC_ENG, "Traffic Engineering"},
{ BGPTYPE_IPV6_EXTD_COMMUNITIES, "IPv6 Extended Community"},
{ BGPTYPE_AIGP, "Accumulated IGP Metric"},
{ BGPTYPE_PE_DISTINGUISHER_LABEL, "PE Distinguisher Label"},
{ BGPTYPE_ENTROPY_LABEL, "Entropy Label"},
{ BGPTYPE_LARGE_COMMUNITY, "Large Community"},
{ BGPTYPE_ATTR_SET, "Attribute Set"},
{ 255, "Reserved for development"},
{ 0, NULL}
};
#define BGP_AS_SET 1
#define BGP_AS_SEQUENCE 2
#define BGP_CONFED_AS_SEQUENCE 3 /* draft-ietf-idr-rfc3065bis-01 */
#define BGP_CONFED_AS_SET 4 /* draft-ietf-idr-rfc3065bis-01 */
#define BGP_AS_SEG_TYPE_MIN BGP_AS_SET
#define BGP_AS_SEG_TYPE_MAX BGP_CONFED_AS_SET
static const struct tok bgp_as_path_segment_open_values[] = {
{ BGP_AS_SEQUENCE, ""},
{ BGP_AS_SET, "{ "},
{ BGP_CONFED_AS_SEQUENCE, "( "},
{ BGP_CONFED_AS_SET, "({ "},
{ 0, NULL}
};
static const struct tok bgp_as_path_segment_close_values[] = {
{ BGP_AS_SEQUENCE, ""},
{ BGP_AS_SET, "}"},
{ BGP_CONFED_AS_SEQUENCE, ")"},
{ BGP_CONFED_AS_SET, "})"},
{ 0, NULL}
};
#define BGP_OPT_AUTH 1
#define BGP_OPT_CAP 2
static const struct tok bgp_opt_values[] = {
{ BGP_OPT_AUTH, "Authentication Information"},
{ BGP_OPT_CAP, "Capabilities Advertisement"},
{ 0, NULL}
};
#define BGP_CAPCODE_MP 1 /* RFC2858 */
#define BGP_CAPCODE_RR 2 /* RFC2918 */
#define BGP_CAPCODE_ORF 3 /* RFC5291 */
#define BGP_CAPCODE_MR 4 /* RFC3107 */
#define BGP_CAPCODE_EXT_NH 5 /* RFC5549 */
#define BGP_CAPCODE_RESTART 64 /* RFC4724 */
#define BGP_CAPCODE_AS_NEW 65 /* RFC6793 */
#define BGP_CAPCODE_DYN_CAP 67 /* draft-ietf-idr-dynamic-cap */
#define BGP_CAPCODE_MULTISESS 68 /* draft-ietf-idr-bgp-multisession */
#define BGP_CAPCODE_ADD_PATH 69 /* RFC7911 */
#define BGP_CAPCODE_ENH_RR 70 /* draft-keyur-bgp-enhanced-route-refresh */
#define BGP_CAPCODE_RR_CISCO 128
static const struct tok bgp_capcode_values[] = {
{ BGP_CAPCODE_MP, "Multiprotocol Extensions"},
{ BGP_CAPCODE_RR, "Route Refresh"},
{ BGP_CAPCODE_ORF, "Cooperative Route Filtering"},
{ BGP_CAPCODE_MR, "Multiple Routes to a Destination"},
{ BGP_CAPCODE_EXT_NH, "Extended Next Hop Encoding"},
{ BGP_CAPCODE_RESTART, "Graceful Restart"},
{ BGP_CAPCODE_AS_NEW, "32-Bit AS Number"},
{ BGP_CAPCODE_DYN_CAP, "Dynamic Capability"},
{ BGP_CAPCODE_MULTISESS, "Multisession BGP"},
{ BGP_CAPCODE_ADD_PATH, "Multiple Paths"},
{ BGP_CAPCODE_ENH_RR, "Enhanced Route Refresh"},
{ BGP_CAPCODE_RR_CISCO, "Route Refresh (Cisco)"},
{ 0, NULL}
};
#define BGP_NOTIFY_MAJOR_MSG 1
#define BGP_NOTIFY_MAJOR_OPEN 2
#define BGP_NOTIFY_MAJOR_UPDATE 3
#define BGP_NOTIFY_MAJOR_HOLDTIME 4
#define BGP_NOTIFY_MAJOR_FSM 5
#define BGP_NOTIFY_MAJOR_CEASE 6
#define BGP_NOTIFY_MAJOR_CAP 7
static const struct tok bgp_notify_major_values[] = {
{ BGP_NOTIFY_MAJOR_MSG, "Message Header Error"},
{ BGP_NOTIFY_MAJOR_OPEN, "OPEN Message Error"},
{ BGP_NOTIFY_MAJOR_UPDATE, "UPDATE Message Error"},
{ BGP_NOTIFY_MAJOR_HOLDTIME,"Hold Timer Expired"},
{ BGP_NOTIFY_MAJOR_FSM, "Finite State Machine Error"},
{ BGP_NOTIFY_MAJOR_CEASE, "Cease"},
{ BGP_NOTIFY_MAJOR_CAP, "Capability Message Error"},
{ 0, NULL}
};
/* draft-ietf-idr-cease-subcode-02 */
#define BGP_NOTIFY_MINOR_CEASE_MAXPRFX 1
static const struct tok bgp_notify_minor_cease_values[] = {
{ BGP_NOTIFY_MINOR_CEASE_MAXPRFX, "Maximum Number of Prefixes Reached"},
{ 2, "Administratively Shutdown"},
{ 3, "Peer Unconfigured"},
{ 4, "Administratively Reset"},
{ 5, "Connection Rejected"},
{ 6, "Other Configuration Change"},
{ 7, "Connection Collision Resolution"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_msg_values[] = {
{ 1, "Connection Not Synchronized"},
{ 2, "Bad Message Length"},
{ 3, "Bad Message Type"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_open_values[] = {
{ 1, "Unsupported Version Number"},
{ 2, "Bad Peer AS"},
{ 3, "Bad BGP Identifier"},
{ 4, "Unsupported Optional Parameter"},
{ 5, "Authentication Failure"},
{ 6, "Unacceptable Hold Time"},
{ 7, "Capability Message Error"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_update_values[] = {
{ 1, "Malformed Attribute List"},
{ 2, "Unrecognized Well-known Attribute"},
{ 3, "Missing Well-known Attribute"},
{ 4, "Attribute Flags Error"},
{ 5, "Attribute Length Error"},
{ 6, "Invalid ORIGIN Attribute"},
{ 7, "AS Routing Loop"},
{ 8, "Invalid NEXT_HOP Attribute"},
{ 9, "Optional Attribute Error"},
{ 10, "Invalid Network Field"},
{ 11, "Malformed AS_PATH"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_fsm_values[] = {
{ 1, "In OpenSent State"},
{ 2, "In OpenConfirm State"},
{ 3, "In Established State"},
{ 0, NULL }
};
static const struct tok bgp_notify_minor_cap_values[] = {
{ 1, "Invalid Action Value" },
{ 2, "Invalid Capability Length" },
{ 3, "Malformed Capability Value" },
{ 4, "Unsupported Capability Code" },
{ 0, NULL }
};
static const struct tok bgp_origin_values[] = {
{ 0, "IGP"},
{ 1, "EGP"},
{ 2, "Incomplete"},
{ 0, NULL}
};
#define BGP_PMSI_TUNNEL_RSVP_P2MP 1
#define BGP_PMSI_TUNNEL_LDP_P2MP 2
#define BGP_PMSI_TUNNEL_PIM_SSM 3
#define BGP_PMSI_TUNNEL_PIM_SM 4
#define BGP_PMSI_TUNNEL_PIM_BIDIR 5
#define BGP_PMSI_TUNNEL_INGRESS 6
#define BGP_PMSI_TUNNEL_LDP_MP2MP 7
static const struct tok bgp_pmsi_tunnel_values[] = {
{ BGP_PMSI_TUNNEL_RSVP_P2MP, "RSVP-TE P2MP LSP"},
{ BGP_PMSI_TUNNEL_LDP_P2MP, "LDP P2MP LSP"},
{ BGP_PMSI_TUNNEL_PIM_SSM, "PIM-SSM Tree"},
{ BGP_PMSI_TUNNEL_PIM_SM, "PIM-SM Tree"},
{ BGP_PMSI_TUNNEL_PIM_BIDIR, "PIM-Bidir Tree"},
{ BGP_PMSI_TUNNEL_INGRESS, "Ingress Replication"},
{ BGP_PMSI_TUNNEL_LDP_MP2MP, "LDP MP2MP LSP"},
{ 0, NULL}
};
static const struct tok bgp_pmsi_flag_values[] = {
{ 0x01, "Leaf Information required"},
{ 0, NULL}
};
#define BGP_AIGP_TLV 1
static const struct tok bgp_aigp_values[] = {
{ BGP_AIGP_TLV, "AIGP"},
{ 0, NULL}
};
/* Subsequent address family identifier, RFC2283 section 7 */
#define SAFNUM_RES 0
#define SAFNUM_UNICAST 1
#define SAFNUM_MULTICAST 2
#define SAFNUM_UNIMULTICAST 3 /* deprecated now */
/* labeled BGP RFC3107 */
#define SAFNUM_LABUNICAST 4
/* RFC6514 */
#define SAFNUM_MULTICAST_VPN 5
/* draft-nalawade-kapoor-tunnel-safi */
#define SAFNUM_TUNNEL 64
/* RFC4761 */
#define SAFNUM_VPLS 65
/* RFC6037 */
#define SAFNUM_MDT 66
/* RFC4364 */
#define SAFNUM_VPNUNICAST 128
/* RFC6513 */
#define SAFNUM_VPNMULTICAST 129
#define SAFNUM_VPNUNIMULTICAST 130 /* deprecated now */
/* RFC4684 */
#define SAFNUM_RT_ROUTING_INFO 132
#define BGP_VPN_RD_LEN 8
static const struct tok bgp_safi_values[] = {
{ SAFNUM_RES, "Reserved"},
{ SAFNUM_UNICAST, "Unicast"},
{ SAFNUM_MULTICAST, "Multicast"},
{ SAFNUM_UNIMULTICAST, "Unicast+Multicast"},
{ SAFNUM_LABUNICAST, "labeled Unicast"},
{ SAFNUM_TUNNEL, "Tunnel"},
{ SAFNUM_VPLS, "VPLS"},
{ SAFNUM_MDT, "MDT"},
{ SAFNUM_VPNUNICAST, "labeled VPN Unicast"},
{ SAFNUM_VPNMULTICAST, "labeled VPN Multicast"},
{ SAFNUM_VPNUNIMULTICAST, "labeled VPN Unicast+Multicast"},
{ SAFNUM_RT_ROUTING_INFO, "Route Target Routing Information"},
{ SAFNUM_MULTICAST_VPN, "Multicast VPN"},
{ 0, NULL }
};
/* well-known community */
#define BGP_COMMUNITY_NO_EXPORT 0xffffff01
#define BGP_COMMUNITY_NO_ADVERT 0xffffff02
#define BGP_COMMUNITY_NO_EXPORT_SUBCONFED 0xffffff03
/* Extended community type - draft-ietf-idr-bgp-ext-communities-05 */
#define BGP_EXT_COM_RT_0 0x0002 /* Route Target,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_RT_1 0x0102 /* Route Target,Format IP address:AN(2bytes) */
#define BGP_EXT_COM_RT_2 0x0202 /* Route Target,Format AN(4bytes):local(2bytes) */
#define BGP_EXT_COM_RO_0 0x0003 /* Route Origin,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_RO_1 0x0103 /* Route Origin,Format IP address:AN(2bytes) */
#define BGP_EXT_COM_RO_2 0x0203 /* Route Origin,Format AN(4bytes):local(2bytes) */
#define BGP_EXT_COM_LINKBAND 0x4004 /* Link Bandwidth,Format AS(2B):Bandwidth(4B) */
/* rfc2547 bgp-mpls-vpns */
#define BGP_EXT_COM_VPN_ORIGIN 0x0005 /* OSPF Domain ID / VPN of Origin - draft-rosen-vpns-ospf-bgp-mpls */
#define BGP_EXT_COM_VPN_ORIGIN2 0x0105 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_VPN_ORIGIN3 0x0205 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_VPN_ORIGIN4 0x8005 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_OSPF_RTYPE 0x0306 /* OSPF Route Type,Format Area(4B):RouteType(1B):Options(1B) */
#define BGP_EXT_COM_OSPF_RTYPE2 0x8000 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_OSPF_RID 0x0107 /* OSPF Router ID,Format RouterID(4B):Unused(2B) */
#define BGP_EXT_COM_OSPF_RID2 0x8001 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_L2INFO 0x800a /* draft-kompella-ppvpn-l2vpn */
#define BGP_EXT_COM_SOURCE_AS 0x0009 /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */
#define BGP_EXT_COM_VRF_RT_IMP 0x010b /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */
#define BGP_EXT_COM_L2VPN_RT_0 0x000a /* L2VPN Identifier,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_L2VPN_RT_1 0xF10a /* L2VPN Identifier,Format IP address:AN(2bytes) */
/* http://www.cisco.com/en/US/tech/tk436/tk428/technologies_tech_note09186a00801eb09a.shtml */
#define BGP_EXT_COM_EIGRP_GEN 0x8800
#define BGP_EXT_COM_EIGRP_METRIC_AS_DELAY 0x8801
#define BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW 0x8802
#define BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU 0x8803
#define BGP_EXT_COM_EIGRP_EXT_REMAS_REMID 0x8804
#define BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC 0x8805
static const struct tok bgp_extd_comm_flag_values[] = {
{ 0x8000, "vendor-specific"},
{ 0x4000, "non-transitive"},
{ 0, NULL},
};
static const struct tok bgp_extd_comm_subtype_values[] = {
{ BGP_EXT_COM_RT_0, "target"},
{ BGP_EXT_COM_RT_1, "target"},
{ BGP_EXT_COM_RT_2, "target"},
{ BGP_EXT_COM_RO_0, "origin"},
{ BGP_EXT_COM_RO_1, "origin"},
{ BGP_EXT_COM_RO_2, "origin"},
{ BGP_EXT_COM_LINKBAND, "link-BW"},
{ BGP_EXT_COM_VPN_ORIGIN, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN2, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN3, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN4, "ospf-domain"},
{ BGP_EXT_COM_OSPF_RTYPE, "ospf-route-type"},
{ BGP_EXT_COM_OSPF_RTYPE2, "ospf-route-type"},
{ BGP_EXT_COM_OSPF_RID, "ospf-router-id"},
{ BGP_EXT_COM_OSPF_RID2, "ospf-router-id"},
{ BGP_EXT_COM_L2INFO, "layer2-info"},
{ BGP_EXT_COM_EIGRP_GEN , "eigrp-general-route (flag, tag)" },
{ BGP_EXT_COM_EIGRP_METRIC_AS_DELAY , "eigrp-route-metric (AS, delay)" },
{ BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW , "eigrp-route-metric (reliability, nexthop, bandwidth)" },
{ BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU , "eigrp-route-metric (load, MTU)" },
{ BGP_EXT_COM_EIGRP_EXT_REMAS_REMID , "eigrp-external-route (remote-AS, remote-ID)" },
{ BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC , "eigrp-external-route (remote-proto, remote-metric)" },
{ BGP_EXT_COM_SOURCE_AS, "source-AS" },
{ BGP_EXT_COM_VRF_RT_IMP, "vrf-route-import"},
{ BGP_EXT_COM_L2VPN_RT_0, "l2vpn-id"},
{ BGP_EXT_COM_L2VPN_RT_1, "l2vpn-id"},
{ 0, NULL},
};
/* OSPF codes for BGP_EXT_COM_OSPF_RTYPE draft-rosen-vpns-ospf-bgp-mpls */
#define BGP_OSPF_RTYPE_RTR 1 /* OSPF Router LSA */
#define BGP_OSPF_RTYPE_NET 2 /* OSPF Network LSA */
#define BGP_OSPF_RTYPE_SUM 3 /* OSPF Summary LSA */
#define BGP_OSPF_RTYPE_EXT 5 /* OSPF External LSA, note that ASBR doesn't apply to MPLS-VPN */
#define BGP_OSPF_RTYPE_NSSA 7 /* OSPF NSSA External*/
#define BGP_OSPF_RTYPE_SHAM 129 /* OSPF-MPLS-VPN Sham link */
#define BGP_OSPF_RTYPE_METRIC_TYPE 0x1 /* LSB of RTYPE Options Field */
static const struct tok bgp_extd_comm_ospf_rtype_values[] = {
{ BGP_OSPF_RTYPE_RTR, "Router" },
{ BGP_OSPF_RTYPE_NET, "Network" },
{ BGP_OSPF_RTYPE_SUM, "Summary" },
{ BGP_OSPF_RTYPE_EXT, "External" },
{ BGP_OSPF_RTYPE_NSSA,"NSSA External" },
{ BGP_OSPF_RTYPE_SHAM,"MPLS-VPN Sham" },
{ 0, NULL },
};
/* ADD-PATH Send/Receive field values */
static const struct tok bgp_add_path_recvsend[] = {
{ 1, "Receive" },
{ 2, "Send" },
{ 3, "Both" },
{ 0, NULL },
};
static char astostr[20];
/*
* as_printf
*
* Convert an AS number into a string and return string pointer.
*
* Depending on bflag is set or not, AS number is converted into ASDOT notation
* or plain number notation.
*
*/
static char *
as_printf(netdissect_options *ndo,
char *str, int size, u_int asnum)
{
if (!ndo->ndo_bflag || asnum <= 0xFFFF) {
snprintf(str, size, "%u", asnum);
} else {
snprintf(str, size, "%u.%u", asnum >> 16, asnum & 0xFFFF);
}
return str;
}
#define ITEMCHECK(minlen) if (itemlen < minlen) goto badtlv;
int
decode_prefix4(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen, plenbytes;
ND_TCHECK(pptr[0]);
ITEMCHECK(1);
plen = pptr[0];
if (32 < plen)
return -1;
itemlen -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[1], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pptr[1], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d", ipaddr_string(ndo, &addr), plen);
return 1 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_prefix4(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen, plenbytes;
/* prefix length and label = 4 bytes */
ND_TCHECK2(pptr[0], 4);
ITEMCHECK(4);
plen = pptr[0]; /* get prefix length */
/* this is one of the weirdnesses of rfc3107
the label length (actually the label + COS bits)
is added to the prefix length;
we also do only read out just one label -
there is no real application for advertisement of
stacked labels in a single BGP message
*/
if (24 > plen)
return -1;
plen-=24; /* adjust prefixlen - labellength */
if (32 < plen)
return -1;
itemlen -= 4;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[4], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pptr[4], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "%s/%d, label:%u %s",
ipaddr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 4 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
/*
* bgp_vpn_ip_print
*
* print an ipv4 or ipv6 address into a buffer dependend on address length.
*/
static char *
bgp_vpn_ip_print(netdissect_options *ndo,
const u_char *pptr, u_int addr_length)
{
/* worst case string is s fully formatted v6 address */
static char addr[sizeof("1234:5678:89ab:cdef:1234:5678:89ab:cdef")];
char *pos = addr;
switch(addr_length) {
case (sizeof(struct in_addr) << 3): /* 32 */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
snprintf(pos, sizeof(addr), "%s", ipaddr_string(ndo, pptr));
break;
case (sizeof(struct in6_addr) << 3): /* 128 */
ND_TCHECK2(pptr[0], sizeof(struct in6_addr));
snprintf(pos, sizeof(addr), "%s", ip6addr_string(ndo, pptr));
break;
default:
snprintf(pos, sizeof(addr), "bogus address length %u", addr_length);
break;
}
pos += strlen(pos);
trunc:
*(pos) = '\0';
return (addr);
}
/*
* bgp_vpn_sg_print
*
* print an multicast s,g entry into a buffer.
* the s,g entry is encoded like this.
*
* +-----------------------------------+
* | Multicast Source Length (1 octet) |
* +-----------------------------------+
* | Multicast Source (Variable) |
* +-----------------------------------+
* | Multicast Group Length (1 octet) |
* +-----------------------------------+
* | Multicast Group (Variable) |
* +-----------------------------------+
*
* return the number of bytes read from the wire.
*/
static int
bgp_vpn_sg_print(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr_length;
u_int total_length, offset;
total_length = 0;
/* Source address length, encoded in bits */
ND_TCHECK2(pptr[0], 1);
addr_length = *pptr++;
/* Source address */
ND_TCHECK2(pptr[0], (addr_length >> 3));
total_length += (addr_length >> 3) + 1;
offset = strlen(buf);
if (addr_length) {
snprintf(buf + offset, buflen - offset, ", Source %s",
bgp_vpn_ip_print(ndo, pptr, addr_length));
pptr += (addr_length >> 3);
}
/* Group address length, encoded in bits */
ND_TCHECK2(pptr[0], 1);
addr_length = *pptr++;
/* Group address */
ND_TCHECK2(pptr[0], (addr_length >> 3));
total_length += (addr_length >> 3) + 1;
offset = strlen(buf);
if (addr_length) {
snprintf(buf + offset, buflen - offset, ", Group %s",
bgp_vpn_ip_print(ndo, pptr, addr_length));
pptr += (addr_length >> 3);
}
trunc:
return (total_length);
}
/* RDs and RTs share the same semantics
* we use bgp_vpn_rd_print for
* printing route targets inside a NLRI */
char *
bgp_vpn_rd_print(netdissect_options *ndo,
const u_char *pptr)
{
/* allocate space for the largest possible string */
static char rd[sizeof("xxxxxxxxxx:xxxxx (xxx.xxx.xxx.xxx:xxxxx)")];
char *pos = rd;
/* ok lets load the RD format */
switch (EXTRACT_16BITS(pptr)) {
/* 2-byte-AS:number fmt*/
case 0:
snprintf(pos, sizeof(rd) - (pos - rd), "%u:%u (= %u.%u.%u.%u)",
EXTRACT_16BITS(pptr+2),
EXTRACT_32BITS(pptr+4),
*(pptr+4), *(pptr+5), *(pptr+6), *(pptr+7));
break;
/* IP-address:AS fmt*/
case 1:
snprintf(pos, sizeof(rd) - (pos - rd), "%u.%u.%u.%u:%u",
*(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6));
break;
/* 4-byte-AS:number fmt*/
case 2:
snprintf(pos, sizeof(rd) - (pos - rd), "%s:%u (%u.%u.%u.%u:%u)",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+2)),
EXTRACT_16BITS(pptr+6), *(pptr+2), *(pptr+3), *(pptr+4),
*(pptr+5), EXTRACT_16BITS(pptr+6));
break;
default:
snprintf(pos, sizeof(rd) - (pos - rd), "unknown RD format");
break;
}
pos += strlen(pos);
*(pos) = '\0';
return (rd);
}
static int
decode_rt_routing_info(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_target[8];
u_int plen;
char asbuf[sizeof(astostr)]; /* bgp_vpn_rd_print() overwrites astostr */
/* NLRI "prefix length" from RFC 2858 Section 4. */
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
/* NLRI "prefix" (ibid), valid lengths are { 0, 32, 33, ..., 96 } bits.
* RFC 4684 Section 4 defines the layout of "origin AS" and "route
* target" fields inside the "prefix" depending on its length.
*/
if (0 == plen) {
/* Without "origin AS", without "route target". */
snprintf(buf, buflen, "default route target");
return 1;
}
if (32 > plen)
return -1;
/* With at least "origin AS", possibly with "route target". */
ND_TCHECK_32BITS(pptr + 1);
as_printf(ndo, asbuf, sizeof(asbuf), EXTRACT_32BITS(pptr + 1));
plen-=32; /* adjust prefix length */
if (64 < plen)
return -1;
/* From now on (plen + 7) / 8 evaluates to { 0, 1, 2, ..., 8 }
* and gives the number of octets in the variable-length "route
* target" field inside this NLRI "prefix". Look for it.
*/
memset(&route_target, 0, sizeof(route_target));
ND_TCHECK2(pptr[5], (plen + 7) / 8);
memcpy(&route_target, &pptr[5], (plen + 7) / 8);
/* Which specification says to do this? */
if (plen % 8) {
((u_char *)&route_target)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "origin AS: %s, route target %s",
asbuf,
bgp_vpn_rd_print(ndo, (u_char *)&route_target));
return 5 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_labeled_vpn_prefix4(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (32 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
((u_char *)&addr)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
ipaddr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
/*
* +-------------------------------+
* | |
* | RD:IPv4-address (12 octets) |
* | |
* +-------------------------------+
* | MDT Group-address (4 octets) |
* +-------------------------------+
*/
#define MDT_VPN_NLRI_LEN 16
static int
decode_mdt_vpn_nlri(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
const u_char *rd;
const u_char *vpn_ip;
ND_TCHECK(pptr[0]);
/* if the NLRI is not predefined length, quit.*/
if (*pptr != MDT_VPN_NLRI_LEN * 8)
return -1;
pptr++;
/* RD */
ND_TCHECK2(pptr[0], 8);
rd = pptr;
pptr+=8;
/* IPv4 address */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
vpn_ip = pptr;
pptr+=sizeof(struct in_addr);
/* MDT Group Address */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
snprintf(buf, buflen, "RD: %s, VPN IP Address: %s, MC Group Address: %s",
bgp_vpn_rd_print(ndo, rd), ipaddr_string(ndo, vpn_ip), ipaddr_string(ndo, pptr));
return MDT_VPN_NLRI_LEN + 1;
trunc:
return -2;
}
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI 1
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI 2
#define BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI 3
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF 4
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE 5
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN 6
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN 7
static const struct tok bgp_multicast_vpn_route_type_values[] = {
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI, "Intra-AS I-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI, "Inter-AS I-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI, "S-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF, "Intra-AS Segment-Leaf"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE, "Source-Active"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN, "Shared Tree Join"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN, "Source Tree Join"},
{ 0, NULL}
};
static int
decode_multicast_vpn(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_type, route_length, addr_length, sg_length;
u_int offset;
ND_TCHECK2(pptr[0], 2);
route_type = *pptr++;
route_length = *pptr++;
snprintf(buf, buflen, "Route-Type: %s (%u), length: %u",
tok2str(bgp_multicast_vpn_route_type_values,
"Unknown", route_type),
route_type, route_length);
switch(route_type) {
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s",
bgp_vpn_rd_print(ndo, pptr),
bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN,
(route_length - BGP_VPN_RD_LEN) << 3));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s",
bgp_vpn_rd_print(ndo, pptr),
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s",
bgp_vpn_rd_print(ndo, pptr));
pptr += BGP_VPN_RD_LEN;
sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen);
addr_length = route_length - sg_length;
ND_TCHECK2(pptr[0], addr_length);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", Originator %s",
bgp_vpn_ip_print(ndo, pptr, addr_length << 3));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s",
bgp_vpn_rd_print(ndo, pptr));
pptr += BGP_VPN_RD_LEN;
bgp_vpn_sg_print(ndo, pptr, buf, buflen);
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */
case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s",
bgp_vpn_rd_print(ndo, pptr),
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));
pptr += BGP_VPN_RD_LEN + 4;
bgp_vpn_sg_print(ndo, pptr, buf, buflen);
break;
/*
* no per route-type printing yet.
*/
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF:
default:
break;
}
return route_length + 2;
trunc:
return -2;
}
/*
* As I remember, some versions of systems have an snprintf() that
* returns -1 if the buffer would have overflowed. If the return
* value is negative, set buflen to 0, to indicate that we've filled
* the buffer up.
*
* If the return value is greater than buflen, that means that
* the buffer would have overflowed; again, set buflen to 0 in
* that case.
*/
#define UPDATE_BUF_BUFLEN(buf, buflen, stringlen) \
if (stringlen<0) \
buflen=0; \
else if ((u_int)stringlen>buflen) \
buflen=0; \
else { \
buflen-=stringlen; \
buf+=stringlen; \
}
static int
decode_labeled_vpn_l2(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
int plen,tlen,stringlen,tlv_type,tlv_len,ttlv_len;
ND_TCHECK2(pptr[0], 2);
plen=EXTRACT_16BITS(pptr);
tlen=plen;
pptr+=2;
/* Old and new L2VPN NLRI share AFI/SAFI
* -> Assume a 12 Byte-length NLRI is auto-discovery-only
* and > 17 as old format. Complain for the middle case
*/
if (plen==12) {
/* assume AD-only with RD, BGPNH */
ND_TCHECK2(pptr[0],12);
buf[0]='\0';
stringlen=snprintf(buf, buflen, "RD: %s, BGPNH: %s",
bgp_vpn_rd_print(ndo, pptr),
ipaddr_string(ndo, pptr+8)
);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
pptr+=12;
tlen-=12;
return plen;
} else if (plen>17) {
/* assume old format */
/* RD, ID, LBLKOFF, LBLBASE */
ND_TCHECK2(pptr[0],15);
buf[0]='\0';
stringlen=snprintf(buf, buflen, "RD: %s, CE-ID: %u, Label-Block Offset: %u, Label Base %u",
bgp_vpn_rd_print(ndo, pptr),
EXTRACT_16BITS(pptr+8),
EXTRACT_16BITS(pptr+10),
EXTRACT_24BITS(pptr+12)>>4); /* the label is offsetted by 4 bits so lets shift it right */
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
pptr+=15;
tlen-=15;
/* ok now the variable part - lets read out TLVs*/
while (tlen>0) {
if (tlen < 3)
return -1;
ND_TCHECK2(pptr[0], 3);
tlv_type=*pptr++;
tlv_len=EXTRACT_16BITS(pptr);
ttlv_len=tlv_len;
pptr+=2;
switch(tlv_type) {
case 1:
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "\n\t\tcircuit status vector (%u) length: %u: 0x",
tlv_type,
tlv_len);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
ttlv_len=ttlv_len/8+1; /* how many bytes do we need to read ? */
while (ttlv_len>0) {
ND_TCHECK(pptr[0]);
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "%02x",*pptr++);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
ttlv_len--;
}
break;
default:
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "\n\t\tunknown TLV #%u, length: %u",
tlv_type,
tlv_len);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
break;
}
tlen-=(tlv_len<<3); /* the tlv-length is expressed in bits so lets shift it right */
}
return plen+2;
} else {
/* complain bitterly ? */
/* fall through */
goto trunc;
}
trunc:
return -2;
}
int
decode_prefix6(netdissect_options *ndo,
const u_char *pd, u_int itemlen, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen, plenbytes;
ND_TCHECK(pd[0]);
ITEMCHECK(1);
plen = pd[0];
if (128 < plen)
return -1;
itemlen -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pd[1], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pd[1], plenbytes);
if (plen % 8) {
addr.s6_addr[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d", ip6addr_string(ndo, &addr), plen);
return 1 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_prefix6(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen, plenbytes;
/* prefix length and label = 4 bytes */
ND_TCHECK2(pptr[0], 4);
ITEMCHECK(4);
plen = pptr[0]; /* get prefix length */
if (24 > plen)
return -1;
plen-=24; /* adjust prefixlen - labellength */
if (128 < plen)
return -1;
itemlen -= 4;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[4], plenbytes);
memcpy(&addr, &pptr[4], plenbytes);
if (plen % 8) {
addr.s6_addr[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "%s/%d, label:%u %s",
ip6addr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 4 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_vpn_prefix6(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (128 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
addr.s6_addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
ip6addr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_clnp_prefix(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr[19];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if (152 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[4], (plen + 7) / 8);
memcpy(&addr, &pptr[4], (plen + 7) / 8);
if (plen % 8) {
addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d",
isonsap_string(ndo, addr,(plen + 7) / 8),
plen);
return 1 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_labeled_vpn_clnp_prefix(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr[19];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (152 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
isonsap_string(ndo, addr,(plen + 7) / 8),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
/*
* bgp_attr_get_as_size
*
* Try to find the size of the ASs encoded in an as-path. It is not obvious, as
* both Old speakers that do not support 4 byte AS, and the new speakers that do
* support, exchange AS-Path with the same path-attribute type value 0x02.
*/
static int
bgp_attr_get_as_size(netdissect_options *ndo,
uint8_t bgpa_type, const u_char *pptr, int len)
{
const u_char *tptr = pptr;
/*
* If the path attribute is the optional AS4 path type, then we already
* know, that ASs must be encoded in 4 byte format.
*/
if (bgpa_type == BGPTYPE_AS4_PATH) {
return 4;
}
/*
* Let us assume that ASs are of 2 bytes in size, and check if the AS-Path
* TLV is good. If not, ask the caller to try with AS encoded as 4 bytes
* each.
*/
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
/*
* If we do not find a valid segment type, our guess might be wrong.
*/
if (tptr[0] < BGP_AS_SEG_TYPE_MIN || tptr[0] > BGP_AS_SEG_TYPE_MAX) {
goto trunc;
}
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * 2;
}
/*
* If we correctly reached end of the AS path attribute data content,
* then most likely ASs were indeed encoded as 2 bytes.
*/
if (tptr == pptr + len) {
return 2;
}
trunc:
/*
* We can come here, either we did not have enough data, or if we
* try to decode 4 byte ASs in 2 byte format. Either way, return 4,
* so that calller can try to decode each AS as of 4 bytes. If indeed
* there was not enough data, it will crib and end the parse anyways.
*/
return 4;
}
static int
bgp_attr_print(netdissect_options *ndo,
u_int atype, const u_char *pptr, u_int len, const unsigned attr_set_level)
{
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 (tlen == BGP_VPN_RD_LEN + 4 + sizeof(struct in_addr)
&& 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 (tlen == BGP_VPN_RD_LEN + 3 + sizeof(struct in6_addr)
&& EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000)
ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3)));
tptr += tlen;
tlen = 0;
}
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
tptr += tlen;
tlen = 0;
goto done;
break;
}
}
}
ND_PRINT((ndo, ", nh-length: %u", nhlen));
tptr += tlen;
ND_TCHECK(tptr[0]);
snpa = tptr[0];
tptr++;
if (snpa) {
ND_PRINT((ndo, "\n\t %u SNPA", snpa));
for (/*nothing*/; snpa > 0; snpa--) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "\n\t %d bytes", tptr[0]));
tptr += tptr[0] + 1;
}
} else {
ND_PRINT((ndo, ", no SNPA"));
}
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*tptr,tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
done:
break;
case BGPTYPE_MP_UNREACH_NLRI:
ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
if (len == BGP_MP_NLRI_MINSIZE)
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
tptr += 3;
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*(tptr-3),tlen);
ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr-3, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
break;
case BGPTYPE_EXTD_COMMUNITIES:
if (len % 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint16_t extd_comm;
ND_TCHECK2(tptr[0], 2);
extd_comm=EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]",
tok2str(bgp_extd_comm_subtype_values,
"unknown extd community typecode",
extd_comm),
extd_comm,
bittok2str(bgp_extd_comm_flag_values, "none", extd_comm)));
ND_TCHECK2(*(tptr+2), 6);
switch(extd_comm) {
case BGP_EXT_COM_RT_0:
case BGP_EXT_COM_RO_0:
case BGP_EXT_COM_L2VPN_RT_0:
ND_PRINT((ndo, ": %u:%u (= %s)",
EXTRACT_16BITS(tptr+2),
EXTRACT_32BITS(tptr+4),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_EXT_COM_RT_1:
case BGP_EXT_COM_RO_1:
case BGP_EXT_COM_L2VPN_RT_1:
case BGP_EXT_COM_VRF_RT_IMP:
ND_PRINT((ndo, ": %s:%u",
ipaddr_string(ndo, tptr+2),
EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_RT_2:
case BGP_EXT_COM_RO_2:
ND_PRINT((ndo, ": %s:%u",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_LINKBAND:
bw.i = EXTRACT_32BITS(tptr+2);
ND_PRINT((ndo, ": bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case BGP_EXT_COM_VPN_ORIGIN:
case BGP_EXT_COM_VPN_ORIGIN2:
case BGP_EXT_COM_VPN_ORIGIN3:
case BGP_EXT_COM_VPN_ORIGIN4:
case BGP_EXT_COM_OSPF_RID:
case BGP_EXT_COM_OSPF_RID2:
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2)));
break;
case BGP_EXT_COM_OSPF_RTYPE:
case BGP_EXT_COM_OSPF_RTYPE2:
ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s",
ipaddr_string(ndo, tptr+2),
tok2str(bgp_extd_comm_ospf_rtype_values,
"unknown (0x%02x)",
*(tptr+6)),
(*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "",
((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : ""));
break;
case BGP_EXT_COM_L2INFO:
ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u",
tok2str(l2vpn_encaps_values,
"unknown encaps",
*(tptr+2)),
*(tptr+3),
EXTRACT_16BITS(tptr+4)));
break;
case BGP_EXT_COM_SOURCE_AS:
ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2)));
break;
default:
ND_TCHECK2(*tptr,8);
print_unknown_data(ndo, tptr, "\n\t ", 8);
break;
}
tlen -=8;
tptr +=8;
}
break;
case BGPTYPE_PMSI_TUNNEL:
{
uint8_t tunnel_type, flags;
ND_TCHECK2(tptr[0], 5);
tunnel_type = *(tptr+1);
flags = *tptr;
tlen = len;
ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u",
tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type),
tunnel_type,
bittok2str(bgp_pmsi_flag_values, "none", flags),
EXTRACT_24BITS(tptr+2)>>4));
tptr +=5;
tlen -= 5;
switch (tunnel_type) {
case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */
case BGP_PMSI_TUNNEL_PIM_BIDIR:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Sender %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_PIM_SSM:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_INGRESS:
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s",
ipaddr_string(ndo, tptr)));
break;
case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */
case BGP_PMSI_TUNNEL_LDP_MP2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
case BGP_PMSI_TUNNEL_RSVP_P2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr, "\n\t ", tlen);
}
}
break;
}
case BGPTYPE_AIGP:
{
uint8_t type;
uint16_t length;
tlen = len;
while (tlen >= 3) {
ND_TCHECK2(tptr[0], 3);
type = *tptr;
length = EXTRACT_16BITS(tptr+1);
tptr += 3;
tlen -= 3;
ND_PRINT((ndo, "\n\t %s TLV (%u), length %u",
tok2str(bgp_aigp_values, "Unknown", type),
type, length));
if (length < 3)
goto trunc;
length -= 3;
/*
* Check if we can read the TLV data.
*/
ND_TCHECK2(tptr[3], length);
switch (type) {
case BGP_AIGP_TLV:
if (length < 8)
goto trunc;
ND_PRINT((ndo, ", metric %" PRIu64,
EXTRACT_64BITS(tptr)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr,"\n\t ", length);
}
}
tptr += length;
tlen -= length;
}
break;
}
case BGPTYPE_ATTR_SET:
ND_TCHECK2(tptr[0], 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, "\n\t Origin AS: %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr))));
tptr+=4;
len -=4;
while (len) {
u_int aflags, alenlen, alen;
ND_TCHECK2(tptr[0], 2);
if (len < 2)
goto trunc;
aflags = *tptr;
atype = *(tptr + 1);
tptr += 2;
len -= 2;
alenlen = bgp_attr_lenlen(aflags, tptr);
ND_TCHECK2(tptr[0], alenlen);
if (len < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, tptr);
tptr += alenlen;
len -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values,
"Unknown Attribute", atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
/* The protocol encoding per se allows ATTR_SET to be nested as many times
* as the message can accommodate. This printer used to be able to recurse
* into ATTR_SET contents until the stack exhaustion, but now there is a
* limit on that (if live protocol exchange goes that many levels deep,
* something is probably wrong anyway). Feel free to refine this value if
* you can find the spec with respective normative text.
*/
if (attr_set_level == 10)
ND_PRINT((ndo, "(too many nested levels, not recursing)"));
else if (!bgp_attr_print(ndo, atype, tptr, alen, attr_set_level + 1))
return 0;
tptr += alen;
len -= alen;
}
break;
case BGPTYPE_LARGE_COMMUNITY:
if (len == 0 || len % 12) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_PRINT((ndo, "\n\t "));
while (len > 0) {
ND_TCHECK2(*tptr, 12);
ND_PRINT((ndo, "%u:%u:%u%s",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
(len > 12) ? ", " : ""));
tptr += 12;
len -= 12;
}
break;
default:
ND_TCHECK2(*pptr,len);
ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr, "\n\t ", len);
break;
}
if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/
ND_TCHECK2(*pptr,len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return 1;
trunc:
return 0;
}
static void
bgp_capabilities_print(netdissect_options *ndo,
const u_char *opt, int caps_len)
{
int cap_type, cap_len, tcap_len, cap_offset;
int i = 0;
while (i < caps_len) {
ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE);
cap_type=opt[i];
cap_len=opt[i+1];
tcap_len=cap_len;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_capcode_values, "Unknown",
cap_type),
cap_type,
cap_len));
ND_TCHECK2(opt[i+2], cap_len);
switch (cap_type) {
case BGP_CAPCODE_MP:
/* AFI (16 bits), Reserved (8 bits), SAFI (8 bits) */
ND_TCHECK_8BITS(opt + i + 5);
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(opt+i+2)),
EXTRACT_16BITS(opt+i+2),
tok2str(bgp_safi_values, "Unknown",
opt[i+5]),
opt[i+5]));
break;
case BGP_CAPCODE_RESTART:
/* Restart Flags (4 bits), Restart Time in seconds (12 bits) */
ND_TCHECK_16BITS(opt + i + 2);
ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us",
((opt[i+2])&0x80) ? "R" : "none",
EXTRACT_16BITS(opt+i+2)&0xfff));
tcap_len-=2;
cap_offset=4;
while(tcap_len>=4) {
ND_TCHECK_8BITS(opt + i + cap_offset + 3);
ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s",
tok2str(af_values,"Unknown",
EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",
opt[i+cap_offset+2]),
opt[i+cap_offset+2],
((opt[i+cap_offset+3])&0x80) ? "yes" : "no" ));
tcap_len-=4;
cap_offset+=4;
}
break;
case BGP_CAPCODE_RR:
case BGP_CAPCODE_RR_CISCO:
break;
case BGP_CAPCODE_AS_NEW:
/*
* Extract the 4 byte AS number encoded.
*/
if (cap_len == 4) {
ND_PRINT((ndo, "\n\t\t 4 Byte AS %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(opt + i + 2))));
}
break;
case BGP_CAPCODE_ADD_PATH:
cap_offset=2;
if (tcap_len == 0) {
ND_PRINT((ndo, " (bogus)")); /* length */
break;
}
while (tcap_len > 0) {
if (tcap_len < 4) {
ND_PRINT((ndo, "\n\t\t(invalid)"));
break;
}
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s",
tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]),
opt[i+cap_offset+2],
tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3])
));
tcap_len-=4;
cap_offset+=4;
}
break;
default:
ND_PRINT((ndo, "\n\t\tno decoder for Capability %u",
cap_type));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
break;
}
if (ndo->ndo_vflag > 1 && cap_len > 0) {
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
}
i += BGP_CAP_HEADER_SIZE + cap_len;
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static void
bgp_open_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp_open bgpo;
struct bgp_opt bgpopt;
const u_char *opt;
int i;
ND_TCHECK2(dat[0], BGP_OPEN_SIZE);
memcpy(&bgpo, dat, BGP_OPEN_SIZE);
ND_PRINT((ndo, "\n\t Version %d, ", bgpo.bgpo_version));
ND_PRINT((ndo, "my AS %s, ",
as_printf(ndo, astostr, sizeof(astostr), ntohs(bgpo.bgpo_myas))));
ND_PRINT((ndo, "Holdtime %us, ", ntohs(bgpo.bgpo_holdtime)));
ND_PRINT((ndo, "ID %s", ipaddr_string(ndo, &bgpo.bgpo_id)));
ND_PRINT((ndo, "\n\t Optional parameters, length: %u", bgpo.bgpo_optlen));
/* some little sanity checking */
if (length < bgpo.bgpo_optlen+BGP_OPEN_SIZE)
return;
/* ugly! */
opt = &((const struct bgp_open *)dat)->bgpo_optlen;
opt++;
i = 0;
while (i < bgpo.bgpo_optlen) {
ND_TCHECK2(opt[i], BGP_OPT_SIZE);
memcpy(&bgpopt, &opt[i], BGP_OPT_SIZE);
if (i + 2 + bgpopt.bgpopt_len > bgpo.bgpo_optlen) {
ND_PRINT((ndo, "\n\t Option %d, length: %u", bgpopt.bgpopt_type, bgpopt.bgpopt_len));
break;
}
ND_PRINT((ndo, "\n\t Option %s (%u), length: %u",
tok2str(bgp_opt_values,"Unknown",
bgpopt.bgpopt_type),
bgpopt.bgpopt_type,
bgpopt.bgpopt_len));
/* now let's decode the options we know*/
switch(bgpopt.bgpopt_type) {
case BGP_OPT_CAP:
bgp_capabilities_print(ndo, &opt[i+BGP_OPT_SIZE],
bgpopt.bgpopt_len);
break;
case BGP_OPT_AUTH:
default:
ND_PRINT((ndo, "\n\t no decoder for option %u",
bgpopt.bgpopt_type));
break;
}
i += BGP_OPT_SIZE + bgpopt.bgpopt_len;
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static void
bgp_update_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
const u_char *p;
int withdrawn_routes_len;
int len;
int i;
ND_TCHECK2(dat[0], BGP_SIZE);
if (length < BGP_SIZE)
goto trunc;
memcpy(&bgp, dat, BGP_SIZE);
p = dat + BGP_SIZE; /*XXX*/
length -= BGP_SIZE;
/* Unfeasible routes */
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
withdrawn_routes_len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len) {
/*
* Without keeping state from the original NLRI message,
* it's not possible to tell if this a v4 or v6 route,
* so only try to decode it if we're not v6 enabled.
*/
ND_TCHECK2(p[0], withdrawn_routes_len);
if (length < withdrawn_routes_len)
goto trunc;
ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len));
p += withdrawn_routes_len;
length -= withdrawn_routes_len;
}
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len == 0 && len == 0 && length == 0) {
/* No withdrawn routes, no path attributes, no NLRI */
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
return;
}
if (len) {
/* do something more useful!*/
while (len) {
int aflags, atype, alenlen, alen;
ND_TCHECK2(p[0], 2);
if (len < 2)
goto trunc;
if (length < 2)
goto trunc;
aflags = *p;
atype = *(p + 1);
p += 2;
len -= 2;
length -= 2;
alenlen = bgp_attr_lenlen(aflags, p);
ND_TCHECK2(p[0], alenlen);
if (len < alenlen)
goto trunc;
if (length < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, p);
p += alenlen;
len -= alenlen;
length -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values, "Unknown Attribute",
atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
if (len < alen)
goto trunc;
if (length < alen)
goto trunc;
if (!bgp_attr_print(ndo, atype, p, alen, 0))
goto trunc;
p += alen;
len -= alen;
length -= alen;
}
}
if (length) {
/*
* XXX - what if they're using the "Advertisement of
* Multiple Paths in BGP" feature:
*
* https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/
*
* http://tools.ietf.org/html/draft-ietf-idr-add-paths-06
*/
ND_PRINT((ndo, "\n\t Updated routes:"));
while (length) {
char buf[MAXHOSTNAMELEN + 100];
i = decode_prefix4(ndo, p, length, buf, sizeof(buf));
if (i == -1) {
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
break;
} else if (i == -2)
goto trunc;
else if (i == -3)
goto trunc; /* bytes left, but not enough */
else {
ND_PRINT((ndo, "\n\t %s", buf));
p += i;
length -= i;
}
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static void
bgp_notification_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp_notification bgpn;
const u_char *tptr;
ND_TCHECK2(dat[0], BGP_NOTIFICATION_SIZE);
memcpy(&bgpn, dat, BGP_NOTIFICATION_SIZE);
/* some little sanity checking */
if (length<BGP_NOTIFICATION_SIZE)
return;
ND_PRINT((ndo, ", %s (%u)",
tok2str(bgp_notify_major_values, "Unknown Error",
bgpn.bgpn_major),
bgpn.bgpn_major));
switch (bgpn.bgpn_major) {
case BGP_NOTIFY_MAJOR_MSG:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_msg_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_OPEN:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_open_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_UPDATE:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_update_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_FSM:
ND_PRINT((ndo, " subcode %s (%u)",
tok2str(bgp_notify_minor_fsm_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_CAP:
ND_PRINT((ndo, " subcode %s (%u)",
tok2str(bgp_notify_minor_cap_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_CEASE:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_cease_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
/* draft-ietf-idr-cease-subcode-02 mentions optionally 7 bytes
* for the maxprefix subtype, which may contain AFI, SAFI and MAXPREFIXES
*/
if(bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_MAXPRFX && length >= BGP_NOTIFICATION_SIZE + 7) {
tptr = dat + BGP_NOTIFICATION_SIZE;
ND_TCHECK2(*tptr, 7);
ND_PRINT((ndo, ", AFI %s (%u), SAFI %s (%u), Max Prefixes: %u",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr),
tok2str(bgp_safi_values, "Unknown", *(tptr+2)),
*(tptr+2),
EXTRACT_32BITS(tptr+3)));
}
break;
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static void
bgp_route_refresh_print(netdissect_options *ndo,
const u_char *pptr, int len)
{
const struct bgp_route_refresh *bgp_route_refresh_header;
ND_TCHECK2(pptr[0], BGP_ROUTE_REFRESH_SIZE);
/* some little sanity checking */
if (len<BGP_ROUTE_REFRESH_SIZE)
return;
bgp_route_refresh_header = (const struct bgp_route_refresh *)pptr;
ND_PRINT((ndo, "\n\t AFI %s (%u), SAFI %s (%u)",
tok2str(af_values,"Unknown",
/* this stinks but the compiler pads the structure
* weird */
EXTRACT_16BITS(&bgp_route_refresh_header->afi)),
EXTRACT_16BITS(&bgp_route_refresh_header->afi),
tok2str(bgp_safi_values,"Unknown",
bgp_route_refresh_header->safi),
bgp_route_refresh_header->safi));
if (ndo->ndo_vflag > 1) {
ND_TCHECK2(*pptr, len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static int
bgp_header_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
ND_TCHECK2(dat[0], BGP_SIZE);
memcpy(&bgp, dat, BGP_SIZE);
ND_PRINT((ndo, "\n\t%s Message (%u), length: %u",
tok2str(bgp_msg_values, "Unknown", bgp.bgp_type),
bgp.bgp_type,
length));
switch (bgp.bgp_type) {
case BGP_OPEN:
bgp_open_print(ndo, dat, length);
break;
case BGP_UPDATE:
bgp_update_print(ndo, dat, length);
break;
case BGP_NOTIFICATION:
bgp_notification_print(ndo, dat, length);
break;
case BGP_KEEPALIVE:
break;
case BGP_ROUTE_REFRESH:
bgp_route_refresh_print(ndo, dat, length);
break;
default:
/* we have no decoder for the BGP message */
ND_TCHECK2(*dat, length);
ND_PRINT((ndo, "\n\t no Message %u decoder", bgp.bgp_type));
print_unknown_data(ndo, dat, "\n\t ", length);
break;
}
return 1;
trunc:
ND_PRINT((ndo, "%s", tstr));
return 0;
}
void
bgp_print(netdissect_options *ndo,
const u_char *dat, int length)
{
const u_char *p;
const u_char *ep;
const u_char *start;
const u_char marker[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
};
struct bgp bgp;
uint16_t hlen;
ep = dat + length;
if (ndo->ndo_snapend < dat + length)
ep = ndo->ndo_snapend;
ND_PRINT((ndo, ": BGP"));
if (ndo->ndo_vflag < 1) /* lets be less chatty */
return;
p = dat;
start = p;
while (p < ep) {
if (!ND_TTEST2(p[0], 1))
break;
if (p[0] != 0xff) {
p++;
continue;
}
if (!ND_TTEST2(p[0], sizeof(marker)))
break;
if (memcmp(p, marker, sizeof(marker)) != 0) {
p++;
continue;
}
/* found BGP header */
ND_TCHECK2(p[0], BGP_SIZE); /*XXX*/
memcpy(&bgp, p, BGP_SIZE);
if (start != p)
ND_PRINT((ndo, " %s", tstr));
hlen = ntohs(bgp.bgp_len);
if (hlen < BGP_SIZE) {
ND_PRINT((ndo, "\n[|BGP Bogus header length %u < %u]", hlen,
BGP_SIZE));
break;
}
if (ND_TTEST2(p[0], hlen)) {
if (!bgp_header_print(ndo, p, hlen))
return;
p += hlen;
start = p;
} else {
ND_PRINT((ndo, "\n[|BGP %s]",
tok2str(bgp_msg_values,
"Unknown Message Type",
bgp.bgp_type)));
break;
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 4
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-674/c/good_333_0 |
crossvul-cpp_data_good_1310_3 | /*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the SQLite parser
** when syntax rules are reduced. The routines in this file handle the
** following kinds of SQL syntax:
**
** CREATE TABLE
** DROP TABLE
** CREATE INDEX
** DROP INDEX
** creating ID lists
** BEGIN TRANSACTION
** COMMIT
** ROLLBACK
*/
#include "sqliteInt.h"
#ifndef SQLITE_OMIT_SHARED_CACHE
/*
** The TableLock structure is only used by the sqlite3TableLock() and
** codeTableLocks() functions.
*/
struct TableLock {
int iDb; /* The database containing the table to be locked */
int iTab; /* The root page of the table to be locked */
u8 isWriteLock; /* True for write lock. False for a read lock */
const char *zLockName; /* Name of the table */
};
/*
** Record the fact that we want to lock a table at run-time.
**
** The table to be locked has root page iTab and is found in database iDb.
** A read or a write lock can be taken depending on isWritelock.
**
** This routine just records the fact that the lock is desired. The
** code to make the lock occur is generated by a later call to
** codeTableLocks() which occurs during sqlite3FinishCoding().
*/
void sqlite3TableLock(
Parse *pParse, /* Parsing context */
int iDb, /* Index of the database containing the table to lock */
int iTab, /* Root page number of the table to be locked */
u8 isWriteLock, /* True for a write lock */
const char *zName /* Name of the table to be locked */
){
Parse *pToplevel = sqlite3ParseToplevel(pParse);
int i;
int nBytes;
TableLock *p;
assert( iDb>=0 );
if( iDb==1 ) return;
if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
for(i=0; i<pToplevel->nTableLock; i++){
p = &pToplevel->aTableLock[i];
if( p->iDb==iDb && p->iTab==iTab ){
p->isWriteLock = (p->isWriteLock || isWriteLock);
return;
}
}
nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
pToplevel->aTableLock =
sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
if( pToplevel->aTableLock ){
p = &pToplevel->aTableLock[pToplevel->nTableLock++];
p->iDb = iDb;
p->iTab = iTab;
p->isWriteLock = isWriteLock;
p->zLockName = zName;
}else{
pToplevel->nTableLock = 0;
sqlite3OomFault(pToplevel->db);
}
}
/*
** Code an OP_TableLock instruction for each table locked by the
** statement (configured by calls to sqlite3TableLock()).
*/
static void codeTableLocks(Parse *pParse){
int i;
Vdbe *pVdbe;
pVdbe = sqlite3GetVdbe(pParse);
assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
for(i=0; i<pParse->nTableLock; i++){
TableLock *p = &pParse->aTableLock[i];
int p1 = p->iDb;
sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
p->zLockName, P4_STATIC);
}
}
#else
#define codeTableLocks(x)
#endif
/*
** Return TRUE if the given yDbMask object is empty - if it contains no
** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
** macros when SQLITE_MAX_ATTACHED is greater than 30.
*/
#if SQLITE_MAX_ATTACHED>30
int sqlite3DbMaskAllZero(yDbMask m){
int i;
for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
return 1;
}
#endif
/*
** This routine is called after a single SQL statement has been
** parsed and a VDBE program to execute that statement has been
** prepared. This routine puts the finishing touches on the
** VDBE program and resets the pParse structure for the next
** parse.
**
** Note that if an error occurred, it might be the case that
** no VDBE code was generated.
*/
void sqlite3FinishCoding(Parse *pParse){
sqlite3 *db;
Vdbe *v;
assert( pParse->pToplevel==0 );
db = pParse->db;
if( pParse->nested ) return;
if( db->mallocFailed || pParse->nErr ){
if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
return;
}
/* Begin by generating some termination code at the end of the
** vdbe program
*/
v = sqlite3GetVdbe(pParse);
assert( !pParse->isMultiWrite
|| sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
if( v ){
sqlite3VdbeAddOp0(v, OP_Halt);
#if SQLITE_USER_AUTHENTICATION
if( pParse->nTableLock>0 && db->init.busy==0 ){
sqlite3UserAuthInit(db);
if( db->auth.authLevel<UAUTH_User ){
sqlite3ErrorMsg(pParse, "user not authenticated");
pParse->rc = SQLITE_AUTH_USER;
return;
}
}
#endif
/* The cookie mask contains one bit for each database file open.
** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
** set for each database that is used. Generate code to start a
** transaction on each used database and to verify the schema cookie
** on each used database.
*/
if( db->mallocFailed==0
&& (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
){
int iDb, i;
assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
sqlite3VdbeJumpHere(v, 0);
for(iDb=0; iDb<db->nDb; iDb++){
Schema *pSchema;
if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
sqlite3VdbeUsesBtree(v, iDb);
pSchema = db->aDb[iDb].pSchema;
sqlite3VdbeAddOp4Int(v,
OP_Transaction, /* Opcode */
iDb, /* P1 */
DbMaskTest(pParse->writeMask,iDb), /* P2 */
pSchema->schema_cookie, /* P3 */
pSchema->iGeneration /* P4 */
);
if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
VdbeComment((v,
"usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
for(i=0; i<pParse->nVtabLock; i++){
char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
}
pParse->nVtabLock = 0;
#endif
/* Once all the cookies have been verified and transactions opened,
** obtain the required table-locks. This is a no-op unless the
** shared-cache feature is enabled.
*/
codeTableLocks(pParse);
/* Initialize any AUTOINCREMENT data structures required.
*/
sqlite3AutoincrementBegin(pParse);
/* Code constant expressions that where factored out of inner loops */
if( pParse->pConstExpr ){
ExprList *pEL = pParse->pConstExpr;
pParse->okConstFactor = 0;
for(i=0; i<pEL->nExpr; i++){
sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
}
}
/* Finally, jump back to the beginning of the executable code. */
sqlite3VdbeGoto(v, 1);
}
}
/* Get the VDBE program ready for execution
*/
if( v && pParse->nErr==0 && !db->mallocFailed ){
/* A minimum of one cursor is required if autoincrement is used
* See ticket [a696379c1f08866] */
assert( pParse->pAinc==0 || pParse->nTab>0 );
sqlite3VdbeMakeReady(v, pParse);
pParse->rc = SQLITE_DONE;
}else{
pParse->rc = SQLITE_ERROR;
}
}
/*
** Run the parser and code generator recursively in order to generate
** code for the SQL statement given onto the end of the pParse context
** currently under construction. When the parser is run recursively
** this way, the final OP_Halt is not appended and other initialization
** and finalization steps are omitted because those are handling by the
** outermost parser.
**
** Not everything is nestable. This facility is designed to permit
** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
** care if you decide to try to use this routine for some other purposes.
*/
void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
va_list ap;
char *zSql;
char *zErrMsg = 0;
sqlite3 *db = pParse->db;
char saveBuf[PARSE_TAIL_SZ];
if( pParse->nErr ) return;
assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
va_start(ap, zFormat);
zSql = sqlite3VMPrintf(db, zFormat, ap);
va_end(ap);
if( zSql==0 ){
/* This can result either from an OOM or because the formatted string
** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set
** an error */
if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
pParse->nErr++;
return;
}
pParse->nested++;
memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
sqlite3RunParser(pParse, zSql, &zErrMsg);
sqlite3DbFree(db, zErrMsg);
sqlite3DbFree(db, zSql);
memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
pParse->nested--;
}
#if SQLITE_USER_AUTHENTICATION
/*
** Return TRUE if zTable is the name of the system table that stores the
** list of users and their access credentials.
*/
int sqlite3UserAuthTable(const char *zTable){
return sqlite3_stricmp(zTable, "sqlite_user")==0;
}
#endif
/*
** Locate the in-memory structure that describes a particular database
** table given the name of that table and (optionally) the name of the
** database containing the table. Return NULL if not found.
**
** If zDatabase is 0, all databases are searched for the table and the
** first matching table is returned. (No checking for duplicate table
** names is done.) The search order is TEMP first, then MAIN, then any
** auxiliary databases added using the ATTACH command.
**
** See also sqlite3LocateTable().
*/
Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
Table *p = 0;
int i;
/* All mutexes are required for schema access. Make sure we hold them. */
assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
#if SQLITE_USER_AUTHENTICATION
/* Only the admin user is allowed to know that the sqlite_user table
** exists */
if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
return 0;
}
#endif
while(1){
for(i=OMIT_TEMPDB; i<db->nDb; i++){
int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
assert( sqlite3SchemaMutexHeld(db, j, 0) );
p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
if( p ) return p;
}
}
/* Not found. If the name we were looking for was temp.sqlite_master
** then change the name to sqlite_temp_master and try again. */
if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
zName = TEMP_MASTER_NAME;
}
return 0;
}
/*
** Locate the in-memory structure that describes a particular database
** table given the name of that table and (optionally) the name of the
** database containing the table. Return NULL if not found. Also leave an
** error message in pParse->zErrMsg.
**
** The difference between this routine and sqlite3FindTable() is that this
** routine leaves an error message in pParse->zErrMsg where
** sqlite3FindTable() does not.
*/
Table *sqlite3LocateTable(
Parse *pParse, /* context in which to report errors */
u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
const char *zName, /* Name of the table we are looking for */
const char *zDbase /* Name of the database. Might be NULL */
){
Table *p;
sqlite3 *db = pParse->db;
/* Read the database schema. If an error occurs, leave an error message
** and code in pParse and return NULL. */
if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
&& SQLITE_OK!=sqlite3ReadSchema(pParse)
){
return 0;
}
p = sqlite3FindTable(db, zName, zDbase);
if( p==0 ){
#ifndef SQLITE_OMIT_VIRTUALTABLE
/* If zName is the not the name of a table in the schema created using
** CREATE, then check to see if it is the name of an virtual table that
** can be an eponymous virtual table. */
if( pParse->disableVtab==0 ){
Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
pMod = sqlite3PragmaVtabRegister(db, zName);
}
if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
return pMod->pEpoTab;
}
}
#endif
if( flags & LOCATE_NOERR ) return 0;
pParse->checkSchema = 1;
}else if( IsVirtual(p) && pParse->disableVtab ){
p = 0;
}
if( p==0 ){
const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
if( zDbase ){
sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
}else{
sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
}
}
return p;
}
/*
** Locate the table identified by *p.
**
** This is a wrapper around sqlite3LocateTable(). The difference between
** sqlite3LocateTable() and this function is that this function restricts
** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
** non-NULL if it is part of a view or trigger program definition. See
** sqlite3FixSrcList() for details.
*/
Table *sqlite3LocateTableItem(
Parse *pParse,
u32 flags,
struct SrcList_item *p
){
const char *zDb;
assert( p->pSchema==0 || p->zDatabase==0 );
if( p->pSchema ){
int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
zDb = pParse->db->aDb[iDb].zDbSName;
}else{
zDb = p->zDatabase;
}
return sqlite3LocateTable(pParse, flags, p->zName, zDb);
}
/*
** Locate the in-memory structure that describes
** a particular index given the name of that index
** and the name of the database that contains the index.
** Return NULL if not found.
**
** If zDatabase is 0, all databases are searched for the
** table and the first matching index is returned. (No checking
** for duplicate index names is done.) The search order is
** TEMP first, then MAIN, then any auxiliary databases added
** using the ATTACH command.
*/
Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
Index *p = 0;
int i;
/* All mutexes are required for schema access. Make sure we hold them. */
assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
for(i=OMIT_TEMPDB; i<db->nDb; i++){
int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
Schema *pSchema = db->aDb[j].pSchema;
assert( pSchema );
if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
assert( sqlite3SchemaMutexHeld(db, j, 0) );
p = sqlite3HashFind(&pSchema->idxHash, zName);
if( p ) break;
}
return p;
}
/*
** Reclaim the memory used by an index
*/
void sqlite3FreeIndex(sqlite3 *db, Index *p){
#ifndef SQLITE_OMIT_ANALYZE
sqlite3DeleteIndexSamples(db, p);
#endif
sqlite3ExprDelete(db, p->pPartIdxWhere);
sqlite3ExprListDelete(db, p->aColExpr);
sqlite3DbFree(db, p->zColAff);
if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
#ifdef SQLITE_ENABLE_STAT4
sqlite3_free(p->aiRowEst);
#endif
sqlite3DbFree(db, p);
}
/*
** For the index called zIdxName which is found in the database iDb,
** unlike that index from its Table then remove the index from
** the index hash table and free all memory structures associated
** with the index.
*/
void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
Index *pIndex;
Hash *pHash;
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
pHash = &db->aDb[iDb].pSchema->idxHash;
pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
if( ALWAYS(pIndex) ){
if( pIndex->pTable->pIndex==pIndex ){
pIndex->pTable->pIndex = pIndex->pNext;
}else{
Index *p;
/* Justification of ALWAYS(); The index must be on the list of
** indices. */
p = pIndex->pTable->pIndex;
while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
if( ALWAYS(p && p->pNext==pIndex) ){
p->pNext = pIndex->pNext;
}
}
sqlite3FreeIndex(db, pIndex);
}
db->mDbFlags |= DBFLAG_SchemaChange;
}
/*
** Look through the list of open database files in db->aDb[] and if
** any have been closed, remove them from the list. Reallocate the
** db->aDb[] structure to a smaller size, if possible.
**
** Entry 0 (the "main" database) and entry 1 (the "temp" database)
** are never candidates for being collapsed.
*/
void sqlite3CollapseDatabaseArray(sqlite3 *db){
int i, j;
for(i=j=2; i<db->nDb; i++){
struct Db *pDb = &db->aDb[i];
if( pDb->pBt==0 ){
sqlite3DbFree(db, pDb->zDbSName);
pDb->zDbSName = 0;
continue;
}
if( j<i ){
db->aDb[j] = db->aDb[i];
}
j++;
}
db->nDb = j;
if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
sqlite3DbFree(db, db->aDb);
db->aDb = db->aDbStatic;
}
}
/*
** Reset the schema for the database at index iDb. Also reset the
** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
** Deferred resets may be run by calling with iDb<0.
*/
void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
int i;
assert( iDb<db->nDb );
if( iDb>=0 ){
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
DbSetProperty(db, iDb, DB_ResetWanted);
DbSetProperty(db, 1, DB_ResetWanted);
db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
}
if( db->nSchemaLock==0 ){
for(i=0; i<db->nDb; i++){
if( DbHasProperty(db, i, DB_ResetWanted) ){
sqlite3SchemaClear(db->aDb[i].pSchema);
}
}
}
}
/*
** Erase all schema information from all attached databases (including
** "main" and "temp") for a single database connection.
*/
void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
int i;
sqlite3BtreeEnterAll(db);
for(i=0; i<db->nDb; i++){
Db *pDb = &db->aDb[i];
if( pDb->pSchema ){
if( db->nSchemaLock==0 ){
sqlite3SchemaClear(pDb->pSchema);
}else{
DbSetProperty(db, i, DB_ResetWanted);
}
}
}
db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
sqlite3VtabUnlockList(db);
sqlite3BtreeLeaveAll(db);
if( db->nSchemaLock==0 ){
sqlite3CollapseDatabaseArray(db);
}
}
/*
** This routine is called when a commit occurs.
*/
void sqlite3CommitInternalChanges(sqlite3 *db){
db->mDbFlags &= ~DBFLAG_SchemaChange;
}
/*
** Delete memory allocated for the column names of a table or view (the
** Table.aCol[] array).
*/
void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
int i;
Column *pCol;
assert( pTable!=0 );
if( (pCol = pTable->aCol)!=0 ){
for(i=0; i<pTable->nCol; i++, pCol++){
sqlite3DbFree(db, pCol->zName);
sqlite3ExprDelete(db, pCol->pDflt);
sqlite3DbFree(db, pCol->zColl);
}
sqlite3DbFree(db, pTable->aCol);
}
}
/*
** Remove the memory data structures associated with the given
** Table. No changes are made to disk by this routine.
**
** This routine just deletes the data structure. It does not unlink
** the table data structure from the hash table. But it does destroy
** memory structures of the indices and foreign keys associated with
** the table.
**
** The db parameter is optional. It is needed if the Table object
** contains lookaside memory. (Table objects in the schema do not use
** lookaside memory, but some ephemeral Table objects do.) Or the
** db parameter can be used with db->pnBytesFreed to measure the memory
** used by the Table object.
*/
static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
Index *pIndex, *pNext;
#ifdef SQLITE_DEBUG
/* Record the number of outstanding lookaside allocations in schema Tables
** prior to doing any free() operations. Since schema Tables do not use
** lookaside, this number should not change.
**
** If malloc has already failed, it may be that it failed while allocating
** a Table object that was going to be marked ephemeral. So do not check
** that no lookaside memory is used in this case either. */
int nLookaside = 0;
if( db && !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){
nLookaside = sqlite3LookasideUsed(db, 0);
}
#endif
/* Delete all indices associated with this table. */
for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
pNext = pIndex->pNext;
assert( pIndex->pSchema==pTable->pSchema
|| (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
char *zName = pIndex->zName;
TESTONLY ( Index *pOld = ) sqlite3HashInsert(
&pIndex->pSchema->idxHash, zName, 0
);
assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
assert( pOld==pIndex || pOld==0 );
}
sqlite3FreeIndex(db, pIndex);
}
/* Delete any foreign keys attached to this table. */
sqlite3FkDelete(db, pTable);
/* Delete the Table structure itself.
*/
sqlite3DeleteColumnNames(db, pTable);
sqlite3DbFree(db, pTable->zName);
sqlite3DbFree(db, pTable->zColAff);
sqlite3SelectDelete(db, pTable->pSelect);
sqlite3ExprListDelete(db, pTable->pCheck);
#ifndef SQLITE_OMIT_VIRTUALTABLE
sqlite3VtabClear(db, pTable);
#endif
sqlite3DbFree(db, pTable);
/* Verify that no lookaside memory was used by schema tables */
assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
}
void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
/* Do not delete the table until the reference count reaches zero. */
if( !pTable ) return;
if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
deleteTable(db, pTable);
}
/*
** Unlink the given table from the hash tables and the delete the
** table structure with all its indices and foreign keys.
*/
void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
Table *p;
Db *pDb;
assert( db!=0 );
assert( iDb>=0 && iDb<db->nDb );
assert( zTabName );
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
pDb = &db->aDb[iDb];
p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
sqlite3DeleteTable(db, p);
db->mDbFlags |= DBFLAG_SchemaChange;
}
/*
** Given a token, return a string that consists of the text of that
** token. Space to hold the returned string
** is obtained from sqliteMalloc() and must be freed by the calling
** function.
**
** Any quotation marks (ex: "name", 'name', [name], or `name`) that
** surround the body of the token are removed.
**
** Tokens are often just pointers into the original SQL text and so
** are not \000 terminated and are not persistent. The returned string
** is \000 terminated and is persistent.
*/
char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
char *zName;
if( pName ){
zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
sqlite3Dequote(zName);
}else{
zName = 0;
}
return zName;
}
/*
** Open the sqlite_master table stored in database number iDb for
** writing. The table is opened using cursor 0.
*/
void sqlite3OpenMasterTable(Parse *p, int iDb){
Vdbe *v = sqlite3GetVdbe(p);
sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
if( p->nTab==0 ){
p->nTab = 1;
}
}
/*
** Parameter zName points to a nul-terminated buffer containing the name
** of a database ("main", "temp" or the name of an attached db). This
** function returns the index of the named database in db->aDb[], or
** -1 if the named db cannot be found.
*/
int sqlite3FindDbName(sqlite3 *db, const char *zName){
int i = -1; /* Database number */
if( zName ){
Db *pDb;
for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
/* "main" is always an acceptable alias for the primary database
** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
}
}
return i;
}
/*
** The token *pName contains the name of a database (either "main" or
** "temp" or the name of an attached db). This routine returns the
** index of the named database in db->aDb[], or -1 if the named db
** does not exist.
*/
int sqlite3FindDb(sqlite3 *db, Token *pName){
int i; /* Database number */
char *zName; /* Name we are searching for */
zName = sqlite3NameFromToken(db, pName);
i = sqlite3FindDbName(db, zName);
sqlite3DbFree(db, zName);
return i;
}
/* The table or view or trigger name is passed to this routine via tokens
** pName1 and pName2. If the table name was fully qualified, for example:
**
** CREATE TABLE xxx.yyy (...);
**
** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
** the table name is not fully qualified, i.e.:
**
** CREATE TABLE yyy(...);
**
** Then pName1 is set to "yyy" and pName2 is "".
**
** This routine sets the *ppUnqual pointer to point at the token (pName1 or
** pName2) that stores the unqualified table name. The index of the
** database "xxx" is returned.
*/
int sqlite3TwoPartName(
Parse *pParse, /* Parsing and code generating context */
Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
Token *pName2, /* The "yyy" in the name "xxx.yyy" */
Token **pUnqual /* Write the unqualified object name here */
){
int iDb; /* Database holding the object */
sqlite3 *db = pParse->db;
assert( pName2!=0 );
if( pName2->n>0 ){
if( db->init.busy ) {
sqlite3ErrorMsg(pParse, "corrupt database");
return -1;
}
*pUnqual = pName2;
iDb = sqlite3FindDb(db, pName1);
if( iDb<0 ){
sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
return -1;
}
}else{
assert( db->init.iDb==0 || db->init.busy || IN_RENAME_OBJECT
|| (db->mDbFlags & DBFLAG_Vacuum)!=0);
iDb = db->init.iDb;
*pUnqual = pName1;
}
return iDb;
}
/*
** True if PRAGMA writable_schema is ON
*/
int sqlite3WritableSchema(sqlite3 *db){
testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
SQLITE_WriteSchema );
testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
SQLITE_Defensive );
testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
(SQLITE_WriteSchema|SQLITE_Defensive) );
return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
}
/*
** This routine is used to check if the UTF-8 string zName is a legal
** unqualified name for a new schema object (table, index, view or
** trigger). All names are legal except those that begin with the string
** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
** is reserved for internal use.
**
** When parsing the sqlite_master table, this routine also checks to
** make sure the "type", "name", and "tbl_name" columns are consistent
** with the SQL.
*/
int sqlite3CheckObjectName(
Parse *pParse, /* Parsing context */
const char *zName, /* Name of the object to check */
const char *zType, /* Type of this object */
const char *zTblName /* Parent table name for triggers and indexes */
){
sqlite3 *db = pParse->db;
if( sqlite3WritableSchema(db) || db->init.imposterTable ){
/* Skip these error checks for writable_schema=ON */
return SQLITE_OK;
}
if( db->init.busy ){
if( sqlite3_stricmp(zType, db->init.azInit[0])
|| sqlite3_stricmp(zName, db->init.azInit[1])
|| sqlite3_stricmp(zTblName, db->init.azInit[2])
){
if( sqlite3Config.bExtraSchemaChecks ){
sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
return SQLITE_ERROR;
}
}
}else{
if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
|| (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))
){
sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
zName);
return SQLITE_ERROR;
}
}
return SQLITE_OK;
}
/*
** Return the PRIMARY KEY index of a table
*/
Index *sqlite3PrimaryKeyIndex(Table *pTab){
Index *p;
for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
return p;
}
/*
** Convert an table column number into a index column number. That is,
** for the column iCol in the table (as defined by the CREATE TABLE statement)
** find the (first) offset of that column in index pIdx. Or return -1
** if column iCol is not used in index pIdx.
*/
i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){
int i;
for(i=0; i<pIdx->nColumn; i++){
if( iCol==pIdx->aiColumn[i] ) return i;
}
return -1;
}
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
/* Convert a storage column number into a table column number.
**
** The storage column number (0,1,2,....) is the index of the value
** as it appears in the record on disk. The true column number
** is the index (0,1,2,...) of the column in the CREATE TABLE statement.
**
** The storage column number is less than the table column number if
** and only there are VIRTUAL columns to the left.
**
** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.
*/
i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){
if( pTab->tabFlags & TF_HasVirtual ){
int i;
for(i=0; i<=iCol; i++){
if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;
}
}
return iCol;
}
#endif
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
/* Convert a table column number into a storage column number.
**
** The storage column number (0,1,2,....) is the index of the value
** as it appears in the record on disk. Or, if the input column is
** the N-th virtual column (zero-based) then the storage number is
** the number of non-virtual columns in the table plus N.
**
** The true column number is the index (0,1,2,...) of the column in
** the CREATE TABLE statement.
**
** If the input column is a VIRTUAL column, then it should not appear
** in storage. But the value sometimes is cached in registers that
** follow the range of registers used to construct storage. This
** avoids computing the same VIRTUAL column multiple times, and provides
** values for use by OP_Param opcodes in triggers. Hence, if the
** input column is a VIRTUAL table, put it after all the other columns.
**
** In the following, N means "normal column", S means STORED, and
** V means VIRTUAL. Suppose the CREATE TABLE has columns like this:
**
** CREATE TABLE ex(N,S,V,N,S,V,N,S,V);
** -- 0 1 2 3 4 5 6 7 8
**
** Then the mapping from this function is as follows:
**
** INPUTS: 0 1 2 3 4 5 6 7 8
** OUTPUTS: 0 1 6 2 3 7 4 5 8
**
** So, in other words, this routine shifts all the virtual columns to
** the end.
**
** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and
** this routine is a no-op macro. If the pTab does not have any virtual
** columns, then this routine is no-op that always return iCol. If iCol
** is negative (indicating the ROWID column) then this routine return iCol.
*/
i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){
int i;
i16 n;
assert( iCol<pTab->nCol );
if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;
for(i=0, n=0; i<iCol; i++){
if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;
}
if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){
/* iCol is a virtual column itself */
return pTab->nNVCol + i - n;
}else{
/* iCol is a normal or stored column */
return n;
}
}
#endif
/*
** Begin constructing a new table representation in memory. This is
** the first of several action routines that get called in response
** to a CREATE TABLE statement. In particular, this routine is called
** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
** flag is true if the table should be stored in the auxiliary database
** file instead of in the main database file. This is normally the case
** when the "TEMP" or "TEMPORARY" keyword occurs in between
** CREATE and TABLE.
**
** The new table record is initialized and put in pParse->pNewTable.
** As more of the CREATE TABLE statement is parsed, additional action
** routines will be called to add more information to this record.
** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
** is called to complete the construction of the new table record.
*/
void sqlite3StartTable(
Parse *pParse, /* Parser context */
Token *pName1, /* First part of the name of the table or view */
Token *pName2, /* Second part of the name of the table or view */
int isTemp, /* True if this is a TEMP table */
int isView, /* True if this is a VIEW */
int isVirtual, /* True if this is a VIRTUAL table */
int noErr /* Do nothing if table already exists */
){
Table *pTable;
char *zName = 0; /* The name of the new table */
sqlite3 *db = pParse->db;
Vdbe *v;
int iDb; /* Database number to create the table in */
Token *pName; /* Unqualified name of the table to create */
if( db->init.busy && db->init.newTnum==1 ){
/* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
iDb = db->init.iDb;
zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
pName = pName1;
}else{
/* The common case */
iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
if( iDb<0 ) return;
if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
/* If creating a temp table, the name may not be qualified. Unless
** the database name is "temp" anyway. */
sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
return;
}
if( !OMIT_TEMPDB && isTemp ) iDb = 1;
zName = sqlite3NameFromToken(db, pName);
if( IN_RENAME_OBJECT ){
sqlite3RenameTokenMap(pParse, (void*)zName, pName);
}
}
pParse->sNameToken = *pName;
if( zName==0 ) return;
if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){
goto begin_table_error;
}
if( db->init.iDb==1 ) isTemp = 1;
#ifndef SQLITE_OMIT_AUTHORIZATION
assert( isTemp==0 || isTemp==1 );
assert( isView==0 || isView==1 );
{
static const u8 aCode[] = {
SQLITE_CREATE_TABLE,
SQLITE_CREATE_TEMP_TABLE,
SQLITE_CREATE_VIEW,
SQLITE_CREATE_TEMP_VIEW
};
char *zDb = db->aDb[iDb].zDbSName;
if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
goto begin_table_error;
}
if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
zName, 0, zDb) ){
goto begin_table_error;
}
}
#endif
/* Make sure the new table name does not collide with an existing
** index or table name in the same database. Issue an error message if
** it does. The exception is if the statement being parsed was passed
** to an sqlite3_declare_vtab() call. In that case only the column names
** and types will be used, so there is no need to test for namespace
** collisions.
*/
if( !IN_SPECIAL_PARSE ){
char *zDb = db->aDb[iDb].zDbSName;
if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
goto begin_table_error;
}
pTable = sqlite3FindTable(db, zName, zDb);
if( pTable ){
if( !noErr ){
sqlite3ErrorMsg(pParse, "table %T already exists", pName);
}else{
assert( !db->init.busy || CORRUPT_DB );
sqlite3CodeVerifySchema(pParse, iDb);
}
goto begin_table_error;
}
if( sqlite3FindIndex(db, zName, zDb)!=0 ){
sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
goto begin_table_error;
}
}
pTable = sqlite3DbMallocZero(db, sizeof(Table));
if( pTable==0 ){
assert( db->mallocFailed );
pParse->rc = SQLITE_NOMEM_BKPT;
pParse->nErr++;
goto begin_table_error;
}
pTable->zName = zName;
pTable->iPKey = -1;
pTable->pSchema = db->aDb[iDb].pSchema;
pTable->nTabRef = 1;
#ifdef SQLITE_DEFAULT_ROWEST
pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
#else
pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
#endif
assert( pParse->pNewTable==0 );
pParse->pNewTable = pTable;
/* If this is the magic sqlite_sequence table used by autoincrement,
** then record a pointer to this table in the main database structure
** so that INSERT can find the table easily.
*/
#ifndef SQLITE_OMIT_AUTOINCREMENT
if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
pTable->pSchema->pSeqTab = pTable;
}
#endif
/* Begin generating the code that will insert the table record into
** the SQLITE_MASTER table. Note in particular that we must go ahead
** and allocate the record number for the table entry now. Before any
** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
** indices to be created and the table record must come before the
** indices. Hence, the record number for the table must be allocated
** now.
*/
if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
int addr1;
int fileFormat;
int reg1, reg2, reg3;
/* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
sqlite3BeginWriteOperation(pParse, 1, iDb);
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( isVirtual ){
sqlite3VdbeAddOp0(v, OP_VBegin);
}
#endif
/* If the file format and encoding in the database have not been set,
** set them now.
*/
reg1 = pParse->regRowid = ++pParse->nMem;
reg2 = pParse->regRoot = ++pParse->nMem;
reg3 = ++pParse->nMem;
sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
sqlite3VdbeUsesBtree(v, iDb);
addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
1 : SQLITE_MAX_FILE_FORMAT;
sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
sqlite3VdbeJumpHere(v, addr1);
/* This just creates a place-holder record in the sqlite_master table.
** The record created does not contain anything yet. It will be replaced
** by the real entry in code generated at sqlite3EndTable().
**
** The rowid for the new entry is left in register pParse->regRowid.
** The root page number of the new table is left in reg pParse->regRoot.
** The rowid and root page number values are needed by the code that
** sqlite3EndTable will generate.
*/
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
if( isView || isVirtual ){
sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
}else
#endif
{
pParse->addrCrTab =
sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
}
sqlite3OpenMasterTable(pParse, iDb);
sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
sqlite3VdbeAddOp0(v, OP_Close);
}
/* Normal (non-error) return. */
return;
/* If an error occurs, we jump here */
begin_table_error:
sqlite3DbFree(db, zName);
return;
}
/* Set properties of a table column based on the (magical)
** name of the column.
*/
#if SQLITE_ENABLE_HIDDEN_COLUMNS
void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
pCol->colFlags |= COLFLAG_HIDDEN;
}else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
pTab->tabFlags |= TF_OOOHidden;
}
}
#endif
/*
** Add a new column to the table currently being constructed.
**
** The parser calls this routine once for each column declaration
** in a CREATE TABLE statement. sqlite3StartTable() gets called
** first to get things going. Then this routine is called for each
** column.
*/
void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
Table *p;
int i;
char *z;
char *zType;
Column *pCol;
sqlite3 *db = pParse->db;
if( (p = pParse->pNewTable)==0 ) return;
if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
return;
}
z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
if( z==0 ) return;
if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, pName);
memcpy(z, pName->z, pName->n);
z[pName->n] = 0;
sqlite3Dequote(z);
for(i=0; i<p->nCol; i++){
if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
sqlite3DbFree(db, z);
return;
}
}
if( (p->nCol & 0x7)==0 ){
Column *aNew;
aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
if( aNew==0 ){
sqlite3DbFree(db, z);
return;
}
p->aCol = aNew;
}
pCol = &p->aCol[p->nCol];
memset(pCol, 0, sizeof(p->aCol[0]));
pCol->zName = z;
sqlite3ColumnPropertiesFromName(p, pCol);
if( pType->n==0 ){
/* If there is no type specified, columns have the default affinity
** 'BLOB' with a default size of 4 bytes. */
pCol->affinity = SQLITE_AFF_BLOB;
pCol->szEst = 1;
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( 4>=sqlite3GlobalConfig.szSorterRef ){
pCol->colFlags |= COLFLAG_SORTERREF;
}
#endif
}else{
zType = z + sqlite3Strlen30(z) + 1;
memcpy(zType, pType->z, pType->n);
zType[pType->n] = 0;
sqlite3Dequote(zType);
pCol->affinity = sqlite3AffinityType(zType, pCol);
pCol->colFlags |= COLFLAG_HASTYPE;
}
p->nCol++;
p->nNVCol++;
pParse->constraintName.n = 0;
}
/*
** This routine is called by the parser while in the middle of
** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
** been seen on a column. This routine sets the notNull flag on
** the column currently under construction.
*/
void sqlite3AddNotNull(Parse *pParse, int onError){
Table *p;
Column *pCol;
p = pParse->pNewTable;
if( p==0 || NEVER(p->nCol<1) ) return;
pCol = &p->aCol[p->nCol-1];
pCol->notNull = (u8)onError;
p->tabFlags |= TF_HasNotNull;
/* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
** on this column. */
if( pCol->colFlags & COLFLAG_UNIQUE ){
Index *pIdx;
for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
if( pIdx->aiColumn[0]==p->nCol-1 ){
pIdx->uniqNotNull = 1;
}
}
}
}
/*
** Scan the column type name zType (length nType) and return the
** associated affinity type.
**
** This routine does a case-independent search of zType for the
** substrings in the following table. If one of the substrings is
** found, the corresponding affinity is returned. If zType contains
** more than one of the substrings, entries toward the top of
** the table take priority. For example, if zType is 'BLOBINT',
** SQLITE_AFF_INTEGER is returned.
**
** Substring | Affinity
** --------------------------------
** 'INT' | SQLITE_AFF_INTEGER
** 'CHAR' | SQLITE_AFF_TEXT
** 'CLOB' | SQLITE_AFF_TEXT
** 'TEXT' | SQLITE_AFF_TEXT
** 'BLOB' | SQLITE_AFF_BLOB
** 'REAL' | SQLITE_AFF_REAL
** 'FLOA' | SQLITE_AFF_REAL
** 'DOUB' | SQLITE_AFF_REAL
**
** If none of the substrings in the above table are found,
** SQLITE_AFF_NUMERIC is returned.
*/
char sqlite3AffinityType(const char *zIn, Column *pCol){
u32 h = 0;
char aff = SQLITE_AFF_NUMERIC;
const char *zChar = 0;
assert( zIn!=0 );
while( zIn[0] ){
h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
zIn++;
if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
aff = SQLITE_AFF_TEXT;
zChar = zIn;
}else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
aff = SQLITE_AFF_TEXT;
}else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
aff = SQLITE_AFF_TEXT;
}else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
&& (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
aff = SQLITE_AFF_BLOB;
if( zIn[0]=='(' ) zChar = zIn;
#ifndef SQLITE_OMIT_FLOATING_POINT
}else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
&& aff==SQLITE_AFF_NUMERIC ){
aff = SQLITE_AFF_REAL;
}else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
&& aff==SQLITE_AFF_NUMERIC ){
aff = SQLITE_AFF_REAL;
}else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
&& aff==SQLITE_AFF_NUMERIC ){
aff = SQLITE_AFF_REAL;
#endif
}else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
aff = SQLITE_AFF_INTEGER;
break;
}
}
/* If pCol is not NULL, store an estimate of the field size. The
** estimate is scaled so that the size of an integer is 1. */
if( pCol ){
int v = 0; /* default size is approx 4 bytes */
if( aff<SQLITE_AFF_NUMERIC ){
if( zChar ){
while( zChar[0] ){
if( sqlite3Isdigit(zChar[0]) ){
/* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
sqlite3GetInt32(zChar, &v);
break;
}
zChar++;
}
}else{
v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
}
}
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( v>=sqlite3GlobalConfig.szSorterRef ){
pCol->colFlags |= COLFLAG_SORTERREF;
}
#endif
v = v/4 + 1;
if( v>255 ) v = 255;
pCol->szEst = v;
}
return aff;
}
/*
** The expression is the default value for the most recently added column
** of the table currently under construction.
**
** Default value expressions must be constant. Raise an exception if this
** is not the case.
**
** This routine is called by the parser while in the middle of
** parsing a CREATE TABLE statement.
*/
void sqlite3AddDefaultValue(
Parse *pParse, /* Parsing context */
Expr *pExpr, /* The parsed expression of the default value */
const char *zStart, /* Start of the default value text */
const char *zEnd /* First character past end of defaut value text */
){
Table *p;
Column *pCol;
sqlite3 *db = pParse->db;
p = pParse->pNewTable;
if( p!=0 ){
pCol = &(p->aCol[p->nCol-1]);
if( !sqlite3ExprIsConstantOrFunction(pExpr, db->init.busy) ){
sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
pCol->zName);
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
}else if( pCol->colFlags & COLFLAG_GENERATED ){
testcase( pCol->colFlags & COLFLAG_VIRTUAL );
testcase( pCol->colFlags & COLFLAG_STORED );
sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column");
#endif
}else{
/* A copy of pExpr is used instead of the original, as pExpr contains
** tokens that point to volatile memory.
*/
Expr x;
sqlite3ExprDelete(db, pCol->pDflt);
memset(&x, 0, sizeof(x));
x.op = TK_SPAN;
x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
x.pLeft = pExpr;
x.flags = EP_Skip;
pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
sqlite3DbFree(db, x.u.zToken);
}
}
if( IN_RENAME_OBJECT ){
sqlite3RenameExprUnmap(pParse, pExpr);
}
sqlite3ExprDelete(db, pExpr);
}
/*
** Backwards Compatibility Hack:
**
** Historical versions of SQLite accepted strings as column names in
** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
**
** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
**
** This is goofy. But to preserve backwards compatibility we continue to
** accept it. This routine does the necessary conversion. It converts
** the expression given in its argument from a TK_STRING into a TK_ID
** if the expression is just a TK_STRING with an optional COLLATE clause.
** If the expression is anything other than TK_STRING, the expression is
** unchanged.
*/
static void sqlite3StringToId(Expr *p){
if( p->op==TK_STRING ){
p->op = TK_ID;
}else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
p->pLeft->op = TK_ID;
}
}
/*
** Tag the given column as being part of the PRIMARY KEY
*/
static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){
pCol->colFlags |= COLFLAG_PRIMKEY;
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
if( pCol->colFlags & COLFLAG_GENERATED ){
testcase( pCol->colFlags & COLFLAG_VIRTUAL );
testcase( pCol->colFlags & COLFLAG_STORED );
sqlite3ErrorMsg(pParse,
"generated columns cannot be part of the PRIMARY KEY");
}
#endif
}
/*
** Designate the PRIMARY KEY for the table. pList is a list of names
** of columns that form the primary key. If pList is NULL, then the
** most recently added column of the table is the primary key.
**
** A table can have at most one primary key. If the table already has
** a primary key (and this is the second primary key) then create an
** error.
**
** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
** then we will try to use that column as the rowid. Set the Table.iPKey
** field of the table under construction to be the index of the
** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
** no INTEGER PRIMARY KEY.
**
** If the key is not an INTEGER PRIMARY KEY, then create a unique
** index for the key. No index is created for INTEGER PRIMARY KEYs.
*/
void sqlite3AddPrimaryKey(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List of field names to be indexed */
int onError, /* What to do with a uniqueness conflict */
int autoInc, /* True if the AUTOINCREMENT keyword is present */
int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
){
Table *pTab = pParse->pNewTable;
Column *pCol = 0;
int iCol = -1, i;
int nTerm;
if( pTab==0 ) goto primary_key_exit;
if( pTab->tabFlags & TF_HasPrimaryKey ){
sqlite3ErrorMsg(pParse,
"table \"%s\" has more than one primary key", pTab->zName);
goto primary_key_exit;
}
pTab->tabFlags |= TF_HasPrimaryKey;
if( pList==0 ){
iCol = pTab->nCol - 1;
pCol = &pTab->aCol[iCol];
makeColumnPartOfPrimaryKey(pParse, pCol);
nTerm = 1;
}else{
nTerm = pList->nExpr;
for(i=0; i<nTerm; i++){
Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
assert( pCExpr!=0 );
sqlite3StringToId(pCExpr);
if( pCExpr->op==TK_ID ){
const char *zCName = pCExpr->u.zToken;
for(iCol=0; iCol<pTab->nCol; iCol++){
if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
pCol = &pTab->aCol[iCol];
makeColumnPartOfPrimaryKey(pParse, pCol);
break;
}
}
}
}
}
if( nTerm==1
&& pCol
&& sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
&& sortOrder!=SQLITE_SO_DESC
){
if( IN_RENAME_OBJECT && pList ){
Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
}
pTab->iPKey = iCol;
pTab->keyConf = (u8)onError;
assert( autoInc==0 || autoInc==1 );
pTab->tabFlags |= autoInc*TF_Autoincrement;
if( pList ) pParse->iPkSortOrder = pList->a[0].sortFlags;
}else if( autoInc ){
#ifndef SQLITE_OMIT_AUTOINCREMENT
sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
"INTEGER PRIMARY KEY");
#endif
}else{
sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
pList = 0;
}
primary_key_exit:
sqlite3ExprListDelete(pParse->db, pList);
return;
}
/*
** Add a new CHECK constraint to the table currently under construction.
*/
void sqlite3AddCheckConstraint(
Parse *pParse, /* Parsing context */
Expr *pCheckExpr /* The check expression */
){
#ifndef SQLITE_OMIT_CHECK
Table *pTab = pParse->pNewTable;
sqlite3 *db = pParse->db;
if( pTab && !IN_DECLARE_VTAB
&& !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
){
pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
if( pParse->constraintName.n ){
sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
}
}else
#endif
{
sqlite3ExprDelete(pParse->db, pCheckExpr);
}
}
/*
** Set the collation function of the most recently parsed table column
** to the CollSeq given.
*/
void sqlite3AddCollateType(Parse *pParse, Token *pToken){
Table *p;
int i;
char *zColl; /* Dequoted name of collation sequence */
sqlite3 *db;
if( (p = pParse->pNewTable)==0 ) return;
i = p->nCol-1;
db = pParse->db;
zColl = sqlite3NameFromToken(db, pToken);
if( !zColl ) return;
if( sqlite3LocateCollSeq(pParse, zColl) ){
Index *pIdx;
sqlite3DbFree(db, p->aCol[i].zColl);
p->aCol[i].zColl = zColl;
/* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
** then an index may have been created on this column before the
** collation type was added. Correct this if it is the case.
*/
for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
assert( pIdx->nKeyCol==1 );
if( pIdx->aiColumn[0]==i ){
pIdx->azColl[0] = p->aCol[i].zColl;
}
}
}else{
sqlite3DbFree(db, zColl);
}
}
/* Change the most recently parsed column to be a GENERATED ALWAYS AS
** column.
*/
void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
u8 eType = COLFLAG_VIRTUAL;
Table *pTab = pParse->pNewTable;
Column *pCol;
if( pTab==0 ){
/* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
goto generated_done;
}
pCol = &(pTab->aCol[pTab->nCol-1]);
if( IN_DECLARE_VTAB ){
sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns");
goto generated_done;
}
if( pCol->pDflt ) goto generated_error;
if( pType ){
if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
/* no-op */
}else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
eType = COLFLAG_STORED;
}else{
goto generated_error;
}
}
if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
pCol->colFlags |= eType;
assert( TF_HasVirtual==COLFLAG_VIRTUAL );
assert( TF_HasStored==COLFLAG_STORED );
pTab->tabFlags |= eType;
if( pCol->colFlags & COLFLAG_PRIMKEY ){
makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */
}
pCol->pDflt = pExpr;
pExpr = 0;
goto generated_done;
generated_error:
sqlite3ErrorMsg(pParse, "error in generated column \"%s\"",
pCol->zName);
generated_done:
sqlite3ExprDelete(pParse->db, pExpr);
#else
/* Throw and error for the GENERATED ALWAYS AS clause if the
** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
sqlite3ErrorMsg(pParse, "generated columns not supported");
sqlite3ExprDelete(pParse->db, pExpr);
#endif
}
/*
** Generate code that will increment the schema cookie.
**
** The schema cookie is used to determine when the schema for the
** database changes. After each schema change, the cookie value
** changes. When a process first reads the schema it records the
** cookie. Thereafter, whenever it goes to access the database,
** it checks the cookie to make sure the schema has not changed
** since it was last read.
**
** This plan is not completely bullet-proof. It is possible for
** the schema to change multiple times and for the cookie to be
** set back to prior value. But schema changes are infrequent
** and the probability of hitting the same cookie value is only
** 1 chance in 2^32. So we're safe enough.
**
** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
** the schema-version whenever the schema changes.
*/
void sqlite3ChangeCookie(Parse *pParse, int iDb){
sqlite3 *db = pParse->db;
Vdbe *v = pParse->pVdbe;
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
(int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
}
/*
** Measure the number of characters needed to output the given
** identifier. The number returned includes any quotes used
** but does not include the null terminator.
**
** The estimate is conservative. It might be larger that what is
** really needed.
*/
static int identLength(const char *z){
int n;
for(n=0; *z; n++, z++){
if( *z=='"' ){ n++; }
}
return n + 2;
}
/*
** The first parameter is a pointer to an output buffer. The second
** parameter is a pointer to an integer that contains the offset at
** which to write into the output buffer. This function copies the
** nul-terminated string pointed to by the third parameter, zSignedIdent,
** to the specified offset in the buffer and updates *pIdx to refer
** to the first byte after the last byte written before returning.
**
** If the string zSignedIdent consists entirely of alpha-numeric
** characters, does not begin with a digit and is not an SQL keyword,
** then it is copied to the output buffer exactly as it is. Otherwise,
** it is quoted using double-quotes.
*/
static void identPut(char *z, int *pIdx, char *zSignedIdent){
unsigned char *zIdent = (unsigned char*)zSignedIdent;
int i, j, needQuote;
i = *pIdx;
for(j=0; zIdent[j]; j++){
if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
}
needQuote = sqlite3Isdigit(zIdent[0])
|| sqlite3KeywordCode(zIdent, j)!=TK_ID
|| zIdent[j]!=0
|| j==0;
if( needQuote ) z[i++] = '"';
for(j=0; zIdent[j]; j++){
z[i++] = zIdent[j];
if( zIdent[j]=='"' ) z[i++] = '"';
}
if( needQuote ) z[i++] = '"';
z[i] = 0;
*pIdx = i;
}
/*
** Generate a CREATE TABLE statement appropriate for the given
** table. Memory to hold the text of the statement is obtained
** from sqliteMalloc() and must be freed by the calling function.
*/
static char *createTableStmt(sqlite3 *db, Table *p){
int i, k, n;
char *zStmt;
char *zSep, *zSep2, *zEnd;
Column *pCol;
n = 0;
for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
n += identLength(pCol->zName) + 5;
}
n += identLength(p->zName);
if( n<50 ){
zSep = "";
zSep2 = ",";
zEnd = ")";
}else{
zSep = "\n ";
zSep2 = ",\n ";
zEnd = "\n)";
}
n += 35 + 6*p->nCol;
zStmt = sqlite3DbMallocRaw(0, n);
if( zStmt==0 ){
sqlite3OomFault(db);
return 0;
}
sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
k = sqlite3Strlen30(zStmt);
identPut(zStmt, &k, p->zName);
zStmt[k++] = '(';
for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
static const char * const azType[] = {
/* SQLITE_AFF_BLOB */ "",
/* SQLITE_AFF_TEXT */ " TEXT",
/* SQLITE_AFF_NUMERIC */ " NUM",
/* SQLITE_AFF_INTEGER */ " INT",
/* SQLITE_AFF_REAL */ " REAL"
};
int len;
const char *zType;
sqlite3_snprintf(n-k, &zStmt[k], zSep);
k += sqlite3Strlen30(&zStmt[k]);
zSep = zSep2;
identPut(zStmt, &k, pCol->zName);
assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
testcase( pCol->affinity==SQLITE_AFF_BLOB );
testcase( pCol->affinity==SQLITE_AFF_TEXT );
testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
testcase( pCol->affinity==SQLITE_AFF_INTEGER );
testcase( pCol->affinity==SQLITE_AFF_REAL );
zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
len = sqlite3Strlen30(zType);
assert( pCol->affinity==SQLITE_AFF_BLOB
|| pCol->affinity==sqlite3AffinityType(zType, 0) );
memcpy(&zStmt[k], zType, len);
k += len;
assert( k<=n );
}
sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
return zStmt;
}
/*
** Resize an Index object to hold N columns total. Return SQLITE_OK
** on success and SQLITE_NOMEM on an OOM error.
*/
static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
char *zExtra;
int nByte;
if( pIdx->nColumn>=N ) return SQLITE_OK;
assert( pIdx->isResized==0 );
nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
zExtra = sqlite3DbMallocZero(db, nByte);
if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
pIdx->azColl = (const char**)zExtra;
zExtra += sizeof(char*)*N;
memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
pIdx->aiColumn = (i16*)zExtra;
zExtra += sizeof(i16)*N;
memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
pIdx->aSortOrder = (u8*)zExtra;
pIdx->nColumn = N;
pIdx->isResized = 1;
return SQLITE_OK;
}
/*
** Estimate the total row width for a table.
*/
static void estimateTableWidth(Table *pTab){
unsigned wTable = 0;
const Column *pTabCol;
int i;
for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
wTable += pTabCol->szEst;
}
if( pTab->iPKey<0 ) wTable++;
pTab->szTabRow = sqlite3LogEst(wTable*4);
}
/*
** Estimate the average size of a row for an index.
*/
static void estimateIndexWidth(Index *pIdx){
unsigned wIndex = 0;
int i;
const Column *aCol = pIdx->pTable->aCol;
for(i=0; i<pIdx->nColumn; i++){
i16 x = pIdx->aiColumn[i];
assert( x<pIdx->pTable->nCol );
wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
}
pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
}
/* Return true if column number x is any of the first nCol entries of aiCol[].
** This is used to determine if the column number x appears in any of the
** first nCol entries of an index.
*/
static int hasColumn(const i16 *aiCol, int nCol, int x){
while( nCol-- > 0 ){
assert( aiCol[0]>=0 );
if( x==*(aiCol++) ){
return 1;
}
}
return 0;
}
/*
** Return true if any of the first nKey entries of index pIdx exactly
** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID
** PRIMARY KEY index. pIdx is an index on the same table. pIdx may
** or may not be the same index as pPk.
**
** The first nKey entries of pIdx are guaranteed to be ordinary columns,
** not a rowid or expression.
**
** This routine differs from hasColumn() in that both the column and the
** collating sequence must match for this routine, but for hasColumn() only
** the column name must match.
*/
static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
int i, j;
assert( nKey<=pIdx->nColumn );
assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
assert( pPk->pTable->tabFlags & TF_WithoutRowid );
assert( pPk->pTable==pIdx->pTable );
testcase( pPk==pIdx );
j = pPk->aiColumn[iCol];
assert( j!=XN_ROWID && j!=XN_EXPR );
for(i=0; i<nKey; i++){
assert( pIdx->aiColumn[i]>=0 || j>=0 );
if( pIdx->aiColumn[i]==j
&& sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
){
return 1;
}
}
return 0;
}
/* Recompute the colNotIdxed field of the Index.
**
** colNotIdxed is a bitmask that has a 0 bit representing each indexed
** columns that are within the first 63 columns of the table. The
** high-order bit of colNotIdxed is always 1. All unindexed columns
** of the table have a 1.
**
** 2019-10-24: For the purpose of this computation, virtual columns are
** not considered to be covered by the index, even if they are in the
** index, because we do not trust the logic in whereIndexExprTrans() to be
** able to find all instances of a reference to the indexed table column
** and convert them into references to the index. Hence we always want
** the actual table at hand in order to recompute the virtual column, if
** necessary.
**
** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
** to determine if the index is covering index.
*/
static void recomputeColumnsNotIndexed(Index *pIdx){
Bitmask m = 0;
int j;
Table *pTab = pIdx->pTable;
for(j=pIdx->nColumn-1; j>=0; j--){
int x = pIdx->aiColumn[j];
if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
testcase( x==BMS-1 );
testcase( x==BMS-2 );
if( x<BMS-1 ) m |= MASKBIT(x);
}
}
pIdx->colNotIdxed = ~m;
assert( (pIdx->colNotIdxed>>63)==1 );
}
/*
** This routine runs at the end of parsing a CREATE TABLE statement that
** has a WITHOUT ROWID clause. The job of this routine is to convert both
** internal schema data structures and the generated VDBE code so that they
** are appropriate for a WITHOUT ROWID table instead of a rowid table.
** Changes include:
**
** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
** into BTREE_BLOBKEY.
** (3) Bypass the creation of the sqlite_master table entry
** for the PRIMARY KEY as the primary key index is now
** identified by the sqlite_master table entry of the table itself.
** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
** schema to the rootpage from the main table.
** (5) Add all table columns to the PRIMARY KEY Index object
** so that the PRIMARY KEY is a covering index. The surplus
** columns are part of KeyInfo.nAllField and are not used for
** sorting or lookup or uniqueness checks.
** (6) Replace the rowid tail on all automatically generated UNIQUE
** indices with the PRIMARY KEY columns.
**
** For virtual tables, only (1) is performed.
*/
static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
Index *pIdx;
Index *pPk;
int nPk;
int nExtra;
int i, j;
sqlite3 *db = pParse->db;
Vdbe *v = pParse->pVdbe;
/* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
*/
if( !db->init.imposterTable ){
for(i=0; i<pTab->nCol; i++){
if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
pTab->aCol[i].notNull = OE_Abort;
}
}
pTab->tabFlags |= TF_HasNotNull;
}
/* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
** into BTREE_BLOBKEY.
*/
if( pParse->addrCrTab ){
assert( v );
sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
}
/* Locate the PRIMARY KEY index. Or, if this table was originally
** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
*/
if( pTab->iPKey>=0 ){
ExprList *pList;
Token ipkToken;
sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
pList = sqlite3ExprListAppend(pParse, 0,
sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
if( pList==0 ) return;
if( IN_RENAME_OBJECT ){
sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
}
pList->a[0].sortFlags = pParse->iPkSortOrder;
assert( pParse->pNewTable==pTab );
pTab->iPKey = -1;
sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
SQLITE_IDXTYPE_PRIMARYKEY);
if( db->mallocFailed || pParse->nErr ) return;
pPk = sqlite3PrimaryKeyIndex(pTab);
assert( pPk->nKeyCol==1 );
}else{
pPk = sqlite3PrimaryKeyIndex(pTab);
assert( pPk!=0 );
/*
** Remove all redundant columns from the PRIMARY KEY. For example, change
** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
** code assumes the PRIMARY KEY contains no repeated columns.
*/
for(i=j=1; i<pPk->nKeyCol; i++){
if( isDupColumn(pPk, j, pPk, i) ){
pPk->nColumn--;
}else{
testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
pPk->azColl[j] = pPk->azColl[i];
pPk->aSortOrder[j] = pPk->aSortOrder[i];
pPk->aiColumn[j++] = pPk->aiColumn[i];
}
}
pPk->nKeyCol = j;
}
assert( pPk!=0 );
pPk->isCovering = 1;
if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
nPk = pPk->nColumn = pPk->nKeyCol;
/* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
** table entry. This is only required if currently generating VDBE
** code for a CREATE TABLE (not when parsing one as part of reading
** a database schema). */
if( v && pPk->tnum>0 ){
assert( db->init.busy==0 );
sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
}
/* The root page of the PRIMARY KEY is the table root page */
pPk->tnum = pTab->tnum;
/* Update the in-memory representation of all UNIQUE indices by converting
** the final rowid column into one or more columns of the PRIMARY KEY.
*/
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
int n;
if( IsPrimaryKeyIndex(pIdx) ) continue;
for(i=n=0; i<nPk; i++){
if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
n++;
}
}
if( n==0 ){
/* This index is a superset of the primary key */
pIdx->nColumn = pIdx->nKeyCol;
continue;
}
if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
pIdx->aiColumn[j] = pPk->aiColumn[i];
pIdx->azColl[j] = pPk->azColl[i];
if( pPk->aSortOrder[i] ){
/* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */
pIdx->bAscKeyBug = 1;
}
j++;
}
}
assert( pIdx->nColumn>=pIdx->nKeyCol+n );
assert( pIdx->nColumn>=j );
}
/* Add all table columns to the PRIMARY KEY index
*/
nExtra = 0;
for(i=0; i<pTab->nCol; i++){
if( !hasColumn(pPk->aiColumn, nPk, i)
&& (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
}
if( resizeIndexObject(db, pPk, nPk+nExtra) ) return;
for(i=0, j=nPk; i<pTab->nCol; i++){
if( !hasColumn(pPk->aiColumn, j, i)
&& (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
){
assert( j<pPk->nColumn );
pPk->aiColumn[j] = i;
pPk->azColl[j] = sqlite3StrBINARY;
j++;
}
}
assert( pPk->nColumn==j );
assert( pTab->nNVCol<=j );
recomputeColumnsNotIndexed(pPk);
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
/*
** Return true if zName is a shadow table name in the current database
** connection.
**
** zName is temporarily modified while this routine is running, but is
** restored to its original value prior to this routine returning.
*/
int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
char *zTail; /* Pointer to the last "_" in zName */
Table *pTab; /* Table that zName is a shadow of */
Module *pMod; /* Module for the virtual table */
zTail = strrchr(zName, '_');
if( zTail==0 ) return 0;
*zTail = 0;
pTab = sqlite3FindTable(db, zName, 0);
*zTail = '_';
if( pTab==0 ) return 0;
if( !IsVirtual(pTab) ) return 0;
pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]);
if( pMod==0 ) return 0;
if( pMod->pModule->iVersion<3 ) return 0;
if( pMod->pModule->xShadowName==0 ) return 0;
return pMod->pModule->xShadowName(zTail+1);
}
#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
/*
** This routine is called to report the final ")" that terminates
** a CREATE TABLE statement.
**
** The table structure that other action routines have been building
** is added to the internal hash tables, assuming no errors have
** occurred.
**
** An entry for the table is made in the master table on disk, unless
** this is a temporary table or db->init.busy==1. When db->init.busy==1
** it means we are reading the sqlite_master table because we just
** connected to the database or because the sqlite_master table has
** recently changed, so the entry for this table already exists in
** the sqlite_master table. We do not want to create it again.
**
** If the pSelect argument is not NULL, it means that this routine
** was called to create a table generated from a
** "CREATE TABLE ... AS SELECT ..." statement. The column names of
** the new table will match the result set of the SELECT.
*/
void sqlite3EndTable(
Parse *pParse, /* Parse context */
Token *pCons, /* The ',' token after the last column defn. */
Token *pEnd, /* The ')' before options in the CREATE TABLE */
u8 tabOpts, /* Extra table options. Usually 0. */
Select *pSelect /* Select from a "CREATE ... AS SELECT" */
){
Table *p; /* The new table */
sqlite3 *db = pParse->db; /* The database connection */
int iDb; /* Database in which the table lives */
Index *pIdx; /* An implied index of the table */
if( pEnd==0 && pSelect==0 ){
return;
}
assert( !db->mallocFailed );
p = pParse->pNewTable;
if( p==0 ) return;
if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
p->tabFlags |= TF_Shadow;
}
/* If the db->init.busy is 1 it means we are reading the SQL off the
** "sqlite_master" or "sqlite_temp_master" table on the disk.
** So do not write to the disk again. Extract the root page number
** for the table from the db->init.newTnum field. (The page number
** should have been put there by the sqliteOpenCb routine.)
**
** If the root page number is 1, that means this is the sqlite_master
** table itself. So mark it read-only.
*/
if( db->init.busy ){
if( pSelect ){
sqlite3ErrorMsg(pParse, "");
return;
}
p->tnum = db->init.newTnum;
if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
}
assert( (p->tabFlags & TF_HasPrimaryKey)==0
|| p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
assert( (p->tabFlags & TF_HasPrimaryKey)!=0
|| (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
/* Special processing for WITHOUT ROWID Tables */
if( tabOpts & TF_WithoutRowid ){
if( (p->tabFlags & TF_Autoincrement) ){
sqlite3ErrorMsg(pParse,
"AUTOINCREMENT not allowed on WITHOUT ROWID tables");
return;
}
if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
return;
}
p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
convertToWithoutRowidTable(pParse, p);
}
iDb = sqlite3SchemaToIndex(db, p->pSchema);
#ifndef SQLITE_OMIT_CHECK
/* Resolve names in all CHECK constraint expressions.
*/
if( p->pCheck ){
sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
}
#endif /* !defined(SQLITE_OMIT_CHECK) */
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
if( p->tabFlags & TF_HasGenerated ){
int ii, nNG = 0;
testcase( p->tabFlags & TF_HasVirtual );
testcase( p->tabFlags & TF_HasStored );
for(ii=0; ii<p->nCol; ii++){
u32 colFlags = p->aCol[ii].colFlags;
if( (colFlags & COLFLAG_GENERATED)!=0 ){
testcase( colFlags & COLFLAG_VIRTUAL );
testcase( colFlags & COLFLAG_STORED );
sqlite3ResolveSelfReference(pParse, p, NC_GenCol,
p->aCol[ii].pDflt, 0);
}else{
nNG++;
}
}
if( nNG==0 ){
sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
return;
}
}
#endif
/* Estimate the average row size for the table and for all implied indices */
estimateTableWidth(p);
for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
estimateIndexWidth(pIdx);
}
/* If not initializing, then create a record for the new table
** in the SQLITE_MASTER table of the database.
**
** If this is a TEMPORARY table, write the entry into the auxiliary
** file instead of into the main database file.
*/
if( !db->init.busy ){
int n;
Vdbe *v;
char *zType; /* "view" or "table" */
char *zType2; /* "VIEW" or "TABLE" */
char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
v = sqlite3GetVdbe(pParse);
if( NEVER(v==0) ) return;
sqlite3VdbeAddOp1(v, OP_Close, 0);
/*
** Initialize zType for the new view or table.
*/
if( p->pSelect==0 ){
/* A regular table */
zType = "table";
zType2 = "TABLE";
#ifndef SQLITE_OMIT_VIEW
}else{
/* A view */
zType = "view";
zType2 = "VIEW";
#endif
}
/* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
** statement to populate the new table. The root-page number for the
** new table is in register pParse->regRoot.
**
** Once the SELECT has been coded by sqlite3Select(), it is in a
** suitable state to query for the column names and types to be used
** by the new table.
**
** A shared-cache write-lock is not required to write to the new table,
** as a schema-lock must have already been obtained to create it. Since
** a schema-lock excludes all other database users, the write-lock would
** be redundant.
*/
if( pSelect ){
SelectDest dest; /* Where the SELECT should store results */
int regYield; /* Register holding co-routine entry-point */
int addrTop; /* Top of the co-routine */
int regRec; /* A record to be insert into the new table */
int regRowid; /* Rowid of the next row to insert */
int addrInsLoop; /* Top of the loop for inserting rows */
Table *pSelTab; /* A table that describes the SELECT results */
regYield = ++pParse->nMem;
regRec = ++pParse->nMem;
regRowid = ++pParse->nMem;
assert(pParse->nTab==1);
sqlite3MayAbort(pParse);
sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
pParse->nTab = 2;
addrTop = sqlite3VdbeCurrentAddr(v) + 1;
sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
if( pParse->nErr ) return;
pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB);
if( pSelTab==0 ) return;
assert( p->aCol==0 );
p->nCol = p->nNVCol = pSelTab->nCol;
p->aCol = pSelTab->aCol;
pSelTab->nCol = 0;
pSelTab->aCol = 0;
sqlite3DeleteTable(db, pSelTab);
sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
sqlite3Select(pParse, pSelect, &dest);
if( pParse->nErr ) return;
sqlite3VdbeEndCoroutine(v, regYield);
sqlite3VdbeJumpHere(v, addrTop - 1);
addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
sqlite3TableAffinity(v, p, 0);
sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
sqlite3VdbeGoto(v, addrInsLoop);
sqlite3VdbeJumpHere(v, addrInsLoop);
sqlite3VdbeAddOp1(v, OP_Close, 1);
}
/* Compute the complete text of the CREATE statement */
if( pSelect ){
zStmt = createTableStmt(db, p);
}else{
Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
n = (int)(pEnd2->z - pParse->sNameToken.z);
if( pEnd2->z[0]!=';' ) n += pEnd2->n;
zStmt = sqlite3MPrintf(db,
"CREATE %s %.*s", zType2, n, pParse->sNameToken.z
);
}
/* A slot for the record has already been allocated in the
** SQLITE_MASTER table. We just need to update that slot with all
** the information we've collected.
*/
sqlite3NestedParse(pParse,
"UPDATE %Q.%s "
"SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
"WHERE rowid=#%d",
db->aDb[iDb].zDbSName, MASTER_NAME,
zType,
p->zName,
p->zName,
pParse->regRoot,
zStmt,
pParse->regRowid
);
sqlite3DbFree(db, zStmt);
sqlite3ChangeCookie(pParse, iDb);
#ifndef SQLITE_OMIT_AUTOINCREMENT
/* Check to see if we need to create an sqlite_sequence table for
** keeping track of autoincrement keys.
*/
if( (p->tabFlags & TF_Autoincrement)!=0 ){
Db *pDb = &db->aDb[iDb];
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
if( pDb->pSchema->pSeqTab==0 ){
sqlite3NestedParse(pParse,
"CREATE TABLE %Q.sqlite_sequence(name,seq)",
pDb->zDbSName
);
}
}
#endif
/* Reparse everything to update our internal data structures */
sqlite3VdbeAddParseSchemaOp(v, iDb,
sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
}
/* Add the table to the in-memory representation of the database.
*/
if( db->init.busy ){
Table *pOld;
Schema *pSchema = p->pSchema;
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
if( pOld ){
assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
sqlite3OomFault(db);
return;
}
pParse->pNewTable = 0;
db->mDbFlags |= DBFLAG_SchemaChange;
#ifndef SQLITE_OMIT_ALTERTABLE
if( !p->pSelect ){
const char *zName = (const char *)pParse->sNameToken.z;
int nName;
assert( !pSelect && pCons && pEnd );
if( pCons->z==0 ){
pCons = pEnd;
}
nName = (int)((const char *)pCons->z - zName);
p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
}
#endif
}
}
#ifndef SQLITE_OMIT_VIEW
/*
** The parser calls this routine in order to create a new VIEW
*/
void sqlite3CreateView(
Parse *pParse, /* The parsing context */
Token *pBegin, /* The CREATE token that begins the statement */
Token *pName1, /* The token that holds the name of the view */
Token *pName2, /* The token that holds the name of the view */
ExprList *pCNames, /* Optional list of view column names */
Select *pSelect, /* A SELECT statement that will become the new view */
int isTemp, /* TRUE for a TEMPORARY view */
int noErr /* Suppress error messages if VIEW already exists */
){
Table *p;
int n;
const char *z;
Token sEnd;
DbFixer sFix;
Token *pName = 0;
int iDb;
sqlite3 *db = pParse->db;
if( pParse->nVar>0 ){
sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
goto create_view_fail;
}
sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
p = pParse->pNewTable;
if( p==0 || pParse->nErr ) goto create_view_fail;
sqlite3TwoPartName(pParse, pName1, pName2, &pName);
iDb = sqlite3SchemaToIndex(db, p->pSchema);
sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
/* Make a copy of the entire SELECT statement that defines the view.
** This will force all the Expr.token.z values to be dynamically
** allocated rather than point to the input string - which means that
** they will persist after the current sqlite3_exec() call returns.
*/
pSelect->selFlags |= SF_View;
if( IN_RENAME_OBJECT ){
p->pSelect = pSelect;
pSelect = 0;
}else{
p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
}
p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
if( db->mallocFailed ) goto create_view_fail;
/* Locate the end of the CREATE VIEW statement. Make sEnd point to
** the end.
*/
sEnd = pParse->sLastToken;
assert( sEnd.z[0]!=0 || sEnd.n==0 );
if( sEnd.z[0]!=';' ){
sEnd.z += sEnd.n;
}
sEnd.n = 0;
n = (int)(sEnd.z - pBegin->z);
assert( n>0 );
z = pBegin->z;
while( sqlite3Isspace(z[n-1]) ){ n--; }
sEnd.z = &z[n-1];
sEnd.n = 1;
/* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
create_view_fail:
sqlite3SelectDelete(db, pSelect);
if( IN_RENAME_OBJECT ){
sqlite3RenameExprlistUnmap(pParse, pCNames);
}
sqlite3ExprListDelete(db, pCNames);
return;
}
#endif /* SQLITE_OMIT_VIEW */
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
/*
** The Table structure pTable is really a VIEW. Fill in the names of
** the columns of the view in the pTable structure. Return the number
** of errors. If an error is seen leave an error message in pParse->zErrMsg.
*/
int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
Table *pSelTab; /* A fake table from which we get the result set */
Select *pSel; /* Copy of the SELECT that implements the view */
int nErr = 0; /* Number of errors encountered */
int n; /* Temporarily holds the number of cursors assigned */
sqlite3 *db = pParse->db; /* Database connection for malloc errors */
#ifndef SQLITE_OMIT_VIRTUALTABLE
int rc;
#endif
#ifndef SQLITE_OMIT_AUTHORIZATION
sqlite3_xauth xAuth; /* Saved xAuth pointer */
#endif
assert( pTable );
#ifndef SQLITE_OMIT_VIRTUALTABLE
db->nSchemaLock++;
rc = sqlite3VtabCallConnect(pParse, pTable);
db->nSchemaLock--;
if( rc ){
return 1;
}
if( IsVirtual(pTable) ) return 0;
#endif
#ifndef SQLITE_OMIT_VIEW
/* A positive nCol means the columns names for this view are
** already known.
*/
if( pTable->nCol>0 ) return 0;
/* A negative nCol is a special marker meaning that we are currently
** trying to compute the column names. If we enter this routine with
** a negative nCol, it means two or more views form a loop, like this:
**
** CREATE VIEW one AS SELECT * FROM two;
** CREATE VIEW two AS SELECT * FROM one;
**
** Actually, the error above is now caught prior to reaching this point.
** But the following test is still important as it does come up
** in the following:
**
** CREATE TABLE main.ex1(a);
** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
** SELECT * FROM temp.ex1;
*/
if( pTable->nCol<0 ){
sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
return 1;
}
assert( pTable->nCol>=0 );
/* If we get this far, it means we need to compute the table names.
** Note that the call to sqlite3ResultSetOfSelect() will expand any
** "*" elements in the results set of the view and will assign cursors
** to the elements of the FROM clause. But we do not want these changes
** to be permanent. So the computation is done on a copy of the SELECT
** statement that defines the view.
*/
assert( pTable->pSelect );
pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
if( pSel ){
#ifndef SQLITE_OMIT_ALTERTABLE
u8 eParseMode = pParse->eParseMode;
pParse->eParseMode = PARSE_MODE_NORMAL;
#endif
n = pParse->nTab;
sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
pTable->nCol = -1;
DisableLookaside;
#ifndef SQLITE_OMIT_AUTHORIZATION
xAuth = db->xAuth;
db->xAuth = 0;
pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
db->xAuth = xAuth;
#else
pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
#endif
pParse->nTab = n;
if( pTable->pCheck ){
/* CREATE VIEW name(arglist) AS ...
** The names of the columns in the table are taken from
** arglist which is stored in pTable->pCheck. The pCheck field
** normally holds CHECK constraints on an ordinary table, but for
** a VIEW it holds the list of column names.
*/
sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
&pTable->nCol, &pTable->aCol);
if( db->mallocFailed==0
&& pParse->nErr==0
&& pTable->nCol==pSel->pEList->nExpr
){
sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel,
SQLITE_AFF_NONE);
}
}else if( pSelTab ){
/* CREATE VIEW name AS... without an argument list. Construct
** the column names from the SELECT statement that defines the view.
*/
assert( pTable->aCol==0 );
pTable->nCol = pSelTab->nCol;
pTable->aCol = pSelTab->aCol;
pSelTab->nCol = 0;
pSelTab->aCol = 0;
assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
}else{
pTable->nCol = 0;
nErr++;
}
pTable->nNVCol = pTable->nCol;
sqlite3DeleteTable(db, pSelTab);
sqlite3SelectDelete(db, pSel);
EnableLookaside;
#ifndef SQLITE_OMIT_ALTERTABLE
pParse->eParseMode = eParseMode;
#endif
} else {
nErr++;
}
pTable->pSchema->schemaFlags |= DB_UnresetViews;
if( db->mallocFailed ){
sqlite3DeleteColumnNames(db, pTable);
pTable->aCol = 0;
pTable->nCol = 0;
}
#endif /* SQLITE_OMIT_VIEW */
return nErr;
}
#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
#ifndef SQLITE_OMIT_VIEW
/*
** Clear the column names from every VIEW in database idx.
*/
static void sqliteViewResetAll(sqlite3 *db, int idx){
HashElem *i;
assert( sqlite3SchemaMutexHeld(db, idx, 0) );
if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
Table *pTab = sqliteHashData(i);
if( pTab->pSelect ){
sqlite3DeleteColumnNames(db, pTab);
pTab->aCol = 0;
pTab->nCol = 0;
}
}
DbClearProperty(db, idx, DB_UnresetViews);
}
#else
# define sqliteViewResetAll(A,B)
#endif /* SQLITE_OMIT_VIEW */
/*
** This function is called by the VDBE to adjust the internal schema
** used by SQLite when the btree layer moves a table root page. The
** root-page of a table or index in database iDb has changed from iFrom
** to iTo.
**
** Ticket #1728: The symbol table might still contain information
** on tables and/or indices that are the process of being deleted.
** If you are unlucky, one of those deleted indices or tables might
** have the same rootpage number as the real table or index that is
** being moved. So we cannot stop searching after the first match
** because the first match might be for one of the deleted indices
** or tables and not the table/index that is actually being moved.
** We must continue looping until all tables and indices with
** rootpage==iFrom have been converted to have a rootpage of iTo
** in order to be certain that we got the right one.
*/
#ifndef SQLITE_OMIT_AUTOVACUUM
void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
HashElem *pElem;
Hash *pHash;
Db *pDb;
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
pDb = &db->aDb[iDb];
pHash = &pDb->pSchema->tblHash;
for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
Table *pTab = sqliteHashData(pElem);
if( pTab->tnum==iFrom ){
pTab->tnum = iTo;
}
}
pHash = &pDb->pSchema->idxHash;
for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
Index *pIdx = sqliteHashData(pElem);
if( pIdx->tnum==iFrom ){
pIdx->tnum = iTo;
}
}
}
#endif
/*
** Write code to erase the table with root-page iTable from database iDb.
** Also write code to modify the sqlite_master table and internal schema
** if a root-page of another table is moved by the btree-layer whilst
** erasing iTable (this can happen with an auto-vacuum database).
*/
static void destroyRootPage(Parse *pParse, int iTable, int iDb){
Vdbe *v = sqlite3GetVdbe(pParse);
int r1 = sqlite3GetTempReg(pParse);
if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
sqlite3MayAbort(pParse);
#ifndef SQLITE_OMIT_AUTOVACUUM
/* OP_Destroy stores an in integer r1. If this integer
** is non-zero, then it is the root page number of a table moved to
** location iTable. The following code modifies the sqlite_master table to
** reflect this.
**
** The "#NNN" in the SQL is a special constant that means whatever value
** is in register NNN. See grammar rules associated with the TK_REGISTER
** token for additional information.
*/
sqlite3NestedParse(pParse,
"UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
#endif
sqlite3ReleaseTempReg(pParse, r1);
}
/*
** Write VDBE code to erase table pTab and all associated indices on disk.
** Code to update the sqlite_master tables and internal schema definitions
** in case a root-page belonging to another table is moved by the btree layer
** is also added (this can happen with an auto-vacuum database).
*/
static void destroyTable(Parse *pParse, Table *pTab){
/* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
** is not defined), then it is important to call OP_Destroy on the
** table and index root-pages in order, starting with the numerically
** largest root-page number. This guarantees that none of the root-pages
** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
** following were coded:
**
** OP_Destroy 4 0
** ...
** OP_Destroy 5 0
**
** and root page 5 happened to be the largest root-page number in the
** database, then root page 5 would be moved to page 4 by the
** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
** a free-list page.
*/
int iTab = pTab->tnum;
int iDestroyed = 0;
while( 1 ){
Index *pIdx;
int iLargest = 0;
if( iDestroyed==0 || iTab<iDestroyed ){
iLargest = iTab;
}
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
int iIdx = pIdx->tnum;
assert( pIdx->pSchema==pTab->pSchema );
if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
iLargest = iIdx;
}
}
if( iLargest==0 ){
return;
}else{
int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
assert( iDb>=0 && iDb<pParse->db->nDb );
destroyRootPage(pParse, iLargest, iDb);
iDestroyed = iLargest;
}
}
}
/*
** Remove entries from the sqlite_statN tables (for N in (1,2,3))
** after a DROP INDEX or DROP TABLE command.
*/
static void sqlite3ClearStatTables(
Parse *pParse, /* The parsing context */
int iDb, /* The database number */
const char *zType, /* "idx" or "tbl" */
const char *zName /* Name of index or table */
){
int i;
const char *zDbName = pParse->db->aDb[iDb].zDbSName;
for(i=1; i<=4; i++){
char zTab[24];
sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
sqlite3NestedParse(pParse,
"DELETE FROM %Q.%s WHERE %s=%Q",
zDbName, zTab, zType, zName
);
}
}
}
/*
** Generate code to drop a table.
*/
void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
Vdbe *v;
sqlite3 *db = pParse->db;
Trigger *pTrigger;
Db *pDb = &db->aDb[iDb];
v = sqlite3GetVdbe(pParse);
assert( v!=0 );
sqlite3BeginWriteOperation(pParse, 1, iDb);
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( IsVirtual(pTab) ){
sqlite3VdbeAddOp0(v, OP_VBegin);
}
#endif
/* Drop all triggers associated with the table being dropped. Code
** is generated to remove entries from sqlite_master and/or
** sqlite_temp_master if required.
*/
pTrigger = sqlite3TriggerList(pParse, pTab);
while( pTrigger ){
assert( pTrigger->pSchema==pTab->pSchema ||
pTrigger->pSchema==db->aDb[1].pSchema );
sqlite3DropTriggerPtr(pParse, pTrigger);
pTrigger = pTrigger->pNext;
}
#ifndef SQLITE_OMIT_AUTOINCREMENT
/* Remove any entries of the sqlite_sequence table associated with
** the table being dropped. This is done before the table is dropped
** at the btree level, in case the sqlite_sequence table needs to
** move as a result of the drop (can happen in auto-vacuum mode).
*/
if( pTab->tabFlags & TF_Autoincrement ){
sqlite3NestedParse(pParse,
"DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
pDb->zDbSName, pTab->zName
);
}
#endif
/* Drop all SQLITE_MASTER table and index entries that refer to the
** table. The program name loops through the master table and deletes
** every row that refers to a table of the same name as the one being
** dropped. Triggers are handled separately because a trigger can be
** created in the temp database that refers to a table in another
** database.
*/
sqlite3NestedParse(pParse,
"DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
pDb->zDbSName, MASTER_NAME, pTab->zName);
if( !isView && !IsVirtual(pTab) ){
destroyTable(pParse, pTab);
}
/* Remove the table entry from SQLite's internal schema and modify
** the schema cookie.
*/
if( IsVirtual(pTab) ){
sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
sqlite3MayAbort(pParse);
}
sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
sqlite3ChangeCookie(pParse, iDb);
sqliteViewResetAll(db, iDb);
}
/*
** Return TRUE if shadow tables should be read-only in the current
** context.
*/
int sqlite3ReadOnlyShadowTables(sqlite3 *db){
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( (db->flags & SQLITE_Defensive)!=0
&& db->pVtabCtx==0
&& db->nVdbeExec==0
){
return 1;
}
#endif
return 0;
}
/*
** Return true if it is not allowed to drop the given table
*/
static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){
if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
return 1;
}
if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
return 1;
}
return 0;
}
/*
** This routine is called to do the work of a DROP TABLE statement.
** pName is the name of the table to be dropped.
*/
void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
Table *pTab;
Vdbe *v;
sqlite3 *db = pParse->db;
int iDb;
if( db->mallocFailed ){
goto exit_drop_table;
}
assert( pParse->nErr==0 );
assert( pName->nSrc==1 );
if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
if( noErr ) db->suppressErr++;
assert( isView==0 || isView==LOCATE_VIEW );
pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
if( noErr ) db->suppressErr--;
if( pTab==0 ){
if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
goto exit_drop_table;
}
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
assert( iDb>=0 && iDb<db->nDb );
/* If pTab is a virtual table, call ViewGetColumnNames() to ensure
** it is initialized.
*/
if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
goto exit_drop_table;
}
#ifndef SQLITE_OMIT_AUTHORIZATION
{
int code;
const char *zTab = SCHEMA_TABLE(iDb);
const char *zDb = db->aDb[iDb].zDbSName;
const char *zArg2 = 0;
if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
goto exit_drop_table;
}
if( isView ){
if( !OMIT_TEMPDB && iDb==1 ){
code = SQLITE_DROP_TEMP_VIEW;
}else{
code = SQLITE_DROP_VIEW;
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
}else if( IsVirtual(pTab) ){
code = SQLITE_DROP_VTABLE;
zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
#endif
}else{
if( !OMIT_TEMPDB && iDb==1 ){
code = SQLITE_DROP_TEMP_TABLE;
}else{
code = SQLITE_DROP_TABLE;
}
}
if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
goto exit_drop_table;
}
if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
goto exit_drop_table;
}
}
#endif
if( tableMayNotBeDropped(db, pTab) ){
sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
goto exit_drop_table;
}
#ifndef SQLITE_OMIT_VIEW
/* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
** on a table.
*/
if( isView && pTab->pSelect==0 ){
sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
goto exit_drop_table;
}
if( !isView && pTab->pSelect ){
sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
goto exit_drop_table;
}
#endif
/* Generate code to remove the table from the master table
** on disk.
*/
v = sqlite3GetVdbe(pParse);
if( v ){
sqlite3BeginWriteOperation(pParse, 1, iDb);
if( !isView ){
sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
sqlite3FkDropTable(pParse, pName, pTab);
}
sqlite3CodeDropTable(pParse, pTab, iDb, isView);
}
exit_drop_table:
sqlite3SrcListDelete(db, pName);
}
/*
** This routine is called to create a new foreign key on the table
** currently under construction. pFromCol determines which columns
** in the current table point to the foreign key. If pFromCol==0 then
** connect the key to the last column inserted. pTo is the name of
** the table referred to (a.k.a the "parent" table). pToCol is a list
** of tables in the parent pTo table. flags contains all
** information about the conflict resolution algorithms specified
** in the ON DELETE, ON UPDATE and ON INSERT clauses.
**
** An FKey structure is created and added to the table currently
** under construction in the pParse->pNewTable field.
**
** The foreign key is set for IMMEDIATE processing. A subsequent call
** to sqlite3DeferForeignKey() might change this to DEFERRED.
*/
void sqlite3CreateForeignKey(
Parse *pParse, /* Parsing context */
ExprList *pFromCol, /* Columns in this table that point to other table */
Token *pTo, /* Name of the other table */
ExprList *pToCol, /* Columns in the other table */
int flags /* Conflict resolution algorithms. */
){
sqlite3 *db = pParse->db;
#ifndef SQLITE_OMIT_FOREIGN_KEY
FKey *pFKey = 0;
FKey *pNextTo;
Table *p = pParse->pNewTable;
int nByte;
int i;
int nCol;
char *z;
assert( pTo!=0 );
if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
if( pFromCol==0 ){
int iCol = p->nCol-1;
if( NEVER(iCol<0) ) goto fk_end;
if( pToCol && pToCol->nExpr!=1 ){
sqlite3ErrorMsg(pParse, "foreign key on %s"
" should reference only one column of table %T",
p->aCol[iCol].zName, pTo);
goto fk_end;
}
nCol = 1;
}else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
sqlite3ErrorMsg(pParse,
"number of columns in foreign key does not match the number of "
"columns in the referenced table");
goto fk_end;
}else{
nCol = pFromCol->nExpr;
}
nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
if( pToCol ){
for(i=0; i<pToCol->nExpr; i++){
nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
}
}
pFKey = sqlite3DbMallocZero(db, nByte );
if( pFKey==0 ){
goto fk_end;
}
pFKey->pFrom = p;
pFKey->pNextFrom = p->pFKey;
z = (char*)&pFKey->aCol[nCol];
pFKey->zTo = z;
if( IN_RENAME_OBJECT ){
sqlite3RenameTokenMap(pParse, (void*)z, pTo);
}
memcpy(z, pTo->z, pTo->n);
z[pTo->n] = 0;
sqlite3Dequote(z);
z += pTo->n+1;
pFKey->nCol = nCol;
if( pFromCol==0 ){
pFKey->aCol[0].iFrom = p->nCol-1;
}else{
for(i=0; i<nCol; i++){
int j;
for(j=0; j<p->nCol; j++){
if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
pFKey->aCol[i].iFrom = j;
break;
}
}
if( j>=p->nCol ){
sqlite3ErrorMsg(pParse,
"unknown column \"%s\" in foreign key definition",
pFromCol->a[i].zName);
goto fk_end;
}
if( IN_RENAME_OBJECT ){
sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zName);
}
}
}
if( pToCol ){
for(i=0; i<nCol; i++){
int n = sqlite3Strlen30(pToCol->a[i].zName);
pFKey->aCol[i].zCol = z;
if( IN_RENAME_OBJECT ){
sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zName);
}
memcpy(z, pToCol->a[i].zName, n);
z[n] = 0;
z += n+1;
}
}
pFKey->isDeferred = 0;
pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
pFKey->zTo, (void *)pFKey
);
if( pNextTo==pFKey ){
sqlite3OomFault(db);
goto fk_end;
}
if( pNextTo ){
assert( pNextTo->pPrevTo==0 );
pFKey->pNextTo = pNextTo;
pNextTo->pPrevTo = pFKey;
}
/* Link the foreign key to the table as the last step.
*/
p->pFKey = pFKey;
pFKey = 0;
fk_end:
sqlite3DbFree(db, pFKey);
#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
sqlite3ExprListDelete(db, pFromCol);
sqlite3ExprListDelete(db, pToCol);
}
/*
** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
** clause is seen as part of a foreign key definition. The isDeferred
** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
** The behavior of the most recently created foreign key is adjusted
** accordingly.
*/
void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
#ifndef SQLITE_OMIT_FOREIGN_KEY
Table *pTab;
FKey *pFKey;
if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
pFKey->isDeferred = (u8)isDeferred;
#endif
}
/*
** Generate code that will erase and refill index *pIdx. This is
** used to initialize a newly created index or to recompute the
** content of an index in response to a REINDEX command.
**
** if memRootPage is not negative, it means that the index is newly
** created. The register specified by memRootPage contains the
** root page number of the index. If memRootPage is negative, then
** the index already exists and must be cleared before being refilled and
** the root page number of the index is taken from pIndex->tnum.
*/
static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
Table *pTab = pIndex->pTable; /* The table that is indexed */
int iTab = pParse->nTab++; /* Btree cursor used for pTab */
int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
int iSorter; /* Cursor opened by OpenSorter (if in use) */
int addr1; /* Address of top of loop */
int addr2; /* Address to jump to for next iteration */
int tnum; /* Root page of index */
int iPartIdxLabel; /* Jump to this label to skip a row */
Vdbe *v; /* Generate code into this virtual machine */
KeyInfo *pKey; /* KeyInfo for index */
int regRecord; /* Register holding assembled index record */
sqlite3 *db = pParse->db; /* The database connection */
int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
#ifndef SQLITE_OMIT_AUTHORIZATION
if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
db->aDb[iDb].zDbSName ) ){
return;
}
#endif
/* Require a write-lock on the table to perform this operation */
sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
v = sqlite3GetVdbe(pParse);
if( v==0 ) return;
if( memRootPage>=0 ){
tnum = memRootPage;
}else{
tnum = pIndex->tnum;
}
pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
assert( pKey!=0 || db->mallocFailed || pParse->nErr );
/* Open the sorter cursor if we are to use one. */
iSorter = pParse->nTab++;
sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
sqlite3KeyInfoRef(pKey), P4_KEYINFO);
/* Open the table. Loop through all rows of the table, inserting index
** records into the sorter. */
sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
regRecord = sqlite3GetTempReg(pParse);
sqlite3MultiWrite(pParse);
sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
sqlite3VdbeJumpHere(v, addr1);
if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
(char *)pKey, P4_KEYINFO);
sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
if( IsUniqueIndex(pIndex) ){
int j2 = sqlite3VdbeGoto(v, 1);
addr2 = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeVerifyAbortable(v, OE_Abort);
sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
pIndex->nKeyCol); VdbeCoverage(v);
sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
sqlite3VdbeJumpHere(v, j2);
}else{
/* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
** abort. The exception is if one of the indexed expressions contains a
** user function that throws an exception when it is evaluated. But the
** overhead of adding a statement journal to a CREATE INDEX statement is
** very small (since most of the pages written do not contain content that
** needs to be restored if the statement aborts), so we call
** sqlite3MayAbort() for all CREATE INDEX statements. */
sqlite3MayAbort(pParse);
addr2 = sqlite3VdbeCurrentAddr(v);
}
sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
if( !pIndex->bAscKeyBug ){
/* This OP_SeekEnd opcode makes index insert for a REINDEX go much
** faster by avoiding unnecessary seeks. But the optimization does
** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
** with DESC primary keys, since those indexes have there keys in
** a different order from the main table.
** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
*/
sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
}
sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
sqlite3ReleaseTempReg(pParse, regRecord);
sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
sqlite3VdbeJumpHere(v, addr1);
sqlite3VdbeAddOp1(v, OP_Close, iTab);
sqlite3VdbeAddOp1(v, OP_Close, iIdx);
sqlite3VdbeAddOp1(v, OP_Close, iSorter);
}
/*
** Allocate heap space to hold an Index object with nCol columns.
**
** Increase the allocation size to provide an extra nExtra bytes
** of 8-byte aligned space after the Index object and return a
** pointer to this extra space in *ppExtra.
*/
Index *sqlite3AllocateIndexObject(
sqlite3 *db, /* Database connection */
i16 nCol, /* Total number of columns in the index */
int nExtra, /* Number of bytes of extra space to alloc */
char **ppExtra /* Pointer to the "extra" space */
){
Index *p; /* Allocated index object */
int nByte; /* Bytes of space for Index object + arrays */
nByte = ROUND8(sizeof(Index)) + /* Index structure */
ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
sizeof(i16)*nCol + /* Index.aiColumn */
sizeof(u8)*nCol); /* Index.aSortOrder */
p = sqlite3DbMallocZero(db, nByte + nExtra);
if( p ){
char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
p->aSortOrder = (u8*)pExtra;
p->nColumn = nCol;
p->nKeyCol = nCol - 1;
*ppExtra = ((char*)p) + nByte;
}
return p;
}
/*
** If expression list pList contains an expression that was parsed with
** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
** pParse and return non-zero. Otherwise, return zero.
*/
int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
if( pList ){
int i;
for(i=0; i<pList->nExpr; i++){
if( pList->a[i].bNulls ){
u8 sf = pList->a[i].sortFlags;
sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s",
(sf==0 || sf==3) ? "FIRST" : "LAST"
);
return 1;
}
}
}
return 0;
}
/*
** Create a new index for an SQL table. pName1.pName2 is the name of the index
** and pTblList is the name of the table that is to be indexed. Both will
** be NULL for a primary key or an index that is created to satisfy a
** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
** as the table to be indexed. pParse->pNewTable is a table that is
** currently being constructed by a CREATE TABLE statement.
**
** pList is a list of columns to be indexed. pList will be NULL if this
** is a primary key or unique-constraint on the most recent column added
** to the table currently under construction.
*/
void sqlite3CreateIndex(
Parse *pParse, /* All information about this parse */
Token *pName1, /* First part of index name. May be NULL */
Token *pName2, /* Second part of index name. May be NULL */
SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
ExprList *pList, /* A list of columns to be indexed */
int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
Token *pStart, /* The CREATE token that begins this statement */
Expr *pPIWhere, /* WHERE clause for partial indices */
int sortOrder, /* Sort order of primary key when pList==NULL */
int ifNotExist, /* Omit error if index already exists */
u8 idxType /* The index type */
){
Table *pTab = 0; /* Table to be indexed */
Index *pIndex = 0; /* The index to be created */
char *zName = 0; /* Name of the index */
int nName; /* Number of characters in zName */
int i, j;
DbFixer sFix; /* For assigning database names to pTable */
int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
sqlite3 *db = pParse->db;
Db *pDb; /* The specific table containing the indexed database */
int iDb; /* Index of the database that is being written */
Token *pName = 0; /* Unqualified name of the index to create */
struct ExprList_item *pListItem; /* For looping over pList */
int nExtra = 0; /* Space allocated for zExtra[] */
int nExtraCol; /* Number of extra columns needed */
char *zExtra = 0; /* Extra space after the Index object */
Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
if( db->mallocFailed || pParse->nErr>0 ){
goto exit_create_index;
}
if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
goto exit_create_index;
}
if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
goto exit_create_index;
}
if( sqlite3HasExplicitNulls(pParse, pList) ){
goto exit_create_index;
}
/*
** Find the table that is to be indexed. Return early if not found.
*/
if( pTblName!=0 ){
/* Use the two-part index name to determine the database
** to search for the table. 'Fix' the table name to this db
** before looking up the table.
*/
assert( pName1 && pName2 );
iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
if( iDb<0 ) goto exit_create_index;
assert( pName && pName->z );
#ifndef SQLITE_OMIT_TEMPDB
/* If the index name was unqualified, check if the table
** is a temp table. If so, set the database to 1. Do not do this
** if initialising a database schema.
*/
if( !db->init.busy ){
pTab = sqlite3SrcListLookup(pParse, pTblName);
if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
iDb = 1;
}
}
#endif
sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
if( sqlite3FixSrcList(&sFix, pTblName) ){
/* Because the parser constructs pTblName from a single identifier,
** sqlite3FixSrcList can never fail. */
assert(0);
}
pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
assert( db->mallocFailed==0 || pTab==0 );
if( pTab==0 ) goto exit_create_index;
if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
sqlite3ErrorMsg(pParse,
"cannot create a TEMP index on non-TEMP table \"%s\"",
pTab->zName);
goto exit_create_index;
}
if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
}else{
assert( pName==0 );
assert( pStart==0 );
pTab = pParse->pNewTable;
if( !pTab ) goto exit_create_index;
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
}
pDb = &db->aDb[iDb];
assert( pTab!=0 );
assert( pParse->nErr==0 );
if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
&& db->init.busy==0
&& pTblName!=0
#if SQLITE_USER_AUTHENTICATION
&& sqlite3UserAuthTable(pTab->zName)==0
#endif
#ifdef SQLITE_ALLOW_SQLITE_MASTER_INDEX
&& sqlite3StrICmp(&pTab->zName[7],"master")!=0
#endif
){
sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
goto exit_create_index;
}
#ifndef SQLITE_OMIT_VIEW
if( pTab->pSelect ){
sqlite3ErrorMsg(pParse, "views may not be indexed");
goto exit_create_index;
}
#endif
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( IsVirtual(pTab) ){
sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
goto exit_create_index;
}
#endif
/*
** Find the name of the index. Make sure there is not already another
** index or table with the same name.
**
** Exception: If we are reading the names of permanent indices from the
** sqlite_master table (because some other process changed the schema) and
** one of the index names collides with the name of a temporary table or
** index, then we will continue to process this index.
**
** If pName==0 it means that we are
** dealing with a primary key or UNIQUE constraint. We have to invent our
** own name.
*/
if( pName ){
zName = sqlite3NameFromToken(db, pName);
if( zName==0 ) goto exit_create_index;
assert( pName->z!=0 );
if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
goto exit_create_index;
}
if( !IN_RENAME_OBJECT ){
if( !db->init.busy ){
if( sqlite3FindTable(db, zName, 0)!=0 ){
sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
goto exit_create_index;
}
}
if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
if( !ifNotExist ){
sqlite3ErrorMsg(pParse, "index %s already exists", zName);
}else{
assert( !db->init.busy );
sqlite3CodeVerifySchema(pParse, iDb);
}
goto exit_create_index;
}
}
}else{
int n;
Index *pLoop;
for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
if( zName==0 ){
goto exit_create_index;
}
/* Automatic index names generated from within sqlite3_declare_vtab()
** must have names that are distinct from normal automatic index names.
** The following statement converts "sqlite3_autoindex..." into
** "sqlite3_butoindex..." in order to make the names distinct.
** The "vtab_err.test" test demonstrates the need of this statement. */
if( IN_SPECIAL_PARSE ) zName[7]++;
}
/* Check for authorization to create an index.
*/
#ifndef SQLITE_OMIT_AUTHORIZATION
if( !IN_RENAME_OBJECT ){
const char *zDb = pDb->zDbSName;
if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
goto exit_create_index;
}
i = SQLITE_CREATE_INDEX;
if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
goto exit_create_index;
}
}
#endif
/* If pList==0, it means this routine was called to make a primary
** key out of the last column added to the table under construction.
** So create a fake list to simulate this.
*/
if( pList==0 ){
Token prevCol;
Column *pCol = &pTab->aCol[pTab->nCol-1];
pCol->colFlags |= COLFLAG_UNIQUE;
sqlite3TokenInit(&prevCol, pCol->zName);
pList = sqlite3ExprListAppend(pParse, 0,
sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
if( pList==0 ) goto exit_create_index;
assert( pList->nExpr==1 );
sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED);
}else{
sqlite3ExprListCheckLength(pParse, pList, "index");
if( pParse->nErr ) goto exit_create_index;
}
/* Figure out how many bytes of space are required to store explicitly
** specified collation sequence names.
*/
for(i=0; i<pList->nExpr; i++){
Expr *pExpr = pList->a[i].pExpr;
assert( pExpr!=0 );
if( pExpr->op==TK_COLLATE ){
nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
}
}
/*
** Allocate the index structure.
*/
nName = sqlite3Strlen30(zName);
nExtraCol = pPk ? pPk->nKeyCol : 1;
assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
nName + nExtra + 1, &zExtra);
if( db->mallocFailed ){
goto exit_create_index;
}
assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
pIndex->zName = zExtra;
zExtra += nName + 1;
memcpy(pIndex->zName, zName, nName+1);
pIndex->pTable = pTab;
pIndex->onError = (u8)onError;
pIndex->uniqNotNull = onError!=OE_None;
pIndex->idxType = idxType;
pIndex->pSchema = db->aDb[iDb].pSchema;
pIndex->nKeyCol = pList->nExpr;
if( pPIWhere ){
sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
pIndex->pPartIdxWhere = pPIWhere;
pPIWhere = 0;
}
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
/* Check to see if we should honor DESC requests on index columns
*/
if( pDb->pSchema->file_format>=4 ){
sortOrderMask = -1; /* Honor DESC */
}else{
sortOrderMask = 0; /* Ignore DESC */
}
/* Analyze the list of expressions that form the terms of the index and
** report any errors. In the common case where the expression is exactly
** a table column, store that column in aiColumn[]. For general expressions,
** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
**
** TODO: Issue a warning if two or more columns of the index are identical.
** TODO: Issue a warning if the table primary key is used as part of the
** index key.
*/
pListItem = pList->a;
if( IN_RENAME_OBJECT ){
pIndex->aColExpr = pList;
pList = 0;
}
for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
Expr *pCExpr; /* The i-th index expression */
int requestedSortOrder; /* ASC or DESC on the i-th expression */
const char *zColl; /* Collation sequence name */
sqlite3StringToId(pListItem->pExpr);
sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
if( pParse->nErr ) goto exit_create_index;
pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
if( pCExpr->op!=TK_COLUMN ){
if( pTab==pParse->pNewTable ){
sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
"UNIQUE constraints");
goto exit_create_index;
}
if( pIndex->aColExpr==0 ){
pIndex->aColExpr = pList;
pList = 0;
}
j = XN_EXPR;
pIndex->aiColumn[i] = XN_EXPR;
pIndex->uniqNotNull = 0;
}else{
j = pCExpr->iColumn;
assert( j<=0x7fff );
if( j<0 ){
j = pTab->iPKey;
}else{
if( pTab->aCol[j].notNull==0 ){
pIndex->uniqNotNull = 0;
}
if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
pIndex->bHasVCol = 1;
}
}
pIndex->aiColumn[i] = (i16)j;
}
zColl = 0;
if( pListItem->pExpr->op==TK_COLLATE ){
int nColl;
zColl = pListItem->pExpr->u.zToken;
nColl = sqlite3Strlen30(zColl) + 1;
assert( nExtra>=nColl );
memcpy(zExtra, zColl, nColl);
zColl = zExtra;
zExtra += nColl;
nExtra -= nColl;
}else if( j>=0 ){
zColl = pTab->aCol[j].zColl;
}
if( !zColl ) zColl = sqlite3StrBINARY;
if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
goto exit_create_index;
}
pIndex->azColl[i] = zColl;
requestedSortOrder = pListItem->sortFlags & sortOrderMask;
pIndex->aSortOrder[i] = (u8)requestedSortOrder;
}
/* Append the table key to the end of the index. For WITHOUT ROWID
** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
** normal tables (when pPk==0) this will be the rowid.
*/
if( pPk ){
for(j=0; j<pPk->nKeyCol; j++){
int x = pPk->aiColumn[j];
assert( x>=0 );
if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
pIndex->nColumn--;
}else{
testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
pIndex->aiColumn[i] = x;
pIndex->azColl[i] = pPk->azColl[j];
pIndex->aSortOrder[i] = pPk->aSortOrder[j];
i++;
}
}
assert( i==pIndex->nColumn );
}else{
pIndex->aiColumn[i] = XN_ROWID;
pIndex->azColl[i] = sqlite3StrBINARY;
}
sqlite3DefaultRowEst(pIndex);
if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
/* If this index contains every column of its table, then mark
** it as a covering index */
assert( HasRowid(pTab)
|| pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
recomputeColumnsNotIndexed(pIndex);
if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
pIndex->isCovering = 1;
for(j=0; j<pTab->nCol; j++){
if( j==pTab->iPKey ) continue;
if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue;
pIndex->isCovering = 0;
break;
}
}
if( pTab==pParse->pNewTable ){
/* This routine has been called to create an automatic index as a
** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
** a PRIMARY KEY or UNIQUE clause following the column definitions.
** i.e. one of:
**
** CREATE TABLE t(x PRIMARY KEY, y);
** CREATE TABLE t(x, y, UNIQUE(x, y));
**
** Either way, check to see if the table already has such an index. If
** so, don't bother creating this one. This only applies to
** automatically created indices. Users can do as they wish with
** explicit indices.
**
** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
** (and thus suppressing the second one) even if they have different
** sort orders.
**
** If there are different collating sequences or if the columns of
** the constraint occur in different orders, then the constraints are
** considered distinct and both result in separate indices.
*/
Index *pIdx;
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
int k;
assert( IsUniqueIndex(pIdx) );
assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
assert( IsUniqueIndex(pIndex) );
if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
for(k=0; k<pIdx->nKeyCol; k++){
const char *z1;
const char *z2;
assert( pIdx->aiColumn[k]>=0 );
if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
z1 = pIdx->azColl[k];
z2 = pIndex->azColl[k];
if( sqlite3StrICmp(z1, z2) ) break;
}
if( k==pIdx->nKeyCol ){
if( pIdx->onError!=pIndex->onError ){
/* This constraint creates the same index as a previous
** constraint specified somewhere in the CREATE TABLE statement.
** However the ON CONFLICT clauses are different. If both this
** constraint and the previous equivalent constraint have explicit
** ON CONFLICT clauses this is an error. Otherwise, use the
** explicitly specified behavior for the index.
*/
if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
sqlite3ErrorMsg(pParse,
"conflicting ON CONFLICT clauses specified", 0);
}
if( pIdx->onError==OE_Default ){
pIdx->onError = pIndex->onError;
}
}
if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
if( IN_RENAME_OBJECT ){
pIndex->pNext = pParse->pNewIndex;
pParse->pNewIndex = pIndex;
pIndex = 0;
}
goto exit_create_index;
}
}
}
if( !IN_RENAME_OBJECT ){
/* Link the new Index structure to its table and to the other
** in-memory database structures.
*/
assert( pParse->nErr==0 );
if( db->init.busy ){
Index *p;
assert( !IN_SPECIAL_PARSE );
assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
if( pTblName!=0 ){
pIndex->tnum = db->init.newTnum;
if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
sqlite3ErrorMsg(pParse, "invalid rootpage");
pParse->rc = SQLITE_CORRUPT_BKPT;
goto exit_create_index;
}
}
p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
pIndex->zName, pIndex);
if( p ){
assert( p==pIndex ); /* Malloc must have failed */
sqlite3OomFault(db);
goto exit_create_index;
}
db->mDbFlags |= DBFLAG_SchemaChange;
}
/* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
** emit code to allocate the index rootpage on disk and make an entry for
** the index in the sqlite_master table and populate the index with
** content. But, do not do this if we are simply reading the sqlite_master
** table to parse the schema, or if this index is the PRIMARY KEY index
** of a WITHOUT ROWID table.
**
** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
** or UNIQUE index in a CREATE TABLE statement. Since the table
** has just been created, it contains no data and the index initialization
** step can be skipped.
*/
else if( HasRowid(pTab) || pTblName!=0 ){
Vdbe *v;
char *zStmt;
int iMem = ++pParse->nMem;
v = sqlite3GetVdbe(pParse);
if( v==0 ) goto exit_create_index;
sqlite3BeginWriteOperation(pParse, 1, iDb);
/* Create the rootpage for the index using CreateIndex. But before
** doing so, code a Noop instruction and store its address in
** Index.tnum. This is required in case this index is actually a
** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
** that case the convertToWithoutRowidTable() routine will replace
** the Noop with a Goto to jump over the VDBE code generated below. */
pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
/* Gather the complete text of the CREATE INDEX statement into
** the zStmt variable
*/
assert( pName!=0 || pStart==0 );
if( pStart ){
int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
if( pName->z[n-1]==';' ) n--;
/* A named index with an explicit CREATE INDEX statement */
zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
onError==OE_None ? "" : " UNIQUE", n, pName->z);
}else{
/* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
/* zStmt = sqlite3MPrintf(""); */
zStmt = 0;
}
/* Add an entry in sqlite_master for this index
*/
sqlite3NestedParse(pParse,
"INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
db->aDb[iDb].zDbSName, MASTER_NAME,
pIndex->zName,
pTab->zName,
iMem,
zStmt
);
sqlite3DbFree(db, zStmt);
/* Fill the index with data and reparse the schema. Code an OP_Expire
** to invalidate all pre-compiled statements.
*/
if( pTblName ){
sqlite3RefillIndex(pParse, pIndex, iMem);
sqlite3ChangeCookie(pParse, iDb);
sqlite3VdbeAddParseSchemaOp(v, iDb,
sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
}
sqlite3VdbeJumpHere(v, pIndex->tnum);
}
}
/* When adding an index to the list of indices for a table, make
** sure all indices labeled OE_Replace come after all those labeled
** OE_Ignore. This is necessary for the correct constraint check
** processing (in sqlite3GenerateConstraintChecks()) as part of
** UPDATE and INSERT statements.
*/
if( db->init.busy || pTblName==0 ){
if( onError!=OE_Replace || pTab->pIndex==0
|| pTab->pIndex->onError==OE_Replace){
pIndex->pNext = pTab->pIndex;
pTab->pIndex = pIndex;
}else{
Index *pOther = pTab->pIndex;
while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
pOther = pOther->pNext;
}
pIndex->pNext = pOther->pNext;
pOther->pNext = pIndex;
}
pIndex = 0;
}
else if( IN_RENAME_OBJECT ){
assert( pParse->pNewIndex==0 );
pParse->pNewIndex = pIndex;
pIndex = 0;
}
/* Clean up before exiting */
exit_create_index:
if( pIndex ) sqlite3FreeIndex(db, pIndex);
sqlite3ExprDelete(db, pPIWhere);
sqlite3ExprListDelete(db, pList);
sqlite3SrcListDelete(db, pTblName);
sqlite3DbFree(db, zName);
}
/*
** Fill the Index.aiRowEst[] array with default information - information
** to be used when we have not run the ANALYZE command.
**
** aiRowEst[0] is supposed to contain the number of elements in the index.
** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
** number of rows in the table that match any particular value of the
** first column of the index. aiRowEst[2] is an estimate of the number
** of rows that match any particular combination of the first 2 columns
** of the index. And so forth. It must always be the case that
*
** aiRowEst[N]<=aiRowEst[N-1]
** aiRowEst[N]>=1
**
** Apart from that, we have little to go on besides intuition as to
** how aiRowEst[] should be initialized. The numbers generated here
** are based on typical values found in actual indices.
*/
void sqlite3DefaultRowEst(Index *pIdx){
/* 10, 9, 8, 7, 6 */
LogEst aVal[] = { 33, 32, 30, 28, 26 };
LogEst *a = pIdx->aiRowLogEst;
int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
int i;
/* Indexes with default row estimates should not have stat1 data */
assert( !pIdx->hasStat1 );
/* Set the first entry (number of rows in the index) to the estimated
** number of rows in the table, or half the number of rows in the table
** for a partial index. But do not let the estimate drop below 10. */
a[0] = pIdx->pTable->nRowLogEst;
if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) );
if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
/* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
** 6 and each subsequent value (if any) is 5. */
memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
a[i] = 23; assert( 23==sqlite3LogEst(5) );
}
assert( 0==sqlite3LogEst(1) );
if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
}
/*
** This routine will drop an existing named index. This routine
** implements the DROP INDEX statement.
*/
void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
Index *pIndex;
Vdbe *v;
sqlite3 *db = pParse->db;
int iDb;
assert( pParse->nErr==0 ); /* Never called with prior errors */
if( db->mallocFailed ){
goto exit_drop_index;
}
assert( pName->nSrc==1 );
if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
goto exit_drop_index;
}
pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
if( pIndex==0 ){
if( !ifExists ){
sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
}else{
sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
}
pParse->checkSchema = 1;
goto exit_drop_index;
}
if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
"or PRIMARY KEY constraint cannot be dropped", 0);
goto exit_drop_index;
}
iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
#ifndef SQLITE_OMIT_AUTHORIZATION
{
int code = SQLITE_DROP_INDEX;
Table *pTab = pIndex->pTable;
const char *zDb = db->aDb[iDb].zDbSName;
const char *zTab = SCHEMA_TABLE(iDb);
if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
goto exit_drop_index;
}
if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
goto exit_drop_index;
}
}
#endif
/* Generate code to remove the index and from the master table */
v = sqlite3GetVdbe(pParse);
if( v ){
sqlite3BeginWriteOperation(pParse, 1, iDb);
sqlite3NestedParse(pParse,
"DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
);
sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
sqlite3ChangeCookie(pParse, iDb);
destroyRootPage(pParse, pIndex->tnum, iDb);
sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
}
exit_drop_index:
sqlite3SrcListDelete(db, pName);
}
/*
** pArray is a pointer to an array of objects. Each object in the
** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
** to extend the array so that there is space for a new object at the end.
**
** When this function is called, *pnEntry contains the current size of
** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
** in total).
**
** If the realloc() is successful (i.e. if no OOM condition occurs), the
** space allocated for the new object is zeroed, *pnEntry updated to
** reflect the new size of the array and a pointer to the new allocation
** returned. *pIdx is set to the index of the new array entry in this case.
**
** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
** unchanged and a copy of pArray returned.
*/
void *sqlite3ArrayAllocate(
sqlite3 *db, /* Connection to notify of malloc failures */
void *pArray, /* Array of objects. Might be reallocated */
int szEntry, /* Size of each object in the array */
int *pnEntry, /* Number of objects currently in use */
int *pIdx /* Write the index of a new slot here */
){
char *z;
sqlite3_int64 n = *pIdx = *pnEntry;
if( (n & (n-1))==0 ){
sqlite3_int64 sz = (n==0) ? 1 : 2*n;
void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
if( pNew==0 ){
*pIdx = -1;
return pArray;
}
pArray = pNew;
}
z = (char*)pArray;
memset(&z[n * szEntry], 0, szEntry);
++*pnEntry;
return pArray;
}
/*
** Append a new element to the given IdList. Create a new IdList if
** need be.
**
** A new IdList is returned, or NULL if malloc() fails.
*/
IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
sqlite3 *db = pParse->db;
int i;
if( pList==0 ){
pList = sqlite3DbMallocZero(db, sizeof(IdList) );
if( pList==0 ) return 0;
}
pList->a = sqlite3ArrayAllocate(
db,
pList->a,
sizeof(pList->a[0]),
&pList->nId,
&i
);
if( i<0 ){
sqlite3IdListDelete(db, pList);
return 0;
}
pList->a[i].zName = sqlite3NameFromToken(db, pToken);
if( IN_RENAME_OBJECT && pList->a[i].zName ){
sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
}
return pList;
}
/*
** Delete an IdList.
*/
void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
int i;
if( pList==0 ) return;
for(i=0; i<pList->nId; i++){
sqlite3DbFree(db, pList->a[i].zName);
}
sqlite3DbFree(db, pList->a);
sqlite3DbFreeNN(db, pList);
}
/*
** Return the index in pList of the identifier named zId. Return -1
** if not found.
*/
int sqlite3IdListIndex(IdList *pList, const char *zName){
int i;
if( pList==0 ) return -1;
for(i=0; i<pList->nId; i++){
if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
}
return -1;
}
/*
** Maximum size of a SrcList object.
** The SrcList object is used to represent the FROM clause of a
** SELECT statement, and the query planner cannot deal with more
** than 64 tables in a join. So any value larger than 64 here
** is sufficient for most uses. Smaller values, like say 10, are
** appropriate for small and memory-limited applications.
*/
#ifndef SQLITE_MAX_SRCLIST
# define SQLITE_MAX_SRCLIST 200
#endif
/*
** Expand the space allocated for the given SrcList object by
** creating nExtra new slots beginning at iStart. iStart is zero based.
** New slots are zeroed.
**
** For example, suppose a SrcList initially contains two entries: A,B.
** To append 3 new entries onto the end, do this:
**
** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
**
** After the call above it would contain: A, B, nil, nil, nil.
** If the iStart argument had been 1 instead of 2, then the result
** would have been: A, nil, nil, nil, B. To prepend the new slots,
** the iStart value would be 0. The result then would
** be: nil, nil, nil, A, B.
**
** If a memory allocation fails or the SrcList becomes too large, leave
** the original SrcList unchanged, return NULL, and leave an error message
** in pParse.
*/
SrcList *sqlite3SrcListEnlarge(
Parse *pParse, /* Parsing context into which errors are reported */
SrcList *pSrc, /* The SrcList to be enlarged */
int nExtra, /* Number of new slots to add to pSrc->a[] */
int iStart /* Index in pSrc->a[] of first new slot */
){
int i;
/* Sanity checking on calling parameters */
assert( iStart>=0 );
assert( nExtra>=1 );
assert( pSrc!=0 );
assert( iStart<=pSrc->nSrc );
/* Allocate additional space if needed */
if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
SrcList *pNew;
sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
sqlite3 *db = pParse->db;
if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
SQLITE_MAX_SRCLIST);
return 0;
}
if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
pNew = sqlite3DbRealloc(db, pSrc,
sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
if( pNew==0 ){
assert( db->mallocFailed );
return 0;
}
pSrc = pNew;
pSrc->nAlloc = nAlloc;
}
/* Move existing slots that come after the newly inserted slots
** out of the way */
for(i=pSrc->nSrc-1; i>=iStart; i--){
pSrc->a[i+nExtra] = pSrc->a[i];
}
pSrc->nSrc += nExtra;
/* Zero the newly allocated slots */
memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
for(i=iStart; i<iStart+nExtra; i++){
pSrc->a[i].iCursor = -1;
}
/* Return a pointer to the enlarged SrcList */
return pSrc;
}
/*
** Append a new table name to the given SrcList. Create a new SrcList if
** need be. A new entry is created in the SrcList even if pTable is NULL.
**
** A SrcList is returned, or NULL if there is an OOM error or if the
** SrcList grows to large. The returned
** SrcList might be the same as the SrcList that was input or it might be
** a new one. If an OOM error does occurs, then the prior value of pList
** that is input to this routine is automatically freed.
**
** If pDatabase is not null, it means that the table has an optional
** database name prefix. Like this: "database.table". The pDatabase
** points to the table name and the pTable points to the database name.
** The SrcList.a[].zName field is filled with the table name which might
** come from pTable (if pDatabase is NULL) or from pDatabase.
** SrcList.a[].zDatabase is filled with the database name from pTable,
** or with NULL if no database is specified.
**
** In other words, if call like this:
**
** sqlite3SrcListAppend(D,A,B,0);
**
** Then B is a table name and the database name is unspecified. If called
** like this:
**
** sqlite3SrcListAppend(D,A,B,C);
**
** Then C is the table name and B is the database name. If C is defined
** then so is B. In other words, we never have a case where:
**
** sqlite3SrcListAppend(D,A,0,C);
**
** Both pTable and pDatabase are assumed to be quoted. They are dequoted
** before being added to the SrcList.
*/
SrcList *sqlite3SrcListAppend(
Parse *pParse, /* Parsing context, in which errors are reported */
SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
Token *pTable, /* Table to append */
Token *pDatabase /* Database of the table */
){
struct SrcList_item *pItem;
sqlite3 *db;
assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
assert( pParse!=0 );
assert( pParse->db!=0 );
db = pParse->db;
if( pList==0 ){
pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
if( pList==0 ) return 0;
pList->nAlloc = 1;
pList->nSrc = 1;
memset(&pList->a[0], 0, sizeof(pList->a[0]));
pList->a[0].iCursor = -1;
}else{
SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
if( pNew==0 ){
sqlite3SrcListDelete(db, pList);
return 0;
}else{
pList = pNew;
}
}
pItem = &pList->a[pList->nSrc-1];
if( pDatabase && pDatabase->z==0 ){
pDatabase = 0;
}
if( pDatabase ){
pItem->zName = sqlite3NameFromToken(db, pDatabase);
pItem->zDatabase = sqlite3NameFromToken(db, pTable);
}else{
pItem->zName = sqlite3NameFromToken(db, pTable);
pItem->zDatabase = 0;
}
return pList;
}
/*
** Assign VdbeCursor index numbers to all tables in a SrcList
*/
void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
int i;
struct SrcList_item *pItem;
assert(pList || pParse->db->mallocFailed );
if( pList ){
for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
if( pItem->iCursor>=0 ) break;
pItem->iCursor = pParse->nTab++;
if( pItem->pSelect ){
sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
}
}
}
}
/*
** Delete an entire SrcList including all its substructure.
*/
void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
int i;
struct SrcList_item *pItem;
if( pList==0 ) return;
for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
sqlite3DbFree(db, pItem->zDatabase);
sqlite3DbFree(db, pItem->zName);
sqlite3DbFree(db, pItem->zAlias);
if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
sqlite3DeleteTable(db, pItem->pTab);
sqlite3SelectDelete(db, pItem->pSelect);
sqlite3ExprDelete(db, pItem->pOn);
sqlite3IdListDelete(db, pItem->pUsing);
}
sqlite3DbFreeNN(db, pList);
}
/*
** This routine is called by the parser to add a new term to the
** end of a growing FROM clause. The "p" parameter is the part of
** the FROM clause that has already been constructed. "p" is NULL
** if this is the first term of the FROM clause. pTable and pDatabase
** are the name of the table and database named in the FROM clause term.
** pDatabase is NULL if the database name qualifier is missing - the
** usual case. If the term has an alias, then pAlias points to the
** alias token. If the term is a subquery, then pSubquery is the
** SELECT statement that the subquery encodes. The pTable and
** pDatabase parameters are NULL for subqueries. The pOn and pUsing
** parameters are the content of the ON and USING clauses.
**
** Return a new SrcList which encodes is the FROM with the new
** term added.
*/
SrcList *sqlite3SrcListAppendFromTerm(
Parse *pParse, /* Parsing context */
SrcList *p, /* The left part of the FROM clause already seen */
Token *pTable, /* Name of the table to add to the FROM clause */
Token *pDatabase, /* Name of the database containing pTable */
Token *pAlias, /* The right-hand side of the AS subexpression */
Select *pSubquery, /* A subquery used in place of a table name */
Expr *pOn, /* The ON clause of a join */
IdList *pUsing /* The USING clause of a join */
){
struct SrcList_item *pItem;
sqlite3 *db = pParse->db;
if( !p && (pOn || pUsing) ){
sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
(pOn ? "ON" : "USING")
);
goto append_from_error;
}
p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
if( p==0 ){
goto append_from_error;
}
assert( p->nSrc>0 );
pItem = &p->a[p->nSrc-1];
assert( (pTable==0)==(pDatabase==0) );
assert( pItem->zName==0 || pDatabase!=0 );
if( IN_RENAME_OBJECT && pItem->zName ){
Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
}
assert( pAlias!=0 );
if( pAlias->n ){
pItem->zAlias = sqlite3NameFromToken(db, pAlias);
}
pItem->pSelect = pSubquery;
pItem->pOn = pOn;
pItem->pUsing = pUsing;
return p;
append_from_error:
assert( p==0 );
sqlite3ExprDelete(db, pOn);
sqlite3IdListDelete(db, pUsing);
sqlite3SelectDelete(db, pSubquery);
return 0;
}
/*
** Add an INDEXED BY or NOT INDEXED clause to the most recently added
** element of the source-list passed as the second argument.
*/
void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
assert( pIndexedBy!=0 );
if( p && pIndexedBy->n>0 ){
struct SrcList_item *pItem;
assert( p->nSrc>0 );
pItem = &p->a[p->nSrc-1];
assert( pItem->fg.notIndexed==0 );
assert( pItem->fg.isIndexedBy==0 );
assert( pItem->fg.isTabFunc==0 );
if( pIndexedBy->n==1 && !pIndexedBy->z ){
/* A "NOT INDEXED" clause was supplied. See parse.y
** construct "indexed_opt" for details. */
pItem->fg.notIndexed = 1;
}else{
pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
pItem->fg.isIndexedBy = 1;
}
}
}
/*
** Add the list of function arguments to the SrcList entry for a
** table-valued-function.
*/
void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
if( p ){
struct SrcList_item *pItem = &p->a[p->nSrc-1];
assert( pItem->fg.notIndexed==0 );
assert( pItem->fg.isIndexedBy==0 );
assert( pItem->fg.isTabFunc==0 );
pItem->u1.pFuncArg = pList;
pItem->fg.isTabFunc = 1;
}else{
sqlite3ExprListDelete(pParse->db, pList);
}
}
/*
** When building up a FROM clause in the parser, the join operator
** is initially attached to the left operand. But the code generator
** expects the join operator to be on the right operand. This routine
** Shifts all join operators from left to right for an entire FROM
** clause.
**
** Example: Suppose the join is like this:
**
** A natural cross join B
**
** The operator is "natural cross join". The A and B operands are stored
** in p->a[0] and p->a[1], respectively. The parser initially stores the
** operator with A. This routine shifts that operator over to B.
*/
void sqlite3SrcListShiftJoinType(SrcList *p){
if( p ){
int i;
for(i=p->nSrc-1; i>0; i--){
p->a[i].fg.jointype = p->a[i-1].fg.jointype;
}
p->a[0].fg.jointype = 0;
}
}
/*
** Generate VDBE code for a BEGIN statement.
*/
void sqlite3BeginTransaction(Parse *pParse, int type){
sqlite3 *db;
Vdbe *v;
int i;
assert( pParse!=0 );
db = pParse->db;
assert( db!=0 );
if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
return;
}
v = sqlite3GetVdbe(pParse);
if( !v ) return;
if( type!=TK_DEFERRED ){
for(i=0; i<db->nDb; i++){
sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
sqlite3VdbeUsesBtree(v, i);
}
}
sqlite3VdbeAddOp0(v, OP_AutoCommit);
}
/*
** Generate VDBE code for a COMMIT or ROLLBACK statement.
** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
** code is generated for a COMMIT.
*/
void sqlite3EndTransaction(Parse *pParse, int eType){
Vdbe *v;
int isRollback;
assert( pParse!=0 );
assert( pParse->db!=0 );
assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
isRollback = eType==TK_ROLLBACK;
if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
return;
}
v = sqlite3GetVdbe(pParse);
if( v ){
sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
}
}
/*
** This function is called by the parser when it parses a command to create,
** release or rollback an SQL savepoint.
*/
void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
char *zName = sqlite3NameFromToken(pParse->db, pName);
if( zName ){
Vdbe *v = sqlite3GetVdbe(pParse);
#ifndef SQLITE_OMIT_AUTHORIZATION
static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
#endif
if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
sqlite3DbFree(pParse->db, zName);
return;
}
sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
}
}
/*
** Make sure the TEMP database is open and available for use. Return
** the number of errors. Leave any error messages in the pParse structure.
*/
int sqlite3OpenTempDatabase(Parse *pParse){
sqlite3 *db = pParse->db;
if( db->aDb[1].pBt==0 && !pParse->explain ){
int rc;
Btree *pBt;
static const int flags =
SQLITE_OPEN_READWRITE |
SQLITE_OPEN_CREATE |
SQLITE_OPEN_EXCLUSIVE |
SQLITE_OPEN_DELETEONCLOSE |
SQLITE_OPEN_TEMP_DB;
rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
if( rc!=SQLITE_OK ){
sqlite3ErrorMsg(pParse, "unable to open a temporary database "
"file for storing temporary tables");
pParse->rc = rc;
return 1;
}
db->aDb[1].pBt = pBt;
assert( db->aDb[1].pSchema );
if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
sqlite3OomFault(db);
return 1;
}
}
return 0;
}
/*
** Record the fact that the schema cookie will need to be verified
** for database iDb. The code to actually verify the schema cookie
** will occur at the end of the top-level VDBE and will be generated
** later, by sqlite3FinishCoding().
*/
void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
Parse *pToplevel = sqlite3ParseToplevel(pParse);
assert( iDb>=0 && iDb<pParse->db->nDb );
assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
assert( iDb<SQLITE_MAX_ATTACHED+2 );
assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
DbMaskSet(pToplevel->cookieMask, iDb);
if( !OMIT_TEMPDB && iDb==1 ){
sqlite3OpenTempDatabase(pToplevel);
}
}
}
/*
** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
** attached database. Otherwise, invoke it for the database named zDb only.
*/
void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
sqlite3 *db = pParse->db;
int i;
for(i=0; i<db->nDb; i++){
Db *pDb = &db->aDb[i];
if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
sqlite3CodeVerifySchema(pParse, i);
}
}
}
/*
** Generate VDBE code that prepares for doing an operation that
** might change the database.
**
** This routine starts a new transaction if we are not already within
** a transaction. If we are already within a transaction, then a checkpoint
** is set if the setStatement parameter is true. A checkpoint should
** be set for operations that might fail (due to a constraint) part of
** the way through and which will need to undo some writes without having to
** rollback the whole transaction. For operations where all constraints
** can be checked before any changes are made to the database, it is never
** necessary to undo a write and the checkpoint should not be set.
*/
void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
Parse *pToplevel = sqlite3ParseToplevel(pParse);
sqlite3CodeVerifySchema(pParse, iDb);
DbMaskSet(pToplevel->writeMask, iDb);
pToplevel->isMultiWrite |= setStatement;
}
/*
** Indicate that the statement currently under construction might write
** more than one entry (example: deleting one row then inserting another,
** inserting multiple rows in a table, or inserting a row and index entries.)
** If an abort occurs after some of these writes have completed, then it will
** be necessary to undo the completed writes.
*/
void sqlite3MultiWrite(Parse *pParse){
Parse *pToplevel = sqlite3ParseToplevel(pParse);
pToplevel->isMultiWrite = 1;
}
/*
** The code generator calls this routine if is discovers that it is
** possible to abort a statement prior to completion. In order to
** perform this abort without corrupting the database, we need to make
** sure that the statement is protected by a statement transaction.
**
** Technically, we only need to set the mayAbort flag if the
** isMultiWrite flag was previously set. There is a time dependency
** such that the abort must occur after the multiwrite. This makes
** some statements involving the REPLACE conflict resolution algorithm
** go a little faster. But taking advantage of this time dependency
** makes it more difficult to prove that the code is correct (in
** particular, it prevents us from writing an effective
** implementation of sqlite3AssertMayAbort()) and so we have chosen
** to take the safe route and skip the optimization.
*/
void sqlite3MayAbort(Parse *pParse){
Parse *pToplevel = sqlite3ParseToplevel(pParse);
pToplevel->mayAbort = 1;
}
/*
** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
** error. The onError parameter determines which (if any) of the statement
** and/or current transaction is rolled back.
*/
void sqlite3HaltConstraint(
Parse *pParse, /* Parsing context */
int errCode, /* extended error code */
int onError, /* Constraint type */
char *p4, /* Error message */
i8 p4type, /* P4_STATIC or P4_TRANSIENT */
u8 p5Errmsg /* P5_ErrMsg type */
){
Vdbe *v = sqlite3GetVdbe(pParse);
assert( (errCode&0xff)==SQLITE_CONSTRAINT );
if( onError==OE_Abort ){
sqlite3MayAbort(pParse);
}
sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
sqlite3VdbeChangeP5(v, p5Errmsg);
}
/*
** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
*/
void sqlite3UniqueConstraint(
Parse *pParse, /* Parsing context */
int onError, /* Constraint type */
Index *pIdx /* The index that triggers the constraint */
){
char *zErr;
int j;
StrAccum errMsg;
Table *pTab = pIdx->pTable;
sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
if( pIdx->aColExpr ){
sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
}else{
for(j=0; j<pIdx->nKeyCol; j++){
char *zCol;
assert( pIdx->aiColumn[j]>=0 );
zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
if( j ) sqlite3_str_append(&errMsg, ", ", 2);
sqlite3_str_appendall(&errMsg, pTab->zName);
sqlite3_str_append(&errMsg, ".", 1);
sqlite3_str_appendall(&errMsg, zCol);
}
}
zErr = sqlite3StrAccumFinish(&errMsg);
sqlite3HaltConstraint(pParse,
IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
: SQLITE_CONSTRAINT_UNIQUE,
onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
}
/*
** Code an OP_Halt due to non-unique rowid.
*/
void sqlite3RowidConstraint(
Parse *pParse, /* Parsing context */
int onError, /* Conflict resolution algorithm */
Table *pTab /* The table with the non-unique rowid */
){
char *zMsg;
int rc;
if( pTab->iPKey>=0 ){
zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
pTab->aCol[pTab->iPKey].zName);
rc = SQLITE_CONSTRAINT_PRIMARYKEY;
}else{
zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
rc = SQLITE_CONSTRAINT_ROWID;
}
sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
P5_ConstraintUnique);
}
/*
** Check to see if pIndex uses the collating sequence pColl. Return
** true if it does and false if it does not.
*/
#ifndef SQLITE_OMIT_REINDEX
static int collationMatch(const char *zColl, Index *pIndex){
int i;
assert( zColl!=0 );
for(i=0; i<pIndex->nColumn; i++){
const char *z = pIndex->azColl[i];
assert( z!=0 || pIndex->aiColumn[i]<0 );
if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
return 1;
}
}
return 0;
}
#endif
/*
** Recompute all indices of pTab that use the collating sequence pColl.
** If pColl==0 then recompute all indices of pTab.
*/
#ifndef SQLITE_OMIT_REINDEX
static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
if( !IsVirtual(pTab) ){
Index *pIndex; /* An index associated with pTab */
for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
if( zColl==0 || collationMatch(zColl, pIndex) ){
int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
sqlite3BeginWriteOperation(pParse, 0, iDb);
sqlite3RefillIndex(pParse, pIndex, -1);
}
}
}
}
#endif
/*
** Recompute all indices of all tables in all databases where the
** indices use the collating sequence pColl. If pColl==0 then recompute
** all indices everywhere.
*/
#ifndef SQLITE_OMIT_REINDEX
static void reindexDatabases(Parse *pParse, char const *zColl){
Db *pDb; /* A single database */
int iDb; /* The database index number */
sqlite3 *db = pParse->db; /* The database connection */
HashElem *k; /* For looping over tables in pDb */
Table *pTab; /* A table in the database */
assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
assert( pDb!=0 );
for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
pTab = (Table*)sqliteHashData(k);
reindexTable(pParse, pTab, zColl);
}
}
}
#endif
/*
** Generate code for the REINDEX command.
**
** REINDEX -- 1
** REINDEX <collation> -- 2
** REINDEX ?<database>.?<tablename> -- 3
** REINDEX ?<database>.?<indexname> -- 4
**
** Form 1 causes all indices in all attached databases to be rebuilt.
** Form 2 rebuilds all indices in all databases that use the named
** collating function. Forms 3 and 4 rebuild the named index or all
** indices associated with the named table.
*/
#ifndef SQLITE_OMIT_REINDEX
void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
char *z; /* Name of a table or index */
const char *zDb; /* Name of the database */
Table *pTab; /* A table in the database */
Index *pIndex; /* An index associated with pTab */
int iDb; /* The database index number */
sqlite3 *db = pParse->db; /* The database connection */
Token *pObjName; /* Name of the table or index to be reindexed */
/* Read the database schema. If an error occurs, leave an error message
** and code in pParse and return NULL. */
if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
return;
}
if( pName1==0 ){
reindexDatabases(pParse, 0);
return;
}else if( NEVER(pName2==0) || pName2->z==0 ){
char *zColl;
assert( pName1->z );
zColl = sqlite3NameFromToken(pParse->db, pName1);
if( !zColl ) return;
pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
if( pColl ){
reindexDatabases(pParse, zColl);
sqlite3DbFree(db, zColl);
return;
}
sqlite3DbFree(db, zColl);
}
iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
if( iDb<0 ) return;
z = sqlite3NameFromToken(db, pObjName);
if( z==0 ) return;
zDb = db->aDb[iDb].zDbSName;
pTab = sqlite3FindTable(db, z, zDb);
if( pTab ){
reindexTable(pParse, pTab, 0);
sqlite3DbFree(db, z);
return;
}
pIndex = sqlite3FindIndex(db, z, zDb);
sqlite3DbFree(db, z);
if( pIndex ){
sqlite3BeginWriteOperation(pParse, 0, iDb);
sqlite3RefillIndex(pParse, pIndex, -1);
return;
}
sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
}
#endif
/*
** Return a KeyInfo structure that is appropriate for the given Index.
**
** The caller should invoke sqlite3KeyInfoUnref() on the returned object
** when it has finished using it.
*/
KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
int i;
int nCol = pIdx->nColumn;
int nKey = pIdx->nKeyCol;
KeyInfo *pKey;
if( pParse->nErr ) return 0;
if( pIdx->uniqNotNull ){
pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
}else{
pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
}
if( pKey ){
assert( sqlite3KeyInfoIsWriteable(pKey) );
for(i=0; i<nCol; i++){
const char *zColl = pIdx->azColl[i];
pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
sqlite3LocateCollSeq(pParse, zColl);
pKey->aSortFlags[i] = pIdx->aSortOrder[i];
assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
}
if( pParse->nErr ){
assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
if( pIdx->bNoQuery==0 ){
/* Deactivate the index because it contains an unknown collating
** sequence. The only way to reactive the index is to reload the
** schema. Adding the missing collating sequence later does not
** reactive the index. The application had the chance to register
** the missing index using the collation-needed callback. For
** simplicity, SQLite will not give the application a second chance.
*/
pIdx->bNoQuery = 1;
pParse->rc = SQLITE_ERROR_RETRY;
}
sqlite3KeyInfoUnref(pKey);
pKey = 0;
}
}
return pKey;
}
#ifndef SQLITE_OMIT_CTE
/*
** This routine is invoked once per CTE by the parser while parsing a
** WITH clause.
*/
With *sqlite3WithAdd(
Parse *pParse, /* Parsing context */
With *pWith, /* Existing WITH clause, or NULL */
Token *pName, /* Name of the common-table */
ExprList *pArglist, /* Optional column name list for the table */
Select *pQuery /* Query used to initialize the table */
){
sqlite3 *db = pParse->db;
With *pNew;
char *zName;
/* Check that the CTE name is unique within this WITH clause. If
** not, store an error in the Parse structure. */
zName = sqlite3NameFromToken(pParse->db, pName);
if( zName && pWith ){
int i;
for(i=0; i<pWith->nCte; i++){
if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
}
}
}
if( pWith ){
sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
pNew = sqlite3DbRealloc(db, pWith, nByte);
}else{
pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
}
assert( (pNew!=0 && zName!=0) || db->mallocFailed );
if( db->mallocFailed ){
sqlite3ExprListDelete(db, pArglist);
sqlite3SelectDelete(db, pQuery);
sqlite3DbFree(db, zName);
pNew = pWith;
}else{
pNew->a[pNew->nCte].pSelect = pQuery;
pNew->a[pNew->nCte].pCols = pArglist;
pNew->a[pNew->nCte].zName = zName;
pNew->a[pNew->nCte].zCteErr = 0;
pNew->nCte++;
}
return pNew;
}
/*
** Free the contents of the With object passed as the second argument.
*/
void sqlite3WithDelete(sqlite3 *db, With *pWith){
if( pWith ){
int i;
for(i=0; i<pWith->nCte; i++){
struct Cte *pCte = &pWith->a[i];
sqlite3ExprListDelete(db, pCte->pCols);
sqlite3SelectDelete(db, pCte->pSelect);
sqlite3DbFree(db, pCte->zName);
}
sqlite3DbFree(db, pWith);
}
}
#endif /* !defined(SQLITE_OMIT_CTE) */
| ./CrossVul/dataset_final_sorted/CWE-674/c/good_1310_3 |
crossvul-cpp_data_good_350_0 | /*
* card-iasecc.c: Support for IAS/ECC smart cards
*
* Copyright (C) 2010 Viktor Tarasov <vtarasov@gmail.com>
* OpenTrust <www.opentrust.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef ENABLE_OPENSSL /* empty file without openssl */
#include <string.h>
#include <stdlib.h>
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <openssl/rsa.h>
#include <openssl/pkcs12.h>
#include <openssl/x509v3.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
#include "opensc.h"
/* #include "sm.h" */
#include "pkcs15.h"
/* #include "hash-strings.h" */
#include "gp.h"
#include "iasecc.h"
#define IASECC_CARD_DEFAULT_FLAGS ( 0 \
| SC_ALGORITHM_ONBOARD_KEY_GEN \
| SC_ALGORITHM_RSA_PAD_ISO9796 \
| SC_ALGORITHM_RSA_PAD_PKCS1 \
| SC_ALGORITHM_RSA_HASH_NONE \
| SC_ALGORITHM_RSA_HASH_SHA1 \
| SC_ALGORITHM_RSA_HASH_SHA256)
/* generic iso 7816 operations table */
static const struct sc_card_operations *iso_ops = NULL;
/* our operations table with overrides */
static struct sc_card_operations iasecc_ops;
static struct sc_card_driver iasecc_drv = {
"IAS-ECC",
"iasecc",
&iasecc_ops,
NULL, 0, NULL
};
static struct sc_atr_table iasecc_known_atrs[] = {
{ "3B:7F:96:00:00:00:31:B8:64:40:70:14:10:73:94:01:80:82:90:00",
"FF:FF:FF:FF:FF:FF:FF:FE:FF:FF:00:00:FF:FF:FF:FF:FF:FF:FF:FF",
"IAS/ECC Gemalto", SC_CARD_TYPE_IASECC_GEMALTO, 0, NULL },
{ "3B:DD:18:00:81:31:FE:45:80:F9:A0:00:00:00:77:01:08:00:07:90:00:FE", NULL,
"IAS/ECC v1.0.1 Oberthur", SC_CARD_TYPE_IASECC_OBERTHUR, 0, NULL },
{ "3B:7D:13:00:00:4D:44:57:2D:49:41:53:2D:43:41:52:44:32", NULL,
"IAS/ECC v1.0.1 Sagem MDW-IAS-CARD2", SC_CARD_TYPE_IASECC_SAGEM, 0, NULL },
{ "3B:7F:18:00:00:00:31:B8:64:50:23:EC:C1:73:94:01:80:82:90:00", NULL,
"IAS/ECC v1.0.1 Sagem ypsID S3", SC_CARD_TYPE_IASECC_SAGEM, 0, NULL },
{ "3B:DF:96:00:80:31:FE:45:00:31:B8:64:04:1F:EC:C1:73:94:01:80:82:90:00:EC", NULL,
"IAS/ECC Morpho MinInt - Agent Card", SC_CARD_TYPE_IASECC_MI, 0, NULL },
{ "3B:DF:18:FF:81:91:FE:1F:C3:00:31:B8:64:0C:01:EC:C1:73:94:01:80:82:90:00:B3", NULL,
"IAS/ECC v1.0.1 Amos", SC_CARD_TYPE_IASECC_AMOS, 0, NULL },
{ "3B:DC:18:FF:81:91:FE:1F:C3:80:73:C8:21:13:66:02:04:03:55:00:02:34", NULL,
"IAS/ECC v1.0.1 Amos", SC_CARD_TYPE_IASECC_AMOS, 0, NULL },
{ "3B:DC:18:FF:81:91:FE:1F:C3:80:73:C8:21:13:66:01:0B:03:52:00:05:38", NULL,
"IAS/ECC v1.0.1 Amos", SC_CARD_TYPE_IASECC_AMOS, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
static struct sc_aid OberthurIASECC_AID = {
{0xA0,0x00,0x00,0x00,0x77,0x01,0x08,0x00,0x07,0x00,0x00,0xFE,0x00,0x00,0x01,0x00}, 16
};
static struct sc_aid MIIASECC_AID = {
{ 0x4D, 0x49, 0x4F, 0x4D, 0x43, 0x54}, 6
};
struct iasecc_pin_status {
unsigned char sha1[SHA_DIGEST_LENGTH];
unsigned char reference;
struct iasecc_pin_status *next;
struct iasecc_pin_status *prev;
};
struct iasecc_pin_status *checked_pins = NULL;
static int iasecc_select_file(struct sc_card *card, const struct sc_path *path, struct sc_file **file_out);
static int iasecc_process_fci(struct sc_card *card, struct sc_file *file, const unsigned char *buf, size_t buflen);
static int iasecc_get_serialnr(struct sc_card *card, struct sc_serial_number *serial);
static int iasecc_sdo_get_data(struct sc_card *card, struct iasecc_sdo *sdo);
static int iasecc_pin_get_policy (struct sc_card *card, struct sc_pin_cmd_data *data);
static int iasecc_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left);
static int iasecc_get_free_reference(struct sc_card *card, struct iasecc_ctl_get_free_reference *ctl_data);
static int iasecc_sdo_put_data(struct sc_card *card, struct iasecc_sdo_update *update);
#ifdef ENABLE_SM
static int _iasecc_sm_read_binary(struct sc_card *card, unsigned int offs, unsigned char *buf, size_t count);
static int _iasecc_sm_update_binary(struct sc_card *card, unsigned int offs, const unsigned char *buff, size_t count);
#endif
static int
iasecc_chv_cache_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd)
{
struct sc_context *ctx = card->ctx;
struct iasecc_pin_status *pin_status = NULL, *current = NULL;
LOG_FUNC_CALLED(ctx);
for(current = checked_pins; current; current = current->next)
if (current->reference == pin_cmd->pin_reference)
break;
if (current) {
sc_log(ctx, "iasecc_chv_cache_verified() current PIN-%i", current->reference);
pin_status = current;
}
else {
pin_status = calloc(1, sizeof(struct iasecc_pin_status));
if (!pin_status)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot callocate PIN status info");
sc_log(ctx, "iasecc_chv_cache_verified() allocated %p", pin_status);
}
pin_status->reference = pin_cmd->pin_reference;
if (pin_cmd->pin1.data)
SHA1(pin_cmd->pin1.data, pin_cmd->pin1.len, pin_status->sha1);
else
memset(pin_status->sha1, 0, SHA_DIGEST_LENGTH);
sc_log_hex(ctx, "iasecc_chv_cache_verified() sha1(PIN)", pin_status->sha1, SHA_DIGEST_LENGTH);
if (!current) {
if (!checked_pins) {
checked_pins = pin_status;
}
else {
checked_pins->prev = pin_status;
pin_status->next = checked_pins;
checked_pins = pin_status;
}
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_chv_cache_clean(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd)
{
struct sc_context *ctx = card->ctx;
struct iasecc_pin_status *current = NULL;
LOG_FUNC_CALLED(ctx);
for(current = checked_pins; current; current = current->next)
if (current->reference == pin_cmd->pin_reference)
break;
if (!current)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
if (current->next && current->prev) {
current->prev->next = current->next;
current->next->prev = current->prev;
}
else if (!current->prev) {
checked_pins = current->next;
}
else if (!current->next && current->prev) {
current->prev->next = NULL;
}
free(current);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static struct iasecc_pin_status *
iasecc_chv_cache_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd)
{
struct sc_context *ctx = card->ctx;
struct iasecc_pin_status *current = NULL;
unsigned char data_sha1[SHA_DIGEST_LENGTH];
LOG_FUNC_CALLED(ctx);
if (pin_cmd->pin1.data)
SHA1(pin_cmd->pin1.data, pin_cmd->pin1.len, data_sha1);
else
memset(data_sha1, 0, SHA_DIGEST_LENGTH);
sc_log_hex(ctx, "data_sha1: %s", data_sha1, SHA_DIGEST_LENGTH);
for(current = checked_pins; current; current = current->next)
if (current->reference == pin_cmd->pin_reference)
break;
if (current && !memcmp(data_sha1, current->sha1, SHA_DIGEST_LENGTH)) {
sc_log(ctx, "PIN-%i status 'verified'", pin_cmd->pin_reference);
return current;
}
sc_log(ctx, "PIN-%i status 'not verified'", pin_cmd->pin_reference);
return NULL;
}
static int
iasecc_select_mf(struct sc_card *card, struct sc_file **file_out)
{
struct sc_context *ctx = card->ctx;
struct sc_file *mf_file = NULL;
struct sc_path path;
int rv;
LOG_FUNC_CALLED(ctx);
if (file_out)
*file_out = NULL;
memset(&path, 0, sizeof(struct sc_path));
if (!card->ef_atr || !card->ef_atr->aid.len) {
struct sc_apdu apdu;
unsigned char apdu_resp[SC_MAX_APDU_BUFFER_SIZE];
/* ISO 'select' command fails when not FCP data returned */
sc_format_path("3F00", &path);
path.type = SC_PATH_TYPE_FILE_ID;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 0x00, 0x00);
apdu.lc = path.len;
apdu.data = path.value;
apdu.datalen = path.len;
apdu.resplen = sizeof(apdu_resp);
apdu.resp = apdu_resp;
if (card->type == SC_CARD_TYPE_IASECC_MI2)
apdu.p2 = 0x04;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, rv, "Cannot select MF");
}
else {
memset(&path, 0, sizeof(path));
path.type = SC_PATH_TYPE_DF_NAME;
memcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len);
path.len = card->ef_atr->aid.len;
rv = iasecc_select_file(card, &path, file_out);
LOG_TEST_RET(ctx, rv, "Unable to ROOT selection");
}
/* Ignore the FCP of the MF, because:
* - some cards do not return it;
* - there is not need of it -- create/delete of the files in MF is not envisaged.
*/
mf_file = sc_file_new();
if (mf_file == NULL)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate MF file");
mf_file->type = SC_FILE_TYPE_DF;
mf_file->path = path;
if (card->cache.valid)
sc_file_free(card->cache.current_df);
card->cache.current_df = NULL;
if (card->cache.valid)
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
sc_file_dup(&card->cache.current_df, mf_file);
card->cache.valid = 1;
if (file_out && *file_out == NULL)
*file_out = mf_file;
else
sc_file_free(mf_file);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_select_aid(struct sc_card *card, struct sc_aid *aid, unsigned char *out, size_t *out_len)
{
struct sc_apdu apdu;
unsigned char apdu_resp[SC_MAX_APDU_BUFFER_SIZE];
int rv;
/* Select application (deselect previously selected application) */
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x04, 0x00);
apdu.lc = aid->len;
apdu.data = aid->value;
apdu.datalen = aid->len;
apdu.resplen = sizeof(apdu_resp);
apdu.resp = apdu_resp;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, rv, "Cannot select AID");
if (*out_len < apdu.resplen)
LOG_TEST_RET(card->ctx, SC_ERROR_BUFFER_TOO_SMALL, "Cannot select AID");
memcpy(out, apdu.resp, apdu.resplen);
return SC_SUCCESS;
}
static int
iasecc_match_card(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
int i;
i = _sc_match_atr(card, iasecc_known_atrs, &card->type);
if (i < 0) {
sc_log(ctx, "card not matched");
return 0;
}
sc_log(ctx, "'%s' card matched", iasecc_known_atrs[i].name);
return 1;
}
static int iasecc_parse_ef_atr(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
struct iasecc_private_data *pdata = (struct iasecc_private_data *) card->drv_data;
struct iasecc_version *version = &pdata->version;
struct iasecc_io_buffer_sizes *sizes = &pdata->max_sizes;
int rv;
LOG_FUNC_CALLED(ctx);
rv = sc_parse_ef_atr(card);
LOG_TEST_RET(ctx, rv, "MF selection error");
if (card->ef_atr->pre_issuing_len < 4)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid pre-issuing data");
version->ic_manufacturer = card->ef_atr->pre_issuing[0];
version->ic_type = card->ef_atr->pre_issuing[1];
version->os_version = card->ef_atr->pre_issuing[2];
version->iasecc_version = card->ef_atr->pre_issuing[3];
sc_log(ctx, "EF.ATR: IC manufacturer/type %X/%X, OS/IasEcc versions %X/%X",
version->ic_manufacturer, version->ic_type, version->os_version, version->iasecc_version);
if (card->ef_atr->issuer_data_len < 16)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid issuer data");
sizes->send = card->ef_atr->issuer_data[2] * 0x100 + card->ef_atr->issuer_data[3];
sizes->send_sc = card->ef_atr->issuer_data[6] * 0x100 + card->ef_atr->issuer_data[7];
sizes->recv = card->ef_atr->issuer_data[10] * 0x100 + card->ef_atr->issuer_data[11];
sizes->recv_sc = card->ef_atr->issuer_data[14] * 0x100 + card->ef_atr->issuer_data[15];
card->max_send_size = sizes->send;
card->max_recv_size = sizes->recv;
/* Most of the card producers interpret 'send' values as "maximum APDU data size".
* Oberthur strictly follows specification and interpret these values as "maximum APDU command size".
* Here we need 'data size'.
*/
if (card->max_send_size > 0xFF)
card->max_send_size -= 5;
sc_log(ctx,
"EF.ATR: max send/recv sizes %"SC_FORMAT_LEN_SIZE_T"X/%"SC_FORMAT_LEN_SIZE_T"X",
card->max_send_size, card->max_recv_size);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_init_gemalto(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
struct sc_path path;
unsigned int flags;
int rv = 0;
LOG_FUNC_CALLED(ctx);
flags = IASECC_CARD_DEFAULT_FLAGS;
_sc_card_add_rsa_alg(card, 1024, flags, 0x10001);
_sc_card_add_rsa_alg(card, 2048, flags, 0x10001);
card->caps = SC_CARD_CAP_RNG;
card->caps |= SC_CARD_CAP_APDU_EXT;
card->caps |= SC_CARD_CAP_USE_FCI_AC;
sc_format_path("3F00", &path);
rv = sc_select_file(card, &path, NULL);
/* Result ignored*/
rv = iasecc_parse_ef_atr(card);
sc_log(ctx, "rv %i", rv);
if (rv == SC_ERROR_FILE_NOT_FOUND) {
sc_log(ctx, "Select MF");
rv = iasecc_select_mf(card, NULL);
sc_log(ctx, "rv %i", rv);
LOG_TEST_RET(ctx, rv, "MF selection error");
rv = iasecc_parse_ef_atr(card);
sc_log(ctx, "rv %i", rv);
}
sc_log(ctx, "rv %i", rv);
LOG_TEST_RET(ctx, rv, "Cannot read/parse EF.ATR");
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_oberthur_match(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
unsigned char *hist = card->reader->atr_info.hist_bytes;
LOG_FUNC_CALLED(ctx);
if (*hist != 0x80 || ((*(hist+1)&0xF0) != 0xF0))
LOG_FUNC_RETURN(ctx, SC_ERROR_OBJECT_NOT_FOUND);
sc_log_hex(ctx, "AID in historical_bytes", hist + 2, *(hist+1) & 0x0F);
if (memcmp(hist + 2, OberthurIASECC_AID.value, *(hist+1) & 0x0F))
LOG_FUNC_RETURN(ctx, SC_ERROR_RECORD_NOT_FOUND);
if (!card->ef_atr)
card->ef_atr = calloc(1, sizeof(struct sc_ef_atr));
if (!card->ef_atr)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(card->ef_atr->aid.value, OberthurIASECC_AID.value, OberthurIASECC_AID.len);
card->ef_atr->aid.len = OberthurIASECC_AID.len;
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_init_oberthur(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
unsigned int flags;
int rv = 0;
LOG_FUNC_CALLED(ctx);
flags = IASECC_CARD_DEFAULT_FLAGS;
_sc_card_add_rsa_alg(card, 1024, flags, 0x10001);
_sc_card_add_rsa_alg(card, 2048, flags, 0x10001);
card->caps = SC_CARD_CAP_RNG;
card->caps |= SC_CARD_CAP_APDU_EXT;
card->caps |= SC_CARD_CAP_USE_FCI_AC;
iasecc_parse_ef_atr(card);
/* if we fail to select CM, */
if (gp_select_card_manager(card)) {
gp_select_isd_rid(card);
}
rv = iasecc_oberthur_match(card);
LOG_TEST_RET(ctx, rv, "unknown Oberthur's IAS/ECC card");
rv = iasecc_select_mf(card, NULL);
LOG_TEST_RET(ctx, rv, "MF selection error");
rv = iasecc_parse_ef_atr(card);
LOG_TEST_RET(ctx, rv, "EF.ATR read or parse error");
sc_log(ctx, "EF.ATR(aid:'%s')", sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len));
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_mi_match(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
unsigned char resp[0x100];
size_t resp_len;
int rv = 0;
LOG_FUNC_CALLED(ctx);
resp_len = sizeof(resp);
rv = iasecc_select_aid(card, &MIIASECC_AID, resp, &resp_len);
LOG_TEST_RET(ctx, rv, "IASECC: failed to select MI IAS/ECC applet");
if (!card->ef_atr)
card->ef_atr = calloc(1, sizeof(struct sc_ef_atr));
if (!card->ef_atr)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(card->ef_atr->aid.value, MIIASECC_AID.value, MIIASECC_AID.len);
card->ef_atr->aid.len = MIIASECC_AID.len;
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_init_amos_or_sagem(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
unsigned int flags;
int rv = 0;
LOG_FUNC_CALLED(ctx);
flags = IASECC_CARD_DEFAULT_FLAGS;
_sc_card_add_rsa_alg(card, 1024, flags, 0x10001);
_sc_card_add_rsa_alg(card, 2048, flags, 0x10001);
card->caps = SC_CARD_CAP_RNG;
card->caps |= SC_CARD_CAP_APDU_EXT;
card->caps |= SC_CARD_CAP_USE_FCI_AC;
if (card->type == SC_CARD_TYPE_IASECC_MI) {
rv = iasecc_mi_match(card);
if (rv)
card->type = SC_CARD_TYPE_IASECC_MI2;
else
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
rv = iasecc_parse_ef_atr(card);
if (rv == SC_ERROR_FILE_NOT_FOUND) {
rv = iasecc_select_mf(card, NULL);
LOG_TEST_RET(ctx, rv, "MF selection error");
rv = iasecc_parse_ef_atr(card);
}
LOG_TEST_RET(ctx, rv, "IASECC: ATR parse failed");
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_init(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
struct iasecc_private_data *private_data = NULL;
int rv = SC_ERROR_NO_CARD_SUPPORT;
LOG_FUNC_CALLED(ctx);
private_data = (struct iasecc_private_data *) calloc(1, sizeof(struct iasecc_private_data));
if (private_data == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
card->cla = 0x00;
card->drv_data = private_data;
if (card->type == SC_CARD_TYPE_IASECC_GEMALTO)
rv = iasecc_init_gemalto(card);
else if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR)
rv = iasecc_init_oberthur(card);
else if (card->type == SC_CARD_TYPE_IASECC_SAGEM)
rv = iasecc_init_amos_or_sagem(card);
else if (card->type == SC_CARD_TYPE_IASECC_AMOS)
rv = iasecc_init_amos_or_sagem(card);
else if (card->type == SC_CARD_TYPE_IASECC_MI)
rv = iasecc_init_amos_or_sagem(card);
else
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_CARD);
if (!rv) {
if (card->ef_atr && card->ef_atr->aid.len) {
struct sc_path path;
memset(&path, 0, sizeof(struct sc_path));
path.type = SC_PATH_TYPE_DF_NAME;
memcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len);
path.len = card->ef_atr->aid.len;
rv = iasecc_select_file(card, &path, NULL);
sc_log(ctx, "Select ECC ROOT with the AID from EF.ATR: rv %i", rv);
LOG_TEST_RET(ctx, rv, "Select EF.ATR AID failed");
}
rv = iasecc_get_serialnr(card, NULL);
}
#ifdef ENABLE_SM
card->sm_ctx.ops.read_binary = _iasecc_sm_read_binary;
card->sm_ctx.ops.update_binary = _iasecc_sm_update_binary;
#endif
if (!rv) {
sc_log(ctx, "EF.ATR(aid:'%s')", sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len));
rv = SC_ERROR_INVALID_CARD;
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_read_binary(struct sc_card *card, unsigned int offs,
unsigned char *buf, size_t count, unsigned long flags)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"iasecc_read_binary(card:%p) offs %i; count %"SC_FORMAT_LEN_SIZE_T"u",
card, offs, count);
if (offs > 0x7fff) {
sc_log(ctx, "invalid EF offset: 0x%X > 0x7FFF", offs);
return SC_ERROR_OFFSET_TOO_LARGE;
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, (offs >> 8) & 0x7F, offs & 0xFF);
apdu.le = count < 0x100 ? count : 0x100;
apdu.resplen = count;
apdu.resp = buf;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "iasecc_read_binary() failed");
sc_log(ctx,
"iasecc_read_binary() apdu.resplen %"SC_FORMAT_LEN_SIZE_T"u",
apdu.resplen);
if (apdu.resplen == IASECC_READ_BINARY_LENGTH_MAX && apdu.resplen < count) {
rv = iasecc_read_binary(card, offs + apdu.resplen, buf + apdu.resplen, count - apdu.resplen, flags);
if (rv != SC_ERROR_WRONG_LENGTH) {
LOG_TEST_RET(ctx, rv, "iasecc_read_binary() read tail failed");
apdu.resplen += rv;
}
}
LOG_FUNC_RETURN(ctx, apdu.resplen);
}
static int
iasecc_erase_binary(struct sc_card *card, unsigned int offs, size_t count, unsigned long flags)
{
struct sc_context *ctx = card->ctx;
unsigned char *tmp = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"iasecc_erase_binary(card:%p) count %"SC_FORMAT_LEN_SIZE_T"u",
card, count);
if (!count)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "'ERASE BINARY' failed: invalid size to erase");
tmp = malloc(count);
if (!tmp)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate temporary buffer");
memset(tmp, 0xFF, count);
rv = sc_update_binary(card, offs, tmp, count, flags);
free(tmp);
LOG_TEST_RET(ctx, rv, "iasecc_erase_binary() update binary error");
LOG_FUNC_RETURN(ctx, rv);
}
#if ENABLE_SM
static int
_iasecc_sm_read_binary(struct sc_card *card, unsigned int offs,
unsigned char *buff, size_t count)
{
struct sc_context *ctx = card->ctx;
const struct sc_acl_entry *entry = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"iasecc_sm_read_binary() card:%p offs:%i count:%"SC_FORMAT_LEN_SIZE_T"u ",
card, offs, count);
if (offs > 0x7fff)
LOG_TEST_RET(ctx, SC_ERROR_OFFSET_TOO_LARGE, "Invalid arguments");
if (count == 0)
return 0;
sc_print_cache(card);
if (card->cache.valid && card->cache.current_ef) {
entry = sc_file_get_acl_entry(card->cache.current_ef, SC_AC_OP_READ);
if (!entry)
LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "iasecc_sm_read() 'READ' ACL not present");
sc_log(ctx, "READ method/reference %X/%X", entry->method, entry->key_ref);
if ((entry->method == SC_AC_SCB) && (entry->key_ref & IASECC_SCB_METHOD_SM)) {
unsigned char se_num = (entry->method == SC_AC_SCB) ? (entry->key_ref & IASECC_SCB_METHOD_MASK_REF) : 0;
rv = iasecc_sm_read_binary(card, se_num, offs, buff, count);
LOG_FUNC_RETURN(ctx, rv);
}
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
_iasecc_sm_update_binary(struct sc_card *card, unsigned int offs,
const unsigned char *buff, size_t count)
{
struct sc_context *ctx = card->ctx;
const struct sc_acl_entry *entry = NULL;
int rv;
if (count == 0)
return SC_SUCCESS;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"iasecc_sm_read_binary() card:%p offs:%i count:%"SC_FORMAT_LEN_SIZE_T"u ",
card, offs, count);
sc_print_cache(card);
if (card->cache.valid && card->cache.current_ef) {
entry = sc_file_get_acl_entry(card->cache.current_ef, SC_AC_OP_UPDATE);
if (!entry)
LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "iasecc_sm_update() 'UPDATE' ACL not present");
sc_log(ctx, "UPDATE method/reference %X/%X", entry->method, entry->key_ref);
if (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) {
unsigned char se_num = entry->method == SC_AC_SCB ? entry->key_ref & IASECC_SCB_METHOD_MASK_REF : 0;
rv = iasecc_sm_update_binary(card, se_num, offs, buff, count);
LOG_FUNC_RETURN(ctx, rv);
}
}
LOG_FUNC_RETURN(ctx, 0);
}
#endif
static int
iasecc_emulate_fcp(struct sc_context *ctx, struct sc_apdu *apdu)
{
unsigned char dummy_df_fcp[] = {
0x62,0xFF,
0x82,0x01,0x38,
0x8A,0x01,0x05,
0xA1,0x04,0x8C,0x02,0x02,0x00,
0x84,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF
};
LOG_FUNC_CALLED(ctx);
if (apdu->p1 != 0x04)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "FCP emulation supported only for the DF-NAME selection type");
if (apdu->datalen > 16)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid DF-NAME length");
if (apdu->resplen < apdu->datalen + 16)
LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "not enough space for FCP data");
memcpy(dummy_df_fcp + 16, apdu->data, apdu->datalen);
dummy_df_fcp[15] = apdu->datalen;
dummy_df_fcp[1] = apdu->datalen + 14;
memcpy(apdu->resp, dummy_df_fcp, apdu->datalen + 16);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
/* TODO: redesign using of cache
* TODO: do not keep intermediate results in 'file_out' argument */
static int
iasecc_select_file(struct sc_card *card, const struct sc_path *path,
struct sc_file **file_out)
{
struct sc_context *ctx = card->ctx;
struct sc_path lpath;
int cache_valid = card->cache.valid, df_from_cache = 0;
int rv, ii;
LOG_FUNC_CALLED(ctx);
memcpy(&lpath, path, sizeof(struct sc_path));
if (file_out)
*file_out = NULL;
sc_log(ctx,
"iasecc_select_file(card:%p) path.len %"SC_FORMAT_LEN_SIZE_T"u; path.type %i; aid_len %"SC_FORMAT_LEN_SIZE_T"u",
card, path->len, path->type, path->aid.len);
sc_log(ctx, "iasecc_select_file() path:%s", sc_print_path(path));
sc_print_cache(card);
if (path->type != SC_PATH_TYPE_DF_NAME
&& lpath.len >= 2
&& lpath.value[0] == 0x3F && lpath.value[1] == 0x00) {
sc_log(ctx, "EF.ATR(aid:'%s')", card->ef_atr ? sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len) : "");
rv = iasecc_select_mf(card, file_out);
LOG_TEST_RET(ctx, rv, "MF selection error");
memmove(&lpath.value[0], &lpath.value[2], lpath.len - 2);
lpath.len -= 2;
}
if (lpath.aid.len) {
struct sc_file *file = NULL;
struct sc_path ppath;
sc_log(ctx,
"iasecc_select_file() select parent AID:%p/%"SC_FORMAT_LEN_SIZE_T"u",
lpath.aid.value, lpath.aid.len);
sc_log(ctx, "iasecc_select_file() select parent AID:%s", sc_dump_hex(lpath.aid.value, lpath.aid.len));
memset(&ppath, 0, sizeof(ppath));
memcpy(ppath.value, lpath.aid.value, lpath.aid.len);
ppath.len = lpath.aid.len;
ppath.type = SC_PATH_TYPE_DF_NAME;
if (card->cache.valid && card->cache.current_df
&& card->cache.current_df->path.len == lpath.aid.len
&& !memcmp(card->cache.current_df->path.value, lpath.aid.value, lpath.aid.len))
df_from_cache = 1;
rv = iasecc_select_file(card, &ppath, &file);
LOG_TEST_RET(ctx, rv, "select AID path failed");
if (file_out)
*file_out = file;
else
sc_file_free(file);
if (lpath.type == SC_PATH_TYPE_DF_NAME)
lpath.type = SC_PATH_TYPE_FROM_CURRENT;
}
if (lpath.type == SC_PATH_TYPE_PATH)
lpath.type = SC_PATH_TYPE_FROM_CURRENT;
if (!lpath.len)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
sc_print_cache(card);
if (card->cache.valid && card->cache.current_df && lpath.type == SC_PATH_TYPE_DF_NAME
&& card->cache.current_df->path.len == lpath.len
&& !memcmp(card->cache.current_df->path.value, lpath.value, lpath.len)) {
sc_log(ctx, "returns current DF path %s", sc_print_path(&card->cache.current_df->path));
if (file_out) {
sc_file_free(*file_out);
sc_file_dup(file_out, card->cache.current_df);
}
sc_print_cache(card);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
do {
struct sc_apdu apdu;
struct sc_file *file = NULL;
unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE];
int pathlen = lpath.len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00);
if (card->type != SC_CARD_TYPE_IASECC_GEMALTO
&& card->type != SC_CARD_TYPE_IASECC_OBERTHUR
&& card->type != SC_CARD_TYPE_IASECC_SAGEM
&& card->type != SC_CARD_TYPE_IASECC_AMOS
&& card->type != SC_CARD_TYPE_IASECC_MI
&& card->type != SC_CARD_TYPE_IASECC_MI2)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Unsupported card");
if (lpath.type == SC_PATH_TYPE_FILE_ID) {
apdu.p1 = 0x02;
if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR) {
apdu.p1 = 0x01;
apdu.p2 = 0x04;
}
if (card->type == SC_CARD_TYPE_IASECC_AMOS)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_MI)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_MI2)
apdu.p2 = 0x04;
}
else if (lpath.type == SC_PATH_TYPE_FROM_CURRENT) {
apdu.p1 = 0x09;
if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_AMOS)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_MI)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_MI2)
apdu.p2 = 0x04;
}
else if (lpath.type == SC_PATH_TYPE_PARENT) {
apdu.p1 = 0x03;
pathlen = 0;
apdu.cse = SC_APDU_CASE_2_SHORT;
}
else if (lpath.type == SC_PATH_TYPE_DF_NAME) {
apdu.p1 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_AMOS)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_MI2)
apdu.p2 = 0x04;
}
else {
sc_log(ctx, "Invalid PATH type: 0x%X", lpath.type);
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "iasecc_select_file() invalid PATH type");
}
for (ii=0; ii<2; ii++) {
apdu.lc = pathlen;
apdu.data = lpath.value;
apdu.datalen = pathlen;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (rv == SC_ERROR_INCORRECT_PARAMETERS &&
lpath.type == SC_PATH_TYPE_DF_NAME && apdu.p2 == 0x00) {
apdu.p2 = 0x0C;
continue;
}
if (ii) {
/* 'SELECT AID' do not returned FCP. Try to emulate. */
apdu.resplen = sizeof(rbuf);
rv = iasecc_emulate_fcp(ctx, &apdu);
LOG_TEST_RET(ctx, rv, "Failed to emulate DF FCP");
}
break;
}
/*
* Using of the cached DF and EF can cause problems in the multi-thread environment.
* FIXME: introduce config. option that invalidates this cache outside the locked card session,
* (or invent something else)
*/
if (rv == SC_ERROR_FILE_NOT_FOUND && cache_valid && df_from_cache) {
sc_invalidate_cache(card);
sc_log(ctx, "iasecc_select_file() file not found, retry without cached DF");
if (file_out) {
sc_file_free(*file_out);
*file_out = NULL;
}
rv = iasecc_select_file(card, path, file_out);
LOG_FUNC_RETURN(ctx, rv);
}
LOG_TEST_RET(ctx, rv, "iasecc_select_file() check SW failed");
sc_log(ctx,
"iasecc_select_file() apdu.resp %"SC_FORMAT_LEN_SIZE_T"u",
apdu.resplen);
if (apdu.resplen) {
sc_log(ctx, "apdu.resp %02X:%02X:%02X...", apdu.resp[0], apdu.resp[1], apdu.resp[2]);
switch (apdu.resp[0]) {
case 0x62:
case 0x6F:
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
file->path = lpath;
rv = iasecc_process_fci(card, file, apdu.resp, apdu.resplen);
if (rv)
LOG_FUNC_RETURN(ctx, rv);
break;
default:
LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
sc_log(ctx, "FileType %i", file->type);
if (file->type == SC_FILE_TYPE_DF) {
if (card->cache.valid)
sc_file_free(card->cache.current_df);
card->cache.current_df = NULL;
if (card->cache.valid)
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
sc_file_dup(&card->cache.current_df, file);
card->cache.valid = 1;
}
else {
if (card->cache.valid)
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
sc_file_dup(&card->cache.current_ef, file);
}
if (file_out) {
sc_file_free(*file_out);
*file_out = file;
}
else {
sc_file_free(file);
}
}
else if (lpath.type == SC_PATH_TYPE_DF_NAME) {
sc_file_free(card->cache.current_df);
card->cache.current_df = NULL;
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
card->cache.valid = 1;
}
} while(0);
sc_print_cache(card);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_process_fci(struct sc_card *card, struct sc_file *file,
const unsigned char *buf, size_t buflen)
{
struct sc_context *ctx = card->ctx;
size_t taglen;
int rv, ii, offs;
const unsigned char *acls = NULL, *tag = NULL;
unsigned char mask;
unsigned char ops_DF[7] = {
SC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_CREATE, 0xFF
};
unsigned char ops_EF[7] = {
SC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_UPDATE, SC_AC_OP_READ
};
LOG_FUNC_CALLED(ctx);
tag = sc_asn1_find_tag(ctx, buf, buflen, 0x6F, &taglen);
sc_log(ctx, "processing FCI: 0x6F tag %p", tag);
if (tag != NULL) {
sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen);
buf = tag;
buflen = taglen;
}
tag = sc_asn1_find_tag(ctx, buf, buflen, 0x62, &taglen);
sc_log(ctx, "processing FCI: 0x62 tag %p", tag);
if (tag != NULL) {
sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen);
buf = tag;
buflen = taglen;
}
rv = iso_ops->process_fci(card, file, buf, buflen);
LOG_TEST_RET(ctx, rv, "ISO parse FCI failed");
/*
Gemalto: 6F 19 80 02 02 ED 82 01 01 83 02 B0 01 88 00 8C 07 7B 17 17 17 17 17 00 8A 01 05 90 00
Sagem: 6F 17 62 15 80 02 00 7D 82 01 01 8C 02 01 00 83 02 2F 00 88 01 F0 8A 01 05 90 00
Oberthur: 62 1B 80 02 05 DC 82 01 01 83 02 B0 01 88 00 A1 09 8C 07 7B 17 FF 17 17 17 00 8A 01 05 90 00
*/
sc_log(ctx, "iasecc_process_fci() type %i; let's parse file ACLs", file->type);
tag = sc_asn1_find_tag(ctx, buf, buflen, IASECC_DOCP_TAG_ACLS, &taglen);
if (tag)
acls = sc_asn1_find_tag(ctx, tag, taglen, IASECC_DOCP_TAG_ACLS_CONTACT, &taglen);
else
acls = sc_asn1_find_tag(ctx, buf, buflen, IASECC_DOCP_TAG_ACLS_CONTACT, &taglen);
if (!acls) {
sc_log(ctx,
"ACLs not found in data(%"SC_FORMAT_LEN_SIZE_T"u) %s",
buflen, sc_dump_hex(buf, buflen));
LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "ACLs tag missing");
}
sc_log(ctx, "ACLs(%"SC_FORMAT_LEN_SIZE_T"u) '%s'", taglen,
sc_dump_hex(acls, taglen));
mask = 0x40, offs = 1;
for (ii = 0; ii < 7; ii++, mask /= 2) {
unsigned char op = file->type == SC_FILE_TYPE_DF ? ops_DF[ii] : ops_EF[ii];
if (!(mask & acls[0]))
continue;
sc_log(ctx, "ACLs mask 0x%X, offs %i, op 0x%X, acls[offs] 0x%X", mask, offs, op, acls[offs]);
if (op == 0xFF) {
;
}
else if (acls[offs] == 0) {
sc_file_add_acl_entry(file, op, SC_AC_NONE, 0);
}
else if (acls[offs] == 0xFF) {
sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0);
}
else if ((acls[offs] & IASECC_SCB_METHOD_MASK) == IASECC_SCB_METHOD_USER_AUTH) {
sc_file_add_acl_entry(file, op, SC_AC_SEN, acls[offs] & IASECC_SCB_METHOD_MASK_REF);
}
else if (acls[offs] & IASECC_SCB_METHOD_MASK) {
sc_file_add_acl_entry(file, op, SC_AC_SCB, acls[offs]);
}
else {
sc_log(ctx, "Warning: non supported SCB method: %X", acls[offs]);
sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0);
}
offs++;
}
LOG_FUNC_RETURN(ctx, 0);
}
static int
iasecc_fcp_encode(struct sc_card *card, struct sc_file *file, unsigned char *out, size_t out_len)
{
struct sc_context *ctx = card->ctx;
unsigned char buf[0x80], type;
unsigned char ops[7] = {
SC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_UPDATE, SC_AC_OP_READ
};
unsigned char smbs[8];
size_t ii, offs = 0, amb, mask, nn_smb;
LOG_FUNC_CALLED(ctx);
if (file->type == SC_FILE_TYPE_DF)
type = IASECC_FCP_TYPE_DF;
else
type = IASECC_FCP_TYPE_EF;
buf[offs++] = IASECC_FCP_TAG_SIZE;
buf[offs++] = 2;
buf[offs++] = (file->size >> 8) & 0xFF;
buf[offs++] = file->size & 0xFF;
buf[offs++] = IASECC_FCP_TAG_TYPE;
buf[offs++] = 1;
buf[offs++] = type;
buf[offs++] = IASECC_FCP_TAG_FID;
buf[offs++] = 2;
buf[offs++] = (file->id >> 8) & 0xFF;
buf[offs++] = file->id & 0xFF;
buf[offs++] = IASECC_FCP_TAG_SFID;
buf[offs++] = 0;
amb = 0, mask = 0x40, nn_smb = 0;
for (ii = 0; ii < sizeof(ops); ii++, mask >>= 1) {
const struct sc_acl_entry *entry;
if (ops[ii]==0xFF)
continue;
entry = sc_file_get_acl_entry(file, ops[ii]);
if (!entry)
continue;
sc_log(ctx, "method %X; reference %X", entry->method, entry->key_ref);
if (entry->method == SC_AC_NEVER)
continue;
else if (entry->method == SC_AC_NONE)
smbs[nn_smb++] = 0x00;
else if (entry->method == SC_AC_CHV)
smbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_USER_AUTH;
else if (entry->method == SC_AC_SEN)
smbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_USER_AUTH;
else if (entry->method == SC_AC_SCB)
smbs[nn_smb++] = entry->key_ref;
else if (entry->method == SC_AC_PRO)
smbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_SM;
else
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Non supported AC method");
amb |= mask;
sc_log(ctx,
"%"SC_FORMAT_LEN_SIZE_T"u: AMB %"SC_FORMAT_LEN_SIZE_T"X; nn_smb %"SC_FORMAT_LEN_SIZE_T"u",
ii, amb, nn_smb);
}
/* TODO: Encode contactless ACLs and life cycle status for all IAS/ECC cards */
if (card->type == SC_CARD_TYPE_IASECC_SAGEM ||
card->type == SC_CARD_TYPE_IASECC_AMOS ) {
unsigned char status = 0;
buf[offs++] = IASECC_FCP_TAG_ACLS;
buf[offs++] = 2*(2 + 1 + nn_smb);
buf[offs++] = IASECC_FCP_TAG_ACLS_CONTACT;
buf[offs++] = nn_smb + 1;
buf[offs++] = amb;
memcpy(buf + offs, smbs, nn_smb);
offs += nn_smb;
/* Same ACLs for contactless */
buf[offs++] = IASECC_FCP_TAG_ACLS_CONTACTLESS;
buf[offs++] = nn_smb + 1;
buf[offs++] = amb;
memcpy(buf + offs, smbs, nn_smb);
offs += nn_smb;
if (file->status == SC_FILE_STATUS_ACTIVATED)
status = 0x05;
else if (file->status == SC_FILE_STATUS_CREATION)
status = 0x01;
if (status) {
buf[offs++] = 0x8A;
buf[offs++] = 0x01;
buf[offs++] = status;
}
}
else {
buf[offs++] = IASECC_FCP_TAG_ACLS;
buf[offs++] = 2 + 1 + nn_smb;
buf[offs++] = IASECC_FCP_TAG_ACLS_CONTACT;
buf[offs++] = nn_smb + 1;
buf[offs++] = amb;
memcpy(buf + offs, smbs, nn_smb);
offs += nn_smb;
}
if (out) {
if (out_len < offs)
LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Buffer too small to encode FCP");
memcpy(out, buf, offs);
}
LOG_FUNC_RETURN(ctx, offs);
}
static int
iasecc_create_file(struct sc_card *card, struct sc_file *file)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
const struct sc_acl_entry *entry = NULL;
unsigned char sbuf[0x100];
size_t sbuf_len;
int rv;
LOG_FUNC_CALLED(ctx);
sc_print_cache(card);
if (file->type != SC_FILE_TYPE_WORKING_EF)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Creation of the file with of this type is not supported");
sbuf_len = iasecc_fcp_encode(card, file, sbuf + 2, sizeof(sbuf)-2);
LOG_TEST_RET(ctx, sbuf_len, "FCP encode error");
sbuf[0] = IASECC_FCP_TAG;
sbuf[1] = sbuf_len;
if (card->cache.valid && card->cache.current_df) {
entry = sc_file_get_acl_entry(card->cache.current_df, SC_AC_OP_CREATE);
if (!entry)
LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "iasecc_create_file() 'CREATE' ACL not present");
sc_log(ctx, "iasecc_create_file() 'CREATE' method/reference %X/%X", entry->method, entry->key_ref);
sc_log(ctx, "iasecc_create_file() create data: '%s'", sc_dump_hex(sbuf, sbuf_len + 2));
if (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) {
rv = iasecc_sm_create_file(card, entry->key_ref & IASECC_SCB_METHOD_MASK_REF, sbuf, sbuf_len + 2);
LOG_TEST_RET(ctx, rv, "iasecc_create_file() SM create file error");
rv = iasecc_select_file(card, &file->path, NULL);
LOG_FUNC_RETURN(ctx, rv);
}
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0, 0);
apdu.data = sbuf;
apdu.datalen = sbuf_len + 2;
apdu.lc = sbuf_len + 2;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "iasecc_create_file() create file error");
rv = iasecc_select_file(card, &file->path, NULL);
LOG_TEST_RET(ctx, rv, "Cannot select newly created file");
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_logout(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
struct sc_path path;
int rv;
LOG_FUNC_CALLED(ctx);
if (!card->ef_atr || !card->ef_atr->aid.len)
return SC_SUCCESS;
memset(&path, 0, sizeof(struct sc_path));
path.type = SC_PATH_TYPE_DF_NAME;
memcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len);
path.len = card->ef_atr->aid.len;
rv = iasecc_select_file(card, &path, NULL);
sc_log(ctx, "Select ECC ROOT with the AID from EF.ATR: rv %i", rv);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_finish(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
struct iasecc_private_data *private_data = (struct iasecc_private_data *)card->drv_data;
struct iasecc_se_info *se_info = private_data->se_info, *next;
LOG_FUNC_CALLED(ctx);
while (se_info) {
sc_file_free(se_info->df);
next = se_info->next;
free(se_info);
se_info = next;
}
free(card->drv_data);
card->drv_data = NULL;
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_delete_file(struct sc_card *card, const struct sc_path *path)
{
struct sc_context *ctx = card->ctx;
const struct sc_acl_entry *entry = NULL;
struct sc_apdu apdu;
struct sc_file *file = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
sc_print_cache(card);
rv = iasecc_select_file(card, path, &file);
if (rv == SC_ERROR_FILE_NOT_FOUND)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
LOG_TEST_RET(ctx, rv, "Cannot select file to delete");
entry = sc_file_get_acl_entry(file, SC_AC_OP_DELETE);
if (!entry)
LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "Cannot delete file: no 'DELETE' acl");
sc_log(ctx, "DELETE method/reference %X/%X", entry->method, entry->key_ref);
if (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) {
unsigned char se_num = (entry->method == SC_AC_SCB) ? (entry->key_ref & IASECC_SCB_METHOD_MASK_REF) : 0;
rv = iasecc_sm_delete_file(card, se_num, file->id);
}
else {
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xE4, 0x00, 0x00);
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "Delete file failed");
if (card->cache.valid)
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
}
sc_file_free(file);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2)
{
if (sw1 == 0x62 && sw2 == 0x82)
return SC_SUCCESS;
return iso_ops->check_sw(card, sw1, sw2);
}
static unsigned
iasecc_get_algorithm(struct sc_context *ctx, const struct sc_security_env *env,
unsigned operation, unsigned mechanism)
{
const struct sc_supported_algo_info *info = NULL;
int ii;
if (!env)
return 0;
for (ii=0;ii<SC_MAX_SUPPORTED_ALGORITHMS && env->supported_algos[ii].reference; ii++)
if ((env->supported_algos[ii].operations & operation)
&& (env->supported_algos[ii].mechanism == mechanism))
break;
if (ii < SC_MAX_SUPPORTED_ALGORITHMS && env->supported_algos[ii].reference) {
info = &env->supported_algos[ii];
sc_log(ctx, "found IAS/ECC algorithm %X:%X:%X:%X",
info->reference, info->mechanism, info->operations, info->algo_ref);
}
else {
sc_log(ctx, "cannot find IAS/ECC algorithm (operation:%X,mechanism:%X)", operation, mechanism);
}
return info ? info->algo_ref : 0;
}
static int
iasecc_se_cache_info(struct sc_card *card, struct iasecc_se_info *se)
{
struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;
struct sc_context *ctx = card->ctx;
struct iasecc_se_info *se_info = NULL, *si = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
se_info = calloc(1, sizeof(struct iasecc_se_info));
if (!se_info)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "SE info allocation error");
memcpy(se_info, se, sizeof(struct iasecc_se_info));
if (card->cache.valid && card->cache.current_df) {
sc_file_dup(&se_info->df, card->cache.current_df);
if (se_info->df == NULL) {
free(se_info);
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot duplicate current DF file");
}
}
rv = iasecc_docp_copy(ctx, &se->docp, &se_info->docp);
if (rv < 0) {
free(se_info->df);
free(se_info);
LOG_TEST_RET(ctx, rv, "Cannot make copy of DOCP");
}
if (!prv->se_info) {
prv->se_info = se_info;
}
else {
for (si = prv->se_info; si->next; si = si->next)
;
si->next = se_info;
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_se_get_info_from_cache(struct sc_card *card, struct iasecc_se_info *se)
{
struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;
struct sc_context *ctx = card->ctx;
struct iasecc_se_info *si = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
for(si = prv->se_info; si; si = si->next) {
if (si->reference != se->reference)
continue;
if (!(card->cache.valid && card->cache.current_df) && si->df)
continue;
if (card->cache.valid && card->cache.current_df && !si->df)
continue;
if (card->cache.valid && card->cache.current_df && si->df)
if (memcmp(&card->cache.current_df->path, &si->df->path, sizeof(struct sc_path)))
continue;
break;
}
if (!si)
return SC_ERROR_OBJECT_NOT_FOUND;
memcpy(se, si, sizeof(struct iasecc_se_info));
if (si->df) {
sc_file_dup(&se->df, si->df);
if (se->df == NULL)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot duplicate current DF file");
}
rv = iasecc_docp_copy(ctx, &si->docp, &se->docp);
LOG_TEST_RET(ctx, rv, "Cannot make copy of DOCP");
LOG_FUNC_RETURN(ctx, rv);
}
int
iasecc_se_get_info(struct sc_card *card, struct iasecc_se_info *se)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char rbuf[0x100];
unsigned char sbuf_iasecc[10] = {
0x4D, 0x08, IASECC_SDO_TEMPLATE_TAG, 0x06,
IASECC_SDO_TAG_HEADER, IASECC_SDO_CLASS_SE | IASECC_OBJECT_REF_LOCAL,
se->reference & 0x3F,
0x02, IASECC_SDO_CLASS_SE, 0x80
};
int rv;
LOG_FUNC_CALLED(ctx);
if (se->reference > IASECC_SE_REF_MAX)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
rv = iasecc_se_get_info_from_cache(card, se);
if (rv == SC_ERROR_OBJECT_NOT_FOUND) {
sc_log(ctx, "No SE#%X info in cache, try to use 'GET DATA'", se->reference);
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xCB, 0x3F, 0xFF);
apdu.data = sbuf_iasecc;
apdu.datalen = sizeof(sbuf_iasecc);
apdu.lc = apdu.datalen;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = sizeof(rbuf);
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "get SE data error");
rv = iasecc_se_parse(card, apdu.resp, apdu.resplen, se);
LOG_TEST_RET(ctx, rv, "cannot parse SE data");
rv = iasecc_se_cache_info(card, se);
LOG_TEST_RET(ctx, rv, "failed to put SE data into cache");
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_set_security_env(struct sc_card *card,
const struct sc_security_env *env, int se_num)
{
struct sc_context *ctx = card->ctx;
struct iasecc_sdo sdo;
struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;
unsigned algo_ref;
struct sc_apdu apdu;
unsigned sign_meth, sign_ref, auth_meth, auth_ref, aflags;
unsigned char cse_crt_at[] = {
0x84, 0x01, 0xFF,
0x80, 0x01, IASECC_ALGORITHM_RSA_PKCS
};
unsigned char cse_crt_dst[] = {
0x84, 0x01, 0xFF,
0x80, 0x01, (IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA1)
};
unsigned char cse_crt_ht[] = {
0x80, 0x01, IASECC_ALGORITHM_SHA1
};
unsigned char cse_crt_ct[] = {
0x84, 0x01, 0xFF,
0x80, 0x01, (IASECC_ALGORITHM_RSA_PKCS_DECRYPT | IASECC_ALGORITHM_SHA1)
};
int rv, operation = env->operation;
/* TODO: take algorithm references from 5032, not from header file. */
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "iasecc_set_security_env(card:%p) operation 0x%X; senv.algorithm 0x%X, senv.algorithm_ref 0x%X",
card, env->operation, env->algorithm, env->algorithm_ref);
memset(&sdo, 0, sizeof(sdo));
sdo.sdo_class = IASECC_SDO_CLASS_RSA_PRIVATE;
sdo.sdo_ref = env->key_ref[0] & ~IASECC_OBJECT_REF_LOCAL;
rv = iasecc_sdo_get_data(card, &sdo);
LOG_TEST_RET(ctx, rv, "Cannot get RSA PRIVATE SDO data");
/* To made by iasecc_sdo_convert_to_file() */
prv->key_size = *(sdo.docp.size.value + 0) * 0x100 + *(sdo.docp.size.value + 1);
sc_log(ctx, "prv->key_size 0x%"SC_FORMAT_LEN_SIZE_T"X", prv->key_size);
rv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_PSO_COMPUTE_SIGNATURE, &sign_meth, &sign_ref);
LOG_TEST_RET(ctx, rv, "Cannot convert SC_AC_OP_SIGN acl");
rv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_INTERNAL_AUTHENTICATE, &auth_meth, &auth_ref);
LOG_TEST_RET(ctx, rv, "Cannot convert SC_AC_OP_INT_AUTH acl");
aflags = env->algorithm_flags;
if (!(aflags & SC_ALGORITHM_RSA_PAD_PKCS1))
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Only supported signature with PKCS1 padding");
if (operation == SC_SEC_OPERATION_SIGN) {
if (!(aflags & (SC_ALGORITHM_RSA_HASH_SHA1 | SC_ALGORITHM_RSA_HASH_SHA256))) {
sc_log(ctx, "CKM_RSA_PKCS asked -- use 'AUTHENTICATE' sign operation instead of 'SIGN'");
operation = SC_SEC_OPERATION_AUTHENTICATE;
}
else if (sign_meth == SC_AC_NEVER) {
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "PSO_DST not allowed for this key");
}
}
if (operation == SC_SEC_OPERATION_SIGN) {
prv->op_method = sign_meth;
prv->op_ref = sign_ref;
}
else if (operation == SC_SEC_OPERATION_AUTHENTICATE) {
if (auth_meth == SC_AC_NEVER)
LOG_TEST_RET(ctx, SC_ERROR_NOT_ALLOWED, "INTERNAL_AUTHENTICATE is not allowed for this key");
prv->op_method = auth_meth;
prv->op_ref = auth_ref;
}
sc_log(ctx, "senv.algorithm 0x%X, senv.algorithm_ref 0x%X", env->algorithm, env->algorithm_ref);
sc_log(ctx,
"se_num %i, operation 0x%X, algorithm 0x%X, algorithm_ref 0x%X, flags 0x%X; key size %"SC_FORMAT_LEN_SIZE_T"u",
se_num, operation, env->algorithm, env->algorithm_ref,
env->algorithm_flags, prv->key_size);
switch (operation) {
case SC_SEC_OPERATION_SIGN:
if (!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1))
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Need RSA_PKCS1 specified");
if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA256) {
algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_HASH, CKM_SHA256);
if (!algo_ref)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Card application do not supports HASH:SHA256");
cse_crt_ht[2] = algo_ref; /* IASECC_ALGORITHM_SHA2 */
algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_SHA256_RSA_PKCS);
if (!algo_ref)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Card application do not supports SIGNATURE:SHA1_RSA_PKCS");
cse_crt_dst[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL;
cse_crt_dst[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA2 */
}
else if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) {
algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_HASH, CKM_SHA_1);
if (!algo_ref)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Card application do not supports HASH:SHA1");
cse_crt_ht[2] = algo_ref; /* IASECC_ALGORITHM_SHA1 */
algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_SHA1_RSA_PKCS);
if (!algo_ref)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Card application do not supports SIGNATURE:SHA1_RSA_PKCS");
cse_crt_dst[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL;
cse_crt_dst[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA1 */
}
else {
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Need RSA_HASH_SHA[1,256] specified");
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_HT);
apdu.data = cse_crt_ht;
apdu.datalen = sizeof(cse_crt_ht);
apdu.lc = sizeof(cse_crt_ht);
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "MSE restore error");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_DST);
apdu.data = cse_crt_dst;
apdu.datalen = sizeof(cse_crt_dst);
apdu.lc = sizeof(cse_crt_dst);
break;
case SC_SEC_OPERATION_AUTHENTICATE:
algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_RSA_PKCS);
if (!algo_ref)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Application do not supports SIGNATURE:RSA_PKCS");
cse_crt_at[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL;
cse_crt_at[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_AT);
apdu.data = cse_crt_at;
apdu.datalen = sizeof(cse_crt_at);
apdu.lc = sizeof(cse_crt_at);
break;
case SC_SEC_OPERATION_DECIPHER:
rv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_PSO_DECRYPT, &prv->op_method, &prv->op_ref);
LOG_TEST_RET(ctx, rv, "Cannot convert SC_AC_OP_PSO_DECRYPT acl");
algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_DECIPHER, CKM_RSA_PKCS);
if (!algo_ref)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Application do not supports DECIPHER:RSA_PKCS");
cse_crt_ct[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL;
cse_crt_ct[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS_DECRYPT | IASECC_ALGORITHM_SHA1 */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_CT);
apdu.data = cse_crt_ct;
apdu.datalen = sizeof(cse_crt_ct);
apdu.lc = sizeof(cse_crt_ct);
break;
default:
LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
}
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "MSE restore error");
prv->security_env = *env;
prv->security_env.operation = operation;
LOG_FUNC_RETURN(ctx, 0);
}
static int
iasecc_chv_verify_pinpad(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left)
{
struct sc_context *ctx = card->ctx;
unsigned char buffer[0x100];
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "CHV PINPAD PIN reference %i", pin_cmd->pin_reference);
rv = iasecc_pin_is_verified(card, pin_cmd, tries_left);
if (!rv)
LOG_FUNC_RETURN(ctx, rv);
if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) {
sc_log(ctx, "Reader not ready for PIN PAD");
LOG_FUNC_RETURN(ctx, SC_ERROR_READER);
}
/* When PIN stored length available
* P10 verify data contains full template of 'VERIFY PIN' APDU.
* Without PIN stored length
* pin-pad has to set the Lc and fill PIN data itself.
* Not all pin-pads support this case
*/
pin_cmd->pin1.len = pin_cmd->pin1.stored_length;
pin_cmd->pin1.length_offset = 5;
memset(buffer, 0xFF, sizeof(buffer));
pin_cmd->pin1.data = buffer;
pin_cmd->cmd = SC_PIN_CMD_VERIFY;
pin_cmd->flags |= SC_PIN_CMD_USE_PINPAD;
/*
if (card->reader && card->reader->ops && card->reader->ops->load_message) {
rv = card->reader->ops->load_message(card->reader, card->slot, 0, "Here we are!");
sc_log(ctx, "Load message returned %i", rv);
}
*/
rv = iso_ops->pin_cmd(card, pin_cmd, tries_left);
sc_log(ctx, "rv %i", rv);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_chv_verify(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd,
int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct sc_acl_entry acl = pin_cmd->pin1.acls[IASECC_ACLS_CHV_VERIFY];
struct sc_apdu apdu;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "Verify CHV PIN(ref:%i,len:%i,acl:%X:%X)", pin_cmd->pin_reference, pin_cmd->pin1.len,
acl.method, acl.key_ref);
if (acl.method & IASECC_SCB_METHOD_SM) {
rv = iasecc_sm_pin_verify(card, acl.key_ref, pin_cmd, tries_left);
LOG_FUNC_RETURN(ctx, rv);
}
if (pin_cmd->pin1.data && !pin_cmd->pin1.len) {
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x20, 0, pin_cmd->pin_reference);
}
else if (pin_cmd->pin1.data && pin_cmd->pin1.len) {
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x20, 0, pin_cmd->pin_reference);
apdu.data = pin_cmd->pin1.data;
apdu.datalen = pin_cmd->pin1.len;
apdu.lc = pin_cmd->pin1.len;
}
else if ((card->reader->capabilities & SC_READER_CAP_PIN_PAD) && !pin_cmd->pin1.data && !pin_cmd->pin1.len) {
rv = iasecc_chv_verify_pinpad(card, pin_cmd, tries_left);
sc_log(ctx, "Result of verifying CHV with PIN pad %i", rv);
LOG_FUNC_RETURN(ctx, rv);
}
else {
LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
}
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
if (tries_left && apdu.sw1 == 0x63 && (apdu.sw2 & 0xF0) == 0xC0)
*tries_left = apdu.sw2 & 0x0F;
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_se_at_to_chv_reference(struct sc_card *card, unsigned reference,
unsigned *chv_reference)
{
struct sc_context *ctx = card->ctx;
struct iasecc_se_info se;
struct sc_crt crt;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "SE reference %i", reference);
if (reference > IASECC_SE_REF_MAX)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
memset(&se, 0, sizeof(se));
se.reference = reference;
rv = iasecc_se_get_info(card, &se);
LOG_TEST_RET(ctx, rv, "SDO get data error");
memset(&crt, 0, sizeof(crt));
crt.tag = IASECC_CRT_TAG_AT;
crt.usage = IASECC_UQB_AT_USER_PASSWORD;
rv = iasecc_se_get_crt(card, &se, &crt);
LOG_TEST_RET(ctx, rv, "no authentication template for USER PASSWORD");
if (chv_reference)
*chv_reference = crt.refs[0];
sc_file_free(se.df);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd_data,
int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct sc_pin_cmd_data pin_cmd;
struct sc_acl_entry acl = pin_cmd_data->pin1.acls[IASECC_ACLS_CHV_VERIFY];
int rv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
LOG_FUNC_CALLED(ctx);
if (pin_cmd_data->pin_type != SC_AC_CHV)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "PIN type is not supported for the verification");
sc_log(ctx, "Verify ACL(method:%X;ref:%X)", acl.method, acl.key_ref);
if (acl.method != IASECC_SCB_ALWAYS)
LOG_FUNC_RETURN(ctx, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED);
pin_cmd = *pin_cmd_data;
pin_cmd.pin1.data = (unsigned char *)"";
pin_cmd.pin1.len = 0;
rv = iasecc_chv_verify(card, &pin_cmd, tries_left);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_pin_verify(struct sc_card *card, unsigned type, unsigned reference,
const unsigned char *data, size_t data_len, int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct sc_pin_cmd_data pin_cmd;
unsigned chv_ref = reference;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"Verify PIN(type:%X,ref:%i,data(len:%"SC_FORMAT_LEN_SIZE_T"u,%p)",
type, reference, data_len, data);
if (type == SC_AC_AUT) {
rv = iasecc_sm_external_authentication(card, reference, tries_left);
LOG_FUNC_RETURN(ctx, rv);
}
else if (type == SC_AC_SCB) {
if (reference & IASECC_SCB_METHOD_USER_AUTH) {
type = SC_AC_SEN;
reference = reference & IASECC_SCB_METHOD_MASK_REF;
}
else {
sc_log(ctx, "Do not try to verify non CHV PINs");
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
}
if (type == SC_AC_SEN) {
rv = iasecc_se_at_to_chv_reference(card, reference, &chv_ref);
LOG_TEST_RET(ctx, rv, "SE AT to CHV reference error");
}
memset(&pin_cmd, 0, sizeof(pin_cmd));
pin_cmd.pin_type = SC_AC_CHV;
pin_cmd.pin_reference = chv_ref;
pin_cmd.cmd = SC_PIN_CMD_VERIFY;
rv = iasecc_pin_get_policy(card, &pin_cmd);
LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error");
pin_cmd.pin1.data = data;
pin_cmd.pin1.len = data_len;
rv = iasecc_pin_is_verified(card, &pin_cmd, tries_left);
if (data && !data_len)
LOG_FUNC_RETURN(ctx, rv);
if (!rv) {
if (iasecc_chv_cache_is_verified(card, &pin_cmd))
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
else if (rv != SC_ERROR_PIN_CODE_INCORRECT && rv != SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {
LOG_FUNC_RETURN(ctx, rv);
}
iasecc_chv_cache_clean(card, &pin_cmd);
rv = iasecc_chv_verify(card, &pin_cmd, tries_left);
LOG_TEST_RET(ctx, rv, "PIN CHV verification error");
rv = iasecc_chv_cache_verified(card, &pin_cmd);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_chv_change_pinpad(struct sc_card *card, unsigned reference, int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct sc_pin_cmd_data pin_cmd;
unsigned char pin1_data[0x100], pin2_data[0x100];
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "CHV PINPAD PIN reference %i", reference);
memset(pin1_data, 0xFF, sizeof(pin1_data));
memset(pin2_data, 0xFF, sizeof(pin2_data));
if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) {
sc_log(ctx, "Reader not ready for PIN PAD");
LOG_FUNC_RETURN(ctx, SC_ERROR_READER);
}
memset(&pin_cmd, 0, sizeof(pin_cmd));
pin_cmd.pin_type = SC_AC_CHV;
pin_cmd.pin_reference = reference;
pin_cmd.cmd = SC_PIN_CMD_CHANGE;
pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD;
rv = iasecc_pin_get_policy(card, &pin_cmd);
LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error");
/* Some pin-pads do not support mode with Lc=0.
* Give them a chance to work with some cards.
*/
if ((pin_cmd.pin1.min_length == pin_cmd.pin1.stored_length) && (pin_cmd.pin1.max_length == pin_cmd.pin1.min_length))
pin_cmd.pin1.len = pin_cmd.pin1.stored_length;
else
pin_cmd.pin1.len = 0;
pin_cmd.pin1.length_offset = 5;
pin_cmd.pin1.data = pin1_data;
memcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin1));
pin_cmd.pin2.data = pin2_data;
sc_log(ctx,
"PIN1 max/min/stored: %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u",
pin_cmd.pin1.max_length, pin_cmd.pin1.min_length,
pin_cmd.pin1.stored_length);
sc_log(ctx,
"PIN2 max/min/stored: %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u",
pin_cmd.pin2.max_length, pin_cmd.pin2.min_length,
pin_cmd.pin2.stored_length);
rv = iso_ops->pin_cmd(card, &pin_cmd, tries_left);
LOG_FUNC_RETURN(ctx, rv);
}
#if 0
static int
iasecc_chv_set_pinpad(struct sc_card *card, unsigned char reference)
{
struct sc_context *ctx = card->ctx;
struct sc_pin_cmd_data pin_cmd;
unsigned char pin_data[0x100];
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "Set CHV PINPAD PIN reference %i", reference);
memset(pin_data, 0xFF, sizeof(pin_data));
if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) {
sc_log(ctx, "Reader not ready for PIN PAD");
LOG_FUNC_RETURN(ctx, SC_ERROR_READER);
}
memset(&pin_cmd, 0, sizeof(pin_cmd));
pin_cmd.pin_type = SC_AC_CHV;
pin_cmd.pin_reference = reference;
pin_cmd.cmd = SC_PIN_CMD_UNBLOCK;
pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD;
rv = iasecc_pin_get_policy(card, &pin_cmd);
LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error");
if ((pin_cmd.pin1.min_length == pin_cmd.pin1.stored_length) && (pin_cmd.pin1.max_length == pin_cmd.pin1.min_length))
pin_cmd.pin1.len = pin_cmd.pin1.stored_length;
else
pin_cmd.pin1.len = 0;
pin_cmd.pin1.length_offset = 5;
pin_cmd.pin1.data = pin_data;
memcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin1));
memset(&pin_cmd.pin1, 0, sizeof(pin_cmd.pin1));
pin_cmd.flags |= SC_PIN_CMD_IMPLICIT_CHANGE;
sc_log(ctx, "PIN1(max:%i,min:%i)", pin_cmd.pin1.max_length, pin_cmd.pin1.min_length);
sc_log(ctx, "PIN2(max:%i,min:%i)", pin_cmd.pin2.max_length, pin_cmd.pin2.min_length);
rv = iso_ops->pin_cmd(card, &pin_cmd, NULL);
LOG_FUNC_RETURN(ctx, rv);
}
#endif
static int
iasecc_pin_get_policy (struct sc_card *card, struct sc_pin_cmd_data *data)
{
struct sc_context *ctx = card->ctx;
struct sc_file *save_current_df = NULL, *save_current_ef = NULL;
struct iasecc_sdo sdo;
struct sc_path path;
unsigned ii;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "iasecc_pin_get_policy(card:%p)", card);
if (data->pin_type != SC_AC_CHV) {
sc_log(ctx, "To unblock PIN it's CHV reference should be presented");
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
}
if (card->cache.valid && card->cache.current_df) {
sc_file_dup(&save_current_df, card->cache.current_df);
if (save_current_df == NULL) {
rv = SC_ERROR_OUT_OF_MEMORY;
sc_log(ctx, "Cannot duplicate current DF file");
goto err;
}
}
if (card->cache.valid && card->cache.current_ef) {
sc_file_dup(&save_current_ef, card->cache.current_ef);
if (save_current_ef == NULL) {
rv = SC_ERROR_OUT_OF_MEMORY;
sc_log(ctx, "Cannot duplicate current EF file");
goto err;
}
}
if (!(data->pin_reference & IASECC_OBJECT_REF_LOCAL) && card->cache.valid && card->cache.current_df) {
sc_format_path("3F00", &path);
path.type = SC_PATH_TYPE_FILE_ID;
rv = iasecc_select_file(card, &path, NULL);
LOG_TEST_GOTO_ERR(ctx, rv, "Unable to select MF");
}
memset(&sdo, 0, sizeof(sdo));
sdo.sdo_class = IASECC_SDO_CLASS_CHV;
sdo.sdo_ref = data->pin_reference & ~IASECC_OBJECT_REF_LOCAL;
sc_log(ctx, "iasecc_pin_get_policy() reference %i", sdo.sdo_ref);
rv = iasecc_sdo_get_data(card, &sdo);
LOG_TEST_GOTO_ERR(ctx, rv, "Cannot get SDO PIN data");
if (sdo.docp.acls_contact.size == 0) {
rv = SC_ERROR_INVALID_DATA;
sc_log(ctx, "Extremely strange ... there is no ACLs");
goto err;
}
sc_log(ctx,
"iasecc_pin_get_policy() sdo.docp.size.size %"SC_FORMAT_LEN_SIZE_T"u",
sdo.docp.size.size);
for (ii=0; ii<sizeof(sdo.docp.scbs); ii++) {
struct iasecc_se_info se;
unsigned char scb = sdo.docp.scbs[ii];
struct sc_acl_entry *acl = &data->pin1.acls[ii];
int crt_num = 0;
memset(&se, 0, sizeof(se));
memset(&acl->crts, 0, sizeof(acl->crts));
sc_log(ctx, "iasecc_pin_get_policy() set info acls: SCB 0x%X", scb);
/* acl->raw_value = scb; */
acl->method = scb & IASECC_SCB_METHOD_MASK;
acl->key_ref = scb & IASECC_SCB_METHOD_MASK_REF;
if (scb==0 || scb==0xFF)
continue;
if (se.reference != (int)acl->key_ref) {
memset(&se, 0, sizeof(se));
se.reference = acl->key_ref;
rv = iasecc_se_get_info(card, &se);
LOG_TEST_GOTO_ERR(ctx, rv, "SDO get data error");
}
if (scb & IASECC_SCB_METHOD_USER_AUTH) {
rv = iasecc_se_get_crt_by_usage(card, &se,
IASECC_CRT_TAG_AT, IASECC_UQB_AT_USER_PASSWORD, &acl->crts[crt_num]);
LOG_TEST_GOTO_ERR(ctx, rv, "no authentication template for 'USER PASSWORD'");
sc_log(ctx, "iasecc_pin_get_policy() scb:0x%X; sdo_ref:[%i,%i,...]",
scb, acl->crts[crt_num].refs[0], acl->crts[crt_num].refs[1]);
crt_num++;
}
if (scb & (IASECC_SCB_METHOD_SM | IASECC_SCB_METHOD_EXT_AUTH)) {
sc_log(ctx, "'SM' and 'EXTERNAL AUTHENTICATION' protection methods are not supported: SCB:0x%X", scb);
/* Set to 'NEVER' if all conditions are needed or
* there is no user authentication method allowed */
if (!crt_num || (scb & IASECC_SCB_METHOD_NEED_ALL))
acl->method = SC_AC_NEVER;
continue;
}
sc_file_free(se.df);
}
if (sdo.data.chv.size_max.value)
data->pin1.max_length = *sdo.data.chv.size_max.value;
if (sdo.data.chv.size_min.value)
data->pin1.min_length = *sdo.data.chv.size_min.value;
if (sdo.docp.tries_maximum.value)
data->pin1.max_tries = *sdo.docp.tries_maximum.value;
if (sdo.docp.tries_remaining.value)
data->pin1.tries_left = *sdo.docp.tries_remaining.value;
if (sdo.docp.size.value) {
for (ii=0; ii<sdo.docp.size.size; ii++)
data->pin1.stored_length = ((data->pin1.stored_length) << 8) + *(sdo.docp.size.value + ii);
}
data->pin1.encoding = SC_PIN_ENCODING_ASCII;
data->pin1.offset = 5;
data->pin1.logged_in = SC_PIN_STATE_UNKNOWN;
sc_log(ctx,
"PIN policy: size max/min %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u, tries max/left %i/%i",
data->pin1.max_length, data->pin1.min_length,
data->pin1.max_tries, data->pin1.tries_left);
iasecc_sdo_free_fields(card, &sdo);
if (save_current_df) {
sc_log(ctx, "iasecc_pin_get_policy() restore current DF");
rv = iasecc_select_file(card, &save_current_df->path, NULL);
LOG_TEST_GOTO_ERR(ctx, rv, "Cannot return to saved DF");
}
if (save_current_ef) {
sc_log(ctx, "iasecc_pin_get_policy() restore current EF");
rv = iasecc_select_file(card, &save_current_ef->path, NULL);
LOG_TEST_GOTO_ERR(ctx, rv, "Cannot return to saved EF");
}
err:
sc_file_free(save_current_df);
sc_file_free(save_current_ef);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_keyset_change(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct iasecc_sdo_update update;
struct iasecc_sdo sdo;
unsigned scb;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "Change keyset(ref:%i,lengths:%i)", data->pin_reference, data->pin2.len);
if (!data->pin2.data || data->pin2.len < 32)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Needs at least 32 bytes for a new keyset value");
memset(&sdo, 0, sizeof(sdo));
sdo.sdo_class = IASECC_SDO_CLASS_KEYSET;
sdo.sdo_ref = data->pin_reference;
rv = iasecc_sdo_get_data(card, &sdo);
LOG_TEST_RET(ctx, rv, "Cannot get keyset data");
if (sdo.docp.acls_contact.size == 0)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Bewildered ... there are no ACLs");
scb = sdo.docp.scbs[IASECC_ACLS_KEYSET_PUT_DATA];
iasecc_sdo_free_fields(card, &sdo);
sc_log(ctx, "SCB:0x%X", scb);
if (!(scb & IASECC_SCB_METHOD_SM))
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Other then protected by SM, the keyset change is not supported");
memset(&update, 0, sizeof(update));
update.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA;
update.sdo_class = sdo.sdo_class;
update.sdo_ref = sdo.sdo_ref;
update.fields[0].parent_tag = IASECC_SDO_KEYSET_TAG;
update.fields[0].tag = IASECC_SDO_KEYSET_TAG_MAC;
/* FIXME is it safe to modify the const value here? */
update.fields[0].value = (unsigned char *) data->pin2.data;
update.fields[0].size = 16;
update.fields[1].parent_tag = IASECC_SDO_KEYSET_TAG;
update.fields[1].tag = IASECC_SDO_KEYSET_TAG_ENC;
/* FIXME is it safe to modify the const value here? */
update.fields[1].value = (unsigned char *) data->pin2.data + 16;
update.fields[1].size = 16;
rv = iasecc_sm_sdo_update(card, (scb & IASECC_SCB_METHOD_MASK_REF), &update);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_pin_change(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned reference = data->pin_reference;
unsigned char pin_data[0x100];
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "Change PIN(ref:%i,type:0x%X,lengths:%i/%i)", reference, data->pin_type, data->pin1.len, data->pin2.len);
if ((card->reader->capabilities & SC_READER_CAP_PIN_PAD)) {
if (!data->pin1.data && !data->pin1.len && !data->pin2.data && !data->pin2.len) {
rv = iasecc_chv_change_pinpad(card, reference, tries_left);
sc_log(ctx, "iasecc_pin_cmd(SC_PIN_CMD_CHANGE) chv_change_pinpad returned %i", rv);
LOG_FUNC_RETURN(ctx, rv);
}
}
if (!data->pin1.data && data->pin1.len)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid PIN1 arguments");
if (!data->pin2.data && data->pin2.len)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid PIN2 arguments");
rv = iasecc_pin_verify(card, data->pin_type, reference, data->pin1.data, data->pin1.len, tries_left);
sc_log(ctx, "iasecc_pin_cmd(SC_PIN_CMD_CHANGE) pin_verify returned %i", rv);
LOG_TEST_RET(ctx, rv, "PIN verification error");
if ((unsigned)(data->pin1.len + data->pin2.len) > sizeof(pin_data))
LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Buffer too small for the 'Change PIN' data");
if (data->pin1.data)
memcpy(pin_data, data->pin1.data, data->pin1.len);
if (data->pin2.data)
memcpy(pin_data + data->pin1.len, data->pin2.data, data->pin2.len);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x24, 0, reference);
apdu.data = pin_data;
apdu.datalen = data->pin1.len + data->pin2.len;
apdu.lc = apdu.datalen;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "PIN cmd failed");
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_pin_reset(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct sc_file *save_current = NULL;
struct iasecc_sdo sdo;
struct sc_apdu apdu;
unsigned reference, scb;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "Reset PIN(ref:%i,lengths:%i/%i)", data->pin_reference, data->pin1.len, data->pin2.len);
if (data->pin_type != SC_AC_CHV)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Unblock procedure can be used only with the PINs of type CHV");
reference = data->pin_reference;
if (!(data->pin_reference & IASECC_OBJECT_REF_LOCAL) && card->cache.valid && card->cache.current_df) {
struct sc_path path;
sc_file_dup(&save_current, card->cache.current_df);
if (save_current == NULL)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot duplicate current DF file");
sc_format_path("3F00", &path);
path.type = SC_PATH_TYPE_FILE_ID;
rv = iasecc_select_file(card, &path, NULL);
LOG_TEST_RET(ctx, rv, "Unable to select MF");
}
memset(&sdo, 0, sizeof(sdo));
sdo.sdo_class = IASECC_SDO_CLASS_CHV;
sdo.sdo_ref = reference & ~IASECC_OBJECT_REF_LOCAL;
rv = iasecc_sdo_get_data(card, &sdo);
LOG_TEST_RET(ctx, rv, "Cannot get PIN data");
if (sdo.docp.acls_contact.size == 0)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Extremely strange ... there are no ACLs");
scb = sdo.docp.scbs[IASECC_ACLS_CHV_RESET];
do {
unsigned need_all = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0;
unsigned char se_num = scb & IASECC_SCB_METHOD_MASK_REF;
if (scb & IASECC_SCB_METHOD_USER_AUTH) {
sc_log(ctx, "Verify PIN in SE %X", se_num);
rv = iasecc_pin_verify(card, SC_AC_SEN, se_num, data->pin1.data, data->pin1.len, tries_left);
LOG_TEST_RET(ctx, rv, "iasecc_pin_reset() verify PUK error");
if (!need_all)
break;
}
if (scb & IASECC_SCB_METHOD_SM) {
rv = iasecc_sm_pin_reset(card, se_num, data);
LOG_FUNC_RETURN(ctx, rv);
}
if (scb & IASECC_SCB_METHOD_EXT_AUTH) {
rv = iasecc_sm_external_authentication(card, reference, tries_left);
LOG_TEST_RET(ctx, rv, "iasecc_pin_reset() external authentication error");
}
} while(0);
iasecc_sdo_free_fields(card, &sdo);
if (data->pin2.len) {
sc_log(ctx, "Reset PIN %X and set new value", reference);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2C, 0x02, reference);
apdu.data = data->pin2.data;
apdu.datalen = data->pin2.len;
apdu.lc = apdu.datalen;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "PIN cmd failed");
}
else if (data->pin2.data) {
sc_log(ctx, "Reset PIN %X and set new value", reference);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x2C, 3, reference);
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "PIN cmd failed");
}
else {
sc_log(ctx, "Reset PIN %X and set new value with PIN-PAD", reference);
#if 0
rv = iasecc_chv_set_pinpad(card, reference);
LOG_TEST_RET(ctx, rv, "Reset PIN failed");
#else
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Reset retry counter with PIN PAD not supported ");
#endif
}
if (save_current) {
rv = iasecc_select_file(card, &save_current->path, NULL);
LOG_TEST_RET(ctx, rv, "Cannot return to saved PATH");
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
struct sc_context *ctx = card->ctx;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "iasecc_pin_cmd() cmd 0x%X, PIN type 0x%X, PIN reference %i, PIN-1 %p:%i, PIN-2 %p:%i",
data->cmd, data->pin_type, data->pin_reference,
data->pin1.data, data->pin1.len, data->pin2.data, data->pin2.len);
switch (data->cmd) {
case SC_PIN_CMD_VERIFY:
rv = iasecc_pin_verify(card, data->pin_type, data->pin_reference, data->pin1.data, data->pin1.len, tries_left);
break;
case SC_PIN_CMD_CHANGE:
if (data->pin_type == SC_AC_AUT)
rv = iasecc_keyset_change(card, data, tries_left);
else
rv = iasecc_pin_change(card, data, tries_left);
break;
case SC_PIN_CMD_UNBLOCK:
rv = iasecc_pin_reset(card, data, tries_left);
break;
case SC_PIN_CMD_GET_INFO:
rv = iasecc_pin_get_policy(card, data);
break;
default:
sc_log(ctx, "Other pin commands not supported yet: 0x%X", data->cmd);
rv = SC_ERROR_NOT_SUPPORTED;
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_get_serialnr(struct sc_card *card, struct sc_serial_number *serial)
{
struct sc_context *ctx = card->ctx;
struct sc_iin *iin = &card->serialnr.iin;
struct sc_apdu apdu;
unsigned char rbuf[0xC0];
size_t ii, offs;
int rv;
LOG_FUNC_CALLED(ctx);
if (card->serialnr.len)
goto end;
memset(&card->serialnr, 0, sizeof(card->serialnr));
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, 0x80 | IASECC_SFI_EF_SN, 0);
apdu.le = sizeof(rbuf);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "Get 'serial number' data failed");
if (rbuf[0] != ISO7812_PAN_SN_TAG)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "serial number parse error");
iin->mii = (rbuf[2] >> 4) & 0x0F;
iin->country = 0;
for (ii=5; ii<8; ii++) {
iin->country *= 10;
iin->country += (rbuf[ii/2] >> ((ii & 0x01) ? 0 : 4)) & 0x0F;
}
iin->issuer_id = 0;
for (ii=8; ii<10; ii++) {
iin->issuer_id *= 10;
iin->issuer_id += (rbuf[ii/2] >> (ii & 0x01 ? 0 : 4)) & 0x0F;
}
offs = rbuf[1] > 8 ? rbuf[1] - 8 : 0;
if (card->type == SC_CARD_TYPE_IASECC_SAGEM) {
/* 5A 0A 92 50 00 20 10 10 25 00 01 3F */
/* 00 02 01 01 02 50 00 13 */
for (ii=0; (ii < rbuf[1] - offs) && (ii + offs + 2 < sizeof(rbuf)); ii++)
*(card->serialnr.value + ii) = ((rbuf[ii + offs + 1] & 0x0F) << 4)
+ ((rbuf[ii + offs + 2] & 0xF0) >> 4) ;
card->serialnr.len = ii;
}
else {
for (ii=0; ii < rbuf[1] - offs; ii++)
*(card->serialnr.value + ii) = rbuf[ii + offs + 2];
card->serialnr.len = ii;
}
do {
char txt[0x200];
for (ii=0;ii<card->serialnr.len;ii++)
sprintf(txt + ii*2, "%02X", *(card->serialnr.value + ii));
sc_log(ctx, "serial number '%s'; mii %i; country %i; issuer_id %li", txt, iin->mii, iin->country, iin->issuer_id);
} while(0);
end:
if (serial)
memcpy(serial, &card->serialnr, sizeof(*serial));
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_sdo_create(struct sc_card *card, struct iasecc_sdo *sdo)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char *data = NULL, sdo_class = sdo->sdo_class;
struct iasecc_sdo_update update;
struct iasecc_extended_tlv *field = NULL;
int rv = SC_ERROR_NOT_SUPPORTED, data_len;
LOG_FUNC_CALLED(ctx);
if (sdo->magic != SC_CARDCTL_IASECC_SDO_MAGIC)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO data");
sc_log(ctx, "iasecc_sdo_create(card:%p) %02X%02X%02X", card,
IASECC_SDO_TAG_HEADER, sdo->sdo_class | 0x80, sdo->sdo_ref);
data_len = iasecc_sdo_encode_create(ctx, sdo, &data);
LOG_TEST_RET(ctx, data_len, "iasecc_sdo_create() cannot encode SDO create data");
sc_log(ctx, "iasecc_sdo_create() create data(%i):%s", data_len, sc_dump_hex(data, data_len));
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF);
apdu.data = data;
apdu.datalen = data_len;
apdu.lc = data_len;
apdu.flags |= SC_APDU_FLAGS_CHAINING;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "iasecc_sdo_create() SDO put data error");
memset(&update, 0, sizeof(update));
update.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA;
update.sdo_class = sdo->sdo_class;
update.sdo_ref = sdo->sdo_ref;
if (sdo_class == IASECC_SDO_CLASS_RSA_PRIVATE) {
update.fields[0] = sdo->data.prv_key.compulsory;
update.fields[0].parent_tag = IASECC_SDO_PRVKEY_TAG;
field = &sdo->data.prv_key.compulsory;
}
else if (sdo_class == IASECC_SDO_CLASS_RSA_PUBLIC) {
update.fields[0] = sdo->data.pub_key.compulsory;
update.fields[0].parent_tag = IASECC_SDO_PUBKEY_TAG;
field = &sdo->data.pub_key.compulsory;
}
else if (sdo_class == IASECC_SDO_CLASS_KEYSET) {
update.fields[0] = sdo->data.keyset.compulsory;
update.fields[0].parent_tag = IASECC_SDO_KEYSET_TAG;
field = &sdo->data.keyset.compulsory;
}
if (update.fields[0].value && !update.fields[0].on_card) {
rv = iasecc_sdo_put_data(card, &update);
LOG_TEST_RET(ctx, rv, "failed to update 'Compulsory usage' data");
if (field)
field->on_card = 1;
}
free(data);
LOG_FUNC_RETURN(ctx, rv);
}
/* Oberthur's specific */
static int
iasecc_sdo_delete(struct sc_card *card, struct iasecc_sdo *sdo)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char data[6] = {
0x70, 0x04, 0xBF, 0xFF, 0xFF, 0x00
};
int rv;
LOG_FUNC_CALLED(ctx);
if (sdo->magic != SC_CARDCTL_IASECC_SDO_MAGIC)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO data");
data[2] = IASECC_SDO_TAG_HEADER;
data[3] = sdo->sdo_class | 0x80;
data[4] = sdo->sdo_ref;
sc_log(ctx, "delete SDO %02X%02X%02X", data[2], data[3], data[4]);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF);
apdu.data = data;
apdu.datalen = sizeof(data);
apdu.lc = sizeof(data);
apdu.flags |= SC_APDU_FLAGS_CHAINING;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "delete SDO error");
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_sdo_put_data(struct sc_card *card, struct iasecc_sdo_update *update)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
int ii, rv;
LOG_FUNC_CALLED(ctx);
if (update->magic != SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO update data");
for(ii=0; update->fields[ii].tag && ii < IASECC_SDO_TAGS_UPDATE_MAX; ii++) {
unsigned char *encoded = NULL;
int encoded_len;
encoded_len = iasecc_sdo_encode_update_field(ctx, update->sdo_class, update->sdo_ref,
&update->fields[ii], &encoded);
sc_log(ctx, "iasecc_sdo_put_data() encode[%i]; tag %X; encoded_len %i", ii, update->fields[ii].tag, encoded_len);
LOG_TEST_RET(ctx, encoded_len, "Cannot encode update data");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF);
apdu.data = encoded;
apdu.datalen = encoded_len;
apdu.lc = encoded_len;
apdu.flags |= SC_APDU_FLAGS_CHAINING;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "SDO put data error");
free(encoded);
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_sdo_key_rsa_put_data(struct sc_card *card, struct iasecc_sdo_rsa_update *update)
{
struct sc_context *ctx = card->ctx;
unsigned char scb;
int rv;
LOG_FUNC_CALLED(ctx);
if (update->sdo_prv_key) {
sc_log(ctx, "encode private rsa in %p", &update->update_prv);
rv = iasecc_sdo_encode_rsa_update(card->ctx, update->sdo_prv_key, update->p15_rsa, &update->update_prv);
LOG_TEST_RET(ctx, rv, "failed to encode update of RSA private key");
}
if (update->sdo_pub_key) {
sc_log(ctx, "encode public rsa in %p", &update->update_pub);
if (card->type == SC_CARD_TYPE_IASECC_SAGEM) {
if (update->sdo_pub_key->data.pub_key.cha.value) {
free(update->sdo_pub_key->data.pub_key.cha.value);
memset(&update->sdo_pub_key->data.pub_key.cha, 0, sizeof(update->sdo_pub_key->data.pub_key.cha));
}
}
rv = iasecc_sdo_encode_rsa_update(card->ctx, update->sdo_pub_key, update->p15_rsa, &update->update_pub);
LOG_TEST_RET(ctx, rv, "failed to encode update of RSA public key");
}
if (update->sdo_prv_key) {
sc_log(ctx, "reference of the private key to store: %X", update->sdo_prv_key->sdo_ref);
if (update->sdo_prv_key->docp.acls_contact.size == 0)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "extremely strange ... there are no ACLs");
scb = update->sdo_prv_key->docp.scbs[IASECC_ACLS_RSAKEY_PUT_DATA];
sc_log(ctx, "'UPDATE PRIVATE RSA' scb 0x%X", scb);
do {
unsigned all_conditions = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0;
if ((scb & IASECC_SCB_METHOD_USER_AUTH) && !all_conditions)
break;
if (scb & IASECC_SCB_METHOD_EXT_AUTH)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Not yet");
if (scb & IASECC_SCB_METHOD_SM) {
#ifdef ENABLE_SM
rv = iasecc_sm_rsa_update(card, scb & IASECC_SCB_METHOD_MASK_REF, update);
LOG_FUNC_RETURN(ctx, rv);
#else
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "built without support of Secure-Messaging");
#endif
}
} while(0);
rv = iasecc_sdo_put_data(card, &update->update_prv);
LOG_TEST_RET(ctx, rv, "failed to update of RSA private key");
}
if (update->sdo_pub_key) {
sc_log(ctx, "reference of the public key to store: %X", update->sdo_pub_key->sdo_ref);
rv = iasecc_sdo_put_data(card, &update->update_pub);
LOG_TEST_RET(ctx, rv, "failed to update of RSA public key");
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_sdo_tag_from_class(unsigned sdo_class)
{
switch (sdo_class & ~IASECC_OBJECT_REF_LOCAL) {
case IASECC_SDO_CLASS_CHV:
return IASECC_SDO_CHV_TAG;
case IASECC_SDO_CLASS_RSA_PRIVATE:
return IASECC_SDO_PRVKEY_TAG;
case IASECC_SDO_CLASS_RSA_PUBLIC:
return IASECC_SDO_PUBKEY_TAG;
case IASECC_SDO_CLASS_SE:
return IASECC_SDO_CLASS_SE;
case IASECC_SDO_CLASS_KEYSET:
return IASECC_SDO_KEYSET_TAG;
}
return -1;
}
static int
iasecc_sdo_get_tagged_data(struct sc_card *card, int sdo_tag, struct iasecc_sdo *sdo)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char sbuf[0x100];
size_t offs = sizeof(sbuf) - 1;
unsigned char rbuf[0x400];
int rv;
LOG_FUNC_CALLED(ctx);
sbuf[offs--] = 0x80;
sbuf[offs--] = sdo_tag & 0xFF;
if ((sdo_tag >> 8) & 0xFF)
sbuf[offs--] = (sdo_tag >> 8) & 0xFF;
sbuf[offs] = sizeof(sbuf) - offs - 1;
offs--;
sbuf[offs--] = sdo->sdo_ref & 0x9F;
sbuf[offs--] = sdo->sdo_class | IASECC_OBJECT_REF_LOCAL;
sbuf[offs--] = IASECC_SDO_TAG_HEADER;
sbuf[offs] = sizeof(sbuf) - offs - 1;
offs--;
sbuf[offs--] = IASECC_SDO_TEMPLATE_TAG;
sbuf[offs] = sizeof(sbuf) - offs - 1;
offs--;
sbuf[offs] = 0x4D;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xCB, 0x3F, 0xFF);
apdu.data = sbuf + offs;
apdu.datalen = sizeof(sbuf) - offs;
apdu.lc = sizeof(sbuf) - offs;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0x100;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "SDO get data error");
rv = iasecc_sdo_parse(card, apdu.resp, apdu.resplen, sdo);
LOG_TEST_RET(ctx, rv, "cannot parse SDO data");
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_sdo_get_data(struct sc_card *card, struct iasecc_sdo *sdo)
{
struct sc_context *ctx = card->ctx;
int rv, sdo_tag;
LOG_FUNC_CALLED(ctx);
sdo_tag = iasecc_sdo_tag_from_class(sdo->sdo_class);
rv = iasecc_sdo_get_tagged_data(card, sdo_tag, sdo);
/* When there is no public data 'GET DATA' returns error */
if (rv != SC_ERROR_INCORRECT_PARAMETERS)
LOG_TEST_RET(ctx, rv, "cannot parse ECC SDO data");
rv = iasecc_sdo_get_tagged_data(card, IASECC_DOCP_TAG, sdo);
LOG_TEST_RET(ctx, rv, "cannot parse ECC DOCP data");
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_sdo_generate(struct sc_card *card, struct iasecc_sdo *sdo)
{
struct sc_context *ctx = card->ctx;
struct iasecc_sdo_update update_pubkey;
struct sc_apdu apdu;
unsigned char scb, sbuf[5], rbuf[0x400], exponent[3] = {0x01, 0x00, 0x01};
int offs = 0, rv = SC_ERROR_NOT_SUPPORTED;
LOG_FUNC_CALLED(ctx);
if (sdo->sdo_class != IASECC_SDO_CLASS_RSA_PRIVATE)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "For a moment, only RSA_PRIVATE class can be accepted for the SDO generation");
if (sdo->docp.acls_contact.size == 0)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Bewildered ... there are no ACLs");
scb = sdo->docp.scbs[IASECC_ACLS_RSAKEY_GENERATE];
sc_log(ctx, "'generate RSA key' SCB 0x%X", scb);
do {
unsigned all_conditions = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0;
if (scb & IASECC_SCB_METHOD_USER_AUTH)
if (!all_conditions)
break;
if (scb & IASECC_SCB_METHOD_EXT_AUTH)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Not yet");
if (scb & IASECC_SCB_METHOD_SM) {
rv = iasecc_sm_rsa_generate(card, scb & IASECC_SCB_METHOD_MASK_REF, sdo);
LOG_FUNC_RETURN(ctx, rv);
}
} while(0);
memset(&update_pubkey, 0, sizeof(update_pubkey));
update_pubkey.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA;
update_pubkey.sdo_class = IASECC_SDO_CLASS_RSA_PUBLIC;
update_pubkey.sdo_ref = sdo->sdo_ref;
update_pubkey.fields[0].parent_tag = IASECC_SDO_PUBKEY_TAG;
update_pubkey.fields[0].tag = IASECC_SDO_PUBKEY_TAG_E;
update_pubkey.fields[0].value = exponent;
update_pubkey.fields[0].size = sizeof(exponent);
rv = iasecc_sdo_put_data(card, &update_pubkey);
LOG_TEST_RET(ctx, rv, "iasecc_sdo_generate() update SDO public key failed");
offs = 0;
sbuf[offs++] = IASECC_SDO_TEMPLATE_TAG;
sbuf[offs++] = 0x03;
sbuf[offs++] = IASECC_SDO_TAG_HEADER;
sbuf[offs++] = IASECC_SDO_CLASS_RSA_PRIVATE | IASECC_OBJECT_REF_LOCAL;
sbuf[offs++] = sdo->sdo_ref & ~IASECC_OBJECT_REF_LOCAL;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x47, 0x00, 0x00);
apdu.data = sbuf;
apdu.datalen = offs;
apdu.lc = offs;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0x100;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "SDO get data error");
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_get_chv_reference_from_se(struct sc_card *card, int *se_reference)
{
struct sc_context *ctx = card->ctx;
struct iasecc_se_info se;
struct sc_crt crt;
int rv;
LOG_FUNC_CALLED(ctx);
if (!se_reference)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid arguments");
memset(&se, 0, sizeof(se));
se.reference = *se_reference;
rv = iasecc_se_get_info(card, &se);
LOG_TEST_RET(ctx, rv, "get SE info error");
memset(&crt, 0, sizeof(crt));
crt.tag = IASECC_CRT_TAG_AT;
crt.usage = IASECC_UQB_AT_USER_PASSWORD;
rv = iasecc_se_get_crt(card, &se, &crt);
LOG_TEST_RET(ctx, rv, "Cannot get 'USER PASSWORD' authentication template");
sc_file_free(se.df);
LOG_FUNC_RETURN(ctx, crt.refs[0]);
}
static int
iasecc_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr)
{
struct sc_context *ctx = card->ctx;
struct iasecc_sdo *sdo = (struct iasecc_sdo *) ptr;
switch (cmd) {
case SC_CARDCTL_GET_SERIALNR:
return iasecc_get_serialnr(card, (struct sc_serial_number *)ptr);
case SC_CARDCTL_IASECC_SDO_CREATE:
sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_CREATE: sdo_class %X", sdo->sdo_class);
return iasecc_sdo_create(card, (struct iasecc_sdo *) ptr);
case SC_CARDCTL_IASECC_SDO_DELETE:
sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_DELETE: sdo_class %X", sdo->sdo_class);
return iasecc_sdo_delete(card, (struct iasecc_sdo *) ptr);
case SC_CARDCTL_IASECC_SDO_PUT_DATA:
sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_PUT_DATA: sdo_class %X", sdo->sdo_class);
return iasecc_sdo_put_data(card, (struct iasecc_sdo_update *) ptr);
case SC_CARDCTL_IASECC_SDO_KEY_RSA_PUT_DATA:
sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_KEY_RSA_PUT_DATA");
return iasecc_sdo_key_rsa_put_data(card, (struct iasecc_sdo_rsa_update *) ptr);
case SC_CARDCTL_IASECC_SDO_GET_DATA:
sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_GET_DATA: sdo_class %X", sdo->sdo_class);
return iasecc_sdo_get_data(card, (struct iasecc_sdo *) ptr);
case SC_CARDCTL_IASECC_SDO_GENERATE:
sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_GET_DATA: sdo_class %X", sdo->sdo_class);
return iasecc_sdo_generate(card, (struct iasecc_sdo *) ptr);
case SC_CARDCTL_GET_SE_INFO:
sc_log(ctx, "CMD SC_CARDCTL_GET_SE_INFO: sdo_class %X", sdo->sdo_class);
return iasecc_se_get_info(card, (struct iasecc_se_info *) ptr);
case SC_CARDCTL_GET_CHV_REFERENCE_IN_SE:
sc_log(ctx, "CMD SC_CARDCTL_GET_CHV_REFERENCE_IN_SE");
return iasecc_get_chv_reference_from_se(card, (int *)ptr);
case SC_CARDCTL_IASECC_GET_FREE_KEY_REFERENCE:
sc_log(ctx, "CMD SC_CARDCTL_IASECC_GET_FREE_KEY_REFERENCE");
return iasecc_get_free_reference(card, (struct iasecc_ctl_get_free_reference *)ptr);
}
return SC_ERROR_NOT_SUPPORTED;
}
static int
iasecc_decipher(struct sc_card *card,
const unsigned char *in, size_t in_len,
unsigned char *out, size_t out_len)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char sbuf[0x200];
unsigned char resp[SC_MAX_APDU_BUFFER_SIZE];
size_t offs;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(card->ctx,
"crgram_len %"SC_FORMAT_LEN_SIZE_T"u; outlen %"SC_FORMAT_LEN_SIZE_T"u",
in_len, out_len);
if (!out || !out_len || in_len > SC_MAX_APDU_BUFFER_SIZE)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
offs = 0;
sbuf[offs++] = 0x81;
memcpy(sbuf + offs, in, in_len);
offs += in_len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);
apdu.flags |= SC_APDU_FLAGS_CHAINING;
apdu.data = sbuf;
apdu.datalen = offs;
apdu.lc = offs;
apdu.resp = resp;
apdu.resplen = sizeof(resp);
apdu.le = 256;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "Card returned error");
if (out_len > apdu.resplen)
out_len = apdu.resplen;
memcpy(out, apdu.resp, out_len);
rv = out_len;
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_qsign_data_sha1(struct sc_context *ctx, const unsigned char *in, size_t in_len,
struct iasecc_qsign_data *out)
{
SHA_CTX sha;
SHA_LONG pre_hash_Nl, *hh[5] = {
&sha.h0, &sha.h1, &sha.h2, &sha.h3, &sha.h4
};
int jj, ii;
int hh_size = sizeof(SHA_LONG), hh_num = SHA_DIGEST_LENGTH / sizeof(SHA_LONG);
LOG_FUNC_CALLED(ctx);
if (!in || !in_len || !out)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
sc_log(ctx,
"sc_pkcs15_get_qsign_data() input data length %"SC_FORMAT_LEN_SIZE_T"u",
in_len);
memset(out, 0, sizeof(struct iasecc_qsign_data));
SHA1_Init(&sha);
SHA1_Update(&sha, in, in_len);
for (jj=0; jj<hh_num; jj++)
for(ii=0; ii<hh_size; ii++)
out->pre_hash[jj*hh_size + ii] = ((*hh[jj] >> 8*(hh_size-1-ii)) & 0xFF);
out->pre_hash_size = SHA_DIGEST_LENGTH;
sc_log(ctx, "Pre SHA1:%s", sc_dump_hex(out->pre_hash, out->pre_hash_size));
pre_hash_Nl = sha.Nl - (sha.Nl % (sizeof(sha.data) * 8));
for (ii=0; ii<hh_size; ii++) {
out->counter[ii] = (sha.Nh >> 8*(hh_size-1-ii)) &0xFF;
out->counter[hh_size+ii] = (pre_hash_Nl >> 8*(hh_size-1-ii)) &0xFF;
}
for (ii=0, out->counter_long=0; ii<(int)sizeof(out->counter); ii++)
out->counter_long = out->counter_long*0x100 + out->counter[ii];
sc_log(ctx, "Pre counter(%li):%s", out->counter_long, sc_dump_hex(out->counter, sizeof(out->counter)));
if (sha.num) {
memcpy(out->last_block, in + in_len - sha.num, sha.num);
out->last_block_size = sha.num;
sc_log(ctx, "Last block(%"SC_FORMAT_LEN_SIZE_T"u):%s",
out->last_block_size,
sc_dump_hex(out->last_block, out->last_block_size));
}
SHA1_Final(out->hash, &sha);
out->hash_size = SHA_DIGEST_LENGTH;
sc_log(ctx, "Expected digest %s\n", sc_dump_hex(out->hash, out->hash_size));
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
#if OPENSSL_VERSION_NUMBER >= 0x00908000L
static int
iasecc_qsign_data_sha256(struct sc_context *ctx, const unsigned char *in, size_t in_len,
struct iasecc_qsign_data *out)
{
SHA256_CTX sha256;
SHA_LONG pre_hash_Nl;
int jj, ii;
int hh_size = sizeof(SHA_LONG), hh_num = SHA256_DIGEST_LENGTH / sizeof(SHA_LONG);
LOG_FUNC_CALLED(ctx);
if (!in || !in_len || !out)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
sc_log(ctx,
"sc_pkcs15_get_qsign_data() input data length %"SC_FORMAT_LEN_SIZE_T"u",
in_len);
memset(out, 0, sizeof(struct iasecc_qsign_data));
SHA256_Init(&sha256);
SHA256_Update(&sha256, in, in_len);
for (jj=0; jj<hh_num; jj++)
for(ii=0; ii<hh_size; ii++)
out->pre_hash[jj*hh_size + ii] = ((sha256.h[jj] >> 8*(hh_size-1-ii)) & 0xFF);
out->pre_hash_size = SHA256_DIGEST_LENGTH;
sc_log(ctx, "Pre hash:%s", sc_dump_hex(out->pre_hash, out->pre_hash_size));
pre_hash_Nl = sha256.Nl - (sha256.Nl % (sizeof(sha256.data) * 8));
for (ii=0; ii<hh_size; ii++) {
out->counter[ii] = (sha256.Nh >> 8*(hh_size-1-ii)) &0xFF;
out->counter[hh_size+ii] = (pre_hash_Nl >> 8*(hh_size-1-ii)) &0xFF;
}
for (ii=0, out->counter_long=0; ii<(int)sizeof(out->counter); ii++)
out->counter_long = out->counter_long*0x100 + out->counter[ii];
sc_log(ctx, "Pre counter(%li):%s", out->counter_long, sc_dump_hex(out->counter, sizeof(out->counter)));
if (sha256.num) {
memcpy(out->last_block, in + in_len - sha256.num, sha256.num);
out->last_block_size = sha256.num;
sc_log(ctx, "Last block(%"SC_FORMAT_LEN_SIZE_T"u):%s",
out->last_block_size,
sc_dump_hex(out->last_block, out->last_block_size));
}
SHA256_Final(out->hash, &sha256);
out->hash_size = SHA256_DIGEST_LENGTH;
sc_log(ctx, "Expected digest %s\n", sc_dump_hex(out->hash, out->hash_size));
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
#endif
static int
iasecc_compute_signature_dst(struct sc_card *card,
const unsigned char *in, size_t in_len, unsigned char *out, size_t out_len)
{
struct sc_context *ctx = card->ctx;
struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;
struct sc_security_env *env = &prv->security_env;
struct iasecc_qsign_data qsign_data;
struct sc_apdu apdu;
size_t offs = 0, hash_len = 0;
unsigned char sbuf[SC_MAX_APDU_BUFFER_SIZE];
unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE];
int rv = SC_SUCCESS;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"iasecc_compute_signature_dst() input length %"SC_FORMAT_LEN_SIZE_T"u",
in_len);
if (env->operation != SC_SEC_OPERATION_SIGN)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "It's not SC_SEC_OPERATION_SIGN");
else if (!(prv->key_size & 0x1E0) || (prv->key_size & ~0x1E0))
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid key size for SC_SEC_OPERATION_SIGN");
memset(&qsign_data, 0, sizeof(qsign_data));
if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) {
rv = iasecc_qsign_data_sha1(card->ctx, in, in_len, &qsign_data);
}
else if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA256) {
#if OPENSSL_VERSION_NUMBER >= 0x00908000L
rv = iasecc_qsign_data_sha256(card->ctx, in, in_len, &qsign_data);
#else
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "SHA256 is not supported by OpenSSL previous to v0.9.8");
#endif
}
else
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Need RSA_HASH_SHA1 or RSA_HASH_SHA256 algorithm");
LOG_TEST_RET(ctx, rv, "Cannot get QSign data");
sc_log(ctx,
"iasecc_compute_signature_dst() hash_len %"SC_FORMAT_LEN_SIZE_T"u; key_size %"SC_FORMAT_LEN_SIZE_T"u",
hash_len, prv->key_size);
memset(sbuf, 0, sizeof(sbuf));
sbuf[offs++] = 0x90;
if (qsign_data.counter_long) {
sbuf[offs++] = qsign_data.hash_size + 8;
memcpy(sbuf + offs, qsign_data.pre_hash, qsign_data.pre_hash_size);
offs += qsign_data.pre_hash_size;
memcpy(sbuf + offs, qsign_data.counter, sizeof(qsign_data.counter));
offs += sizeof(qsign_data.counter);
}
else {
sbuf[offs++] = 0;
}
sbuf[offs++] = 0x80;
sbuf[offs++] = qsign_data.last_block_size;
memcpy(sbuf + offs, qsign_data.last_block, qsign_data.last_block_size);
offs += qsign_data.last_block_size;
sc_log(ctx,
"iasecc_compute_signature_dst() offs %"SC_FORMAT_LEN_SIZE_T"u; OP(meth:%X,ref:%X)",
offs, prv->op_method, prv->op_ref);
if (prv->op_method == SC_AC_SCB && (prv->op_ref & IASECC_SCB_METHOD_SM))
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Not yet");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2A, 0x90, 0xA0);
apdu.data = sbuf;
apdu.datalen = offs;
apdu.lc = offs;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "Compute signature failed");
sc_log(ctx, "iasecc_compute_signature_dst() partial hash OK");
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0x2A, 0x9E, 0x9A);
apdu.resp = rbuf;
apdu.resplen = prv->key_size;
apdu.le = prv->key_size;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "Compute signature failed");
sc_log(ctx,
"iasecc_compute_signature_dst() DST resplen %"SC_FORMAT_LEN_SIZE_T"u",
apdu.resplen);
if (apdu.resplen > out_len)
LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Result buffer too small for the DST signature");
memcpy(out, apdu.resp, apdu.resplen);
LOG_FUNC_RETURN(ctx, apdu.resplen);
}
static int
iasecc_compute_signature_at(struct sc_card *card,
const unsigned char *in, size_t in_len, unsigned char *out, size_t out_len)
{
struct sc_context *ctx = card->ctx;
struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;
struct sc_security_env *env = &prv->security_env;
struct sc_apdu apdu;
size_t offs = 0, sz = 0;
unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE];
int rv;
LOG_FUNC_CALLED(ctx);
if (env->operation != SC_SEC_OPERATION_AUTHENTICATE)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "It's not SC_SEC_OPERATION_AUTHENTICATE");
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x88, 0x00, 0x00);
apdu.datalen = in_len;
apdu.data = in;
apdu.lc = in_len;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0x100;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "Compute signature failed");
do {
if (offs + apdu.resplen > out_len)
LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Buffer too small to return signature");
memcpy(out + offs, rbuf, apdu.resplen);
offs += apdu.resplen;
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00)
break;
if (apdu.sw1 == 0x61) {
sz = apdu.sw2 == 0x00 ? 0x100 : apdu.sw2;
rv = iso_ops->get_response(card, &sz, rbuf);
LOG_TEST_RET(ctx, rv, "Get response error");
apdu.resplen = rv;
}
else {
LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "Impossible error: SW1 is not 0x90 neither 0x61");
}
} while(rv > 0);
LOG_FUNC_RETURN(ctx, offs);
}
static int
iasecc_compute_signature(struct sc_card *card,
const unsigned char *in, size_t in_len, unsigned char *out, size_t out_len)
{
struct sc_context *ctx;
struct iasecc_private_data *prv;
struct sc_security_env *env;
if (!card || !in || !out)
return SC_ERROR_INVALID_ARGUMENTS;
ctx = card->ctx;
prv = (struct iasecc_private_data *) card->drv_data;
env = &prv->security_env;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"inlen %"SC_FORMAT_LEN_SIZE_T"u, outlen %"SC_FORMAT_LEN_SIZE_T"u",
in_len, out_len);
if (env->operation == SC_SEC_OPERATION_SIGN)
return iasecc_compute_signature_dst(card, in, in_len, out, out_len);
else if (env->operation == SC_SEC_OPERATION_AUTHENTICATE)
return iasecc_compute_signature_at(card, in, in_len, out, out_len);
LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
}
static int
iasecc_read_public_key(struct sc_card *card, unsigned type,
struct sc_path *key_path, unsigned ref, unsigned size,
unsigned char **out, size_t *out_len)
{
struct sc_context *ctx = card->ctx;
struct iasecc_sdo sdo;
struct sc_pkcs15_bignum bn[2];
struct sc_pkcs15_pubkey_rsa rsa_key;
int rv;
LOG_FUNC_CALLED(ctx);
if (type != SC_ALGORITHM_RSA)
LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
sc_log(ctx, "read public kay(ref:%i;size:%i)", ref, size);
memset(&sdo, 0, sizeof(sdo));
sdo.sdo_class = IASECC_SDO_CLASS_RSA_PUBLIC;
sdo.sdo_ref = ref & ~IASECC_OBJECT_REF_LOCAL;
rv = iasecc_sdo_get_data(card, &sdo);
LOG_TEST_RET(ctx, rv, "failed to read public key: cannot get RSA SDO data");
if (out)
*out = NULL;
if (out_len)
*out_len = 0;
bn[0].data = (unsigned char *) malloc(sdo.data.pub_key.n.size);
if (!bn[0].data)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "failed to read public key: cannot allocate modulus");
bn[0].len = sdo.data.pub_key.n.size;
memcpy(bn[0].data, sdo.data.pub_key.n.value, sdo.data.pub_key.n.size);
bn[1].data = (unsigned char *) malloc(sdo.data.pub_key.e.size);
if (!bn[1].data)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "failed to read public key: cannot allocate exponent");
bn[1].len = sdo.data.pub_key.e.size;
memcpy(bn[1].data, sdo.data.pub_key.e.value, sdo.data.pub_key.e.size);
rsa_key.modulus = bn[0];
rsa_key.exponent = bn[1];
rv = sc_pkcs15_encode_pubkey_rsa(ctx, &rsa_key, out, out_len);
LOG_TEST_RET(ctx, rv, "failed to read public key: cannot encode RSA public key");
if (out && out_len)
sc_log(ctx, "encoded public key: %s", sc_dump_hex(*out, *out_len));
if (bn[0].data)
free(bn[0].data);
if (bn[1].data)
free(bn[1].data);
iasecc_sdo_free_fields(card, &sdo);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_get_free_reference(struct sc_card *card, struct iasecc_ctl_get_free_reference *ctl_data)
{
struct sc_context *ctx = card->ctx;
struct iasecc_sdo *sdo = NULL;
int idx, rv;
LOG_FUNC_CALLED(ctx);
if ((ctl_data->key_size % 0x40) || ctl_data->index < 1 || (ctl_data->index > IASECC_OBJECT_REF_MAX))
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
sc_log(ctx, "get reference for key(index:%i,usage:%X,access:%X)", ctl_data->index, ctl_data->usage, ctl_data->access);
/* TODO: when looking for the slot for the signature keys, check also PSO_SIGNATURE ACL */
for (idx = ctl_data->index; idx <= IASECC_OBJECT_REF_MAX; idx++) {
unsigned char sdo_tag[3] = {
IASECC_SDO_TAG_HEADER, IASECC_OBJECT_REF_LOCAL | IASECC_SDO_CLASS_RSA_PRIVATE, idx
};
size_t sz;
if (sdo)
iasecc_sdo_free(card, sdo);
rv = iasecc_sdo_allocate_and_parse(card, sdo_tag, 3, &sdo);
LOG_TEST_RET(ctx, rv, "cannot parse SDO data");
rv = iasecc_sdo_get_data(card, sdo);
if (rv == SC_ERROR_DATA_OBJECT_NOT_FOUND) {
iasecc_sdo_free(card, sdo);
sc_log(ctx, "found empty key slot %i", idx);
break;
}
else
LOG_TEST_RET(ctx, rv, "get new key reference failed");
sz = *(sdo->docp.size.value + 0) * 0x100 + *(sdo->docp.size.value + 1);
sc_log(ctx,
"SDO(idx:%i) size %"SC_FORMAT_LEN_SIZE_T"u; key_size %"SC_FORMAT_LEN_SIZE_T"u",
idx, sz, ctl_data->key_size);
if (sz != ctl_data->key_size / 8) {
sc_log(ctx,
"key index %i ignored: different key sizes %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u",
idx, sz, ctl_data->key_size / 8);
continue;
}
if (sdo->docp.non_repudiation.value) {
sc_log(ctx, "non repudiation flag %X", sdo->docp.non_repudiation.value[0]);
if ((ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && !(*sdo->docp.non_repudiation.value)) {
sc_log(ctx, "key index %i ignored: need non repudiation", idx);
continue;
}
if (!(ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && *sdo->docp.non_repudiation.value) {
sc_log(ctx, "key index %i ignored: don't need non-repudiation", idx);
continue;
}
}
if (ctl_data->access & SC_PKCS15_PRKEY_ACCESS_LOCAL) {
if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_GENERATE] == IASECC_SCB_NEVER) {
sc_log(ctx, "key index %i ignored: GENERATE KEY not allowed", idx);
continue;
}
}
else {
if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PUT_DATA] == IASECC_SCB_NEVER) {
sc_log(ctx, "key index %i ignored: PUT DATA not allowed", idx);
continue;
}
}
if ((ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && (ctl_data->usage & SC_PKCS15_PRKEY_USAGE_SIGN)) {
if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PSO_SIGN] == IASECC_SCB_NEVER) {
sc_log(ctx, "key index %i ignored: PSO SIGN not allowed", idx);
continue;
}
}
else if (ctl_data->usage & SC_PKCS15_PRKEY_USAGE_SIGN) {
if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_INTERNAL_AUTH] == IASECC_SCB_NEVER) {
sc_log(ctx, "key index %i ignored: INTERNAL AUTHENTICATE not allowed", idx);
continue;
}
}
if (ctl_data->usage & (SC_PKCS15_PRKEY_USAGE_DECRYPT | SC_PKCS15_PRKEY_USAGE_UNWRAP)) {
if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PSO_DECIPHER] == IASECC_SCB_NEVER) {
sc_log(ctx, "key index %i ignored: PSO DECIPHER not allowed", idx);
continue;
}
}
break;
}
ctl_data->index = idx;
if (idx > IASECC_OBJECT_REF_MAX)
LOG_FUNC_RETURN(ctx, SC_ERROR_DATA_OBJECT_NOT_FOUND);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static struct sc_card_driver *
sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (!iso_ops)
iso_ops = iso_drv->ops;
iasecc_ops = *iso_ops;
iasecc_ops.match_card = iasecc_match_card;
iasecc_ops.init = iasecc_init;
iasecc_ops.finish = iasecc_finish;
iasecc_ops.read_binary = iasecc_read_binary;
/* write_binary: ISO7816 implementation works */
/* update_binary: ISO7816 implementation works */
iasecc_ops.erase_binary = iasecc_erase_binary;
/* resize_binary */
/* read_record: Untested */
/* write_record: Untested */
/* append_record: Untested */
/* update_record: Untested */
iasecc_ops.select_file = iasecc_select_file;
/* get_response: Untested */
/* get_challenge: ISO7816 implementation works */
iasecc_ops.logout = iasecc_logout;
/* restore_security_env */
iasecc_ops.set_security_env = iasecc_set_security_env;
iasecc_ops.decipher = iasecc_decipher;
iasecc_ops.compute_signature = iasecc_compute_signature;
iasecc_ops.create_file = iasecc_create_file;
iasecc_ops.delete_file = iasecc_delete_file;
/* list_files */
iasecc_ops.check_sw = iasecc_check_sw;
iasecc_ops.card_ctl = iasecc_card_ctl;
iasecc_ops.process_fci = iasecc_process_fci;
/* construct_fci: Not needed */
iasecc_ops.pin_cmd = iasecc_pin_cmd;
/* get_data: Not implemented */
/* put_data: Not implemented */
/* delete_record: Not implemented */
iasecc_ops.read_public_key = iasecc_read_public_key;
return &iasecc_drv;
}
struct sc_card_driver *
sc_get_iasecc_driver(void)
{
return sc_get_driver();
}
#else
/* we need to define the functions below to export them */
#include "errors.h"
int
iasecc_se_get_info()
{
return SC_ERROR_NOT_SUPPORTED;
}
#endif /* ENABLE_OPENSSL */
| ./CrossVul/dataset_final_sorted/CWE-674/c/good_350_0 |
crossvul-cpp_data_bad_333_0 | /*
* Copyright (C) 1999 WIDE Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Extensively modified by Hannes Gredler (hannes@gredler.at) for more
* complete BGP support.
*/
/* \summary: Border Gateway Protocol (BGP) printer */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <netdissect-stdinc.h>
#include <stdio.h>
#include <string.h>
#include "netdissect.h"
#include "addrtoname.h"
#include "extract.h"
#include "af.h"
#include "l2vpn.h"
static const char tstr[] = "[|BGP]";
struct bgp {
uint8_t bgp_marker[16];
uint16_t bgp_len;
uint8_t bgp_type;
};
#define BGP_SIZE 19 /* unaligned */
#define BGP_OPEN 1
#define BGP_UPDATE 2
#define BGP_NOTIFICATION 3
#define BGP_KEEPALIVE 4
#define BGP_ROUTE_REFRESH 5
static const struct tok bgp_msg_values[] = {
{ BGP_OPEN, "Open"},
{ BGP_UPDATE, "Update"},
{ BGP_NOTIFICATION, "Notification"},
{ BGP_KEEPALIVE, "Keepalive"},
{ BGP_ROUTE_REFRESH, "Route Refresh"},
{ 0, NULL}
};
struct bgp_open {
uint8_t bgpo_marker[16];
uint16_t bgpo_len;
uint8_t bgpo_type;
uint8_t bgpo_version;
uint16_t bgpo_myas;
uint16_t bgpo_holdtime;
uint32_t bgpo_id;
uint8_t bgpo_optlen;
/* options should follow */
};
#define BGP_OPEN_SIZE 29 /* unaligned */
struct bgp_opt {
uint8_t bgpopt_type;
uint8_t bgpopt_len;
/* variable length */
};
#define BGP_OPT_SIZE 2 /* some compilers may pad to 4 bytes */
#define BGP_CAP_HEADER_SIZE 2 /* some compilers may pad to 4 bytes */
struct bgp_notification {
uint8_t bgpn_marker[16];
uint16_t bgpn_len;
uint8_t bgpn_type;
uint8_t bgpn_major;
uint8_t bgpn_minor;
};
#define BGP_NOTIFICATION_SIZE 21 /* unaligned */
struct bgp_route_refresh {
uint8_t bgp_marker[16];
uint16_t len;
uint8_t type;
uint8_t afi[2]; /* the compiler messes this structure up */
uint8_t res; /* when doing misaligned sequences of int8 and int16 */
uint8_t safi; /* afi should be int16 - so we have to access it using */
}; /* EXTRACT_16BITS(&bgp_route_refresh->afi) (sigh) */
#define BGP_ROUTE_REFRESH_SIZE 23
#define bgp_attr_lenlen(flags, p) \
(((flags) & 0x10) ? 2 : 1)
#define bgp_attr_len(flags, p) \
(((flags) & 0x10) ? EXTRACT_16BITS(p) : *(p))
#define BGPTYPE_ORIGIN 1
#define BGPTYPE_AS_PATH 2
#define BGPTYPE_NEXT_HOP 3
#define BGPTYPE_MULTI_EXIT_DISC 4
#define BGPTYPE_LOCAL_PREF 5
#define BGPTYPE_ATOMIC_AGGREGATE 6
#define BGPTYPE_AGGREGATOR 7
#define BGPTYPE_COMMUNITIES 8 /* RFC1997 */
#define BGPTYPE_ORIGINATOR_ID 9 /* RFC4456 */
#define BGPTYPE_CLUSTER_LIST 10 /* RFC4456 */
#define BGPTYPE_DPA 11 /* deprecated, draft-ietf-idr-bgp-dpa */
#define BGPTYPE_ADVERTISERS 12 /* deprecated RFC1863 */
#define BGPTYPE_RCID_PATH 13 /* deprecated RFC1863 */
#define BGPTYPE_MP_REACH_NLRI 14 /* RFC4760 */
#define BGPTYPE_MP_UNREACH_NLRI 15 /* RFC4760 */
#define BGPTYPE_EXTD_COMMUNITIES 16 /* RFC4360 */
#define BGPTYPE_AS4_PATH 17 /* RFC6793 */
#define BGPTYPE_AGGREGATOR4 18 /* RFC6793 */
#define BGPTYPE_PMSI_TUNNEL 22 /* RFC6514 */
#define BGPTYPE_TUNNEL_ENCAP 23 /* RFC5512 */
#define BGPTYPE_TRAFFIC_ENG 24 /* RFC5543 */
#define BGPTYPE_IPV6_EXTD_COMMUNITIES 25 /* RFC5701 */
#define BGPTYPE_AIGP 26 /* RFC7311 */
#define BGPTYPE_PE_DISTINGUISHER_LABEL 27 /* RFC6514 */
#define BGPTYPE_ENTROPY_LABEL 28 /* RFC6790 */
#define BGPTYPE_LARGE_COMMUNITY 32 /* draft-ietf-idr-large-community-05 */
#define BGPTYPE_ATTR_SET 128 /* RFC6368 */
#define BGP_MP_NLRI_MINSIZE 3 /* End of RIB Marker detection */
static const struct tok bgp_attr_values[] = {
{ BGPTYPE_ORIGIN, "Origin"},
{ BGPTYPE_AS_PATH, "AS Path"},
{ BGPTYPE_AS4_PATH, "AS4 Path"},
{ BGPTYPE_NEXT_HOP, "Next Hop"},
{ BGPTYPE_MULTI_EXIT_DISC, "Multi Exit Discriminator"},
{ BGPTYPE_LOCAL_PREF, "Local Preference"},
{ BGPTYPE_ATOMIC_AGGREGATE, "Atomic Aggregate"},
{ BGPTYPE_AGGREGATOR, "Aggregator"},
{ BGPTYPE_AGGREGATOR4, "Aggregator4"},
{ BGPTYPE_COMMUNITIES, "Community"},
{ BGPTYPE_ORIGINATOR_ID, "Originator ID"},
{ BGPTYPE_CLUSTER_LIST, "Cluster List"},
{ BGPTYPE_DPA, "DPA"},
{ BGPTYPE_ADVERTISERS, "Advertisers"},
{ BGPTYPE_RCID_PATH, "RCID Path / Cluster ID"},
{ BGPTYPE_MP_REACH_NLRI, "Multi-Protocol Reach NLRI"},
{ BGPTYPE_MP_UNREACH_NLRI, "Multi-Protocol Unreach NLRI"},
{ BGPTYPE_EXTD_COMMUNITIES, "Extended Community"},
{ BGPTYPE_PMSI_TUNNEL, "PMSI Tunnel"},
{ BGPTYPE_TUNNEL_ENCAP, "Tunnel Encapsulation"},
{ BGPTYPE_TRAFFIC_ENG, "Traffic Engineering"},
{ BGPTYPE_IPV6_EXTD_COMMUNITIES, "IPv6 Extended Community"},
{ BGPTYPE_AIGP, "Accumulated IGP Metric"},
{ BGPTYPE_PE_DISTINGUISHER_LABEL, "PE Distinguisher Label"},
{ BGPTYPE_ENTROPY_LABEL, "Entropy Label"},
{ BGPTYPE_LARGE_COMMUNITY, "Large Community"},
{ BGPTYPE_ATTR_SET, "Attribute Set"},
{ 255, "Reserved for development"},
{ 0, NULL}
};
#define BGP_AS_SET 1
#define BGP_AS_SEQUENCE 2
#define BGP_CONFED_AS_SEQUENCE 3 /* draft-ietf-idr-rfc3065bis-01 */
#define BGP_CONFED_AS_SET 4 /* draft-ietf-idr-rfc3065bis-01 */
#define BGP_AS_SEG_TYPE_MIN BGP_AS_SET
#define BGP_AS_SEG_TYPE_MAX BGP_CONFED_AS_SET
static const struct tok bgp_as_path_segment_open_values[] = {
{ BGP_AS_SEQUENCE, ""},
{ BGP_AS_SET, "{ "},
{ BGP_CONFED_AS_SEQUENCE, "( "},
{ BGP_CONFED_AS_SET, "({ "},
{ 0, NULL}
};
static const struct tok bgp_as_path_segment_close_values[] = {
{ BGP_AS_SEQUENCE, ""},
{ BGP_AS_SET, "}"},
{ BGP_CONFED_AS_SEQUENCE, ")"},
{ BGP_CONFED_AS_SET, "})"},
{ 0, NULL}
};
#define BGP_OPT_AUTH 1
#define BGP_OPT_CAP 2
static const struct tok bgp_opt_values[] = {
{ BGP_OPT_AUTH, "Authentication Information"},
{ BGP_OPT_CAP, "Capabilities Advertisement"},
{ 0, NULL}
};
#define BGP_CAPCODE_MP 1 /* RFC2858 */
#define BGP_CAPCODE_RR 2 /* RFC2918 */
#define BGP_CAPCODE_ORF 3 /* RFC5291 */
#define BGP_CAPCODE_MR 4 /* RFC3107 */
#define BGP_CAPCODE_EXT_NH 5 /* RFC5549 */
#define BGP_CAPCODE_RESTART 64 /* RFC4724 */
#define BGP_CAPCODE_AS_NEW 65 /* RFC6793 */
#define BGP_CAPCODE_DYN_CAP 67 /* draft-ietf-idr-dynamic-cap */
#define BGP_CAPCODE_MULTISESS 68 /* draft-ietf-idr-bgp-multisession */
#define BGP_CAPCODE_ADD_PATH 69 /* RFC7911 */
#define BGP_CAPCODE_ENH_RR 70 /* draft-keyur-bgp-enhanced-route-refresh */
#define BGP_CAPCODE_RR_CISCO 128
static const struct tok bgp_capcode_values[] = {
{ BGP_CAPCODE_MP, "Multiprotocol Extensions"},
{ BGP_CAPCODE_RR, "Route Refresh"},
{ BGP_CAPCODE_ORF, "Cooperative Route Filtering"},
{ BGP_CAPCODE_MR, "Multiple Routes to a Destination"},
{ BGP_CAPCODE_EXT_NH, "Extended Next Hop Encoding"},
{ BGP_CAPCODE_RESTART, "Graceful Restart"},
{ BGP_CAPCODE_AS_NEW, "32-Bit AS Number"},
{ BGP_CAPCODE_DYN_CAP, "Dynamic Capability"},
{ BGP_CAPCODE_MULTISESS, "Multisession BGP"},
{ BGP_CAPCODE_ADD_PATH, "Multiple Paths"},
{ BGP_CAPCODE_ENH_RR, "Enhanced Route Refresh"},
{ BGP_CAPCODE_RR_CISCO, "Route Refresh (Cisco)"},
{ 0, NULL}
};
#define BGP_NOTIFY_MAJOR_MSG 1
#define BGP_NOTIFY_MAJOR_OPEN 2
#define BGP_NOTIFY_MAJOR_UPDATE 3
#define BGP_NOTIFY_MAJOR_HOLDTIME 4
#define BGP_NOTIFY_MAJOR_FSM 5
#define BGP_NOTIFY_MAJOR_CEASE 6
#define BGP_NOTIFY_MAJOR_CAP 7
static const struct tok bgp_notify_major_values[] = {
{ BGP_NOTIFY_MAJOR_MSG, "Message Header Error"},
{ BGP_NOTIFY_MAJOR_OPEN, "OPEN Message Error"},
{ BGP_NOTIFY_MAJOR_UPDATE, "UPDATE Message Error"},
{ BGP_NOTIFY_MAJOR_HOLDTIME,"Hold Timer Expired"},
{ BGP_NOTIFY_MAJOR_FSM, "Finite State Machine Error"},
{ BGP_NOTIFY_MAJOR_CEASE, "Cease"},
{ BGP_NOTIFY_MAJOR_CAP, "Capability Message Error"},
{ 0, NULL}
};
/* draft-ietf-idr-cease-subcode-02 */
#define BGP_NOTIFY_MINOR_CEASE_MAXPRFX 1
static const struct tok bgp_notify_minor_cease_values[] = {
{ BGP_NOTIFY_MINOR_CEASE_MAXPRFX, "Maximum Number of Prefixes Reached"},
{ 2, "Administratively Shutdown"},
{ 3, "Peer Unconfigured"},
{ 4, "Administratively Reset"},
{ 5, "Connection Rejected"},
{ 6, "Other Configuration Change"},
{ 7, "Connection Collision Resolution"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_msg_values[] = {
{ 1, "Connection Not Synchronized"},
{ 2, "Bad Message Length"},
{ 3, "Bad Message Type"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_open_values[] = {
{ 1, "Unsupported Version Number"},
{ 2, "Bad Peer AS"},
{ 3, "Bad BGP Identifier"},
{ 4, "Unsupported Optional Parameter"},
{ 5, "Authentication Failure"},
{ 6, "Unacceptable Hold Time"},
{ 7, "Capability Message Error"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_update_values[] = {
{ 1, "Malformed Attribute List"},
{ 2, "Unrecognized Well-known Attribute"},
{ 3, "Missing Well-known Attribute"},
{ 4, "Attribute Flags Error"},
{ 5, "Attribute Length Error"},
{ 6, "Invalid ORIGIN Attribute"},
{ 7, "AS Routing Loop"},
{ 8, "Invalid NEXT_HOP Attribute"},
{ 9, "Optional Attribute Error"},
{ 10, "Invalid Network Field"},
{ 11, "Malformed AS_PATH"},
{ 0, NULL}
};
static const struct tok bgp_notify_minor_fsm_values[] = {
{ 1, "In OpenSent State"},
{ 2, "In OpenConfirm State"},
{ 3, "In Established State"},
{ 0, NULL }
};
static const struct tok bgp_notify_minor_cap_values[] = {
{ 1, "Invalid Action Value" },
{ 2, "Invalid Capability Length" },
{ 3, "Malformed Capability Value" },
{ 4, "Unsupported Capability Code" },
{ 0, NULL }
};
static const struct tok bgp_origin_values[] = {
{ 0, "IGP"},
{ 1, "EGP"},
{ 2, "Incomplete"},
{ 0, NULL}
};
#define BGP_PMSI_TUNNEL_RSVP_P2MP 1
#define BGP_PMSI_TUNNEL_LDP_P2MP 2
#define BGP_PMSI_TUNNEL_PIM_SSM 3
#define BGP_PMSI_TUNNEL_PIM_SM 4
#define BGP_PMSI_TUNNEL_PIM_BIDIR 5
#define BGP_PMSI_TUNNEL_INGRESS 6
#define BGP_PMSI_TUNNEL_LDP_MP2MP 7
static const struct tok bgp_pmsi_tunnel_values[] = {
{ BGP_PMSI_TUNNEL_RSVP_P2MP, "RSVP-TE P2MP LSP"},
{ BGP_PMSI_TUNNEL_LDP_P2MP, "LDP P2MP LSP"},
{ BGP_PMSI_TUNNEL_PIM_SSM, "PIM-SSM Tree"},
{ BGP_PMSI_TUNNEL_PIM_SM, "PIM-SM Tree"},
{ BGP_PMSI_TUNNEL_PIM_BIDIR, "PIM-Bidir Tree"},
{ BGP_PMSI_TUNNEL_INGRESS, "Ingress Replication"},
{ BGP_PMSI_TUNNEL_LDP_MP2MP, "LDP MP2MP LSP"},
{ 0, NULL}
};
static const struct tok bgp_pmsi_flag_values[] = {
{ 0x01, "Leaf Information required"},
{ 0, NULL}
};
#define BGP_AIGP_TLV 1
static const struct tok bgp_aigp_values[] = {
{ BGP_AIGP_TLV, "AIGP"},
{ 0, NULL}
};
/* Subsequent address family identifier, RFC2283 section 7 */
#define SAFNUM_RES 0
#define SAFNUM_UNICAST 1
#define SAFNUM_MULTICAST 2
#define SAFNUM_UNIMULTICAST 3 /* deprecated now */
/* labeled BGP RFC3107 */
#define SAFNUM_LABUNICAST 4
/* RFC6514 */
#define SAFNUM_MULTICAST_VPN 5
/* draft-nalawade-kapoor-tunnel-safi */
#define SAFNUM_TUNNEL 64
/* RFC4761 */
#define SAFNUM_VPLS 65
/* RFC6037 */
#define SAFNUM_MDT 66
/* RFC4364 */
#define SAFNUM_VPNUNICAST 128
/* RFC6513 */
#define SAFNUM_VPNMULTICAST 129
#define SAFNUM_VPNUNIMULTICAST 130 /* deprecated now */
/* RFC4684 */
#define SAFNUM_RT_ROUTING_INFO 132
#define BGP_VPN_RD_LEN 8
static const struct tok bgp_safi_values[] = {
{ SAFNUM_RES, "Reserved"},
{ SAFNUM_UNICAST, "Unicast"},
{ SAFNUM_MULTICAST, "Multicast"},
{ SAFNUM_UNIMULTICAST, "Unicast+Multicast"},
{ SAFNUM_LABUNICAST, "labeled Unicast"},
{ SAFNUM_TUNNEL, "Tunnel"},
{ SAFNUM_VPLS, "VPLS"},
{ SAFNUM_MDT, "MDT"},
{ SAFNUM_VPNUNICAST, "labeled VPN Unicast"},
{ SAFNUM_VPNMULTICAST, "labeled VPN Multicast"},
{ SAFNUM_VPNUNIMULTICAST, "labeled VPN Unicast+Multicast"},
{ SAFNUM_RT_ROUTING_INFO, "Route Target Routing Information"},
{ SAFNUM_MULTICAST_VPN, "Multicast VPN"},
{ 0, NULL }
};
/* well-known community */
#define BGP_COMMUNITY_NO_EXPORT 0xffffff01
#define BGP_COMMUNITY_NO_ADVERT 0xffffff02
#define BGP_COMMUNITY_NO_EXPORT_SUBCONFED 0xffffff03
/* Extended community type - draft-ietf-idr-bgp-ext-communities-05 */
#define BGP_EXT_COM_RT_0 0x0002 /* Route Target,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_RT_1 0x0102 /* Route Target,Format IP address:AN(2bytes) */
#define BGP_EXT_COM_RT_2 0x0202 /* Route Target,Format AN(4bytes):local(2bytes) */
#define BGP_EXT_COM_RO_0 0x0003 /* Route Origin,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_RO_1 0x0103 /* Route Origin,Format IP address:AN(2bytes) */
#define BGP_EXT_COM_RO_2 0x0203 /* Route Origin,Format AN(4bytes):local(2bytes) */
#define BGP_EXT_COM_LINKBAND 0x4004 /* Link Bandwidth,Format AS(2B):Bandwidth(4B) */
/* rfc2547 bgp-mpls-vpns */
#define BGP_EXT_COM_VPN_ORIGIN 0x0005 /* OSPF Domain ID / VPN of Origin - draft-rosen-vpns-ospf-bgp-mpls */
#define BGP_EXT_COM_VPN_ORIGIN2 0x0105 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_VPN_ORIGIN3 0x0205 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_VPN_ORIGIN4 0x8005 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_OSPF_RTYPE 0x0306 /* OSPF Route Type,Format Area(4B):RouteType(1B):Options(1B) */
#define BGP_EXT_COM_OSPF_RTYPE2 0x8000 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_OSPF_RID 0x0107 /* OSPF Router ID,Format RouterID(4B):Unused(2B) */
#define BGP_EXT_COM_OSPF_RID2 0x8001 /* duplicate - keep for backwards compatability */
#define BGP_EXT_COM_L2INFO 0x800a /* draft-kompella-ppvpn-l2vpn */
#define BGP_EXT_COM_SOURCE_AS 0x0009 /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */
#define BGP_EXT_COM_VRF_RT_IMP 0x010b /* RFC-ietf-l3vpn-2547bis-mcast-bgp-08.txt */
#define BGP_EXT_COM_L2VPN_RT_0 0x000a /* L2VPN Identifier,Format AS(2bytes):AN(4bytes) */
#define BGP_EXT_COM_L2VPN_RT_1 0xF10a /* L2VPN Identifier,Format IP address:AN(2bytes) */
/* http://www.cisco.com/en/US/tech/tk436/tk428/technologies_tech_note09186a00801eb09a.shtml */
#define BGP_EXT_COM_EIGRP_GEN 0x8800
#define BGP_EXT_COM_EIGRP_METRIC_AS_DELAY 0x8801
#define BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW 0x8802
#define BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU 0x8803
#define BGP_EXT_COM_EIGRP_EXT_REMAS_REMID 0x8804
#define BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC 0x8805
static const struct tok bgp_extd_comm_flag_values[] = {
{ 0x8000, "vendor-specific"},
{ 0x4000, "non-transitive"},
{ 0, NULL},
};
static const struct tok bgp_extd_comm_subtype_values[] = {
{ BGP_EXT_COM_RT_0, "target"},
{ BGP_EXT_COM_RT_1, "target"},
{ BGP_EXT_COM_RT_2, "target"},
{ BGP_EXT_COM_RO_0, "origin"},
{ BGP_EXT_COM_RO_1, "origin"},
{ BGP_EXT_COM_RO_2, "origin"},
{ BGP_EXT_COM_LINKBAND, "link-BW"},
{ BGP_EXT_COM_VPN_ORIGIN, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN2, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN3, "ospf-domain"},
{ BGP_EXT_COM_VPN_ORIGIN4, "ospf-domain"},
{ BGP_EXT_COM_OSPF_RTYPE, "ospf-route-type"},
{ BGP_EXT_COM_OSPF_RTYPE2, "ospf-route-type"},
{ BGP_EXT_COM_OSPF_RID, "ospf-router-id"},
{ BGP_EXT_COM_OSPF_RID2, "ospf-router-id"},
{ BGP_EXT_COM_L2INFO, "layer2-info"},
{ BGP_EXT_COM_EIGRP_GEN , "eigrp-general-route (flag, tag)" },
{ BGP_EXT_COM_EIGRP_METRIC_AS_DELAY , "eigrp-route-metric (AS, delay)" },
{ BGP_EXT_COM_EIGRP_METRIC_REL_NH_BW , "eigrp-route-metric (reliability, nexthop, bandwidth)" },
{ BGP_EXT_COM_EIGRP_METRIC_LOAD_MTU , "eigrp-route-metric (load, MTU)" },
{ BGP_EXT_COM_EIGRP_EXT_REMAS_REMID , "eigrp-external-route (remote-AS, remote-ID)" },
{ BGP_EXT_COM_EIGRP_EXT_REMPROTO_REMMETRIC , "eigrp-external-route (remote-proto, remote-metric)" },
{ BGP_EXT_COM_SOURCE_AS, "source-AS" },
{ BGP_EXT_COM_VRF_RT_IMP, "vrf-route-import"},
{ BGP_EXT_COM_L2VPN_RT_0, "l2vpn-id"},
{ BGP_EXT_COM_L2VPN_RT_1, "l2vpn-id"},
{ 0, NULL},
};
/* OSPF codes for BGP_EXT_COM_OSPF_RTYPE draft-rosen-vpns-ospf-bgp-mpls */
#define BGP_OSPF_RTYPE_RTR 1 /* OSPF Router LSA */
#define BGP_OSPF_RTYPE_NET 2 /* OSPF Network LSA */
#define BGP_OSPF_RTYPE_SUM 3 /* OSPF Summary LSA */
#define BGP_OSPF_RTYPE_EXT 5 /* OSPF External LSA, note that ASBR doesn't apply to MPLS-VPN */
#define BGP_OSPF_RTYPE_NSSA 7 /* OSPF NSSA External*/
#define BGP_OSPF_RTYPE_SHAM 129 /* OSPF-MPLS-VPN Sham link */
#define BGP_OSPF_RTYPE_METRIC_TYPE 0x1 /* LSB of RTYPE Options Field */
static const struct tok bgp_extd_comm_ospf_rtype_values[] = {
{ BGP_OSPF_RTYPE_RTR, "Router" },
{ BGP_OSPF_RTYPE_NET, "Network" },
{ BGP_OSPF_RTYPE_SUM, "Summary" },
{ BGP_OSPF_RTYPE_EXT, "External" },
{ BGP_OSPF_RTYPE_NSSA,"NSSA External" },
{ BGP_OSPF_RTYPE_SHAM,"MPLS-VPN Sham" },
{ 0, NULL },
};
/* ADD-PATH Send/Receive field values */
static const struct tok bgp_add_path_recvsend[] = {
{ 1, "Receive" },
{ 2, "Send" },
{ 3, "Both" },
{ 0, NULL },
};
static char astostr[20];
/*
* as_printf
*
* Convert an AS number into a string and return string pointer.
*
* Depending on bflag is set or not, AS number is converted into ASDOT notation
* or plain number notation.
*
*/
static char *
as_printf(netdissect_options *ndo,
char *str, int size, u_int asnum)
{
if (!ndo->ndo_bflag || asnum <= 0xFFFF) {
snprintf(str, size, "%u", asnum);
} else {
snprintf(str, size, "%u.%u", asnum >> 16, asnum & 0xFFFF);
}
return str;
}
#define ITEMCHECK(minlen) if (itemlen < minlen) goto badtlv;
int
decode_prefix4(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen, plenbytes;
ND_TCHECK(pptr[0]);
ITEMCHECK(1);
plen = pptr[0];
if (32 < plen)
return -1;
itemlen -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[1], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pptr[1], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d", ipaddr_string(ndo, &addr), plen);
return 1 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_prefix4(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen, plenbytes;
/* prefix length and label = 4 bytes */
ND_TCHECK2(pptr[0], 4);
ITEMCHECK(4);
plen = pptr[0]; /* get prefix length */
/* this is one of the weirdnesses of rfc3107
the label length (actually the label + COS bits)
is added to the prefix length;
we also do only read out just one label -
there is no real application for advertisement of
stacked labels in a single BGP message
*/
if (24 > plen)
return -1;
plen-=24; /* adjust prefixlen - labellength */
if (32 < plen)
return -1;
itemlen -= 4;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[4], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pptr[4], plenbytes);
if (plen % 8) {
((u_char *)&addr)[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "%s/%d, label:%u %s",
ipaddr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 4 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
/*
* bgp_vpn_ip_print
*
* print an ipv4 or ipv6 address into a buffer dependend on address length.
*/
static char *
bgp_vpn_ip_print(netdissect_options *ndo,
const u_char *pptr, u_int addr_length)
{
/* worst case string is s fully formatted v6 address */
static char addr[sizeof("1234:5678:89ab:cdef:1234:5678:89ab:cdef")];
char *pos = addr;
switch(addr_length) {
case (sizeof(struct in_addr) << 3): /* 32 */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
snprintf(pos, sizeof(addr), "%s", ipaddr_string(ndo, pptr));
break;
case (sizeof(struct in6_addr) << 3): /* 128 */
ND_TCHECK2(pptr[0], sizeof(struct in6_addr));
snprintf(pos, sizeof(addr), "%s", ip6addr_string(ndo, pptr));
break;
default:
snprintf(pos, sizeof(addr), "bogus address length %u", addr_length);
break;
}
pos += strlen(pos);
trunc:
*(pos) = '\0';
return (addr);
}
/*
* bgp_vpn_sg_print
*
* print an multicast s,g entry into a buffer.
* the s,g entry is encoded like this.
*
* +-----------------------------------+
* | Multicast Source Length (1 octet) |
* +-----------------------------------+
* | Multicast Source (Variable) |
* +-----------------------------------+
* | Multicast Group Length (1 octet) |
* +-----------------------------------+
* | Multicast Group (Variable) |
* +-----------------------------------+
*
* return the number of bytes read from the wire.
*/
static int
bgp_vpn_sg_print(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr_length;
u_int total_length, offset;
total_length = 0;
/* Source address length, encoded in bits */
ND_TCHECK2(pptr[0], 1);
addr_length = *pptr++;
/* Source address */
ND_TCHECK2(pptr[0], (addr_length >> 3));
total_length += (addr_length >> 3) + 1;
offset = strlen(buf);
if (addr_length) {
snprintf(buf + offset, buflen - offset, ", Source %s",
bgp_vpn_ip_print(ndo, pptr, addr_length));
pptr += (addr_length >> 3);
}
/* Group address length, encoded in bits */
ND_TCHECK2(pptr[0], 1);
addr_length = *pptr++;
/* Group address */
ND_TCHECK2(pptr[0], (addr_length >> 3));
total_length += (addr_length >> 3) + 1;
offset = strlen(buf);
if (addr_length) {
snprintf(buf + offset, buflen - offset, ", Group %s",
bgp_vpn_ip_print(ndo, pptr, addr_length));
pptr += (addr_length >> 3);
}
trunc:
return (total_length);
}
/* RDs and RTs share the same semantics
* we use bgp_vpn_rd_print for
* printing route targets inside a NLRI */
char *
bgp_vpn_rd_print(netdissect_options *ndo,
const u_char *pptr)
{
/* allocate space for the largest possible string */
static char rd[sizeof("xxxxxxxxxx:xxxxx (xxx.xxx.xxx.xxx:xxxxx)")];
char *pos = rd;
/* ok lets load the RD format */
switch (EXTRACT_16BITS(pptr)) {
/* 2-byte-AS:number fmt*/
case 0:
snprintf(pos, sizeof(rd) - (pos - rd), "%u:%u (= %u.%u.%u.%u)",
EXTRACT_16BITS(pptr+2),
EXTRACT_32BITS(pptr+4),
*(pptr+4), *(pptr+5), *(pptr+6), *(pptr+7));
break;
/* IP-address:AS fmt*/
case 1:
snprintf(pos, sizeof(rd) - (pos - rd), "%u.%u.%u.%u:%u",
*(pptr+2), *(pptr+3), *(pptr+4), *(pptr+5), EXTRACT_16BITS(pptr+6));
break;
/* 4-byte-AS:number fmt*/
case 2:
snprintf(pos, sizeof(rd) - (pos - rd), "%s:%u (%u.%u.%u.%u:%u)",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(pptr+2)),
EXTRACT_16BITS(pptr+6), *(pptr+2), *(pptr+3), *(pptr+4),
*(pptr+5), EXTRACT_16BITS(pptr+6));
break;
default:
snprintf(pos, sizeof(rd) - (pos - rd), "unknown RD format");
break;
}
pos += strlen(pos);
*(pos) = '\0';
return (rd);
}
static int
decode_rt_routing_info(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_target[8];
u_int plen;
char asbuf[sizeof(astostr)]; /* bgp_vpn_rd_print() overwrites astostr */
/* NLRI "prefix length" from RFC 2858 Section 4. */
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
/* NLRI "prefix" (ibid), valid lengths are { 0, 32, 33, ..., 96 } bits.
* RFC 4684 Section 4 defines the layout of "origin AS" and "route
* target" fields inside the "prefix" depending on its length.
*/
if (0 == plen) {
/* Without "origin AS", without "route target". */
snprintf(buf, buflen, "default route target");
return 1;
}
if (32 > plen)
return -1;
/* With at least "origin AS", possibly with "route target". */
ND_TCHECK_32BITS(pptr + 1);
as_printf(ndo, asbuf, sizeof(asbuf), EXTRACT_32BITS(pptr + 1));
plen-=32; /* adjust prefix length */
if (64 < plen)
return -1;
/* From now on (plen + 7) / 8 evaluates to { 0, 1, 2, ..., 8 }
* and gives the number of octets in the variable-length "route
* target" field inside this NLRI "prefix". Look for it.
*/
memset(&route_target, 0, sizeof(route_target));
ND_TCHECK2(pptr[5], (plen + 7) / 8);
memcpy(&route_target, &pptr[5], (plen + 7) / 8);
/* Which specification says to do this? */
if (plen % 8) {
((u_char *)&route_target)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "origin AS: %s, route target %s",
asbuf,
bgp_vpn_rd_print(ndo, (u_char *)&route_target));
return 5 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_labeled_vpn_prefix4(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
struct in_addr addr;
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (32 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
((u_char *)&addr)[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
ipaddr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
/*
* +-------------------------------+
* | |
* | RD:IPv4-address (12 octets) |
* | |
* +-------------------------------+
* | MDT Group-address (4 octets) |
* +-------------------------------+
*/
#define MDT_VPN_NLRI_LEN 16
static int
decode_mdt_vpn_nlri(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
const u_char *rd;
const u_char *vpn_ip;
ND_TCHECK(pptr[0]);
/* if the NLRI is not predefined length, quit.*/
if (*pptr != MDT_VPN_NLRI_LEN * 8)
return -1;
pptr++;
/* RD */
ND_TCHECK2(pptr[0], 8);
rd = pptr;
pptr+=8;
/* IPv4 address */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
vpn_ip = pptr;
pptr+=sizeof(struct in_addr);
/* MDT Group Address */
ND_TCHECK2(pptr[0], sizeof(struct in_addr));
snprintf(buf, buflen, "RD: %s, VPN IP Address: %s, MC Group Address: %s",
bgp_vpn_rd_print(ndo, rd), ipaddr_string(ndo, vpn_ip), ipaddr_string(ndo, pptr));
return MDT_VPN_NLRI_LEN + 1;
trunc:
return -2;
}
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI 1
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI 2
#define BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI 3
#define BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF 4
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE 5
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN 6
#define BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN 7
static const struct tok bgp_multicast_vpn_route_type_values[] = {
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI, "Intra-AS I-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI, "Inter-AS I-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI, "S-PMSI"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF, "Intra-AS Segment-Leaf"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE, "Source-Active"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN, "Shared Tree Join"},
{ BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN, "Source Tree Join"},
{ 0, NULL}
};
static int
decode_multicast_vpn(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t route_type, route_length, addr_length, sg_length;
u_int offset;
ND_TCHECK2(pptr[0], 2);
route_type = *pptr++;
route_length = *pptr++;
snprintf(buf, buflen, "Route-Type: %s (%u), length: %u",
tok2str(bgp_multicast_vpn_route_type_values,
"Unknown", route_type),
route_type, route_length);
switch(route_type) {
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_I_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Originator %s",
bgp_vpn_rd_print(ndo, pptr),
bgp_vpn_ip_print(ndo, pptr + BGP_VPN_RD_LEN,
(route_length - BGP_VPN_RD_LEN) << 3));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTER_AS_I_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s",
bgp_vpn_rd_print(ndo, pptr),
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_S_PMSI:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s",
bgp_vpn_rd_print(ndo, pptr));
pptr += BGP_VPN_RD_LEN;
sg_length = bgp_vpn_sg_print(ndo, pptr, buf, buflen);
addr_length = route_length - sg_length;
ND_TCHECK2(pptr[0], addr_length);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", Originator %s",
bgp_vpn_ip_print(ndo, pptr, addr_length << 3));
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_ACTIVE:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s",
bgp_vpn_rd_print(ndo, pptr));
pptr += BGP_VPN_RD_LEN;
bgp_vpn_sg_print(ndo, pptr, buf, buflen);
break;
case BGP_MULTICAST_VPN_ROUTE_TYPE_SHARED_TREE_JOIN: /* fall through */
case BGP_MULTICAST_VPN_ROUTE_TYPE_SOURCE_TREE_JOIN:
ND_TCHECK2(pptr[0], BGP_VPN_RD_LEN + 4);
offset = strlen(buf);
snprintf(buf + offset, buflen - offset, ", RD: %s, Source-AS %s",
bgp_vpn_rd_print(ndo, pptr),
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(pptr + BGP_VPN_RD_LEN)));
pptr += BGP_VPN_RD_LEN + 4;
bgp_vpn_sg_print(ndo, pptr, buf, buflen);
break;
/*
* no per route-type printing yet.
*/
case BGP_MULTICAST_VPN_ROUTE_TYPE_INTRA_AS_SEG_LEAF:
default:
break;
}
return route_length + 2;
trunc:
return -2;
}
/*
* As I remember, some versions of systems have an snprintf() that
* returns -1 if the buffer would have overflowed. If the return
* value is negative, set buflen to 0, to indicate that we've filled
* the buffer up.
*
* If the return value is greater than buflen, that means that
* the buffer would have overflowed; again, set buflen to 0 in
* that case.
*/
#define UPDATE_BUF_BUFLEN(buf, buflen, stringlen) \
if (stringlen<0) \
buflen=0; \
else if ((u_int)stringlen>buflen) \
buflen=0; \
else { \
buflen-=stringlen; \
buf+=stringlen; \
}
static int
decode_labeled_vpn_l2(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
int plen,tlen,stringlen,tlv_type,tlv_len,ttlv_len;
ND_TCHECK2(pptr[0], 2);
plen=EXTRACT_16BITS(pptr);
tlen=plen;
pptr+=2;
/* Old and new L2VPN NLRI share AFI/SAFI
* -> Assume a 12 Byte-length NLRI is auto-discovery-only
* and > 17 as old format. Complain for the middle case
*/
if (plen==12) {
/* assume AD-only with RD, BGPNH */
ND_TCHECK2(pptr[0],12);
buf[0]='\0';
stringlen=snprintf(buf, buflen, "RD: %s, BGPNH: %s",
bgp_vpn_rd_print(ndo, pptr),
ipaddr_string(ndo, pptr+8)
);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
pptr+=12;
tlen-=12;
return plen;
} else if (plen>17) {
/* assume old format */
/* RD, ID, LBLKOFF, LBLBASE */
ND_TCHECK2(pptr[0],15);
buf[0]='\0';
stringlen=snprintf(buf, buflen, "RD: %s, CE-ID: %u, Label-Block Offset: %u, Label Base %u",
bgp_vpn_rd_print(ndo, pptr),
EXTRACT_16BITS(pptr+8),
EXTRACT_16BITS(pptr+10),
EXTRACT_24BITS(pptr+12)>>4); /* the label is offsetted by 4 bits so lets shift it right */
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
pptr+=15;
tlen-=15;
/* ok now the variable part - lets read out TLVs*/
while (tlen>0) {
if (tlen < 3)
return -1;
ND_TCHECK2(pptr[0], 3);
tlv_type=*pptr++;
tlv_len=EXTRACT_16BITS(pptr);
ttlv_len=tlv_len;
pptr+=2;
switch(tlv_type) {
case 1:
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "\n\t\tcircuit status vector (%u) length: %u: 0x",
tlv_type,
tlv_len);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
ttlv_len=ttlv_len/8+1; /* how many bytes do we need to read ? */
while (ttlv_len>0) {
ND_TCHECK(pptr[0]);
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "%02x",*pptr++);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
ttlv_len--;
}
break;
default:
if (buflen!=0) {
stringlen=snprintf(buf,buflen, "\n\t\tunknown TLV #%u, length: %u",
tlv_type,
tlv_len);
UPDATE_BUF_BUFLEN(buf, buflen, stringlen);
}
break;
}
tlen-=(tlv_len<<3); /* the tlv-length is expressed in bits so lets shift it right */
}
return plen+2;
} else {
/* complain bitterly ? */
/* fall through */
goto trunc;
}
trunc:
return -2;
}
int
decode_prefix6(netdissect_options *ndo,
const u_char *pd, u_int itemlen, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen, plenbytes;
ND_TCHECK(pd[0]);
ITEMCHECK(1);
plen = pd[0];
if (128 < plen)
return -1;
itemlen -= 1;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pd[1], plenbytes);
ITEMCHECK(plenbytes);
memcpy(&addr, &pd[1], plenbytes);
if (plen % 8) {
addr.s6_addr[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d", ip6addr_string(ndo, &addr), plen);
return 1 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_prefix6(netdissect_options *ndo,
const u_char *pptr, u_int itemlen, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen, plenbytes;
/* prefix length and label = 4 bytes */
ND_TCHECK2(pptr[0], 4);
ITEMCHECK(4);
plen = pptr[0]; /* get prefix length */
if (24 > plen)
return -1;
plen-=24; /* adjust prefixlen - labellength */
if (128 < plen)
return -1;
itemlen -= 4;
memset(&addr, 0, sizeof(addr));
plenbytes = (plen + 7) / 8;
ND_TCHECK2(pptr[4], plenbytes);
memcpy(&addr, &pptr[4], plenbytes);
if (plen % 8) {
addr.s6_addr[plenbytes - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "%s/%d, label:%u %s",
ip6addr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 4 + plenbytes;
trunc:
return -2;
badtlv:
return -3;
}
static int
decode_labeled_vpn_prefix6(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
struct in6_addr addr;
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (128 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
addr.s6_addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
ip6addr_string(ndo, &addr),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_clnp_prefix(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr[19];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if (152 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[4], (plen + 7) / 8);
memcpy(&addr, &pptr[4], (plen + 7) / 8);
if (plen % 8) {
addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
snprintf(buf, buflen, "%s/%d",
isonsap_string(ndo, addr,(plen + 7) / 8),
plen);
return 1 + (plen + 7) / 8;
trunc:
return -2;
}
static int
decode_labeled_vpn_clnp_prefix(netdissect_options *ndo,
const u_char *pptr, char *buf, u_int buflen)
{
uint8_t addr[19];
u_int plen;
ND_TCHECK(pptr[0]);
plen = pptr[0]; /* get prefix length */
if ((24+64) > plen)
return -1;
plen-=(24+64); /* adjust prefixlen - labellength - RD len*/
if (152 < plen)
return -1;
memset(&addr, 0, sizeof(addr));
ND_TCHECK2(pptr[12], (plen + 7) / 8);
memcpy(&addr, &pptr[12], (plen + 7) / 8);
if (plen % 8) {
addr[(plen + 7) / 8 - 1] &=
((0xff00 >> (plen % 8)) & 0xff);
}
/* the label may get offsetted by 4 bits so lets shift it right */
snprintf(buf, buflen, "RD: %s, %s/%d, label:%u %s",
bgp_vpn_rd_print(ndo, pptr+4),
isonsap_string(ndo, addr,(plen + 7) / 8),
plen,
EXTRACT_24BITS(pptr+1)>>4,
((pptr[3]&1)==0) ? "(BOGUS: Bottom of Stack NOT set!)" : "(bottom)" );
return 12 + (plen + 7) / 8;
trunc:
return -2;
}
/*
* bgp_attr_get_as_size
*
* Try to find the size of the ASs encoded in an as-path. It is not obvious, as
* both Old speakers that do not support 4 byte AS, and the new speakers that do
* support, exchange AS-Path with the same path-attribute type value 0x02.
*/
static int
bgp_attr_get_as_size(netdissect_options *ndo,
uint8_t bgpa_type, const u_char *pptr, int len)
{
const u_char *tptr = pptr;
/*
* If the path attribute is the optional AS4 path type, then we already
* know, that ASs must be encoded in 4 byte format.
*/
if (bgpa_type == BGPTYPE_AS4_PATH) {
return 4;
}
/*
* Let us assume that ASs are of 2 bytes in size, and check if the AS-Path
* TLV is good. If not, ask the caller to try with AS encoded as 4 bytes
* each.
*/
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
/*
* If we do not find a valid segment type, our guess might be wrong.
*/
if (tptr[0] < BGP_AS_SEG_TYPE_MIN || tptr[0] > BGP_AS_SEG_TYPE_MAX) {
goto trunc;
}
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * 2;
}
/*
* If we correctly reached end of the AS path attribute data content,
* then most likely ASs were indeed encoded as 2 bytes.
*/
if (tptr == pptr + len) {
return 2;
}
trunc:
/*
* We can come here, either we did not have enough data, or if we
* try to decode 4 byte ASs in 2 byte format. Either way, return 4,
* so that calller can try to decode each AS as of 4 bytes. If indeed
* there was not enough data, it will crib and end the parse anyways.
*/
return 4;
}
static int
bgp_attr_print(netdissect_options *ndo,
u_int atype, const u_char *pptr, u_int len)
{
int i;
uint16_t af;
uint8_t safi, snpa, nhlen;
union { /* copy buffer for bandwidth values */
float f;
uint32_t i;
} bw;
int advance;
u_int tlen;
const u_char *tptr;
char buf[MAXHOSTNAMELEN + 100];
int as_size;
tptr = pptr;
tlen=len;
switch (atype) {
case BGPTYPE_ORIGIN:
if (len != 1)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK(*tptr);
ND_PRINT((ndo, "%s", tok2str(bgp_origin_values,
"Unknown Origin Typecode",
tptr[0])));
}
break;
/*
* Process AS4 byte path and AS2 byte path attributes here.
*/
case BGPTYPE_AS4_PATH:
case BGPTYPE_AS_PATH:
if (len % 2) {
ND_PRINT((ndo, "invalid len"));
break;
}
if (!len) {
ND_PRINT((ndo, "empty"));
break;
}
/*
* BGP updates exchanged between New speakers that support 4
* byte AS, ASs are always encoded in 4 bytes. There is no
* definitive way to find this, just by the packet's
* contents. So, check for packet's TLV's sanity assuming
* 2 bytes first, and it does not pass, assume that ASs are
* encoded in 4 bytes format and move on.
*/
as_size = bgp_attr_get_as_size(ndo, atype, pptr, len);
while (tptr < pptr + len) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_open_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
for (i = 0; i < tptr[1] * as_size; i += as_size) {
ND_TCHECK2(tptr[2 + i], as_size);
ND_PRINT((ndo, "%s ",
as_printf(ndo, astostr, sizeof(astostr),
as_size == 2 ?
EXTRACT_16BITS(&tptr[2 + i]) :
EXTRACT_32BITS(&tptr[2 + i]))));
}
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "%s", tok2str(bgp_as_path_segment_close_values,
"?", tptr[0])));
ND_TCHECK(tptr[1]);
tptr += 2 + tptr[1] * as_size;
}
break;
case BGPTYPE_NEXT_HOP:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
}
break;
case BGPTYPE_MULTI_EXIT_DISC:
case BGPTYPE_LOCAL_PREF:
if (len != 4)
ND_PRINT((ndo, "invalid len"));
else {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%u", EXTRACT_32BITS(tptr)));
}
break;
case BGPTYPE_ATOMIC_AGGREGATE:
if (len != 0)
ND_PRINT((ndo, "invalid len"));
break;
case BGPTYPE_AGGREGATOR:
/*
* Depending on the AS encoded is of 2 bytes or of 4 bytes,
* the length of this PA can be either 6 bytes or 8 bytes.
*/
if (len != 6 && len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], len);
if (len == 6) {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_16BITS(tptr)),
ipaddr_string(ndo, tptr + 2)));
} else {
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr)), ipaddr_string(ndo, tptr + 4)));
}
break;
case BGPTYPE_AGGREGATOR4:
if (len != 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, " AS #%s, origin %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr)),
ipaddr_string(ndo, tptr + 4)));
break;
case BGPTYPE_COMMUNITIES:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint32_t comm;
ND_TCHECK2(tptr[0], 4);
comm = EXTRACT_32BITS(tptr);
switch (comm) {
case BGP_COMMUNITY_NO_EXPORT:
ND_PRINT((ndo, " NO_EXPORT"));
break;
case BGP_COMMUNITY_NO_ADVERT:
ND_PRINT((ndo, " NO_ADVERTISE"));
break;
case BGP_COMMUNITY_NO_EXPORT_SUBCONFED:
ND_PRINT((ndo, " NO_EXPORT_SUBCONFED"));
break;
default:
ND_PRINT((ndo, "%u:%u%s",
(comm >> 16) & 0xffff,
comm & 0xffff,
(tlen>4) ? ", " : ""));
break;
}
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_ORIGINATOR_ID:
if (len != 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
break;
case BGPTYPE_CLUSTER_LIST:
if (len % 4) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "%s%s",
ipaddr_string(ndo, tptr),
(tlen>4) ? ", " : ""));
tlen -=4;
tptr +=4;
}
break;
case BGPTYPE_MP_REACH_NLRI:
ND_TCHECK2(tptr[0], 3);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
goto done;
break;
}
tptr +=3;
ND_TCHECK(tptr[0]);
nhlen = tptr[0];
tlen = nhlen;
tptr++;
if (tlen) {
int nnh = 0;
ND_PRINT((ndo, "\n\t nexthop: "));
while (tlen > 0) {
if ( nnh++ > 0 ) {
ND_PRINT((ndo, ", " ));
}
switch(af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN):
case (AFNUM_INET<<8 | SAFNUM_MDT):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s",ipaddr_string(ndo, tptr)));
tlen -= sizeof(struct in_addr);
tptr += sizeof(struct in_addr);
}
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ipaddr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
if (tlen < (int)sizeof(struct in6_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr));
ND_PRINT((ndo, "%s", ip6addr_string(ndo, tptr)));
tlen -= sizeof(struct in6_addr);
tptr += sizeof(struct in6_addr);
}
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)(sizeof(struct in6_addr)+BGP_VPN_RD_LEN)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN)));
tlen -= (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
tptr += (sizeof(struct in6_addr)+BGP_VPN_RD_LEN);
}
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < (int)sizeof(struct in_addr)) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], sizeof(struct in_addr));
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr)));
tlen -= (sizeof(struct in_addr));
tptr += (sizeof(struct in_addr));
}
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "%s", isonsap_string(ndo, tptr, tlen)));
tptr += tlen;
tlen = 0;
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
if (tlen < BGP_VPN_RD_LEN+1) {
ND_PRINT((ndo, "invalid len"));
tlen = 0;
} else {
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "RD: %s, %s",
bgp_vpn_rd_print(ndo, tptr),
isonsap_string(ndo, tptr+BGP_VPN_RD_LEN,tlen-BGP_VPN_RD_LEN)));
/* rfc986 mapped IPv4 address ? */
if (tlen == BGP_VPN_RD_LEN + 4 + sizeof(struct in_addr)
&& 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 (tlen == BGP_VPN_RD_LEN + 3 + sizeof(struct in6_addr)
&& EXTRACT_24BITS(tptr+BGP_VPN_RD_LEN) == 0x350000)
ND_PRINT((ndo, " = %s", ip6addr_string(ndo, tptr+BGP_VPN_RD_LEN+3)));
tptr += tlen;
tlen = 0;
}
break;
default:
ND_TCHECK2(tptr[0], tlen);
ND_PRINT((ndo, "no AFI %u/SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
tptr += tlen;
tlen = 0;
goto done;
break;
}
}
}
ND_PRINT((ndo, ", nh-length: %u", nhlen));
tptr += tlen;
ND_TCHECK(tptr[0]);
snpa = tptr[0];
tptr++;
if (snpa) {
ND_PRINT((ndo, "\n\t %u SNPA", snpa));
for (/*nothing*/; snpa > 0; snpa--) {
ND_TCHECK(tptr[0]);
ND_PRINT((ndo, "\n\t %d bytes", tptr[0]));
tptr += tptr[0] + 1;
}
} else {
ND_PRINT((ndo, ", no SNPA"));
}
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_RT_ROUTING_INFO):
advance = decode_rt_routing_info(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*tptr,tlen);
ND_PRINT((ndo, "\n\t no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
done:
break;
case BGPTYPE_MP_UNREACH_NLRI:
ND_TCHECK2(tptr[0], BGP_MP_NLRI_MINSIZE);
af = EXTRACT_16BITS(tptr);
safi = tptr[2];
ND_PRINT((ndo, "\n\t AFI: %s (%u), %sSAFI: %s (%u)",
tok2str(af_values, "Unknown AFI", af),
af,
(safi>128) ? "vendor specific " : "", /* 128 is meanwhile wellknown */
tok2str(bgp_safi_values, "Unknown SAFI", safi),
safi));
if (len == BGP_MP_NLRI_MINSIZE)
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
tptr += 3;
while (tptr < pptr + len) {
switch (af<<8 | safi) {
case (AFNUM_INET<<8 | SAFNUM_UNICAST):
case (AFNUM_INET<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix4(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix4(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_UNICAST):
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_UNIMULTICAST):
advance = decode_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_LABUNICAST):
advance = decode_labeled_prefix6(ndo, tptr, len, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else if (advance == -3)
break; /* bytes left, but not enough */
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET6<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_INET6<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_prefix6(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_VPLS<<8 | SAFNUM_VPLS):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_L2VPN<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_l2(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_UNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_MULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_UNIMULTICAST):
advance = decode_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNMULTICAST):
case (AFNUM_NSAP<<8 | SAFNUM_VPNUNIMULTICAST):
advance = decode_labeled_vpn_clnp_prefix(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MDT):
advance = decode_mdt_vpn_nlri(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
case (AFNUM_INET<<8 | SAFNUM_MULTICAST_VPN): /* fall through */
case (AFNUM_INET6<<8 | SAFNUM_MULTICAST_VPN):
advance = decode_multicast_vpn(ndo, tptr, buf, sizeof(buf));
if (advance == -1)
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
else if (advance == -2)
goto trunc;
else
ND_PRINT((ndo, "\n\t %s", buf));
break;
default:
ND_TCHECK2(*(tptr-3),tlen);
ND_PRINT((ndo, "no AFI %u / SAFI %u decoder", af, safi));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, tptr-3, "\n\t ", tlen);
advance = 0;
tptr = pptr + len;
break;
}
if (advance < 0)
break;
tptr += advance;
}
break;
case BGPTYPE_EXTD_COMMUNITIES:
if (len % 8) {
ND_PRINT((ndo, "invalid len"));
break;
}
while (tlen>0) {
uint16_t extd_comm;
ND_TCHECK2(tptr[0], 2);
extd_comm=EXTRACT_16BITS(tptr);
ND_PRINT((ndo, "\n\t %s (0x%04x), Flags [%s]",
tok2str(bgp_extd_comm_subtype_values,
"unknown extd community typecode",
extd_comm),
extd_comm,
bittok2str(bgp_extd_comm_flag_values, "none", extd_comm)));
ND_TCHECK2(*(tptr+2), 6);
switch(extd_comm) {
case BGP_EXT_COM_RT_0:
case BGP_EXT_COM_RO_0:
case BGP_EXT_COM_L2VPN_RT_0:
ND_PRINT((ndo, ": %u:%u (= %s)",
EXTRACT_16BITS(tptr+2),
EXTRACT_32BITS(tptr+4),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_EXT_COM_RT_1:
case BGP_EXT_COM_RO_1:
case BGP_EXT_COM_L2VPN_RT_1:
case BGP_EXT_COM_VRF_RT_IMP:
ND_PRINT((ndo, ": %s:%u",
ipaddr_string(ndo, tptr+2),
EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_RT_2:
case BGP_EXT_COM_RO_2:
ND_PRINT((ndo, ": %s:%u",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(tptr+2)), EXTRACT_16BITS(tptr+6)));
break;
case BGP_EXT_COM_LINKBAND:
bw.i = EXTRACT_32BITS(tptr+2);
ND_PRINT((ndo, ": bandwidth: %.3f Mbps",
bw.f*8/1000000));
break;
case BGP_EXT_COM_VPN_ORIGIN:
case BGP_EXT_COM_VPN_ORIGIN2:
case BGP_EXT_COM_VPN_ORIGIN3:
case BGP_EXT_COM_VPN_ORIGIN4:
case BGP_EXT_COM_OSPF_RID:
case BGP_EXT_COM_OSPF_RID2:
ND_PRINT((ndo, "%s", ipaddr_string(ndo, tptr+2)));
break;
case BGP_EXT_COM_OSPF_RTYPE:
case BGP_EXT_COM_OSPF_RTYPE2:
ND_PRINT((ndo, ": area:%s, router-type:%s, metric-type:%s%s",
ipaddr_string(ndo, tptr+2),
tok2str(bgp_extd_comm_ospf_rtype_values,
"unknown (0x%02x)",
*(tptr+6)),
(*(tptr+7) & BGP_OSPF_RTYPE_METRIC_TYPE) ? "E2" : "",
((*(tptr+6) == BGP_OSPF_RTYPE_EXT) || (*(tptr+6) == BGP_OSPF_RTYPE_NSSA)) ? "E1" : ""));
break;
case BGP_EXT_COM_L2INFO:
ND_PRINT((ndo, ": %s Control Flags [0x%02x]:MTU %u",
tok2str(l2vpn_encaps_values,
"unknown encaps",
*(tptr+2)),
*(tptr+3),
EXTRACT_16BITS(tptr+4)));
break;
case BGP_EXT_COM_SOURCE_AS:
ND_PRINT((ndo, ": AS %u", EXTRACT_16BITS(tptr+2)));
break;
default:
ND_TCHECK2(*tptr,8);
print_unknown_data(ndo, tptr, "\n\t ", 8);
break;
}
tlen -=8;
tptr +=8;
}
break;
case BGPTYPE_PMSI_TUNNEL:
{
uint8_t tunnel_type, flags;
ND_TCHECK2(tptr[0], 5);
tunnel_type = *(tptr+1);
flags = *tptr;
tlen = len;
ND_PRINT((ndo, "\n\t Tunnel-type %s (%u), Flags [%s], MPLS Label %u",
tok2str(bgp_pmsi_tunnel_values, "Unknown", tunnel_type),
tunnel_type,
bittok2str(bgp_pmsi_flag_values, "none", flags),
EXTRACT_24BITS(tptr+2)>>4));
tptr +=5;
tlen -= 5;
switch (tunnel_type) {
case BGP_PMSI_TUNNEL_PIM_SM: /* fall through */
case BGP_PMSI_TUNNEL_PIM_BIDIR:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Sender %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_PIM_SSM:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, P-Group %s",
ipaddr_string(ndo, tptr),
ipaddr_string(ndo, tptr+4)));
break;
case BGP_PMSI_TUNNEL_INGRESS:
ND_TCHECK2(tptr[0], 4);
ND_PRINT((ndo, "\n\t Tunnel-Endpoint %s",
ipaddr_string(ndo, tptr)));
break;
case BGP_PMSI_TUNNEL_LDP_P2MP: /* fall through */
case BGP_PMSI_TUNNEL_LDP_MP2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Root-Node %s, LSP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
case BGP_PMSI_TUNNEL_RSVP_P2MP:
ND_TCHECK2(tptr[0], 8);
ND_PRINT((ndo, "\n\t Extended-Tunnel-ID %s, P2MP-ID 0x%08x",
ipaddr_string(ndo, tptr),
EXTRACT_32BITS(tptr+4)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr, "\n\t ", tlen);
}
}
break;
}
case BGPTYPE_AIGP:
{
uint8_t type;
uint16_t length;
tlen = len;
while (tlen >= 3) {
ND_TCHECK2(tptr[0], 3);
type = *tptr;
length = EXTRACT_16BITS(tptr+1);
tptr += 3;
tlen -= 3;
ND_PRINT((ndo, "\n\t %s TLV (%u), length %u",
tok2str(bgp_aigp_values, "Unknown", type),
type, length));
if (length < 3)
goto trunc;
length -= 3;
/*
* Check if we can read the TLV data.
*/
ND_TCHECK2(tptr[3], length);
switch (type) {
case BGP_AIGP_TLV:
if (length < 8)
goto trunc;
ND_PRINT((ndo, ", metric %" PRIu64,
EXTRACT_64BITS(tptr)));
break;
default:
if (ndo->ndo_vflag <= 1) {
print_unknown_data(ndo, tptr,"\n\t ", length);
}
}
tptr += length;
tlen -= length;
}
break;
}
case BGPTYPE_ATTR_SET:
ND_TCHECK2(tptr[0], 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, "\n\t Origin AS: %s",
as_printf(ndo, astostr, sizeof(astostr), EXTRACT_32BITS(tptr))));
tptr+=4;
len -=4;
while (len) {
u_int aflags, alenlen, alen;
ND_TCHECK2(tptr[0], 2);
if (len < 2)
goto trunc;
aflags = *tptr;
atype = *(tptr + 1);
tptr += 2;
len -= 2;
alenlen = bgp_attr_lenlen(aflags, tptr);
ND_TCHECK2(tptr[0], alenlen);
if (len < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, tptr);
tptr += alenlen;
len -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values,
"Unknown Attribute", atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
/* FIXME check for recursion */
if (!bgp_attr_print(ndo, atype, tptr, alen))
return 0;
tptr += alen;
len -= alen;
}
break;
case BGPTYPE_LARGE_COMMUNITY:
if (len == 0 || len % 12) {
ND_PRINT((ndo, "invalid len"));
break;
}
ND_PRINT((ndo, "\n\t "));
while (len > 0) {
ND_TCHECK2(*tptr, 12);
ND_PRINT((ndo, "%u:%u:%u%s",
EXTRACT_32BITS(tptr),
EXTRACT_32BITS(tptr + 4),
EXTRACT_32BITS(tptr + 8),
(len > 12) ? ", " : ""));
tptr += 12;
len -= 12;
}
break;
default:
ND_TCHECK2(*pptr,len);
ND_PRINT((ndo, "\n\t no Attribute %u decoder", atype)); /* we have no decoder for the attribute */
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, pptr, "\n\t ", len);
break;
}
if (ndo->ndo_vflag > 1 && len) { /* omit zero length attributes*/
ND_TCHECK2(*pptr,len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return 1;
trunc:
return 0;
}
static void
bgp_capabilities_print(netdissect_options *ndo,
const u_char *opt, int caps_len)
{
int cap_type, cap_len, tcap_len, cap_offset;
int i = 0;
while (i < caps_len) {
ND_TCHECK2(opt[i], BGP_CAP_HEADER_SIZE);
cap_type=opt[i];
cap_len=opt[i+1];
tcap_len=cap_len;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_capcode_values, "Unknown",
cap_type),
cap_type,
cap_len));
ND_TCHECK2(opt[i+2], cap_len);
switch (cap_type) {
case BGP_CAPCODE_MP:
/* AFI (16 bits), Reserved (8 bits), SAFI (8 bits) */
ND_TCHECK_8BITS(opt + i + 5);
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u)",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(opt+i+2)),
EXTRACT_16BITS(opt+i+2),
tok2str(bgp_safi_values, "Unknown",
opt[i+5]),
opt[i+5]));
break;
case BGP_CAPCODE_RESTART:
/* Restart Flags (4 bits), Restart Time in seconds (12 bits) */
ND_TCHECK_16BITS(opt + i + 2);
ND_PRINT((ndo, "\n\t\tRestart Flags: [%s], Restart Time %us",
((opt[i+2])&0x80) ? "R" : "none",
EXTRACT_16BITS(opt+i+2)&0xfff));
tcap_len-=2;
cap_offset=4;
while(tcap_len>=4) {
ND_TCHECK_8BITS(opt + i + cap_offset + 3);
ND_PRINT((ndo, "\n\t\t AFI %s (%u), SAFI %s (%u), Forwarding state preserved: %s",
tok2str(af_values,"Unknown",
EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",
opt[i+cap_offset+2]),
opt[i+cap_offset+2],
((opt[i+cap_offset+3])&0x80) ? "yes" : "no" ));
tcap_len-=4;
cap_offset+=4;
}
break;
case BGP_CAPCODE_RR:
case BGP_CAPCODE_RR_CISCO:
break;
case BGP_CAPCODE_AS_NEW:
/*
* Extract the 4 byte AS number encoded.
*/
if (cap_len == 4) {
ND_PRINT((ndo, "\n\t\t 4 Byte AS %s",
as_printf(ndo, astostr, sizeof(astostr),
EXTRACT_32BITS(opt + i + 2))));
}
break;
case BGP_CAPCODE_ADD_PATH:
cap_offset=2;
if (tcap_len == 0) {
ND_PRINT((ndo, " (bogus)")); /* length */
break;
}
while (tcap_len > 0) {
if (tcap_len < 4) {
ND_PRINT((ndo, "\n\t\t(invalid)"));
break;
}
ND_PRINT((ndo, "\n\t\tAFI %s (%u), SAFI %s (%u), Send/Receive: %s",
tok2str(af_values,"Unknown",EXTRACT_16BITS(opt+i+cap_offset)),
EXTRACT_16BITS(opt+i+cap_offset),
tok2str(bgp_safi_values,"Unknown",opt[i+cap_offset+2]),
opt[i+cap_offset+2],
tok2str(bgp_add_path_recvsend,"Bogus (0x%02x)",opt[i+cap_offset+3])
));
tcap_len-=4;
cap_offset+=4;
}
break;
default:
ND_PRINT((ndo, "\n\t\tno decoder for Capability %u",
cap_type));
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
break;
}
if (ndo->ndo_vflag > 1 && cap_len > 0) {
print_unknown_data(ndo, &opt[i+2], "\n\t\t", cap_len);
}
i += BGP_CAP_HEADER_SIZE + cap_len;
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static void
bgp_open_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp_open bgpo;
struct bgp_opt bgpopt;
const u_char *opt;
int i;
ND_TCHECK2(dat[0], BGP_OPEN_SIZE);
memcpy(&bgpo, dat, BGP_OPEN_SIZE);
ND_PRINT((ndo, "\n\t Version %d, ", bgpo.bgpo_version));
ND_PRINT((ndo, "my AS %s, ",
as_printf(ndo, astostr, sizeof(astostr), ntohs(bgpo.bgpo_myas))));
ND_PRINT((ndo, "Holdtime %us, ", ntohs(bgpo.bgpo_holdtime)));
ND_PRINT((ndo, "ID %s", ipaddr_string(ndo, &bgpo.bgpo_id)));
ND_PRINT((ndo, "\n\t Optional parameters, length: %u", bgpo.bgpo_optlen));
/* some little sanity checking */
if (length < bgpo.bgpo_optlen+BGP_OPEN_SIZE)
return;
/* ugly! */
opt = &((const struct bgp_open *)dat)->bgpo_optlen;
opt++;
i = 0;
while (i < bgpo.bgpo_optlen) {
ND_TCHECK2(opt[i], BGP_OPT_SIZE);
memcpy(&bgpopt, &opt[i], BGP_OPT_SIZE);
if (i + 2 + bgpopt.bgpopt_len > bgpo.bgpo_optlen) {
ND_PRINT((ndo, "\n\t Option %d, length: %u", bgpopt.bgpopt_type, bgpopt.bgpopt_len));
break;
}
ND_PRINT((ndo, "\n\t Option %s (%u), length: %u",
tok2str(bgp_opt_values,"Unknown",
bgpopt.bgpopt_type),
bgpopt.bgpopt_type,
bgpopt.bgpopt_len));
/* now let's decode the options we know*/
switch(bgpopt.bgpopt_type) {
case BGP_OPT_CAP:
bgp_capabilities_print(ndo, &opt[i+BGP_OPT_SIZE],
bgpopt.bgpopt_len);
break;
case BGP_OPT_AUTH:
default:
ND_PRINT((ndo, "\n\t no decoder for option %u",
bgpopt.bgpopt_type));
break;
}
i += BGP_OPT_SIZE + bgpopt.bgpopt_len;
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static void
bgp_update_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
const u_char *p;
int withdrawn_routes_len;
int len;
int i;
ND_TCHECK2(dat[0], BGP_SIZE);
if (length < BGP_SIZE)
goto trunc;
memcpy(&bgp, dat, BGP_SIZE);
p = dat + BGP_SIZE; /*XXX*/
length -= BGP_SIZE;
/* Unfeasible routes */
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
withdrawn_routes_len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len) {
/*
* Without keeping state from the original NLRI message,
* it's not possible to tell if this a v4 or v6 route,
* so only try to decode it if we're not v6 enabled.
*/
ND_TCHECK2(p[0], withdrawn_routes_len);
if (length < withdrawn_routes_len)
goto trunc;
ND_PRINT((ndo, "\n\t Withdrawn routes: %d bytes", withdrawn_routes_len));
p += withdrawn_routes_len;
length -= withdrawn_routes_len;
}
ND_TCHECK2(p[0], 2);
if (length < 2)
goto trunc;
len = EXTRACT_16BITS(p);
p += 2;
length -= 2;
if (withdrawn_routes_len == 0 && len == 0 && length == 0) {
/* No withdrawn routes, no path attributes, no NLRI */
ND_PRINT((ndo, "\n\t End-of-Rib Marker (empty NLRI)"));
return;
}
if (len) {
/* do something more useful!*/
while (len) {
int aflags, atype, alenlen, alen;
ND_TCHECK2(p[0], 2);
if (len < 2)
goto trunc;
if (length < 2)
goto trunc;
aflags = *p;
atype = *(p + 1);
p += 2;
len -= 2;
length -= 2;
alenlen = bgp_attr_lenlen(aflags, p);
ND_TCHECK2(p[0], alenlen);
if (len < alenlen)
goto trunc;
if (length < alenlen)
goto trunc;
alen = bgp_attr_len(aflags, p);
p += alenlen;
len -= alenlen;
length -= alenlen;
ND_PRINT((ndo, "\n\t %s (%u), length: %u",
tok2str(bgp_attr_values, "Unknown Attribute",
atype),
atype,
alen));
if (aflags) {
ND_PRINT((ndo, ", Flags [%s%s%s%s",
aflags & 0x80 ? "O" : "",
aflags & 0x40 ? "T" : "",
aflags & 0x20 ? "P" : "",
aflags & 0x10 ? "E" : ""));
if (aflags & 0xf)
ND_PRINT((ndo, "+%x", aflags & 0xf));
ND_PRINT((ndo, "]: "));
}
if (len < alen)
goto trunc;
if (length < alen)
goto trunc;
if (!bgp_attr_print(ndo, atype, p, alen))
goto trunc;
p += alen;
len -= alen;
length -= alen;
}
}
if (length) {
/*
* XXX - what if they're using the "Advertisement of
* Multiple Paths in BGP" feature:
*
* https://datatracker.ietf.org/doc/draft-ietf-idr-add-paths/
*
* http://tools.ietf.org/html/draft-ietf-idr-add-paths-06
*/
ND_PRINT((ndo, "\n\t Updated routes:"));
while (length) {
char buf[MAXHOSTNAMELEN + 100];
i = decode_prefix4(ndo, p, length, buf, sizeof(buf));
if (i == -1) {
ND_PRINT((ndo, "\n\t (illegal prefix length)"));
break;
} else if (i == -2)
goto trunc;
else if (i == -3)
goto trunc; /* bytes left, but not enough */
else {
ND_PRINT((ndo, "\n\t %s", buf));
p += i;
length -= i;
}
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static void
bgp_notification_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp_notification bgpn;
const u_char *tptr;
ND_TCHECK2(dat[0], BGP_NOTIFICATION_SIZE);
memcpy(&bgpn, dat, BGP_NOTIFICATION_SIZE);
/* some little sanity checking */
if (length<BGP_NOTIFICATION_SIZE)
return;
ND_PRINT((ndo, ", %s (%u)",
tok2str(bgp_notify_major_values, "Unknown Error",
bgpn.bgpn_major),
bgpn.bgpn_major));
switch (bgpn.bgpn_major) {
case BGP_NOTIFY_MAJOR_MSG:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_msg_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_OPEN:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_open_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_UPDATE:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_update_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_FSM:
ND_PRINT((ndo, " subcode %s (%u)",
tok2str(bgp_notify_minor_fsm_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_CAP:
ND_PRINT((ndo, " subcode %s (%u)",
tok2str(bgp_notify_minor_cap_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
break;
case BGP_NOTIFY_MAJOR_CEASE:
ND_PRINT((ndo, ", subcode %s (%u)",
tok2str(bgp_notify_minor_cease_values, "Unknown",
bgpn.bgpn_minor),
bgpn.bgpn_minor));
/* draft-ietf-idr-cease-subcode-02 mentions optionally 7 bytes
* for the maxprefix subtype, which may contain AFI, SAFI and MAXPREFIXES
*/
if(bgpn.bgpn_minor == BGP_NOTIFY_MINOR_CEASE_MAXPRFX && length >= BGP_NOTIFICATION_SIZE + 7) {
tptr = dat + BGP_NOTIFICATION_SIZE;
ND_TCHECK2(*tptr, 7);
ND_PRINT((ndo, ", AFI %s (%u), SAFI %s (%u), Max Prefixes: %u",
tok2str(af_values, "Unknown",
EXTRACT_16BITS(tptr)),
EXTRACT_16BITS(tptr),
tok2str(bgp_safi_values, "Unknown", *(tptr+2)),
*(tptr+2),
EXTRACT_32BITS(tptr+3)));
}
break;
default:
break;
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static void
bgp_route_refresh_print(netdissect_options *ndo,
const u_char *pptr, int len)
{
const struct bgp_route_refresh *bgp_route_refresh_header;
ND_TCHECK2(pptr[0], BGP_ROUTE_REFRESH_SIZE);
/* some little sanity checking */
if (len<BGP_ROUTE_REFRESH_SIZE)
return;
bgp_route_refresh_header = (const struct bgp_route_refresh *)pptr;
ND_PRINT((ndo, "\n\t AFI %s (%u), SAFI %s (%u)",
tok2str(af_values,"Unknown",
/* this stinks but the compiler pads the structure
* weird */
EXTRACT_16BITS(&bgp_route_refresh_header->afi)),
EXTRACT_16BITS(&bgp_route_refresh_header->afi),
tok2str(bgp_safi_values,"Unknown",
bgp_route_refresh_header->safi),
bgp_route_refresh_header->safi));
if (ndo->ndo_vflag > 1) {
ND_TCHECK2(*pptr, len);
print_unknown_data(ndo, pptr, "\n\t ", len);
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
static int
bgp_header_print(netdissect_options *ndo,
const u_char *dat, int length)
{
struct bgp bgp;
ND_TCHECK2(dat[0], BGP_SIZE);
memcpy(&bgp, dat, BGP_SIZE);
ND_PRINT((ndo, "\n\t%s Message (%u), length: %u",
tok2str(bgp_msg_values, "Unknown", bgp.bgp_type),
bgp.bgp_type,
length));
switch (bgp.bgp_type) {
case BGP_OPEN:
bgp_open_print(ndo, dat, length);
break;
case BGP_UPDATE:
bgp_update_print(ndo, dat, length);
break;
case BGP_NOTIFICATION:
bgp_notification_print(ndo, dat, length);
break;
case BGP_KEEPALIVE:
break;
case BGP_ROUTE_REFRESH:
bgp_route_refresh_print(ndo, dat, length);
break;
default:
/* we have no decoder for the BGP message */
ND_TCHECK2(*dat, length);
ND_PRINT((ndo, "\n\t no Message %u decoder", bgp.bgp_type));
print_unknown_data(ndo, dat, "\n\t ", length);
break;
}
return 1;
trunc:
ND_PRINT((ndo, "%s", tstr));
return 0;
}
void
bgp_print(netdissect_options *ndo,
const u_char *dat, int length)
{
const u_char *p;
const u_char *ep;
const u_char *start;
const u_char marker[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
};
struct bgp bgp;
uint16_t hlen;
ep = dat + length;
if (ndo->ndo_snapend < dat + length)
ep = ndo->ndo_snapend;
ND_PRINT((ndo, ": BGP"));
if (ndo->ndo_vflag < 1) /* lets be less chatty */
return;
p = dat;
start = p;
while (p < ep) {
if (!ND_TTEST2(p[0], 1))
break;
if (p[0] != 0xff) {
p++;
continue;
}
if (!ND_TTEST2(p[0], sizeof(marker)))
break;
if (memcmp(p, marker, sizeof(marker)) != 0) {
p++;
continue;
}
/* found BGP header */
ND_TCHECK2(p[0], BGP_SIZE); /*XXX*/
memcpy(&bgp, p, BGP_SIZE);
if (start != p)
ND_PRINT((ndo, " %s", tstr));
hlen = ntohs(bgp.bgp_len);
if (hlen < BGP_SIZE) {
ND_PRINT((ndo, "\n[|BGP Bogus header length %u < %u]", hlen,
BGP_SIZE));
break;
}
if (ND_TTEST2(p[0], hlen)) {
if (!bgp_header_print(ndo, p, hlen))
return;
p += hlen;
start = p;
} else {
ND_PRINT((ndo, "\n[|BGP %s]",
tok2str(bgp_msg_values,
"Unknown Message Type",
bgp.bgp_type)));
break;
}
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
/*
* Local Variables:
* c-style: whitesmith
* c-basic-offset: 4
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-674/c/bad_333_0 |
crossvul-cpp_data_good_4436_0 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* lib/krb5/asn.1/asn1_encode.c */
/*
* Copyright 1994, 2008 by the Massachusetts Institute of Technology.
* All Rights Reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*/
#include "asn1_encode.h"
struct asn1buf_st {
uint8_t *ptr; /* Position, moving backwards; may be NULL */
size_t count; /* Count of bytes written so far */
};
/**** Functions for encoding primitive types ****/
/* Insert one byte into buf going backwards. */
static inline void
insert_byte(asn1buf *buf, uint8_t o)
{
if (buf->ptr != NULL) {
buf->ptr--;
*buf->ptr = o;
}
buf->count++;
}
/* Insert a block of bytes into buf going backwards (but without reversing
* bytes). */
static inline void
insert_bytes(asn1buf *buf, const void *bytes, size_t len)
{
if (buf->ptr != NULL) {
memcpy(buf->ptr - len, bytes, len);
buf->ptr -= len;
}
buf->count += len;
}
void
k5_asn1_encode_bool(asn1buf *buf, intmax_t val)
{
insert_byte(buf, val ? 0xFF : 0x00);
}
void
k5_asn1_encode_int(asn1buf *buf, intmax_t val)
{
long valcopy;
int digit;
valcopy = val;
do {
digit = valcopy & 0xFF;
insert_byte(buf, digit);
valcopy = valcopy >> 8;
} while (valcopy != 0 && valcopy != ~0);
/* Make sure the high bit is of the proper signed-ness. */
if (val > 0 && (digit & 0x80) == 0x80)
insert_byte(buf, 0);
else if (val < 0 && (digit & 0x80) != 0x80)
insert_byte(buf, 0xFF);
}
void
k5_asn1_encode_uint(asn1buf *buf, uintmax_t val)
{
uintmax_t valcopy;
int digit;
valcopy = val;
do {
digit = valcopy & 0xFF;
insert_byte(buf, digit);
valcopy = valcopy >> 8;
} while (valcopy != 0);
/* Make sure the high bit is of the proper signed-ness. */
if (digit & 0x80)
insert_byte(buf, 0);
}
krb5_error_code
k5_asn1_encode_bytestring(asn1buf *buf, uint8_t *const *val, size_t len)
{
if (len > 0 && val == NULL)
return ASN1_MISSING_FIELD;
insert_bytes(buf, *val, len);
return 0;
}
krb5_error_code
k5_asn1_encode_generaltime(asn1buf *buf, time_t val)
{
struct tm *gtime, gtimebuf;
char s[16], *sp;
time_t gmt_time = val;
int len;
/*
* Time encoding: YYYYMMDDhhmmssZ
*/
if (gmt_time == 0) {
sp = "19700101000000Z";
} else {
/*
* Sanity check this just to be paranoid, as gmtime can return NULL,
* and some bogus implementations might overrun on the sprintf.
*/
#ifdef HAVE_GMTIME_R
#ifdef GMTIME_R_RETURNS_INT
if (gmtime_r(&gmt_time, >imebuf) != 0)
return ASN1_BAD_GMTIME;
#else
if (gmtime_r(&gmt_time, >imebuf) == NULL)
return ASN1_BAD_GMTIME;
#endif
#else /* HAVE_GMTIME_R */
gtime = gmtime(&gmt_time);
if (gtime == NULL)
return ASN1_BAD_GMTIME;
memcpy(>imebuf, gtime, sizeof(gtimebuf));
#endif /* HAVE_GMTIME_R */
gtime = >imebuf;
if (gtime->tm_year > 8099 || gtime->tm_mon > 11 ||
gtime->tm_mday > 31 || gtime->tm_hour > 23 ||
gtime->tm_min > 59 || gtime->tm_sec > 59)
return ASN1_BAD_GMTIME;
len = snprintf(s, sizeof(s), "%04d%02d%02d%02d%02d%02dZ",
1900 + gtime->tm_year, gtime->tm_mon + 1,
gtime->tm_mday, gtime->tm_hour,
gtime->tm_min, gtime->tm_sec);
if (SNPRINTF_OVERFLOW(len, sizeof(s)))
/* Shouldn't be possible given above tests. */
return ASN1_BAD_GMTIME;
sp = s;
}
insert_bytes(buf, sp, 15);
return 0;
}
krb5_error_code
k5_asn1_encode_bitstring(asn1buf *buf, uint8_t *const *val, size_t len)
{
insert_bytes(buf, *val, len);
insert_byte(buf, 0);
return 0;
}
/**** Functions for decoding primitive types ****/
krb5_error_code
k5_asn1_decode_bool(const uint8_t *asn1, size_t len, intmax_t *val)
{
if (len != 1)
return ASN1_BAD_LENGTH;
*val = (*asn1 != 0);
return 0;
}
/* Decode asn1/len as the contents of a DER integer, placing the signed result
* in val. */
krb5_error_code
k5_asn1_decode_int(const uint8_t *asn1, size_t len, intmax_t *val)
{
intmax_t n;
size_t i;
if (len == 0)
return ASN1_BAD_LENGTH;
n = (asn1[0] & 0x80) ? -1 : 0;
/* Check length; allow extra octet if first octet is 0. */
if (len > sizeof(intmax_t) + (asn1[0] == 0))
return ASN1_OVERFLOW;
for (i = 0; i < len; i++)
n = (n << 8) | asn1[i];
*val = n;
return 0;
}
/* Decode asn1/len as the contents of a DER integer, placing the unsigned
* result in val. */
krb5_error_code
k5_asn1_decode_uint(const uint8_t *asn1, size_t len, uintmax_t *val)
{
uintmax_t n;
size_t i;
if (len == 0)
return ASN1_BAD_LENGTH;
/* Check for negative values and check length. */
if ((asn1[0] & 0x80) || len > sizeof(uintmax_t) + (asn1[0] == 0))
return ASN1_OVERFLOW;
for (i = 0, n = 0; i < len; i++)
n = (n << 8) | asn1[i];
*val = n;
return 0;
}
krb5_error_code
k5_asn1_decode_bytestring(const uint8_t *asn1, size_t len,
uint8_t **str_out, size_t *len_out)
{
uint8_t *str;
*str_out = NULL;
*len_out = 0;
if (len == 0)
return 0;
str = malloc(len);
if (str == NULL)
return ENOMEM;
memcpy(str, asn1, len);
*str_out = str;
*len_out = len;
return 0;
}
krb5_error_code
k5_asn1_decode_generaltime(const uint8_t *asn1, size_t len, time_t *time_out)
{
const char *s = (char *)asn1;
struct tm ts;
time_t t;
*time_out = 0;
if (len != 15)
return ASN1_BAD_LENGTH;
/* Time encoding: YYYYMMDDhhmmssZ */
if (s[14] != 'Z')
return ASN1_BAD_FORMAT;
if (memcmp(s, "19700101000000Z", 15) == 0) {
*time_out = 0;
return 0;
}
#define c2i(c) ((c) - '0')
ts.tm_year = 1000 * c2i(s[0]) + 100 * c2i(s[1]) + 10 * c2i(s[2]) +
c2i(s[3]) - 1900;
ts.tm_mon = 10 * c2i(s[4]) + c2i(s[5]) - 1;
ts.tm_mday = 10 * c2i(s[6]) + c2i(s[7]);
ts.tm_hour = 10 * c2i(s[8]) + c2i(s[9]);
ts.tm_min = 10 * c2i(s[10]) + c2i(s[11]);
ts.tm_sec = 10 * c2i(s[12]) + c2i(s[13]);
ts.tm_isdst = -1;
t = krb5int_gmt_mktime(&ts);
if (t == -1)
return ASN1_BAD_TIMEFORMAT;
*time_out = t;
return 0;
}
/*
* Note: we return the number of bytes, not bits, in the bit string. If the
* number of bits is not a multiple of 8 we effectively round up to the next
* multiple of 8.
*/
krb5_error_code
k5_asn1_decode_bitstring(const uint8_t *asn1, size_t len,
uint8_t **bits_out, size_t *len_out)
{
uint8_t unused, *bits;
*bits_out = NULL;
*len_out = 0;
if (len == 0)
return ASN1_BAD_LENGTH;
unused = *asn1++;
len--;
if (unused > 7)
return ASN1_BAD_FORMAT;
bits = malloc(len);
if (bits == NULL)
return ENOMEM;
memcpy(bits, asn1, len);
if (len > 1)
bits[len - 1] &= (0xff << unused);
*bits_out = bits;
*len_out = len;
return 0;
}
/**** Functions for encoding and decoding tags ****/
/* Encode a DER tag into buf with the tag parameters in t and the content
* length len. Place the length of the encoded tag in *retlen. */
static krb5_error_code
make_tag(asn1buf *buf, const taginfo *t, size_t len)
{
asn1_tagnum tag_copy;
size_t len_copy, oldcount;
if (t->tagnum > ASN1_TAGNUM_MAX)
return ASN1_OVERFLOW;
/* Encode the length of the content within the tag. */
if (len < 128) {
insert_byte(buf, len & 0x7F);
} else {
oldcount = buf->count;
for (len_copy = len; len_copy != 0; len_copy >>= 8)
insert_byte(buf, len_copy & 0xFF);
insert_byte(buf, 0x80 | ((buf->count - oldcount) & 0x7F));
}
/* Encode the tag and construction bit. */
if (t->tagnum < 31) {
insert_byte(buf, t->asn1class | t->construction | t->tagnum);
} else {
tag_copy = t->tagnum;
insert_byte(buf, tag_copy & 0x7F);
tag_copy >>= 7;
for (; tag_copy != 0; tag_copy >>= 7)
insert_byte(buf, 0x80 | (tag_copy & 0x7F));
insert_byte(buf, t->asn1class | t->construction | 0x1F);
}
return 0;
}
/*
* Read a BER tag and length from asn1/len. Place the tag parameters in
* tag_out. Set contents_out/clen_out to the octet range of the tag's
* contents, and remainder_out/rlen_out to the octet range after the end of the
* BER encoding.
*
* (krb5 ASN.1 encodings should be in DER, but for compatibility with some
* really ancient implementations we handle the indefinite length form in tags.
* However, we still insist on the primitive form of string types.)
*/
static krb5_error_code
get_tag(const uint8_t *asn1, size_t len, taginfo *tag_out,
const uint8_t **contents_out, size_t *clen_out,
const uint8_t **remainder_out, size_t *rlen_out, int recursion)
{
krb5_error_code ret;
uint8_t o;
const uint8_t *c, *p, *tag_start = asn1;
size_t clen, llen, i;
taginfo t;
*contents_out = *remainder_out = NULL;
*clen_out = *rlen_out = 0;
if (len == 0)
return ASN1_OVERRUN;
o = *asn1++;
len--;
tag_out->asn1class = o & 0xC0;
tag_out->construction = o & 0x20;
if ((o & 0x1F) != 0x1F) {
tag_out->tagnum = o & 0x1F;
} else {
tag_out->tagnum = 0;
do {
if (len == 0)
return ASN1_OVERRUN;
o = *asn1++;
len--;
tag_out->tagnum = (tag_out->tagnum << 7) | (o & 0x7F);
} while (o & 0x80);
}
if (len == 0)
return ASN1_OVERRUN;
o = *asn1++;
len--;
if (o == 0x80) {
/* Indefinite form (should not be present in DER, but we accept it). */
if (tag_out->construction != CONSTRUCTED)
return ASN1_MISMATCH_INDEF;
if (recursion >= 32)
return ASN1_OVERFLOW;
p = asn1;
while (!(len >= 2 && p[0] == 0 && p[1] == 0)) {
ret = get_tag(p, len, &t, &c, &clen, &p, &len, recursion + 1);
if (ret)
return ret;
}
tag_out->tag_end_len = 2;
*contents_out = asn1;
*clen_out = p - asn1;
*remainder_out = p + 2;
*rlen_out = len - 2;
} else if ((o & 0x80) == 0) {
/* Short form (first octet gives content length). */
if (o > len)
return ASN1_OVERRUN;
tag_out->tag_end_len = 0;
*contents_out = asn1;
*clen_out = o;
*remainder_out = asn1 + *clen_out;
*rlen_out = len - (*remainder_out - asn1);
} else {
/* Long form (first octet gives number of base-256 length octets). */
llen = o & 0x7F;
if (llen > len)
return ASN1_OVERRUN;
if (llen > sizeof(*clen_out))
return ASN1_OVERFLOW;
for (i = 0, clen = 0; i < llen; i++)
clen = (clen << 8) | asn1[i];
if (clen > len - llen)
return ASN1_OVERRUN;
tag_out->tag_end_len = 0;
*contents_out = asn1 + llen;
*clen_out = clen;
*remainder_out = *contents_out + clen;
*rlen_out = len - (*remainder_out - asn1);
}
tag_out->tag_len = *contents_out - tag_start;
return 0;
}
#ifdef POINTERS_ARE_ALL_THE_SAME
#define LOADPTR(PTR, TYPE) (*(const void *const *)(PTR))
#define STOREPTR(PTR, TYPE, VAL) (*(void **)(VAL) = (PTR))
#else
#define LOADPTR(PTR, PTRINFO) \
(assert((PTRINFO)->loadptr != NULL), (PTRINFO)->loadptr(PTR))
#define STOREPTR(PTR, PTRINFO, VAL) \
(assert((PTRINFO)->storeptr != NULL), (PTRINFO)->storeptr(PTR, VAL))
#endif
static size_t
get_nullterm_sequence_len(const void *valp, const struct atype_info *seq)
{
size_t i;
const struct atype_info *a;
const struct ptr_info *ptr;
const void *elt, *eltptr;
a = seq;
i = 0;
assert(a->type == atype_ptr);
assert(seq->size != 0);
ptr = a->tinfo;
while (1) {
eltptr = (const char *)valp + i * seq->size;
elt = LOADPTR(eltptr, ptr);
if (elt == NULL)
break;
i++;
}
return i;
}
static krb5_error_code
encode_sequence_of(asn1buf *buf, size_t seqlen, const void *val,
const struct atype_info *eltinfo);
static krb5_error_code
encode_nullterm_sequence_of(asn1buf *buf, const void *val,
const struct atype_info *type, int can_be_empty)
{
size_t len = get_nullterm_sequence_len(val, type);
if (!can_be_empty && len == 0)
return ASN1_MISSING_FIELD;
return encode_sequence_of(buf, len, val, type);
}
static intmax_t
load_int(const void *val, size_t size)
{
switch (size) {
case 1: return *(int8_t *)val;
case 2: return *(int16_t *)val;
case 4: return *(int32_t *)val;
case 8: return *(int64_t *)val;
default: abort();
}
}
static uintmax_t
load_uint(const void *val, size_t size)
{
switch (size) {
case 1: return *(uint8_t *)val;
case 2: return *(uint16_t *)val;
case 4: return *(uint32_t *)val;
case 8: return *(uint64_t *)val;
default: abort();
}
}
static krb5_error_code
load_count(const void *val, const struct counted_info *counted,
size_t *count_out)
{
const void *countptr = (const char *)val + counted->lenoff;
assert(sizeof(size_t) <= sizeof(uintmax_t));
if (counted->lensigned) {
intmax_t xlen = load_int(countptr, counted->lensize);
if (xlen < 0 || (uintmax_t)xlen > SIZE_MAX)
return EINVAL;
*count_out = xlen;
} else {
uintmax_t xlen = load_uint(countptr, counted->lensize);
if ((size_t)xlen != xlen || xlen > SIZE_MAX)
return EINVAL;
*count_out = xlen;
}
return 0;
}
static krb5_error_code
store_int(intmax_t intval, size_t size, void *val)
{
switch (size) {
case 1:
if ((int8_t)intval != intval)
return ASN1_OVERFLOW;
*(int8_t *)val = intval;
return 0;
case 2:
if ((int16_t)intval != intval)
return ASN1_OVERFLOW;
*(int16_t *)val = intval;
return 0;
case 4:
if ((int32_t)intval != intval)
return ASN1_OVERFLOW;
*(int32_t *)val = intval;
return 0;
case 8:
if ((int64_t)intval != intval)
return ASN1_OVERFLOW;
*(int64_t *)val = intval;
return 0;
default:
abort();
}
}
static krb5_error_code
store_uint(uintmax_t intval, size_t size, void *val)
{
switch (size) {
case 1:
if ((uint8_t)intval != intval)
return ASN1_OVERFLOW;
*(uint8_t *)val = intval;
return 0;
case 2:
if ((uint16_t)intval != intval)
return ASN1_OVERFLOW;
*(uint16_t *)val = intval;
return 0;
case 4:
if ((uint32_t)intval != intval)
return ASN1_OVERFLOW;
*(uint32_t *)val = intval;
return 0;
case 8:
if ((uint64_t)intval != intval)
return ASN1_OVERFLOW;
*(uint64_t *)val = intval;
return 0;
default:
abort();
}
}
/* Store a count value in an integer field of a structure. If count is
* SIZE_MAX and the target is a signed field, store -1. */
static krb5_error_code
store_count(size_t count, const struct counted_info *counted, void *val)
{
void *countptr = (char *)val + counted->lenoff;
if (counted->lensigned) {
if (count == SIZE_MAX)
return store_int(-1, counted->lensize, countptr);
else if ((intmax_t)count < 0)
return ASN1_OVERFLOW;
else
return store_int(count, counted->lensize, countptr);
} else
return store_uint(count, counted->lensize, countptr);
}
/* Split a DER encoding into tag and contents. Insert the contents into buf,
* then return the length of the contents and the tag. */
static krb5_error_code
split_der(asn1buf *buf, uint8_t *const *der, size_t len, taginfo *tag_out)
{
krb5_error_code ret;
const uint8_t *contents, *remainder;
size_t clen, rlen;
ret = get_tag(*der, len, tag_out, &contents, &clen, &remainder, &rlen, 0);
if (ret)
return ret;
if (rlen != 0)
return ASN1_BAD_LENGTH;
insert_bytes(buf, contents, clen);
return 0;
}
/*
* Store the DER encoding given by t and asn1/len into the char * or
* uint8_t * pointed to by val. Set *count_out to the length of the
* DER encoding.
*/
static krb5_error_code
store_der(const taginfo *t, const uint8_t *asn1, size_t len, void *val,
size_t *count_out)
{
uint8_t *der;
size_t der_len;
*count_out = 0;
der_len = t->tag_len + len + t->tag_end_len;
der = malloc(der_len);
if (der == NULL)
return ENOMEM;
memcpy(der, asn1 - t->tag_len, der_len);
*(uint8_t **)val = der;
*count_out = der_len;
return 0;
}
static krb5_error_code
encode_sequence(asn1buf *buf, const void *val, const struct seq_info *seq);
static krb5_error_code
encode_cntype(asn1buf *buf, const void *val, size_t len,
const struct cntype_info *c, taginfo *tag_out);
/* Encode a value (contents only, no outer tag) according to a type, and return
* its encoded tag information. */
static krb5_error_code
encode_atype(asn1buf *buf, const void *val, const struct atype_info *a,
taginfo *tag_out)
{
krb5_error_code ret;
if (val == NULL)
return ASN1_MISSING_FIELD;
switch (a->type) {
case atype_fn: {
const struct fn_info *fn = a->tinfo;
assert(fn->enc != NULL);
return fn->enc(buf, val, tag_out);
}
case atype_sequence:
assert(a->tinfo != NULL);
ret = encode_sequence(buf, val, a->tinfo);
if (ret)
return ret;
tag_out->asn1class = UNIVERSAL;
tag_out->construction = CONSTRUCTED;
tag_out->tagnum = ASN1_SEQUENCE;
break;
case atype_ptr: {
const struct ptr_info *ptr = a->tinfo;
assert(ptr->basetype != NULL);
return encode_atype(buf, LOADPTR(val, ptr), ptr->basetype, tag_out);
}
case atype_offset: {
const struct offset_info *off = a->tinfo;
assert(off->basetype != NULL);
return encode_atype(buf, (const char *)val + off->dataoff,
off->basetype, tag_out);
}
case atype_optional: {
const struct optional_info *opt = a->tinfo;
assert(opt->is_present != NULL);
if (opt->is_present(val))
return encode_atype(buf, val, opt->basetype, tag_out);
else
return ASN1_OMITTED;
}
case atype_counted: {
const struct counted_info *counted = a->tinfo;
const void *dataptr = (const char *)val + counted->dataoff;
size_t count;
assert(counted->basetype != NULL);
ret = load_count(val, counted, &count);
if (ret)
return ret;
return encode_cntype(buf, dataptr, count, counted->basetype, tag_out);
}
case atype_nullterm_sequence_of:
case atype_nonempty_nullterm_sequence_of:
assert(a->tinfo != NULL);
ret = encode_nullterm_sequence_of(buf, val, a->tinfo,
a->type ==
atype_nullterm_sequence_of);
if (ret)
return ret;
tag_out->asn1class = UNIVERSAL;
tag_out->construction = CONSTRUCTED;
tag_out->tagnum = ASN1_SEQUENCE;
break;
case atype_tagged_thing: {
const struct tagged_info *tag = a->tinfo;
size_t oldcount = buf->count;
ret = encode_atype(buf, val, tag->basetype, tag_out);
if (ret)
return ret;
if (!tag->implicit) {
ret = make_tag(buf, tag_out, buf->count - oldcount);
if (ret)
return ret;
tag_out->construction = tag->construction;
}
tag_out->asn1class = tag->tagtype;
tag_out->tagnum = tag->tagval;
break;
}
case atype_bool:
k5_asn1_encode_bool(buf, load_int(val, a->size));
tag_out->asn1class = UNIVERSAL;
tag_out->construction = PRIMITIVE;
tag_out->tagnum = ASN1_BOOLEAN;
break;
case atype_int:
k5_asn1_encode_int(buf, load_int(val, a->size));
tag_out->asn1class = UNIVERSAL;
tag_out->construction = PRIMITIVE;
tag_out->tagnum = ASN1_INTEGER;
break;
case atype_uint:
k5_asn1_encode_uint(buf, load_uint(val, a->size));
tag_out->asn1class = UNIVERSAL;
tag_out->construction = PRIMITIVE;
tag_out->tagnum = ASN1_INTEGER;
break;
case atype_int_immediate: {
const struct immediate_info *imm = a->tinfo;
k5_asn1_encode_int(buf, imm->val);
tag_out->asn1class = UNIVERSAL;
tag_out->construction = PRIMITIVE;
tag_out->tagnum = ASN1_INTEGER;
break;
}
default:
assert(a->type > atype_min);
assert(a->type < atype_max);
abort();
}
return 0;
}
static krb5_error_code
encode_atype_and_tag(asn1buf *buf, const void *val, const struct atype_info *a)
{
taginfo t;
krb5_error_code ret;
size_t oldcount = buf->count;
ret = encode_atype(buf, val, a, &t);
if (ret)
return ret;
ret = make_tag(buf, &t, buf->count - oldcount);
if (ret)
return ret;
return 0;
}
/*
* Encode an object and count according to a cntype_info structure. val is a
* pointer to the object being encoded, which in most cases is itself a
* pointer (but is a union in the cntype_choice case).
*/
static krb5_error_code
encode_cntype(asn1buf *buf, const void *val, size_t count,
const struct cntype_info *c, taginfo *tag_out)
{
krb5_error_code ret;
switch (c->type) {
case cntype_string: {
const struct string_info *string = c->tinfo;
assert(string->enc != NULL);
ret = string->enc(buf, val, count);
if (ret)
return ret;
tag_out->asn1class = UNIVERSAL;
tag_out->construction = PRIMITIVE;
tag_out->tagnum = string->tagval;
break;
}
case cntype_der:
return split_der(buf, val, count, tag_out);
case cntype_seqof: {
const struct atype_info *a = c->tinfo;
const struct ptr_info *ptr = a->tinfo;
assert(a->type == atype_ptr);
val = LOADPTR(val, ptr);
ret = encode_sequence_of(buf, count, val, ptr->basetype);
if (ret)
return ret;
tag_out->asn1class = UNIVERSAL;
tag_out->construction = CONSTRUCTED;
tag_out->tagnum = ASN1_SEQUENCE;
break;
}
case cntype_choice: {
const struct choice_info *choice = c->tinfo;
if (count >= choice->n_options)
return ASN1_MISSING_FIELD;
return encode_atype(buf, val, choice->options[count], tag_out);
}
default:
assert(c->type > cntype_min);
assert(c->type < cntype_max);
abort();
}
return 0;
}
static krb5_error_code
encode_sequence(asn1buf *buf, const void *val, const struct seq_info *seq)
{
krb5_error_code ret;
size_t i;
for (i = seq->n_fields; i > 0; i--) {
ret = encode_atype_and_tag(buf, val, seq->fields[i - 1]);
if (ret == ASN1_OMITTED)
continue;
else if (ret != 0)
return ret;
}
return 0;
}
static krb5_error_code
encode_sequence_of(asn1buf *buf, size_t seqlen, const void *val,
const struct atype_info *eltinfo)
{
krb5_error_code ret;
size_t i;
const void *eltptr;
assert(eltinfo->size != 0);
for (i = seqlen; i > 0; i--) {
eltptr = (const char *)val + (i - 1) * eltinfo->size;
ret = encode_atype_and_tag(buf, eltptr, eltinfo);
if (ret)
return ret;
}
return 0;
}
/**** Functions for freeing C objects based on type info ****/
static void free_atype_ptr(const struct atype_info *a, void *val);
static void free_sequence(const struct seq_info *seq, void *val);
static void free_sequence_of(const struct atype_info *eltinfo, void *val,
size_t count);
static void free_cntype(const struct cntype_info *a, void *val, size_t count);
/*
* Free a C object according to a type description. Do not free pointers at
* the first level; they may be referenced by other fields of a sequence, and
* will be freed by free_atype_ptr in a second pass.
*/
static void
free_atype(const struct atype_info *a, void *val)
{
switch (a->type) {
case atype_fn: {
const struct fn_info *fn = a->tinfo;
if (fn->free_func != NULL)
fn->free_func(val);
break;
}
case atype_sequence:
free_sequence(a->tinfo, val);
break;
case atype_ptr: {
const struct ptr_info *ptrinfo = a->tinfo;
void *ptr = LOADPTR(val, ptrinfo);
if (ptr != NULL) {
free_atype(ptrinfo->basetype, ptr);
free_atype_ptr(ptrinfo->basetype, ptr);
}
break;
}
case atype_offset: {
const struct offset_info *off = a->tinfo;
assert(off->basetype != NULL);
free_atype(off->basetype, (char *)val + off->dataoff);
break;
}
case atype_optional: {
const struct optional_info *opt = a->tinfo;
free_atype(opt->basetype, val);
break;
}
case atype_counted: {
const struct counted_info *counted = a->tinfo;
void *dataptr = (char *)val + counted->dataoff;
size_t count;
if (load_count(val, counted, &count) == 0)
free_cntype(counted->basetype, dataptr, count);
break;
}
case atype_nullterm_sequence_of:
case atype_nonempty_nullterm_sequence_of: {
size_t count = get_nullterm_sequence_len(val, a->tinfo);
free_sequence_of(a->tinfo, val, count);
break;
}
case atype_tagged_thing: {
const struct tagged_info *tag = a->tinfo;
free_atype(tag->basetype, val);
break;
}
case atype_bool:
case atype_int:
case atype_uint:
case atype_int_immediate:
break;
default:
abort();
}
}
static void
free_atype_ptr(const struct atype_info *a, void *val)
{
switch (a->type) {
case atype_fn:
case atype_sequence:
case atype_counted:
case atype_nullterm_sequence_of:
case atype_nonempty_nullterm_sequence_of:
case atype_bool:
case atype_int:
case atype_uint:
case atype_int_immediate:
break;
case atype_ptr: {
const struct ptr_info *ptrinfo = a->tinfo;
void *ptr = LOADPTR(val, ptrinfo);
free(ptr);
STOREPTR(NULL, ptrinfo, val);
break;
}
case atype_offset: {
const struct offset_info *off = a->tinfo;
assert(off->basetype != NULL);
free_atype_ptr(off->basetype, (char *)val + off->dataoff);
break;
}
case atype_optional: {
const struct optional_info *opt = a->tinfo;
free_atype_ptr(opt->basetype, val);
break;
}
case atype_tagged_thing: {
const struct tagged_info *tag = a->tinfo;
free_atype_ptr(tag->basetype, val);
break;
}
default:
abort();
}
}
static void
free_cntype(const struct cntype_info *c, void *val, size_t count)
{
switch (c->type) {
case cntype_string:
case cntype_der:
free(*(char **)val);
*(char **)val = NULL;
break;
case cntype_seqof: {
const struct atype_info *a = c->tinfo;
const struct ptr_info *ptrinfo = a->tinfo;
void *seqptr = LOADPTR(val, ptrinfo);
free_sequence_of(ptrinfo->basetype, seqptr, count);
free(seqptr);
STOREPTR(NULL, ptrinfo, val);
break;
}
case cntype_choice: {
const struct choice_info *choice = c->tinfo;
if (count < choice->n_options) {
free_atype(choice->options[count], val);
free_atype_ptr(choice->options[count], val);
}
break;
}
default:
abort();
}
}
static void
free_sequence(const struct seq_info *seq, void *val)
{
size_t i;
for (i = 0; i < seq->n_fields; i++)
free_atype(seq->fields[i], val);
for (i = 0; i < seq->n_fields; i++)
free_atype_ptr(seq->fields[i], val);
}
static void
free_sequence_of(const struct atype_info *eltinfo, void *val, size_t count)
{
void *eltptr;
assert(eltinfo->size != 0);
while (count-- > 0) {
eltptr = (char *)val + count * eltinfo->size;
free_atype(eltinfo, eltptr);
free_atype_ptr(eltinfo, eltptr);
}
}
/**** Functions for decoding objects based on type info ****/
/* Return nonzero if t is an expected tag for an ASN.1 object of type a. */
static int
check_atype_tag(const struct atype_info *a, const taginfo *t)
{
switch (a->type) {
case atype_fn: {
const struct fn_info *fn = a->tinfo;
assert(fn->check_tag != NULL);
return fn->check_tag(t);
}
case atype_sequence:
case atype_nullterm_sequence_of:
case atype_nonempty_nullterm_sequence_of:
return (t->asn1class == UNIVERSAL && t->construction == CONSTRUCTED &&
t->tagnum == ASN1_SEQUENCE);
case atype_ptr: {
const struct ptr_info *ptrinfo = a->tinfo;
return check_atype_tag(ptrinfo->basetype, t);
}
case atype_offset: {
const struct offset_info *off = a->tinfo;
return check_atype_tag(off->basetype, t);
}
case atype_optional: {
const struct optional_info *opt = a->tinfo;
return check_atype_tag(opt->basetype, t);
}
case atype_counted: {
const struct counted_info *counted = a->tinfo;
switch (counted->basetype->type) {
case cntype_string: {
const struct string_info *string = counted->basetype->tinfo;
return (t->asn1class == UNIVERSAL &&
t->construction == PRIMITIVE &&
t->tagnum == string->tagval);
}
case cntype_seqof:
return (t->asn1class == UNIVERSAL &&
t->construction == CONSTRUCTED &&
t->tagnum == ASN1_SEQUENCE);
case cntype_der:
/*
* We treat any tag as matching a stored DER encoding. In some
* cases we know what the tag should be; in others, we truly want
* to accept any tag. If it ever becomes an issue, we could add
* optional tag info to the type and check it here.
*/
return 1;
case cntype_choice:
/*
* ASN.1 choices may or may not be extensible. For now, we treat
* all choices as extensible and match any tag. We should consider
* modeling whether choices are extensible before making the
* encoder visible to plugins.
*/
return 1;
default:
abort();
}
}
case atype_tagged_thing: {
const struct tagged_info *tag = a->tinfo;
/* NOTE: Doesn't check construction bit for implicit tags. */
if (!tag->implicit && t->construction != tag->construction)
return 0;
return (t->asn1class == tag->tagtype && t->tagnum == tag->tagval);
}
case atype_bool:
return (t->asn1class == UNIVERSAL && t->construction == PRIMITIVE &&
t->tagnum == ASN1_BOOLEAN);
case atype_int:
case atype_uint:
case atype_int_immediate:
return (t->asn1class == UNIVERSAL && t->construction == PRIMITIVE &&
t->tagnum == ASN1_INTEGER);
default:
abort();
}
}
static krb5_error_code
decode_cntype(const taginfo *t, const uint8_t *asn1, size_t len,
const struct cntype_info *c, void *val, size_t *count_out);
static krb5_error_code
decode_atype_to_ptr(const taginfo *t, const uint8_t *asn1, size_t len,
const struct atype_info *basetype, void **ptr_out);
static krb5_error_code
decode_sequence(const uint8_t *asn1, size_t len, const struct seq_info *seq,
void *val);
static krb5_error_code
decode_sequence_of(const uint8_t *asn1, size_t len,
const struct atype_info *elemtype, void **seq_out,
size_t *count_out);
/* Given the enclosing tag t, decode from asn1/len the contents of the ASN.1
* type specified by a, placing the result into val (caller-allocated). */
static krb5_error_code
decode_atype(const taginfo *t, const uint8_t *asn1, size_t len,
const struct atype_info *a, void *val)
{
krb5_error_code ret;
switch (a->type) {
case atype_fn: {
const struct fn_info *fn = a->tinfo;
assert(fn->dec != NULL);
return fn->dec(t, asn1, len, val);
}
case atype_sequence:
return decode_sequence(asn1, len, a->tinfo, val);
case atype_ptr: {
const struct ptr_info *ptrinfo = a->tinfo;
void *ptr = LOADPTR(val, ptrinfo);
assert(ptrinfo->basetype != NULL);
if (ptr != NULL) {
/* Container was already allocated by a previous sequence field. */
return decode_atype(t, asn1, len, ptrinfo->basetype, ptr);
} else {
ret = decode_atype_to_ptr(t, asn1, len, ptrinfo->basetype, &ptr);
if (ret)
return ret;
STOREPTR(ptr, ptrinfo, val);
break;
}
}
case atype_offset: {
const struct offset_info *off = a->tinfo;
assert(off->basetype != NULL);
return decode_atype(t, asn1, len, off->basetype,
(char *)val + off->dataoff);
}
case atype_optional: {
const struct optional_info *opt = a->tinfo;
return decode_atype(t, asn1, len, opt->basetype, val);
}
case atype_counted: {
const struct counted_info *counted = a->tinfo;
void *dataptr = (char *)val + counted->dataoff;
size_t count;
assert(counted->basetype != NULL);
ret = decode_cntype(t, asn1, len, counted->basetype, dataptr, &count);
if (ret)
return ret;
return store_count(count, counted, val);
}
case atype_tagged_thing: {
const struct tagged_info *tag = a->tinfo;
taginfo inner_tag;
const taginfo *tp = t;
const uint8_t *rem;
size_t rlen;
if (!tag->implicit) {
ret = get_tag(asn1, len, &inner_tag, &asn1, &len, &rem, &rlen, 0);
if (ret)
return ret;
/* Note: we don't check rlen (it should be 0). */
tp = &inner_tag;
if (!check_atype_tag(tag->basetype, tp))
return ASN1_BAD_ID;
}
return decode_atype(tp, asn1, len, tag->basetype, val);
}
case atype_bool: {
intmax_t intval;
ret = k5_asn1_decode_bool(asn1, len, &intval);
if (ret)
return ret;
return store_int(intval, a->size, val);
}
case atype_int: {
intmax_t intval;
ret = k5_asn1_decode_int(asn1, len, &intval);
if (ret)
return ret;
return store_int(intval, a->size, val);
}
case atype_uint: {
uintmax_t intval;
ret = k5_asn1_decode_uint(asn1, len, &intval);
if (ret)
return ret;
return store_uint(intval, a->size, val);
}
case atype_int_immediate: {
const struct immediate_info *imm = a->tinfo;
intmax_t intval;
ret = k5_asn1_decode_int(asn1, len, &intval);
if (ret)
return ret;
if (intval != imm->val && imm->err != 0)
return imm->err;
break;
}
default:
/* Null-terminated sequence types are handled in decode_atype_to_ptr,
* since they create variable-sized objects. */
assert(a->type != atype_nullterm_sequence_of);
assert(a->type != atype_nonempty_nullterm_sequence_of);
assert(a->type > atype_min);
assert(a->type < atype_max);
abort();
}
return 0;
}
/*
* Given the enclosing tag t, decode from asn1/len the contents of the
* ASN.1 type described by c, placing the counted result into val/count_out.
* If the resulting count should be -1 (for an unknown union distinguisher),
* set *count_out to SIZE_MAX.
*/
static krb5_error_code
decode_cntype(const taginfo *t, const uint8_t *asn1, size_t len,
const struct cntype_info *c, void *val, size_t *count_out)
{
krb5_error_code ret;
switch (c->type) {
case cntype_string: {
const struct string_info *string = c->tinfo;
assert(string->dec != NULL);
return string->dec(asn1, len, val, count_out);
}
case cntype_der:
return store_der(t, asn1, len, val, count_out);
case cntype_seqof: {
const struct atype_info *a = c->tinfo;
const struct ptr_info *ptrinfo = a->tinfo;
void *seq;
assert(a->type == atype_ptr);
ret = decode_sequence_of(asn1, len, ptrinfo->basetype, &seq,
count_out);
if (ret)
return ret;
STOREPTR(seq, ptrinfo, val);
break;
}
case cntype_choice: {
const struct choice_info *choice = c->tinfo;
size_t i;
for (i = 0; i < choice->n_options; i++) {
if (check_atype_tag(choice->options[i], t)) {
ret = decode_atype(t, asn1, len, choice->options[i], val);
if (ret)
return ret;
*count_out = i;
return 0;
}
}
/* SIZE_MAX will be stored as -1 in the distinguisher. If we start
* modeling non-extensible choices we should check that here. */
*count_out = SIZE_MAX;
break;
}
default:
assert(c->type > cntype_min);
assert(c->type < cntype_max);
abort();
}
return 0;
}
/* Add a null pointer to the end of a sequence. ptr is consumed on success
* (to be replaced by *ptr_out), left alone on failure. */
static krb5_error_code
null_terminate(const struct atype_info *eltinfo, void *ptr, size_t count,
void **ptr_out)
{
const struct ptr_info *ptrinfo = eltinfo->tinfo;
void *endptr;
assert(eltinfo->type == atype_ptr);
ptr = realloc(ptr, (count + 1) * eltinfo->size);
if (ptr == NULL)
return ENOMEM;
endptr = (char *)ptr + count * eltinfo->size;
STOREPTR(NULL, ptrinfo, endptr);
*ptr_out = ptr;
return 0;
}
static krb5_error_code
decode_atype_to_ptr(const taginfo *t, const uint8_t *asn1, size_t len,
const struct atype_info *a, void **ptr_out)
{
krb5_error_code ret;
void *ptr;
size_t count;
*ptr_out = NULL;
switch (a->type) {
case atype_nullterm_sequence_of:
case atype_nonempty_nullterm_sequence_of:
ret = decode_sequence_of(asn1, len, a->tinfo, &ptr, &count);
if (ret)
return ret;
ret = null_terminate(a->tinfo, ptr, count, &ptr);
if (ret) {
free_sequence_of(a->tinfo, ptr, count);
return ret;
}
/* Historically we do not enforce non-emptiness of sequences when
* decoding, even when it is required by the ASN.1 type. */
break;
default:
ptr = calloc(a->size, 1);
if (ptr == NULL)
return ENOMEM;
ret = decode_atype(t, asn1, len, a, ptr);
if (ret) {
free(ptr);
return ret;
}
break;
}
*ptr_out = ptr;
return 0;
}
/* Initialize a C object when the corresponding ASN.1 type was omitted within a
* sequence. If the ASN.1 type is not optional, return ASN1_MISSING_FIELD. */
static krb5_error_code
omit_atype(const struct atype_info *a, void *val)
{
switch (a->type)
{
case atype_fn:
case atype_sequence:
case atype_nullterm_sequence_of:
case atype_nonempty_nullterm_sequence_of:
case atype_counted:
case atype_bool:
case atype_int:
case atype_uint:
case atype_int_immediate:
return ASN1_MISSING_FIELD;
case atype_ptr: {
const struct ptr_info *ptrinfo = a->tinfo;
return omit_atype(ptrinfo->basetype, val);
}
case atype_offset: {
const struct offset_info *off = a->tinfo;
return omit_atype(off->basetype, (char *)val + off->dataoff);
}
case atype_tagged_thing: {
const struct tagged_info *tag = a->tinfo;
return omit_atype(tag->basetype, val);
}
case atype_optional: {
const struct optional_info *opt = a->tinfo;
if (opt->init != NULL)
opt->init(val);
return 0;
}
default:
abort();
}
}
/* Decode an ASN.1 sequence into a C object. */
static krb5_error_code
decode_sequence(const uint8_t *asn1, size_t len, const struct seq_info *seq,
void *val)
{
krb5_error_code ret;
const uint8_t *contents;
size_t i, j, clen;
taginfo t;
assert(seq->n_fields > 0);
for (i = 0; i < seq->n_fields; i++) {
if (len == 0)
break;
ret = get_tag(asn1, len, &t, &contents, &clen, &asn1, &len, 0);
if (ret)
goto error;
/*
* Find the applicable sequence field. This logic is a little
* oversimplified; we could match an element to an optional extensible
* choice or optional stored-DER type when we ought to match a
* subsequent non-optional field. But it's unwise and (hopefully) very
* rare for ASN.1 modules to require such precision.
*/
for (; i < seq->n_fields; i++) {
if (check_atype_tag(seq->fields[i], &t))
break;
ret = omit_atype(seq->fields[i], val);
if (ret)
goto error;
}
/* We currently model all sequences as extensible. We should consider
* changing this before making the encoder visible to plugins. */
if (i == seq->n_fields)
break;
ret = decode_atype(&t, contents, clen, seq->fields[i], val);
if (ret)
goto error;
}
/* Initialize any fields in the C object which were not accounted for in
* the sequence. Error out if any of them aren't optional. */
for (; i < seq->n_fields; i++) {
ret = omit_atype(seq->fields[i], val);
if (ret)
goto error;
}
return 0;
error:
/* Free what we've decoded so far. Free pointers in a second pass in
* case multiple fields refer to the same pointer. */
for (j = 0; j < i; j++)
free_atype(seq->fields[j], val);
for (j = 0; j < i; j++)
free_atype_ptr(seq->fields[j], val);
return ret;
}
static krb5_error_code
decode_sequence_of(const uint8_t *asn1, size_t len,
const struct atype_info *elemtype, void **seq_out,
size_t *count_out)
{
krb5_error_code ret;
void *seq = NULL, *elem, *newseq;
const uint8_t *contents;
size_t clen, count = 0;
taginfo t;
*seq_out = NULL;
*count_out = 0;
while (len > 0) {
ret = get_tag(asn1, len, &t, &contents, &clen, &asn1, &len, 0);
if (ret)
goto error;
if (!check_atype_tag(elemtype, &t)) {
ret = ASN1_BAD_ID;
goto error;
}
newseq = realloc(seq, (count + 1) * elemtype->size);
if (newseq == NULL) {
ret = ENOMEM;
goto error;
}
seq = newseq;
elem = (char *)seq + count * elemtype->size;
memset(elem, 0, elemtype->size);
ret = decode_atype(&t, contents, clen, elemtype, elem);
if (ret)
goto error;
count++;
}
*seq_out = seq;
*count_out = count;
return 0;
error:
free_sequence_of(elemtype, seq, count);
free(seq);
return ret;
}
/* These three entry points are only needed for the kdc_req_body hack and may
* go away at some point. Define them here so we can use short names above. */
krb5_error_code
k5_asn1_encode_atype(asn1buf *buf, const void *val, const struct atype_info *a,
taginfo *tag_out)
{
return encode_atype(buf, val, a, tag_out);
}
krb5_error_code
k5_asn1_decode_atype(const taginfo *t, const uint8_t *asn1, size_t len,
const struct atype_info *a, void *val)
{
return decode_atype(t, asn1, len, a, val);
}
krb5_error_code
k5_asn1_full_encode(const void *rep, const struct atype_info *a,
krb5_data **code_out)
{
krb5_error_code ret;
asn1buf buf;
krb5_data *d;
uint8_t *bytes;
*code_out = NULL;
if (rep == NULL)
return ASN1_MISSING_FIELD;
/* Make a first pass over rep to count the encoding size. */
buf.ptr = NULL;
buf.count = 0;
ret = encode_atype_and_tag(&buf, rep, a);
if (ret)
return ret;
/* Allocate space for the encoding. */
bytes = malloc(buf.count + 1);
if (bytes == NULL)
return ENOMEM;
bytes[buf.count] = 0;
/* Make a second pass over rep to encode it. buf.ptr moves backwards as we
* encode, and will always exactly return to the base. */
buf.ptr = bytes + buf.count;
buf.count = 0;
ret = encode_atype_and_tag(&buf, rep, a);
if (ret) {
free(bytes);
return ret;
}
assert(buf.ptr == bytes);
/* Create the output data object. */
*code_out = malloc(sizeof(*d));
if (*code_out == NULL) {
free(bytes);
return ENOMEM;
}
**code_out = make_data(bytes, buf.count);
return 0;
}
krb5_error_code
k5_asn1_full_decode(const krb5_data *code, const struct atype_info *a,
void **retrep)
{
krb5_error_code ret;
const uint8_t *contents, *remainder;
size_t clen, rlen;
taginfo t;
*retrep = NULL;
ret = get_tag((uint8_t *)code->data, code->length, &t, &contents,
&clen, &remainder, &rlen, 0);
if (ret)
return ret;
/* rlen should be 0, but we don't check it (and due to padding in
* non-length-preserving enctypes, it will sometimes be nonzero). */
if (!check_atype_tag(a, &t))
return ASN1_BAD_ID;
return decode_atype_to_ptr(&t, contents, clen, a, retrep);
}
| ./CrossVul/dataset_final_sorted/CWE-674/c/good_4436_0 |
crossvul-cpp_data_bad_162_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;
}
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);
}
JsVar *jspFindPrototypeFor(const char *className) {
JsVar *obj = jsvObjectGetChild(execInfo.root, className, 0);
if (!obj) return 0;
JsVar *proto = jsvObjectGetChild(obj, JSPARSE_PROTOTYPE_VAR, 0);
jsvUnLock(obj);
return proto;
}
/** 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)
inheritsFrom = jspFindPrototypeFor("Object");
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 that references the object we actually requested the
* member from..
*/
if (child && returnName) {
// Get rid of existing name
if (jsvIsName(child)) {
JsVar *t = jsvGetValueOfName(child);
jsvUnLock(child);
child = t;
}
// 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);
}
#ifndef SAVE_ON_FLASH
/* If we've got something that we care about the parent of (eg. a getter/setter)
* then we repackage it into a 'NewChild' name that references the parent before
* we leave. Note: You can't do this on everything because normally NewChild
* forces a new child to be blindly created. It works on Getters/Setters because
* we *always* run those rather than adding them.
*/
if (parent && jsvIsName(a) && !jsvIsNewChild(a)) {
JsVar *value = jsvGetValueOfName(a);
if (jsvIsGetterOrSetter(value)) { // no need to do this for functions since we've just executed whatever we needed to
JsVar *nameVar = jsvCopyNameOnly(a,false,true);
JsVar *newChild = jsvCreateNewChild(parent, nameVar, value);
jsvUnLock2(nameVar, a);
a = newChild;
}
jsvUnLock(value);
}
#endif
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);
}
#ifndef SAVE_ON_FLASH
bool isGetter, isSetter;
if (lex->tk==LEX_ID && jsvIsString(varName)) {
isGetter = jsvIsStringEqual(varName, "get");
isSetter = jsvIsStringEqual(varName, "set");
if (isGetter || isSetter) {
jsvUnLock(varName);
varName = jslGetTokenValueAsVar(lex);
JSP_ASSERT_MATCH(LEX_ID);
JsVar *method = jspeFunctionDefinition(false);
jsvAddGetterOrSetter(contents, varName, isGetter, method);
jsvUnLock(method);
}
} else
#endif
{
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,jsvUnLock4(funcName,classFunction,classInternalName,classPrototype),0);
#ifndef SAVE_ON_FLASH
bool isGetter, isSetter;
if (lex->tk==LEX_ID) {
isGetter = jsvIsStringEqual(funcName, "get");
isSetter = jsvIsStringEqual(funcName, "set");
if (isGetter || isSetter) {
jsvUnLock(funcName);
funcName = jslGetTokenValueAsVar(lex);
JSP_ASSERT_MATCH(LEX_ID);
}
}
#endif
JsVar *method = jspeFunctionDefinition(false);
if (classFunction && classPrototype) {
JsVar *obj = isStatic ? classFunction : classPrototype;
if (jsvIsStringEqual(funcName, "constructor")) {
jswrap_function_replaceWith(classFunction, method);
#ifndef SAVE_ON_FLASH
} else if (isGetter || isSetter) {
jsvAddGetterOrSetter(obj, funcName, isGetter, method);
#endif
} else {
funcName = jsvMakeIntoVariableName(funcName, 0);
jsvSetValueOfName(funcName, method);
jsvAddName(obj, 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
jsvReplaceWith(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
jsvReplaceWith(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=='=') {
jsvReplaceWithOrAddToRoot(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);
jsvReplaceWith(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 `{ ... }` */
NO_INLINE void jspeSkipBlock() {
// fast skip of blocks
int brackets = 1;
while (lex->tk && brackets) {
if (lex->tk == '{') brackets++;
else if (lex->tk == '}') {
brackets--;
if (!brackets) return;
}
JSP_ASSERT_MATCH(lex->tk);
}
}
/** 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;
if (!JSP_SHOULD_EXECUTE) {
jspeSkipBlock();
return;
}
}
} else {
jspeSkipBlock();
}
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)
jsvReplaceWith(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 *jspGetBuiltinPrototype(JsVar *obj) {
if (jsvIsArray(obj)) {
JsVar *v = jspFindPrototypeFor("Array");
if (v) return v;
}
if (jsvIsObject(obj) || jsvIsArray(obj)) {
JsVar *v = jspFindPrototypeFor("Object");
if (v==obj) { // don't return ourselves
jsvUnLock(v);
v = 0;
}
return v;
}
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 || lex->tk == LEX_R_OF) {
bool isForOf = lex->tk == LEX_R_OF;
// for (i in array) or for (i of array)
// where i = forStatement
if (JSP_SHOULD_EXECUTE && !jsvIsName(forStatement)) {
jsvUnLock(forStatement);
jsExceptionHere(JSET_ERROR, "for(a %s b) - 'a' must be a variable name, not %t", isForOf?"of":"in", forStatement);
return 0;
}
JSP_ASSERT_MATCH(lex->tk); // skip over in/of
JsVar *array = jsvSkipNameAndUnLock(jspeExpression());
JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock2(forStatement, array), 0);
JslCharPos forBodyStart = jslCharPosClone(&lex->tokenStart);
// Simply scan over the loop the first time without executing to figure out where it ends
// OPT: we could skip the first parse and actually execute the first time
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();
// Now start executing properly
if (JSP_SHOULD_EXECUTE) {
if (jsvIsIterable(array)) {
JsvIsInternalChecker checkerFunction = jsvGetInternalFunctionCheckerFor(array);
JsVar *foundPrototype = 0;
if (!isForOf) // for..in
foundPrototype = jspGetBuiltinPrototype(array);
JsvIterator it;
jsvIteratorNew(&it, array, isForOf ?
/* for of */ JSIF_EVERY_ARRAY_ELEMENT :
/* for in */ 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 *iteratorValue;
if (isForOf) { // for (... of ...)
iteratorValue = jsvIteratorGetValue(&it);
} else { // for (... in ...)
iteratorValue = jsvIsName(loopIndexVar) ?
jsvCopyNameOnly(loopIndexVar, false/*no copy children*/, false/*not a name*/) :
loopIndexVar;
assert(jsvGetRefs(iteratorValue)==0);
}
if (isForOf || iteratorValue) { // could be out of memory
assert(!jsvIsName(iteratorValue));
jsvReplaceWithOrAddToRoot(forStatement, iteratorValue);
if (iteratorValue!=loopIndexVar) jsvUnLock(iteratorValue);
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;
}
}
}
jsvIteratorNext(&it);
jsvUnLock(loopIndexVar);
// if using for..in we'll skip down the prototype chain when we reach the end of the current one
if (!jsvIteratorHasElement(&it) && !isForOf && foundPrototype) {
jsvIteratorFree(&it);
JsVar *iterable = foundPrototype;
jsvIteratorNew(&it, iterable, JSIF_DEFINED_ARRAY_ElEMENTS);
checkerFunction = jsvGetInternalFunctionCheckerFor(iterable);
foundPrototype = jspGetBuiltinPrototype(iterable);
jsvUnLock(iterable);
}
}
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) {
jsvReplaceWith(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 {
jsvReplaceWith(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-674/c/bad_162_1 |
crossvul-cpp_data_bad_1310_2 | /*
** 2005 February 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that used to generate VDBE code
** that implements the ALTER TABLE command.
*/
#include "sqliteInt.h"
/*
** The code in this file only exists if we are not omitting the
** ALTER TABLE logic from the build.
*/
#ifndef SQLITE_OMIT_ALTERTABLE
/*
** Parameter zName is the name of a table that is about to be altered
** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
** If the table is a system table, this function leaves an error message
** in pParse->zErr (system tables may not be altered) and returns non-zero.
**
** Or, if zName is not a system table, zero is returned.
*/
static int isAlterableTable(Parse *pParse, Table *pTab){
if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
#ifndef SQLITE_OMIT_VIRTUALTABLE
|| ( (pTab->tabFlags & TF_Shadow)!=0
&& sqlite3ReadOnlyShadowTables(pParse->db)
)
#endif
){
sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
return 1;
}
return 0;
}
/*
** Generate code to verify that the schemas of database zDb and, if
** bTemp is not true, database "temp", can still be parsed. This is
** called at the end of the generation of an ALTER TABLE ... RENAME ...
** statement to ensure that the operation has not rendered any schema
** objects unusable.
*/
static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){
sqlite3NestedParse(pParse,
"SELECT 1 "
"FROM \"%w\".%s "
"WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
" AND sql NOT LIKE 'create virtual%%'"
" AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ",
zDb, MASTER_NAME,
zDb, bTemp
);
if( bTemp==0 ){
sqlite3NestedParse(pParse,
"SELECT 1 "
"FROM temp.%s "
"WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
" AND sql NOT LIKE 'create virtual%%'"
" AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ",
MASTER_NAME, zDb
);
}
}
/*
** Generate code to reload the schema for database iDb. And, if iDb!=1, for
** the temp database as well.
*/
static void renameReloadSchema(Parse *pParse, int iDb){
Vdbe *v = pParse->pVdbe;
if( v ){
sqlite3ChangeCookie(pParse, iDb);
sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0);
if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0);
}
}
/*
** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
** command.
*/
void sqlite3AlterRenameTable(
Parse *pParse, /* Parser context. */
SrcList *pSrc, /* The table to rename. */
Token *pName /* The new table name. */
){
int iDb; /* Database that contains the table */
char *zDb; /* Name of database iDb */
Table *pTab; /* Table being renamed */
char *zName = 0; /* NULL-terminated version of pName */
sqlite3 *db = pParse->db; /* Database connection */
int nTabName; /* Number of UTF-8 characters in zTabName */
const char *zTabName; /* Original name of the table */
Vdbe *v;
VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
u32 savedDbFlags; /* Saved value of db->mDbFlags */
savedDbFlags = db->mDbFlags;
if( NEVER(db->mallocFailed) ) goto exit_rename_table;
assert( pSrc->nSrc==1 );
assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
if( !pTab ) goto exit_rename_table;
iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
zDb = db->aDb[iDb].zDbSName;
db->mDbFlags |= DBFLAG_PreferBuiltin;
/* Get a NULL terminated version of the new table name. */
zName = sqlite3NameFromToken(db, pName);
if( !zName ) goto exit_rename_table;
/* Check that a table or index named 'zName' does not already exist
** in database iDb. If so, this is an error.
*/
if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
sqlite3ErrorMsg(pParse,
"there is already another table or index with this name: %s", zName);
goto exit_rename_table;
}
/* Make sure it is not a system table being altered, or a reserved name
** that the table is being renamed to.
*/
if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
goto exit_rename_table;
}
if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){
goto exit_rename_table;
}
#ifndef SQLITE_OMIT_VIEW
if( pTab->pSelect ){
sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
goto exit_rename_table;
}
#endif
#ifndef SQLITE_OMIT_AUTHORIZATION
/* Invoke the authorization callback. */
if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
goto exit_rename_table;
}
#endif
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( sqlite3ViewGetColumnNames(pParse, pTab) ){
goto exit_rename_table;
}
if( IsVirtual(pTab) ){
pVTab = sqlite3GetVTable(db, pTab);
if( pVTab->pVtab->pModule->xRename==0 ){
pVTab = 0;
}
}
#endif
/* Begin a transaction for database iDb. Then modify the schema cookie
** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
** nested SQL may raise an exception. */
v = sqlite3GetVdbe(pParse);
if( v==0 ){
goto exit_rename_table;
}
sqlite3MayAbort(pParse);
/* figure out how many UTF-8 characters are in zName */
zTabName = pTab->zName;
nTabName = sqlite3Utf8CharLen(zTabName, -1);
/* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
** the schema to use the new table name. */
sqlite3NestedParse(pParse,
"UPDATE \"%w\".%s SET "
"sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
"WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
"AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
, zDb, MASTER_NAME, zDb, zTabName, zName, (iDb==1), zTabName
);
/* Update the tbl_name and name columns of the sqlite_master table
** as required. */
sqlite3NestedParse(pParse,
"UPDATE %Q.%s SET "
"tbl_name = %Q, "
"name = CASE "
"WHEN type='table' THEN %Q "
"WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
" AND type='index' THEN "
"'sqlite_autoindex_' || %Q || substr(name,%d+18) "
"ELSE name END "
"WHERE tbl_name=%Q COLLATE nocase AND "
"(type='table' OR type='index' OR type='trigger');",
zDb, MASTER_NAME,
zName, zName, zName,
nTabName, zTabName
);
#ifndef SQLITE_OMIT_AUTOINCREMENT
/* If the sqlite_sequence table exists in this database, then update
** it with the new table name.
*/
if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
sqlite3NestedParse(pParse,
"UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
zDb, zName, pTab->zName);
}
#endif
/* If the table being renamed is not itself part of the temp database,
** edit view and trigger definitions within the temp database
** as required. */
if( iDb!=1 ){
sqlite3NestedParse(pParse,
"UPDATE sqlite_temp_master SET "
"sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
"tbl_name = "
"CASE WHEN tbl_name=%Q COLLATE nocase AND "
" sqlite_rename_test(%Q, sql, type, name, 1) "
"THEN %Q ELSE tbl_name END "
"WHERE type IN ('view', 'trigger')"
, zDb, zTabName, zName, zTabName, zDb, zName);
}
/* If this is a virtual table, invoke the xRename() function if
** one is defined. The xRename() callback will modify the names
** of any resources used by the v-table implementation (including other
** SQLite tables) that are identified by the name of the virtual table.
*/
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( pVTab ){
int i = ++pParse->nMem;
sqlite3VdbeLoadString(v, i, zName);
sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
}
#endif
renameReloadSchema(pParse, iDb);
renameTestSchema(pParse, zDb, iDb==1);
exit_rename_table:
sqlite3SrcListDelete(db, pSrc);
sqlite3DbFree(db, zName);
db->mDbFlags = savedDbFlags;
}
/*
** This function is called after an "ALTER TABLE ... ADD" statement
** has been parsed. Argument pColDef contains the text of the new
** column definition.
**
** The Table structure pParse->pNewTable was extended to include
** the new column during parsing.
*/
void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
Table *pNew; /* Copy of pParse->pNewTable */
Table *pTab; /* Table being altered */
int iDb; /* Database number */
const char *zDb; /* Database name */
const char *zTab; /* Table name */
char *zCol; /* Null-terminated column definition */
Column *pCol; /* The new column */
Expr *pDflt; /* Default value for the new column */
sqlite3 *db; /* The database connection; */
Vdbe *v; /* The prepared statement under construction */
int r1; /* Temporary registers */
db = pParse->db;
if( pParse->nErr || db->mallocFailed ) return;
pNew = pParse->pNewTable;
assert( pNew );
assert( sqlite3BtreeHoldsAllMutexes(db) );
iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
zDb = db->aDb[iDb].zDbSName;
zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
pCol = &pNew->aCol[pNew->nCol-1];
pDflt = pCol->pDflt;
pTab = sqlite3FindTable(db, zTab, zDb);
assert( pTab );
#ifndef SQLITE_OMIT_AUTHORIZATION
/* Invoke the authorization callback. */
if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
return;
}
#endif
/* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
** If there is a NOT NULL constraint, then the default value for the
** column must not be NULL.
*/
if( pCol->colFlags & COLFLAG_PRIMKEY ){
sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
return;
}
if( pNew->pIndex ){
sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
return;
}
if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
/* If the default value for the new column was specified with a
** literal NULL, then set pDflt to 0. This simplifies checking
** for an SQL NULL default below.
*/
assert( pDflt==0 || pDflt->op==TK_SPAN );
if( pDflt && pDflt->pLeft->op==TK_NULL ){
pDflt = 0;
}
if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
sqlite3ErrorMsg(pParse,
"Cannot add a REFERENCES column with non-NULL default value");
return;
}
if( pCol->notNull && !pDflt ){
sqlite3ErrorMsg(pParse,
"Cannot add a NOT NULL column with default value NULL");
return;
}
/* Ensure the default expression is something that sqlite3ValueFromExpr()
** can handle (i.e. not CURRENT_TIME etc.)
*/
if( pDflt ){
sqlite3_value *pVal = 0;
int rc;
rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
if( rc!=SQLITE_OK ){
assert( db->mallocFailed == 1 );
return;
}
if( !pVal ){
sqlite3ErrorMsg(pParse,"Cannot add a column with non-constant default");
return;
}
sqlite3ValueFree(pVal);
}
}else if( pCol->colFlags & COLFLAG_STORED ){
sqlite3ErrorMsg(pParse, "cannot add a STORED column");
return;
}
/* Modify the CREATE TABLE statement. */
zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
if( zCol ){
char *zEnd = &zCol[pColDef->n-1];
u32 savedDbFlags = db->mDbFlags;
while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
*zEnd-- = '\0';
}
db->mDbFlags |= DBFLAG_PreferBuiltin;
sqlite3NestedParse(pParse,
"UPDATE \"%w\".%s SET "
"sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
"WHERE type = 'table' AND name = %Q",
zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
zTab
);
sqlite3DbFree(db, zCol);
db->mDbFlags = savedDbFlags;
}
/* Make sure the schema version is at least 3. But do not upgrade
** from less than 3 to 4, as that will corrupt any preexisting DESC
** index.
*/
v = sqlite3GetVdbe(pParse);
if( v ){
r1 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
sqlite3VdbeUsesBtree(v, iDb);
sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
sqlite3ReleaseTempReg(pParse, r1);
}
/* Reload the table definition */
renameReloadSchema(pParse, iDb);
}
/*
** This function is called by the parser after the table-name in
** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
** pSrc is the full-name of the table being altered.
**
** This routine makes a (partial) copy of the Table structure
** for the table being altered and sets Parse.pNewTable to point
** to it. Routines called by the parser as the column definition
** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
** the copy. The copy of the Table structure is deleted by tokenize.c
** after parsing is finished.
**
** Routine sqlite3AlterFinishAddColumn() will be called to complete
** coding the "ALTER TABLE ... ADD" statement.
*/
void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
Table *pNew;
Table *pTab;
int iDb;
int i;
int nAlloc;
sqlite3 *db = pParse->db;
/* Look up the table being altered. */
assert( pParse->pNewTable==0 );
assert( sqlite3BtreeHoldsAllMutexes(db) );
if( db->mallocFailed ) goto exit_begin_add_column;
pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
if( !pTab ) goto exit_begin_add_column;
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( IsVirtual(pTab) ){
sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
goto exit_begin_add_column;
}
#endif
/* Make sure this is not an attempt to ALTER a view. */
if( pTab->pSelect ){
sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
goto exit_begin_add_column;
}
if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
goto exit_begin_add_column;
}
sqlite3MayAbort(pParse);
assert( pTab->addColOffset>0 );
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
/* Put a copy of the Table struct in Parse.pNewTable for the
** sqlite3AddColumn() function and friends to modify. But modify
** the name by adding an "sqlite_altertab_" prefix. By adding this
** prefix, we insure that the name will not collide with an existing
** table because user table are not allowed to have the "sqlite_"
** prefix on their name.
*/
pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
if( !pNew ) goto exit_begin_add_column;
pParse->pNewTable = pNew;
pNew->nTabRef = 1;
pNew->nCol = pTab->nCol;
assert( pNew->nCol>0 );
nAlloc = (((pNew->nCol-1)/8)*8)+8;
assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
if( !pNew->aCol || !pNew->zName ){
assert( db->mallocFailed );
goto exit_begin_add_column;
}
memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
for(i=0; i<pNew->nCol; i++){
Column *pCol = &pNew->aCol[i];
pCol->zName = sqlite3DbStrDup(db, pCol->zName);
pCol->zColl = 0;
pCol->pDflt = 0;
}
pNew->pSchema = db->aDb[iDb].pSchema;
pNew->addColOffset = pTab->addColOffset;
pNew->nTabRef = 1;
exit_begin_add_column:
sqlite3SrcListDelete(db, pSrc);
return;
}
/*
** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
** command. This function checks if the table is a view or virtual
** table (columns of views or virtual tables may not be renamed). If so,
** it loads an error message into pParse and returns non-zero.
**
** Or, if pTab is not a view or virtual table, zero is returned.
*/
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
static int isRealTable(Parse *pParse, Table *pTab){
const char *zType = 0;
#ifndef SQLITE_OMIT_VIEW
if( pTab->pSelect ){
zType = "view";
}
#endif
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( IsVirtual(pTab) ){
zType = "virtual table";
}
#endif
if( zType ){
sqlite3ErrorMsg(
pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
);
return 1;
}
return 0;
}
#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
# define isRealTable(x,y) (0)
#endif
/*
** Handles the following parser reduction:
**
** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
*/
void sqlite3AlterRenameColumn(
Parse *pParse, /* Parsing context */
SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
Token *pOld, /* Name of column being changed */
Token *pNew /* New column name */
){
sqlite3 *db = pParse->db; /* Database connection */
Table *pTab; /* Table being updated */
int iCol; /* Index of column being renamed */
char *zOld = 0; /* Old column name */
char *zNew = 0; /* New column name */
const char *zDb; /* Name of schema containing the table */
int iSchema; /* Index of the schema */
int bQuote; /* True to quote the new name */
/* Locate the table to be altered */
pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
if( !pTab ) goto exit_rename_column;
/* Cannot alter a system table */
if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
/* Which schema holds the table to be altered */
iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
assert( iSchema>=0 );
zDb = db->aDb[iSchema].zDbSName;
#ifndef SQLITE_OMIT_AUTHORIZATION
/* Invoke the authorization callback. */
if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
goto exit_rename_column;
}
#endif
/* Make sure the old name really is a column name in the table to be
** altered. Set iCol to be the index of the column being renamed */
zOld = sqlite3NameFromToken(db, pOld);
if( !zOld ) goto exit_rename_column;
for(iCol=0; iCol<pTab->nCol; iCol++){
if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
}
if( iCol==pTab->nCol ){
sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
goto exit_rename_column;
}
/* Do the rename operation using a recursive UPDATE statement that
** uses the sqlite_rename_column() SQL function to compute the new
** CREATE statement text for the sqlite_master table.
*/
sqlite3MayAbort(pParse);
zNew = sqlite3NameFromToken(db, pNew);
if( !zNew ) goto exit_rename_column;
assert( pNew->n>0 );
bQuote = sqlite3Isquote(pNew->z[0]);
sqlite3NestedParse(pParse,
"UPDATE \"%w\".%s SET "
"sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
"WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
" AND (type != 'index' OR tbl_name = %Q)"
" AND sql NOT LIKE 'create virtual%%'",
zDb, MASTER_NAME,
zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
pTab->zName
);
sqlite3NestedParse(pParse,
"UPDATE temp.%s SET "
"sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
"WHERE type IN ('trigger', 'view')",
MASTER_NAME,
zDb, pTab->zName, iCol, zNew, bQuote
);
/* Drop and reload the database schema. */
renameReloadSchema(pParse, iSchema);
renameTestSchema(pParse, zDb, iSchema==1);
exit_rename_column:
sqlite3SrcListDelete(db, pSrc);
sqlite3DbFree(db, zOld);
sqlite3DbFree(db, zNew);
return;
}
/*
** Each RenameToken object maps an element of the parse tree into
** the token that generated that element. The parse tree element
** might be one of:
**
** * A pointer to an Expr that represents an ID
** * The name of a table column in Column.zName
**
** A list of RenameToken objects can be constructed during parsing.
** Each new object is created by sqlite3RenameTokenMap().
** As the parse tree is transformed, the sqlite3RenameTokenRemap()
** routine is used to keep the mapping current.
**
** After the parse finishes, renameTokenFind() routine can be used
** to look up the actual token value that created some element in
** the parse tree.
*/
struct RenameToken {
void *p; /* Parse tree element created by token t */
Token t; /* The token that created parse tree element p */
RenameToken *pNext; /* Next is a list of all RenameToken objects */
};
/*
** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
** down into the Walker.
*/
typedef struct RenameCtx RenameCtx;
struct RenameCtx {
RenameToken *pList; /* List of tokens to overwrite */
int nList; /* Number of tokens in pList */
int iCol; /* Index of column being renamed */
Table *pTab; /* Table being ALTERed */
const char *zOld; /* Old column name */
};
#ifdef SQLITE_DEBUG
/*
** This function is only for debugging. It performs two tasks:
**
** 1. Checks that pointer pPtr does not already appear in the
** rename-token list.
**
** 2. Dereferences each pointer in the rename-token list.
**
** The second is most effective when debugging under valgrind or
** address-sanitizer or similar. If any of these pointers no longer
** point to valid objects, an exception is raised by the memory-checking
** tool.
**
** The point of this is to prevent comparisons of invalid pointer values.
** Even though this always seems to work, it is undefined according to the
** C standard. Example of undefined comparison:
**
** sqlite3_free(x);
** if( x==y ) ...
**
** Technically, as x no longer points into a valid object or to the byte
** following a valid object, it may not be used in comparison operations.
*/
static void renameTokenCheckAll(Parse *pParse, void *pPtr){
if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
RenameToken *p;
u8 i = 0;
for(p=pParse->pRename; p; p=p->pNext){
if( p->p ){
assert( p->p!=pPtr );
i += *(u8*)(p->p);
}
}
}
}
#else
# define renameTokenCheckAll(x,y)
#endif
/*
** Remember that the parser tree element pPtr was created using
** the token pToken.
**
** In other words, construct a new RenameToken object and add it
** to the list of RenameToken objects currently being built up
** in pParse->pRename.
**
** The pPtr argument is returned so that this routine can be used
** with tail recursion in tokenExpr() routine, for a small performance
** improvement.
*/
void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
RenameToken *pNew;
assert( pPtr || pParse->db->mallocFailed );
renameTokenCheckAll(pParse, pPtr);
if( pParse->eParseMode!=PARSE_MODE_UNMAP ){
pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
if( pNew ){
pNew->p = pPtr;
pNew->t = *pToken;
pNew->pNext = pParse->pRename;
pParse->pRename = pNew;
}
}
return pPtr;
}
/*
** It is assumed that there is already a RenameToken object associated
** with parse tree element pFrom. This function remaps the associated token
** to parse tree element pTo.
*/
void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
RenameToken *p;
renameTokenCheckAll(pParse, pTo);
for(p=pParse->pRename; p; p=p->pNext){
if( p->p==pFrom ){
p->p = pTo;
break;
}
}
}
/*
** Walker callback used by sqlite3RenameExprUnmap().
*/
static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
Parse *pParse = pWalker->pParse;
sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
return WRC_Continue;
}
/*
** Iterate through the Select objects that are part of WITH clauses attached
** to select statement pSelect.
*/
static void renameWalkWith(Walker *pWalker, Select *pSelect){
if( pSelect->pWith ){
int i;
for(i=0; i<pSelect->pWith->nCte; i++){
Select *p = pSelect->pWith->a[i].pSelect;
NameContext sNC;
memset(&sNC, 0, sizeof(sNC));
sNC.pParse = pWalker->pParse;
sqlite3SelectPrep(sNC.pParse, p, &sNC);
sqlite3WalkSelect(pWalker, p);
}
}
}
/*
** Walker callback used by sqlite3RenameExprUnmap().
*/
static int renameUnmapSelectCb(Walker *pWalker, Select *p){
Parse *pParse = pWalker->pParse;
int i;
if( pParse->nErr ) return WRC_Abort;
if( ALWAYS(p->pEList) ){
ExprList *pList = p->pEList;
for(i=0; i<pList->nExpr; i++){
if( pList->a[i].zName ){
sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zName);
}
}
}
if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
SrcList *pSrc = p->pSrc;
for(i=0; i<pSrc->nSrc; i++){
sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
}
}
renameWalkWith(pWalker, p);
return WRC_Continue;
}
/*
** Remove all nodes that are part of expression pExpr from the rename list.
*/
void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
u8 eMode = pParse->eParseMode;
Walker sWalker;
memset(&sWalker, 0, sizeof(Walker));
sWalker.pParse = pParse;
sWalker.xExprCallback = renameUnmapExprCb;
sWalker.xSelectCallback = renameUnmapSelectCb;
pParse->eParseMode = PARSE_MODE_UNMAP;
sqlite3WalkExpr(&sWalker, pExpr);
pParse->eParseMode = eMode;
}
/*
** Remove all nodes that are part of expression-list pEList from the
** rename list.
*/
void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
if( pEList ){
int i;
Walker sWalker;
memset(&sWalker, 0, sizeof(Walker));
sWalker.pParse = pParse;
sWalker.xExprCallback = renameUnmapExprCb;
sqlite3WalkExprList(&sWalker, pEList);
for(i=0; i<pEList->nExpr; i++){
sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zName);
}
}
}
/*
** Free the list of RenameToken objects given in the second argument
*/
static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
RenameToken *pNext;
RenameToken *p;
for(p=pToken; p; p=pNext){
pNext = p->pNext;
sqlite3DbFree(db, p);
}
}
/*
** Search the Parse object passed as the first argument for a RenameToken
** object associated with parse tree element pPtr. If found, remove it
** from the Parse object and add it to the list maintained by the
** RenameCtx object passed as the second argument.
*/
static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
RenameToken **pp;
assert( pPtr!=0 );
for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
if( (*pp)->p==pPtr ){
RenameToken *pToken = *pp;
*pp = pToken->pNext;
pToken->pNext = pCtx->pList;
pCtx->pList = pToken;
pCtx->nList++;
break;
}
}
}
/*
** This is a Walker select callback. It does nothing. It is only required
** because without a dummy callback, sqlite3WalkExpr() and similar do not
** descend into sub-select statements.
*/
static int renameColumnSelectCb(Walker *pWalker, Select *p){
renameWalkWith(pWalker, p);
return WRC_Continue;
}
/*
** This is a Walker expression callback.
**
** For every TK_COLUMN node in the expression tree, search to see
** if the column being references is the column being renamed by an
** ALTER TABLE statement. If it is, then attach its associated
** RenameToken object to the list of RenameToken objects being
** constructed in RenameCtx object at pWalker->u.pRename.
*/
static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
RenameCtx *p = pWalker->u.pRename;
if( pExpr->op==TK_TRIGGER
&& pExpr->iColumn==p->iCol
&& pWalker->pParse->pTriggerTab==p->pTab
){
renameTokenFind(pWalker->pParse, p, (void*)pExpr);
}else if( pExpr->op==TK_COLUMN
&& pExpr->iColumn==p->iCol
&& p->pTab==pExpr->y.pTab
){
renameTokenFind(pWalker->pParse, p, (void*)pExpr);
}
return WRC_Continue;
}
/*
** The RenameCtx contains a list of tokens that reference a column that
** is being renamed by an ALTER TABLE statement. Return the "last"
** RenameToken in the RenameCtx and remove that RenameToken from the
** RenameContext. "Last" means the last RenameToken encountered when
** the input SQL is parsed from left to right. Repeated calls to this routine
** return all column name tokens in the order that they are encountered
** in the SQL statement.
*/
static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
RenameToken *pBest = pCtx->pList;
RenameToken *pToken;
RenameToken **pp;
for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
if( pToken->t.z>pBest->t.z ) pBest = pToken;
}
for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
*pp = pBest->pNext;
return pBest;
}
/*
** An error occured while parsing or otherwise processing a database
** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
** ALTER TABLE RENAME COLUMN program. The error message emitted by the
** sub-routine is currently stored in pParse->zErrMsg. This function
** adds context to the error message and then stores it in pCtx.
*/
static void renameColumnParseError(
sqlite3_context *pCtx,
int bPost,
sqlite3_value *pType,
sqlite3_value *pObject,
Parse *pParse
){
const char *zT = (const char*)sqlite3_value_text(pType);
const char *zN = (const char*)sqlite3_value_text(pObject);
char *zErr;
zErr = sqlite3_mprintf("error in %s %s%s: %s",
zT, zN, (bPost ? " after rename" : ""),
pParse->zErrMsg
);
sqlite3_result_error(pCtx, zErr, -1);
sqlite3_free(zErr);
}
/*
** For each name in the the expression-list pEList (i.e. each
** pEList->a[i].zName) that matches the string in zOld, extract the
** corresponding rename-token from Parse object pParse and add it
** to the RenameCtx pCtx.
*/
static void renameColumnElistNames(
Parse *pParse,
RenameCtx *pCtx,
ExprList *pEList,
const char *zOld
){
if( pEList ){
int i;
for(i=0; i<pEList->nExpr; i++){
char *zName = pEList->a[i].zName;
if( 0==sqlite3_stricmp(zName, zOld) ){
renameTokenFind(pParse, pCtx, (void*)zName);
}
}
}
}
/*
** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
** that matches the string in zOld, extract the corresponding rename-token
** from Parse object pParse and add it to the RenameCtx pCtx.
*/
static void renameColumnIdlistNames(
Parse *pParse,
RenameCtx *pCtx,
IdList *pIdList,
const char *zOld
){
if( pIdList ){
int i;
for(i=0; i<pIdList->nId; i++){
char *zName = pIdList->a[i].zName;
if( 0==sqlite3_stricmp(zName, zOld) ){
renameTokenFind(pParse, pCtx, (void*)zName);
}
}
}
}
/*
** Parse the SQL statement zSql using Parse object (*p). The Parse object
** is initialized by this function before it is used.
*/
static int renameParseSql(
Parse *p, /* Memory to use for Parse object */
const char *zDb, /* Name of schema SQL belongs to */
int bTable, /* 1 -> RENAME TABLE, 0 -> RENAME COLUMN */
sqlite3 *db, /* Database handle */
const char *zSql, /* SQL to parse */
int bTemp /* True if SQL is from temp schema */
){
int rc;
char *zErr = 0;
db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
/* Parse the SQL statement passed as the first argument. If no error
** occurs and the parse does not result in a new table, index or
** trigger object, the database must be corrupt. */
memset(p, 0, sizeof(Parse));
p->eParseMode = PARSE_MODE_RENAME;
p->db = db;
p->nQueryLoop = 1;
rc = sqlite3RunParser(p, zSql, &zErr);
assert( p->zErrMsg==0 );
assert( rc!=SQLITE_OK || zErr==0 );
p->zErrMsg = zErr;
if( db->mallocFailed ) rc = SQLITE_NOMEM;
if( rc==SQLITE_OK
&& p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
){
rc = SQLITE_CORRUPT_BKPT;
}
#ifdef SQLITE_DEBUG
/* Ensure that all mappings in the Parse.pRename list really do map to
** a part of the input string. */
if( rc==SQLITE_OK ){
int nSql = sqlite3Strlen30(zSql);
RenameToken *pToken;
for(pToken=p->pRename; pToken; pToken=pToken->pNext){
assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
}
}
#endif
db->init.iDb = 0;
return rc;
}
/*
** This function edits SQL statement zSql, replacing each token identified
** by the linked list pRename with the text of zNew. If argument bQuote is
** true, then zNew is always quoted first. If no error occurs, the result
** is loaded into context object pCtx as the result.
**
** Or, if an error occurs (i.e. an OOM condition), an error is left in
** pCtx and an SQLite error code returned.
*/
static int renameEditSql(
sqlite3_context *pCtx, /* Return result here */
RenameCtx *pRename, /* Rename context */
const char *zSql, /* SQL statement to edit */
const char *zNew, /* New token text */
int bQuote /* True to always quote token */
){
int nNew = sqlite3Strlen30(zNew);
int nSql = sqlite3Strlen30(zSql);
sqlite3 *db = sqlite3_context_db_handle(pCtx);
int rc = SQLITE_OK;
char *zQuot;
char *zOut;
int nQuot;
/* Set zQuot to point to a buffer containing a quoted copy of the
** identifier zNew. If the corresponding identifier in the original
** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
** point to zQuot so that all substitutions are made using the
** quoted version of the new column name. */
zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
if( zQuot==0 ){
return SQLITE_NOMEM;
}else{
nQuot = sqlite3Strlen30(zQuot);
}
if( bQuote ){
zNew = zQuot;
nNew = nQuot;
}
/* At this point pRename->pList contains a list of RenameToken objects
** corresponding to all tokens in the input SQL that must be replaced
** with the new column name. All that remains is to construct and
** return the edited SQL string. */
assert( nQuot>=nNew );
zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
if( zOut ){
int nOut = nSql;
memcpy(zOut, zSql, nSql);
while( pRename->pList ){
int iOff; /* Offset of token to replace in zOut */
RenameToken *pBest = renameColumnTokenNext(pRename);
u32 nReplace;
const char *zReplace;
if( sqlite3IsIdChar(*pBest->t.z) ){
nReplace = nNew;
zReplace = zNew;
}else{
nReplace = nQuot;
zReplace = zQuot;
}
iOff = pBest->t.z - zSql;
if( pBest->t.n!=nReplace ){
memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
nOut - (iOff + pBest->t.n)
);
nOut += nReplace - pBest->t.n;
zOut[nOut] = '\0';
}
memcpy(&zOut[iOff], zReplace, nReplace);
sqlite3DbFree(db, pBest);
}
sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
sqlite3DbFree(db, zOut);
}else{
rc = SQLITE_NOMEM;
}
sqlite3_free(zQuot);
return rc;
}
/*
** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
** it was read from the schema of database zDb. Return SQLITE_OK if
** successful. Otherwise, return an SQLite error code and leave an error
** message in the Parse object.
*/
static int renameResolveTrigger(Parse *pParse, const char *zDb){
sqlite3 *db = pParse->db;
Trigger *pNew = pParse->pNewTrigger;
TriggerStep *pStep;
NameContext sNC;
int rc = SQLITE_OK;
memset(&sNC, 0, sizeof(sNC));
sNC.pParse = pParse;
assert( pNew->pTabSchema );
pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
);
pParse->eTriggerOp = pNew->op;
/* ALWAYS() because if the table of the trigger does not exist, the
** error would have been hit before this point */
if( ALWAYS(pParse->pTriggerTab) ){
rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
}
/* Resolve symbols in WHEN clause */
if( rc==SQLITE_OK && pNew->pWhen ){
rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
}
for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
if( pStep->pSelect ){
sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
if( pParse->nErr ) rc = pParse->rc;
}
if( rc==SQLITE_OK && pStep->zTarget ){
Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
if( pTarget==0 ){
rc = SQLITE_ERROR;
}else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
SrcList sSrc;
memset(&sSrc, 0, sizeof(sSrc));
sSrc.nSrc = 1;
sSrc.a[0].zName = pStep->zTarget;
sSrc.a[0].pTab = pTarget;
sNC.pSrcList = &sSrc;
if( pStep->pWhere ){
rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
}
if( rc==SQLITE_OK ){
rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
}
assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
if( pStep->pUpsert ){
Upsert *pUpsert = pStep->pUpsert;
assert( rc==SQLITE_OK );
pUpsert->pUpsertSrc = &sSrc;
sNC.uNC.pUpsert = pUpsert;
sNC.ncFlags = NC_UUpsert;
rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
if( rc==SQLITE_OK ){
ExprList *pUpsertSet = pUpsert->pUpsertSet;
rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
}
if( rc==SQLITE_OK ){
rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
}
if( rc==SQLITE_OK ){
rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
}
sNC.ncFlags = 0;
}
sNC.pSrcList = 0;
}
}
}
return rc;
}
/*
** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
** objects that are part of the trigger passed as the second argument.
*/
static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
TriggerStep *pStep;
/* Find tokens to edit in WHEN clause */
sqlite3WalkExpr(pWalker, pTrigger->pWhen);
/* Find tokens to edit in trigger steps */
for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
sqlite3WalkSelect(pWalker, pStep->pSelect);
sqlite3WalkExpr(pWalker, pStep->pWhere);
sqlite3WalkExprList(pWalker, pStep->pExprList);
if( pStep->pUpsert ){
Upsert *pUpsert = pStep->pUpsert;
sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
}
}
}
/*
** Free the contents of Parse object (*pParse). Do not free the memory
** occupied by the Parse object itself.
*/
static void renameParseCleanup(Parse *pParse){
sqlite3 *db = pParse->db;
Index *pIdx;
if( pParse->pVdbe ){
sqlite3VdbeFinalize(pParse->pVdbe);
}
sqlite3DeleteTable(db, pParse->pNewTable);
while( (pIdx = pParse->pNewIndex)!=0 ){
pParse->pNewIndex = pIdx->pNext;
sqlite3FreeIndex(db, pIdx);
}
sqlite3DeleteTrigger(db, pParse->pNewTrigger);
sqlite3DbFree(db, pParse->zErrMsg);
renameTokenFree(db, pParse->pRename);
sqlite3ParserReset(pParse);
}
/*
** SQL function:
**
** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
**
** 0. zSql: SQL statement to rewrite
** 1. type: Type of object ("table", "view" etc.)
** 2. object: Name of object
** 3. Database: Database name (e.g. "main")
** 4. Table: Table name
** 5. iCol: Index of column to rename
** 6. zNew: New column name
** 7. bQuote: Non-zero if the new column name should be quoted.
** 8. bTemp: True if zSql comes from temp schema
**
** Do a column rename operation on the CREATE statement given in zSql.
** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
** into zNew. The name should be quoted if bQuote is true.
**
** This function is used internally by the ALTER TABLE RENAME COLUMN command.
** It is only accessible to SQL created using sqlite3NestedParse(). It is
** not reachable from ordinary SQL passed into sqlite3_prepare().
*/
static void renameColumnFunc(
sqlite3_context *context,
int NotUsed,
sqlite3_value **argv
){
sqlite3 *db = sqlite3_context_db_handle(context);
RenameCtx sCtx;
const char *zSql = (const char*)sqlite3_value_text(argv[0]);
const char *zDb = (const char*)sqlite3_value_text(argv[3]);
const char *zTable = (const char*)sqlite3_value_text(argv[4]);
int iCol = sqlite3_value_int(argv[5]);
const char *zNew = (const char*)sqlite3_value_text(argv[6]);
int bQuote = sqlite3_value_int(argv[7]);
int bTemp = sqlite3_value_int(argv[8]);
const char *zOld;
int rc;
Parse sParse;
Walker sWalker;
Index *pIdx;
int i;
Table *pTab;
#ifndef SQLITE_OMIT_AUTHORIZATION
sqlite3_xauth xAuth = db->xAuth;
#endif
UNUSED_PARAMETER(NotUsed);
if( zSql==0 ) return;
if( zTable==0 ) return;
if( zNew==0 ) return;
if( iCol<0 ) return;
sqlite3BtreeEnterAll(db);
pTab = sqlite3FindTable(db, zTable, zDb);
if( pTab==0 || iCol>=pTab->nCol ){
sqlite3BtreeLeaveAll(db);
return;
}
zOld = pTab->aCol[iCol].zName;
memset(&sCtx, 0, sizeof(sCtx));
sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
#ifndef SQLITE_OMIT_AUTHORIZATION
db->xAuth = 0;
#endif
rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp);
/* Find tokens that need to be replaced. */
memset(&sWalker, 0, sizeof(Walker));
sWalker.pParse = &sParse;
sWalker.xExprCallback = renameColumnExprCb;
sWalker.xSelectCallback = renameColumnSelectCb;
sWalker.u.pRename = &sCtx;
sCtx.pTab = pTab;
if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
if( sParse.pNewTable ){
Select *pSelect = sParse.pNewTable->pSelect;
if( pSelect ){
sParse.rc = SQLITE_OK;
sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0);
rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
if( rc==SQLITE_OK ){
sqlite3WalkSelect(&sWalker, pSelect);
}
if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
}else{
/* A regular table */
int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
FKey *pFKey;
assert( sParse.pNewTable->pSelect==0 );
sCtx.pTab = sParse.pNewTable;
if( bFKOnly==0 ){
renameTokenFind(
&sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
);
if( sCtx.iCol<0 ){
renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
}
sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
}
for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
}
}
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
for(i=0; i<sParse.pNewTable->nCol; i++){
sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
}
#endif
for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
for(i=0; i<pFKey->nCol; i++){
if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
}
if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
&& 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
){
renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
}
}
}
}
}else if( sParse.pNewIndex ){
sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
}else{
/* A trigger */
TriggerStep *pStep;
rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
if( pStep->zTarget ){
Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
if( pTarget==pTab ){
if( pStep->pUpsert ){
ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
}
renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
}
}
}
/* Find tokens to edit in UPDATE OF clause */
if( sParse.pTriggerTab==pTab ){
renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
}
/* Find tokens to edit in various expressions and selects */
renameWalkTrigger(&sWalker, sParse.pNewTrigger);
}
assert( rc==SQLITE_OK );
rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
renameColumnFunc_done:
if( rc!=SQLITE_OK ){
if( sParse.zErrMsg ){
renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
}else{
sqlite3_result_error_code(context, rc);
}
}
renameParseCleanup(&sParse);
renameTokenFree(db, sCtx.pList);
#ifndef SQLITE_OMIT_AUTHORIZATION
db->xAuth = xAuth;
#endif
sqlite3BtreeLeaveAll(db);
}
/*
** Walker expression callback used by "RENAME TABLE".
*/
static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
RenameCtx *p = pWalker->u.pRename;
if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
}
return WRC_Continue;
}
/*
** Walker select callback used by "RENAME TABLE".
*/
static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
int i;
RenameCtx *p = pWalker->u.pRename;
SrcList *pSrc = pSelect->pSrc;
if( pSrc==0 ){
assert( pWalker->pParse->db->mallocFailed );
return WRC_Abort;
}
for(i=0; i<pSrc->nSrc; i++){
struct SrcList_item *pItem = &pSrc->a[i];
if( pItem->pTab==p->pTab ){
renameTokenFind(pWalker->pParse, p, pItem->zName);
}
}
renameWalkWith(pWalker, pSelect);
return WRC_Continue;
}
/*
** This C function implements an SQL user function that is used by SQL code
** generated by the ALTER TABLE ... RENAME command to modify the definition
** of any foreign key constraints that use the table being renamed as the
** parent table. It is passed three arguments:
**
** 0: The database containing the table being renamed.
** 1. type: Type of object ("table", "view" etc.)
** 2. object: Name of object
** 3: The complete text of the schema statement being modified,
** 4: The old name of the table being renamed, and
** 5: The new name of the table being renamed.
** 6: True if the schema statement comes from the temp db.
**
** It returns the new schema statement. For example:
**
** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
** -> 'CREATE TABLE t1(a REFERENCES t3)'
*/
static void renameTableFunc(
sqlite3_context *context,
int NotUsed,
sqlite3_value **argv
){
sqlite3 *db = sqlite3_context_db_handle(context);
const char *zDb = (const char*)sqlite3_value_text(argv[0]);
const char *zInput = (const char*)sqlite3_value_text(argv[3]);
const char *zOld = (const char*)sqlite3_value_text(argv[4]);
const char *zNew = (const char*)sqlite3_value_text(argv[5]);
int bTemp = sqlite3_value_int(argv[6]);
UNUSED_PARAMETER(NotUsed);
if( zInput && zOld && zNew ){
Parse sParse;
int rc;
int bQuote = 1;
RenameCtx sCtx;
Walker sWalker;
#ifndef SQLITE_OMIT_AUTHORIZATION
sqlite3_xauth xAuth = db->xAuth;
db->xAuth = 0;
#endif
sqlite3BtreeEnterAll(db);
memset(&sCtx, 0, sizeof(RenameCtx));
sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
memset(&sWalker, 0, sizeof(Walker));
sWalker.pParse = &sParse;
sWalker.xExprCallback = renameTableExprCb;
sWalker.xSelectCallback = renameTableSelectCb;
sWalker.u.pRename = &sCtx;
rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
if( rc==SQLITE_OK ){
int isLegacy = (db->flags & SQLITE_LegacyAlter);
if( sParse.pNewTable ){
Table *pTab = sParse.pNewTable;
if( pTab->pSelect ){
if( isLegacy==0 ){
NameContext sNC;
memset(&sNC, 0, sizeof(sNC));
sNC.pParse = &sParse;
sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
if( sParse.nErr ) rc = sParse.rc;
sqlite3WalkSelect(&sWalker, pTab->pSelect);
}
}else{
/* Modify any FK definitions to point to the new table. */
#ifndef SQLITE_OMIT_FOREIGN_KEY
if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
FKey *pFKey;
for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
}
}
}
#endif
/* If this is the table being altered, fix any table refs in CHECK
** expressions. Also update the name that appears right after the
** "CREATE [VIRTUAL] TABLE" bit. */
if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
sCtx.pTab = pTab;
if( isLegacy==0 ){
sqlite3WalkExprList(&sWalker, pTab->pCheck);
}
renameTokenFind(&sParse, &sCtx, pTab->zName);
}
}
}
else if( sParse.pNewIndex ){
renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
if( isLegacy==0 ){
sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
}
}
#ifndef SQLITE_OMIT_TRIGGER
else{
Trigger *pTrigger = sParse.pNewTrigger;
TriggerStep *pStep;
if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
&& sCtx.pTab->pSchema==pTrigger->pTabSchema
){
renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
}
if( isLegacy==0 ){
rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
if( rc==SQLITE_OK ){
renameWalkTrigger(&sWalker, pTrigger);
for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
renameTokenFind(&sParse, &sCtx, pStep->zTarget);
}
}
}
}
}
#endif
}
if( rc==SQLITE_OK ){
rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
}
if( rc!=SQLITE_OK ){
if( sParse.zErrMsg ){
renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
}else{
sqlite3_result_error_code(context, rc);
}
}
renameParseCleanup(&sParse);
renameTokenFree(db, sCtx.pList);
sqlite3BtreeLeaveAll(db);
#ifndef SQLITE_OMIT_AUTHORIZATION
db->xAuth = xAuth;
#endif
}
return;
}
/*
** An SQL user function that checks that there are no parse or symbol
** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
** After an ALTER TABLE .. RENAME operation is performed and the schema
** reloaded, this function is called on each SQL statement in the schema
** to ensure that it is still usable.
**
** 0: Database name ("main", "temp" etc.).
** 1: SQL statement.
** 2: Object type ("view", "table", "trigger" or "index").
** 3: Object name.
** 4: True if object is from temp schema.
**
** Unless it finds an error, this function normally returns NULL. However, it
** returns integer value 1 if:
**
** * the SQL argument creates a trigger, and
** * the table that the trigger is attached to is in database zDb.
*/
static void renameTableTest(
sqlite3_context *context,
int NotUsed,
sqlite3_value **argv
){
sqlite3 *db = sqlite3_context_db_handle(context);
char const *zDb = (const char*)sqlite3_value_text(argv[0]);
char const *zInput = (const char*)sqlite3_value_text(argv[1]);
int bTemp = sqlite3_value_int(argv[4]);
int isLegacy = (db->flags & SQLITE_LegacyAlter);
#ifndef SQLITE_OMIT_AUTHORIZATION
sqlite3_xauth xAuth = db->xAuth;
db->xAuth = 0;
#endif
UNUSED_PARAMETER(NotUsed);
if( zDb && zInput ){
int rc;
Parse sParse;
rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
if( rc==SQLITE_OK ){
if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
NameContext sNC;
memset(&sNC, 0, sizeof(sNC));
sNC.pParse = &sParse;
sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
if( sParse.nErr ) rc = sParse.rc;
}
else if( sParse.pNewTrigger ){
if( isLegacy==0 ){
rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
}
if( rc==SQLITE_OK ){
int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
int i2 = sqlite3FindDbName(db, zDb);
if( i1==i2 ) sqlite3_result_int(context, 1);
}
}
}
if( rc!=SQLITE_OK ){
renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
}
renameParseCleanup(&sParse);
}
#ifndef SQLITE_OMIT_AUTHORIZATION
db->xAuth = xAuth;
#endif
}
/*
** Register built-in functions used to help implement ALTER TABLE
*/
void sqlite3AlterFunctions(void){
static FuncDef aAlterTableFuncs[] = {
INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
INTERNAL_FUNCTION(sqlite_rename_test, 5, renameTableTest),
};
sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
}
#endif /* SQLITE_ALTER_TABLE */
| ./CrossVul/dataset_final_sorted/CWE-674/c/bad_1310_2 |
crossvul-cpp_data_bad_1310_3 | /*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the SQLite parser
** when syntax rules are reduced. The routines in this file handle the
** following kinds of SQL syntax:
**
** CREATE TABLE
** DROP TABLE
** CREATE INDEX
** DROP INDEX
** creating ID lists
** BEGIN TRANSACTION
** COMMIT
** ROLLBACK
*/
#include "sqliteInt.h"
#ifndef SQLITE_OMIT_SHARED_CACHE
/*
** The TableLock structure is only used by the sqlite3TableLock() and
** codeTableLocks() functions.
*/
struct TableLock {
int iDb; /* The database containing the table to be locked */
int iTab; /* The root page of the table to be locked */
u8 isWriteLock; /* True for write lock. False for a read lock */
const char *zLockName; /* Name of the table */
};
/*
** Record the fact that we want to lock a table at run-time.
**
** The table to be locked has root page iTab and is found in database iDb.
** A read or a write lock can be taken depending on isWritelock.
**
** This routine just records the fact that the lock is desired. The
** code to make the lock occur is generated by a later call to
** codeTableLocks() which occurs during sqlite3FinishCoding().
*/
void sqlite3TableLock(
Parse *pParse, /* Parsing context */
int iDb, /* Index of the database containing the table to lock */
int iTab, /* Root page number of the table to be locked */
u8 isWriteLock, /* True for a write lock */
const char *zName /* Name of the table to be locked */
){
Parse *pToplevel = sqlite3ParseToplevel(pParse);
int i;
int nBytes;
TableLock *p;
assert( iDb>=0 );
if( iDb==1 ) return;
if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
for(i=0; i<pToplevel->nTableLock; i++){
p = &pToplevel->aTableLock[i];
if( p->iDb==iDb && p->iTab==iTab ){
p->isWriteLock = (p->isWriteLock || isWriteLock);
return;
}
}
nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
pToplevel->aTableLock =
sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
if( pToplevel->aTableLock ){
p = &pToplevel->aTableLock[pToplevel->nTableLock++];
p->iDb = iDb;
p->iTab = iTab;
p->isWriteLock = isWriteLock;
p->zLockName = zName;
}else{
pToplevel->nTableLock = 0;
sqlite3OomFault(pToplevel->db);
}
}
/*
** Code an OP_TableLock instruction for each table locked by the
** statement (configured by calls to sqlite3TableLock()).
*/
static void codeTableLocks(Parse *pParse){
int i;
Vdbe *pVdbe;
pVdbe = sqlite3GetVdbe(pParse);
assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
for(i=0; i<pParse->nTableLock; i++){
TableLock *p = &pParse->aTableLock[i];
int p1 = p->iDb;
sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
p->zLockName, P4_STATIC);
}
}
#else
#define codeTableLocks(x)
#endif
/*
** Return TRUE if the given yDbMask object is empty - if it contains no
** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
** macros when SQLITE_MAX_ATTACHED is greater than 30.
*/
#if SQLITE_MAX_ATTACHED>30
int sqlite3DbMaskAllZero(yDbMask m){
int i;
for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
return 1;
}
#endif
/*
** This routine is called after a single SQL statement has been
** parsed and a VDBE program to execute that statement has been
** prepared. This routine puts the finishing touches on the
** VDBE program and resets the pParse structure for the next
** parse.
**
** Note that if an error occurred, it might be the case that
** no VDBE code was generated.
*/
void sqlite3FinishCoding(Parse *pParse){
sqlite3 *db;
Vdbe *v;
assert( pParse->pToplevel==0 );
db = pParse->db;
if( pParse->nested ) return;
if( db->mallocFailed || pParse->nErr ){
if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
return;
}
/* Begin by generating some termination code at the end of the
** vdbe program
*/
v = sqlite3GetVdbe(pParse);
assert( !pParse->isMultiWrite
|| sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
if( v ){
sqlite3VdbeAddOp0(v, OP_Halt);
#if SQLITE_USER_AUTHENTICATION
if( pParse->nTableLock>0 && db->init.busy==0 ){
sqlite3UserAuthInit(db);
if( db->auth.authLevel<UAUTH_User ){
sqlite3ErrorMsg(pParse, "user not authenticated");
pParse->rc = SQLITE_AUTH_USER;
return;
}
}
#endif
/* The cookie mask contains one bit for each database file open.
** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
** set for each database that is used. Generate code to start a
** transaction on each used database and to verify the schema cookie
** on each used database.
*/
if( db->mallocFailed==0
&& (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
){
int iDb, i;
assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
sqlite3VdbeJumpHere(v, 0);
for(iDb=0; iDb<db->nDb; iDb++){
Schema *pSchema;
if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
sqlite3VdbeUsesBtree(v, iDb);
pSchema = db->aDb[iDb].pSchema;
sqlite3VdbeAddOp4Int(v,
OP_Transaction, /* Opcode */
iDb, /* P1 */
DbMaskTest(pParse->writeMask,iDb), /* P2 */
pSchema->schema_cookie, /* P3 */
pSchema->iGeneration /* P4 */
);
if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
VdbeComment((v,
"usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
for(i=0; i<pParse->nVtabLock; i++){
char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
}
pParse->nVtabLock = 0;
#endif
/* Once all the cookies have been verified and transactions opened,
** obtain the required table-locks. This is a no-op unless the
** shared-cache feature is enabled.
*/
codeTableLocks(pParse);
/* Initialize any AUTOINCREMENT data structures required.
*/
sqlite3AutoincrementBegin(pParse);
/* Code constant expressions that where factored out of inner loops */
if( pParse->pConstExpr ){
ExprList *pEL = pParse->pConstExpr;
pParse->okConstFactor = 0;
for(i=0; i<pEL->nExpr; i++){
sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
}
}
/* Finally, jump back to the beginning of the executable code. */
sqlite3VdbeGoto(v, 1);
}
}
/* Get the VDBE program ready for execution
*/
if( v && pParse->nErr==0 && !db->mallocFailed ){
/* A minimum of one cursor is required if autoincrement is used
* See ticket [a696379c1f08866] */
assert( pParse->pAinc==0 || pParse->nTab>0 );
sqlite3VdbeMakeReady(v, pParse);
pParse->rc = SQLITE_DONE;
}else{
pParse->rc = SQLITE_ERROR;
}
}
/*
** Run the parser and code generator recursively in order to generate
** code for the SQL statement given onto the end of the pParse context
** currently under construction. When the parser is run recursively
** this way, the final OP_Halt is not appended and other initialization
** and finalization steps are omitted because those are handling by the
** outermost parser.
**
** Not everything is nestable. This facility is designed to permit
** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
** care if you decide to try to use this routine for some other purposes.
*/
void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
va_list ap;
char *zSql;
char *zErrMsg = 0;
sqlite3 *db = pParse->db;
char saveBuf[PARSE_TAIL_SZ];
if( pParse->nErr ) return;
assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
va_start(ap, zFormat);
zSql = sqlite3VMPrintf(db, zFormat, ap);
va_end(ap);
if( zSql==0 ){
/* This can result either from an OOM or because the formatted string
** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set
** an error */
if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
pParse->nErr++;
return;
}
pParse->nested++;
memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
sqlite3RunParser(pParse, zSql, &zErrMsg);
sqlite3DbFree(db, zErrMsg);
sqlite3DbFree(db, zSql);
memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
pParse->nested--;
}
#if SQLITE_USER_AUTHENTICATION
/*
** Return TRUE if zTable is the name of the system table that stores the
** list of users and their access credentials.
*/
int sqlite3UserAuthTable(const char *zTable){
return sqlite3_stricmp(zTable, "sqlite_user")==0;
}
#endif
/*
** Locate the in-memory structure that describes a particular database
** table given the name of that table and (optionally) the name of the
** database containing the table. Return NULL if not found.
**
** If zDatabase is 0, all databases are searched for the table and the
** first matching table is returned. (No checking for duplicate table
** names is done.) The search order is TEMP first, then MAIN, then any
** auxiliary databases added using the ATTACH command.
**
** See also sqlite3LocateTable().
*/
Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
Table *p = 0;
int i;
/* All mutexes are required for schema access. Make sure we hold them. */
assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
#if SQLITE_USER_AUTHENTICATION
/* Only the admin user is allowed to know that the sqlite_user table
** exists */
if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
return 0;
}
#endif
while(1){
for(i=OMIT_TEMPDB; i<db->nDb; i++){
int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
if( zDatabase==0 || sqlite3StrICmp(zDatabase, db->aDb[j].zDbSName)==0 ){
assert( sqlite3SchemaMutexHeld(db, j, 0) );
p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
if( p ) return p;
}
}
/* Not found. If the name we were looking for was temp.sqlite_master
** then change the name to sqlite_temp_master and try again. */
if( sqlite3StrICmp(zName, MASTER_NAME)!=0 ) break;
if( sqlite3_stricmp(zDatabase, db->aDb[1].zDbSName)!=0 ) break;
zName = TEMP_MASTER_NAME;
}
return 0;
}
/*
** Locate the in-memory structure that describes a particular database
** table given the name of that table and (optionally) the name of the
** database containing the table. Return NULL if not found. Also leave an
** error message in pParse->zErrMsg.
**
** The difference between this routine and sqlite3FindTable() is that this
** routine leaves an error message in pParse->zErrMsg where
** sqlite3FindTable() does not.
*/
Table *sqlite3LocateTable(
Parse *pParse, /* context in which to report errors */
u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
const char *zName, /* Name of the table we are looking for */
const char *zDbase /* Name of the database. Might be NULL */
){
Table *p;
sqlite3 *db = pParse->db;
/* Read the database schema. If an error occurs, leave an error message
** and code in pParse and return NULL. */
if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
&& SQLITE_OK!=sqlite3ReadSchema(pParse)
){
return 0;
}
p = sqlite3FindTable(db, zName, zDbase);
if( p==0 ){
#ifndef SQLITE_OMIT_VIRTUALTABLE
/* If zName is the not the name of a table in the schema created using
** CREATE, then check to see if it is the name of an virtual table that
** can be an eponymous virtual table. */
if( pParse->disableVtab==0 ){
Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
pMod = sqlite3PragmaVtabRegister(db, zName);
}
if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
return pMod->pEpoTab;
}
}
#endif
if( flags & LOCATE_NOERR ) return 0;
pParse->checkSchema = 1;
}else if( IsVirtual(p) && pParse->disableVtab ){
p = 0;
}
if( p==0 ){
const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
if( zDbase ){
sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
}else{
sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
}
}
return p;
}
/*
** Locate the table identified by *p.
**
** This is a wrapper around sqlite3LocateTable(). The difference between
** sqlite3LocateTable() and this function is that this function restricts
** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
** non-NULL if it is part of a view or trigger program definition. See
** sqlite3FixSrcList() for details.
*/
Table *sqlite3LocateTableItem(
Parse *pParse,
u32 flags,
struct SrcList_item *p
){
const char *zDb;
assert( p->pSchema==0 || p->zDatabase==0 );
if( p->pSchema ){
int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
zDb = pParse->db->aDb[iDb].zDbSName;
}else{
zDb = p->zDatabase;
}
return sqlite3LocateTable(pParse, flags, p->zName, zDb);
}
/*
** Locate the in-memory structure that describes
** a particular index given the name of that index
** and the name of the database that contains the index.
** Return NULL if not found.
**
** If zDatabase is 0, all databases are searched for the
** table and the first matching index is returned. (No checking
** for duplicate index names is done.) The search order is
** TEMP first, then MAIN, then any auxiliary databases added
** using the ATTACH command.
*/
Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
Index *p = 0;
int i;
/* All mutexes are required for schema access. Make sure we hold them. */
assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
for(i=OMIT_TEMPDB; i<db->nDb; i++){
int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
Schema *pSchema = db->aDb[j].pSchema;
assert( pSchema );
if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zDbSName) ) continue;
assert( sqlite3SchemaMutexHeld(db, j, 0) );
p = sqlite3HashFind(&pSchema->idxHash, zName);
if( p ) break;
}
return p;
}
/*
** Reclaim the memory used by an index
*/
void sqlite3FreeIndex(sqlite3 *db, Index *p){
#ifndef SQLITE_OMIT_ANALYZE
sqlite3DeleteIndexSamples(db, p);
#endif
sqlite3ExprDelete(db, p->pPartIdxWhere);
sqlite3ExprListDelete(db, p->aColExpr);
sqlite3DbFree(db, p->zColAff);
if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
#ifdef SQLITE_ENABLE_STAT4
sqlite3_free(p->aiRowEst);
#endif
sqlite3DbFree(db, p);
}
/*
** For the index called zIdxName which is found in the database iDb,
** unlike that index from its Table then remove the index from
** the index hash table and free all memory structures associated
** with the index.
*/
void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
Index *pIndex;
Hash *pHash;
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
pHash = &db->aDb[iDb].pSchema->idxHash;
pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
if( ALWAYS(pIndex) ){
if( pIndex->pTable->pIndex==pIndex ){
pIndex->pTable->pIndex = pIndex->pNext;
}else{
Index *p;
/* Justification of ALWAYS(); The index must be on the list of
** indices. */
p = pIndex->pTable->pIndex;
while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
if( ALWAYS(p && p->pNext==pIndex) ){
p->pNext = pIndex->pNext;
}
}
sqlite3FreeIndex(db, pIndex);
}
db->mDbFlags |= DBFLAG_SchemaChange;
}
/*
** Look through the list of open database files in db->aDb[] and if
** any have been closed, remove them from the list. Reallocate the
** db->aDb[] structure to a smaller size, if possible.
**
** Entry 0 (the "main" database) and entry 1 (the "temp" database)
** are never candidates for being collapsed.
*/
void sqlite3CollapseDatabaseArray(sqlite3 *db){
int i, j;
for(i=j=2; i<db->nDb; i++){
struct Db *pDb = &db->aDb[i];
if( pDb->pBt==0 ){
sqlite3DbFree(db, pDb->zDbSName);
pDb->zDbSName = 0;
continue;
}
if( j<i ){
db->aDb[j] = db->aDb[i];
}
j++;
}
db->nDb = j;
if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
sqlite3DbFree(db, db->aDb);
db->aDb = db->aDbStatic;
}
}
/*
** Reset the schema for the database at index iDb. Also reset the
** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
** Deferred resets may be run by calling with iDb<0.
*/
void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
int i;
assert( iDb<db->nDb );
if( iDb>=0 ){
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
DbSetProperty(db, iDb, DB_ResetWanted);
DbSetProperty(db, 1, DB_ResetWanted);
db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
}
if( db->nSchemaLock==0 ){
for(i=0; i<db->nDb; i++){
if( DbHasProperty(db, i, DB_ResetWanted) ){
sqlite3SchemaClear(db->aDb[i].pSchema);
}
}
}
}
/*
** Erase all schema information from all attached databases (including
** "main" and "temp") for a single database connection.
*/
void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
int i;
sqlite3BtreeEnterAll(db);
for(i=0; i<db->nDb; i++){
Db *pDb = &db->aDb[i];
if( pDb->pSchema ){
if( db->nSchemaLock==0 ){
sqlite3SchemaClear(pDb->pSchema);
}else{
DbSetProperty(db, i, DB_ResetWanted);
}
}
}
db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
sqlite3VtabUnlockList(db);
sqlite3BtreeLeaveAll(db);
if( db->nSchemaLock==0 ){
sqlite3CollapseDatabaseArray(db);
}
}
/*
** This routine is called when a commit occurs.
*/
void sqlite3CommitInternalChanges(sqlite3 *db){
db->mDbFlags &= ~DBFLAG_SchemaChange;
}
/*
** Delete memory allocated for the column names of a table or view (the
** Table.aCol[] array).
*/
void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
int i;
Column *pCol;
assert( pTable!=0 );
if( (pCol = pTable->aCol)!=0 ){
for(i=0; i<pTable->nCol; i++, pCol++){
sqlite3DbFree(db, pCol->zName);
sqlite3ExprDelete(db, pCol->pDflt);
sqlite3DbFree(db, pCol->zColl);
}
sqlite3DbFree(db, pTable->aCol);
}
}
/*
** Remove the memory data structures associated with the given
** Table. No changes are made to disk by this routine.
**
** This routine just deletes the data structure. It does not unlink
** the table data structure from the hash table. But it does destroy
** memory structures of the indices and foreign keys associated with
** the table.
**
** The db parameter is optional. It is needed if the Table object
** contains lookaside memory. (Table objects in the schema do not use
** lookaside memory, but some ephemeral Table objects do.) Or the
** db parameter can be used with db->pnBytesFreed to measure the memory
** used by the Table object.
*/
static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
Index *pIndex, *pNext;
#ifdef SQLITE_DEBUG
/* Record the number of outstanding lookaside allocations in schema Tables
** prior to doing any free() operations. Since schema Tables do not use
** lookaside, this number should not change.
**
** If malloc has already failed, it may be that it failed while allocating
** a Table object that was going to be marked ephemeral. So do not check
** that no lookaside memory is used in this case either. */
int nLookaside = 0;
if( db && !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){
nLookaside = sqlite3LookasideUsed(db, 0);
}
#endif
/* Delete all indices associated with this table. */
for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
pNext = pIndex->pNext;
assert( pIndex->pSchema==pTable->pSchema
|| (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
if( (db==0 || db->pnBytesFreed==0) && !IsVirtual(pTable) ){
char *zName = pIndex->zName;
TESTONLY ( Index *pOld = ) sqlite3HashInsert(
&pIndex->pSchema->idxHash, zName, 0
);
assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
assert( pOld==pIndex || pOld==0 );
}
sqlite3FreeIndex(db, pIndex);
}
/* Delete any foreign keys attached to this table. */
sqlite3FkDelete(db, pTable);
/* Delete the Table structure itself.
*/
sqlite3DeleteColumnNames(db, pTable);
sqlite3DbFree(db, pTable->zName);
sqlite3DbFree(db, pTable->zColAff);
sqlite3SelectDelete(db, pTable->pSelect);
sqlite3ExprListDelete(db, pTable->pCheck);
#ifndef SQLITE_OMIT_VIRTUALTABLE
sqlite3VtabClear(db, pTable);
#endif
sqlite3DbFree(db, pTable);
/* Verify that no lookaside memory was used by schema tables */
assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
}
void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
/* Do not delete the table until the reference count reaches zero. */
if( !pTable ) return;
if( ((!db || db->pnBytesFreed==0) && (--pTable->nTabRef)>0) ) return;
deleteTable(db, pTable);
}
/*
** Unlink the given table from the hash tables and the delete the
** table structure with all its indices and foreign keys.
*/
void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
Table *p;
Db *pDb;
assert( db!=0 );
assert( iDb>=0 && iDb<db->nDb );
assert( zTabName );
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
pDb = &db->aDb[iDb];
p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
sqlite3DeleteTable(db, p);
db->mDbFlags |= DBFLAG_SchemaChange;
}
/*
** Given a token, return a string that consists of the text of that
** token. Space to hold the returned string
** is obtained from sqliteMalloc() and must be freed by the calling
** function.
**
** Any quotation marks (ex: "name", 'name', [name], or `name`) that
** surround the body of the token are removed.
**
** Tokens are often just pointers into the original SQL text and so
** are not \000 terminated and are not persistent. The returned string
** is \000 terminated and is persistent.
*/
char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
char *zName;
if( pName ){
zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
sqlite3Dequote(zName);
}else{
zName = 0;
}
return zName;
}
/*
** Open the sqlite_master table stored in database number iDb for
** writing. The table is opened using cursor 0.
*/
void sqlite3OpenMasterTable(Parse *p, int iDb){
Vdbe *v = sqlite3GetVdbe(p);
sqlite3TableLock(p, iDb, MASTER_ROOT, 1, MASTER_NAME);
sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
if( p->nTab==0 ){
p->nTab = 1;
}
}
/*
** Parameter zName points to a nul-terminated buffer containing the name
** of a database ("main", "temp" or the name of an attached db). This
** function returns the index of the named database in db->aDb[], or
** -1 if the named db cannot be found.
*/
int sqlite3FindDbName(sqlite3 *db, const char *zName){
int i = -1; /* Database number */
if( zName ){
Db *pDb;
for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
/* "main" is always an acceptable alias for the primary database
** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
}
}
return i;
}
/*
** The token *pName contains the name of a database (either "main" or
** "temp" or the name of an attached db). This routine returns the
** index of the named database in db->aDb[], or -1 if the named db
** does not exist.
*/
int sqlite3FindDb(sqlite3 *db, Token *pName){
int i; /* Database number */
char *zName; /* Name we are searching for */
zName = sqlite3NameFromToken(db, pName);
i = sqlite3FindDbName(db, zName);
sqlite3DbFree(db, zName);
return i;
}
/* The table or view or trigger name is passed to this routine via tokens
** pName1 and pName2. If the table name was fully qualified, for example:
**
** CREATE TABLE xxx.yyy (...);
**
** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
** the table name is not fully qualified, i.e.:
**
** CREATE TABLE yyy(...);
**
** Then pName1 is set to "yyy" and pName2 is "".
**
** This routine sets the *ppUnqual pointer to point at the token (pName1 or
** pName2) that stores the unqualified table name. The index of the
** database "xxx" is returned.
*/
int sqlite3TwoPartName(
Parse *pParse, /* Parsing and code generating context */
Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
Token *pName2, /* The "yyy" in the name "xxx.yyy" */
Token **pUnqual /* Write the unqualified object name here */
){
int iDb; /* Database holding the object */
sqlite3 *db = pParse->db;
assert( pName2!=0 );
if( pName2->n>0 ){
if( db->init.busy ) {
sqlite3ErrorMsg(pParse, "corrupt database");
return -1;
}
*pUnqual = pName2;
iDb = sqlite3FindDb(db, pName1);
if( iDb<0 ){
sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
return -1;
}
}else{
assert( db->init.iDb==0 || db->init.busy || IN_RENAME_OBJECT
|| (db->mDbFlags & DBFLAG_Vacuum)!=0);
iDb = db->init.iDb;
*pUnqual = pName1;
}
return iDb;
}
/*
** True if PRAGMA writable_schema is ON
*/
int sqlite3WritableSchema(sqlite3 *db){
testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
SQLITE_WriteSchema );
testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
SQLITE_Defensive );
testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
(SQLITE_WriteSchema|SQLITE_Defensive) );
return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
}
/*
** This routine is used to check if the UTF-8 string zName is a legal
** unqualified name for a new schema object (table, index, view or
** trigger). All names are legal except those that begin with the string
** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
** is reserved for internal use.
**
** When parsing the sqlite_master table, this routine also checks to
** make sure the "type", "name", and "tbl_name" columns are consistent
** with the SQL.
*/
int sqlite3CheckObjectName(
Parse *pParse, /* Parsing context */
const char *zName, /* Name of the object to check */
const char *zType, /* Type of this object */
const char *zTblName /* Parent table name for triggers and indexes */
){
sqlite3 *db = pParse->db;
if( sqlite3WritableSchema(db) || db->init.imposterTable ){
/* Skip these error checks for writable_schema=ON */
return SQLITE_OK;
}
if( db->init.busy ){
if( sqlite3_stricmp(zType, db->init.azInit[0])
|| sqlite3_stricmp(zName, db->init.azInit[1])
|| sqlite3_stricmp(zTblName, db->init.azInit[2])
){
if( sqlite3Config.bExtraSchemaChecks ){
sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
return SQLITE_ERROR;
}
}
}else{
if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
|| (sqlite3ReadOnlyShadowTables(db) && sqlite3ShadowTableName(db, zName))
){
sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
zName);
return SQLITE_ERROR;
}
}
return SQLITE_OK;
}
/*
** Return the PRIMARY KEY index of a table
*/
Index *sqlite3PrimaryKeyIndex(Table *pTab){
Index *p;
for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
return p;
}
/*
** Convert an table column number into a index column number. That is,
** for the column iCol in the table (as defined by the CREATE TABLE statement)
** find the (first) offset of that column in index pIdx. Or return -1
** if column iCol is not used in index pIdx.
*/
i16 sqlite3TableColumnToIndex(Index *pIdx, i16 iCol){
int i;
for(i=0; i<pIdx->nColumn; i++){
if( iCol==pIdx->aiColumn[i] ) return i;
}
return -1;
}
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
/* Convert a storage column number into a table column number.
**
** The storage column number (0,1,2,....) is the index of the value
** as it appears in the record on disk. The true column number
** is the index (0,1,2,...) of the column in the CREATE TABLE statement.
**
** The storage column number is less than the table column number if
** and only there are VIRTUAL columns to the left.
**
** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.
*/
i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){
if( pTab->tabFlags & TF_HasVirtual ){
int i;
for(i=0; i<=iCol; i++){
if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;
}
}
return iCol;
}
#endif
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
/* Convert a table column number into a storage column number.
**
** The storage column number (0,1,2,....) is the index of the value
** as it appears in the record on disk. Or, if the input column is
** the N-th virtual column (zero-based) then the storage number is
** the number of non-virtual columns in the table plus N.
**
** The true column number is the index (0,1,2,...) of the column in
** the CREATE TABLE statement.
**
** If the input column is a VIRTUAL column, then it should not appear
** in storage. But the value sometimes is cached in registers that
** follow the range of registers used to construct storage. This
** avoids computing the same VIRTUAL column multiple times, and provides
** values for use by OP_Param opcodes in triggers. Hence, if the
** input column is a VIRTUAL table, put it after all the other columns.
**
** In the following, N means "normal column", S means STORED, and
** V means VIRTUAL. Suppose the CREATE TABLE has columns like this:
**
** CREATE TABLE ex(N,S,V,N,S,V,N,S,V);
** -- 0 1 2 3 4 5 6 7 8
**
** Then the mapping from this function is as follows:
**
** INPUTS: 0 1 2 3 4 5 6 7 8
** OUTPUTS: 0 1 6 2 3 7 4 5 8
**
** So, in other words, this routine shifts all the virtual columns to
** the end.
**
** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and
** this routine is a no-op macro. If the pTab does not have any virtual
** columns, then this routine is no-op that always return iCol. If iCol
** is negative (indicating the ROWID column) then this routine return iCol.
*/
i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){
int i;
i16 n;
assert( iCol<pTab->nCol );
if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;
for(i=0, n=0; i<iCol; i++){
if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;
}
if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){
/* iCol is a virtual column itself */
return pTab->nNVCol + i - n;
}else{
/* iCol is a normal or stored column */
return n;
}
}
#endif
/*
** Begin constructing a new table representation in memory. This is
** the first of several action routines that get called in response
** to a CREATE TABLE statement. In particular, this routine is called
** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
** flag is true if the table should be stored in the auxiliary database
** file instead of in the main database file. This is normally the case
** when the "TEMP" or "TEMPORARY" keyword occurs in between
** CREATE and TABLE.
**
** The new table record is initialized and put in pParse->pNewTable.
** As more of the CREATE TABLE statement is parsed, additional action
** routines will be called to add more information to this record.
** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
** is called to complete the construction of the new table record.
*/
void sqlite3StartTable(
Parse *pParse, /* Parser context */
Token *pName1, /* First part of the name of the table or view */
Token *pName2, /* Second part of the name of the table or view */
int isTemp, /* True if this is a TEMP table */
int isView, /* True if this is a VIEW */
int isVirtual, /* True if this is a VIRTUAL table */
int noErr /* Do nothing if table already exists */
){
Table *pTable;
char *zName = 0; /* The name of the new table */
sqlite3 *db = pParse->db;
Vdbe *v;
int iDb; /* Database number to create the table in */
Token *pName; /* Unqualified name of the table to create */
if( db->init.busy && db->init.newTnum==1 ){
/* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
iDb = db->init.iDb;
zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
pName = pName1;
}else{
/* The common case */
iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
if( iDb<0 ) return;
if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
/* If creating a temp table, the name may not be qualified. Unless
** the database name is "temp" anyway. */
sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
return;
}
if( !OMIT_TEMPDB && isTemp ) iDb = 1;
zName = sqlite3NameFromToken(db, pName);
if( IN_RENAME_OBJECT ){
sqlite3RenameTokenMap(pParse, (void*)zName, pName);
}
}
pParse->sNameToken = *pName;
if( zName==0 ) return;
if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName) ){
goto begin_table_error;
}
if( db->init.iDb==1 ) isTemp = 1;
#ifndef SQLITE_OMIT_AUTHORIZATION
assert( isTemp==0 || isTemp==1 );
assert( isView==0 || isView==1 );
{
static const u8 aCode[] = {
SQLITE_CREATE_TABLE,
SQLITE_CREATE_TEMP_TABLE,
SQLITE_CREATE_VIEW,
SQLITE_CREATE_TEMP_VIEW
};
char *zDb = db->aDb[iDb].zDbSName;
if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
goto begin_table_error;
}
if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
zName, 0, zDb) ){
goto begin_table_error;
}
}
#endif
/* Make sure the new table name does not collide with an existing
** index or table name in the same database. Issue an error message if
** it does. The exception is if the statement being parsed was passed
** to an sqlite3_declare_vtab() call. In that case only the column names
** and types will be used, so there is no need to test for namespace
** collisions.
*/
if( !IN_SPECIAL_PARSE ){
char *zDb = db->aDb[iDb].zDbSName;
if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
goto begin_table_error;
}
pTable = sqlite3FindTable(db, zName, zDb);
if( pTable ){
if( !noErr ){
sqlite3ErrorMsg(pParse, "table %T already exists", pName);
}else{
assert( !db->init.busy || CORRUPT_DB );
sqlite3CodeVerifySchema(pParse, iDb);
}
goto begin_table_error;
}
if( sqlite3FindIndex(db, zName, zDb)!=0 ){
sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
goto begin_table_error;
}
}
pTable = sqlite3DbMallocZero(db, sizeof(Table));
if( pTable==0 ){
assert( db->mallocFailed );
pParse->rc = SQLITE_NOMEM_BKPT;
pParse->nErr++;
goto begin_table_error;
}
pTable->zName = zName;
pTable->iPKey = -1;
pTable->pSchema = db->aDb[iDb].pSchema;
pTable->nTabRef = 1;
#ifdef SQLITE_DEFAULT_ROWEST
pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
#else
pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
#endif
assert( pParse->pNewTable==0 );
pParse->pNewTable = pTable;
/* If this is the magic sqlite_sequence table used by autoincrement,
** then record a pointer to this table in the main database structure
** so that INSERT can find the table easily.
*/
#ifndef SQLITE_OMIT_AUTOINCREMENT
if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
pTable->pSchema->pSeqTab = pTable;
}
#endif
/* Begin generating the code that will insert the table record into
** the SQLITE_MASTER table. Note in particular that we must go ahead
** and allocate the record number for the table entry now. Before any
** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
** indices to be created and the table record must come before the
** indices. Hence, the record number for the table must be allocated
** now.
*/
if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
int addr1;
int fileFormat;
int reg1, reg2, reg3;
/* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
sqlite3BeginWriteOperation(pParse, 1, iDb);
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( isVirtual ){
sqlite3VdbeAddOp0(v, OP_VBegin);
}
#endif
/* If the file format and encoding in the database have not been set,
** set them now.
*/
reg1 = pParse->regRowid = ++pParse->nMem;
reg2 = pParse->regRoot = ++pParse->nMem;
reg3 = ++pParse->nMem;
sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
sqlite3VdbeUsesBtree(v, iDb);
addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
1 : SQLITE_MAX_FILE_FORMAT;
sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
sqlite3VdbeJumpHere(v, addr1);
/* This just creates a place-holder record in the sqlite_master table.
** The record created does not contain anything yet. It will be replaced
** by the real entry in code generated at sqlite3EndTable().
**
** The rowid for the new entry is left in register pParse->regRowid.
** The root page number of the new table is left in reg pParse->regRoot.
** The rowid and root page number values are needed by the code that
** sqlite3EndTable will generate.
*/
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
if( isView || isVirtual ){
sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
}else
#endif
{
pParse->addrCrTab =
sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
}
sqlite3OpenMasterTable(pParse, iDb);
sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
sqlite3VdbeAddOp0(v, OP_Close);
}
/* Normal (non-error) return. */
return;
/* If an error occurs, we jump here */
begin_table_error:
sqlite3DbFree(db, zName);
return;
}
/* Set properties of a table column based on the (magical)
** name of the column.
*/
#if SQLITE_ENABLE_HIDDEN_COLUMNS
void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
pCol->colFlags |= COLFLAG_HIDDEN;
}else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
pTab->tabFlags |= TF_OOOHidden;
}
}
#endif
/*
** Add a new column to the table currently being constructed.
**
** The parser calls this routine once for each column declaration
** in a CREATE TABLE statement. sqlite3StartTable() gets called
** first to get things going. Then this routine is called for each
** column.
*/
void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
Table *p;
int i;
char *z;
char *zType;
Column *pCol;
sqlite3 *db = pParse->db;
if( (p = pParse->pNewTable)==0 ) return;
if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
return;
}
z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
if( z==0 ) return;
if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, pName);
memcpy(z, pName->z, pName->n);
z[pName->n] = 0;
sqlite3Dequote(z);
for(i=0; i<p->nCol; i++){
if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
sqlite3DbFree(db, z);
return;
}
}
if( (p->nCol & 0x7)==0 ){
Column *aNew;
aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
if( aNew==0 ){
sqlite3DbFree(db, z);
return;
}
p->aCol = aNew;
}
pCol = &p->aCol[p->nCol];
memset(pCol, 0, sizeof(p->aCol[0]));
pCol->zName = z;
sqlite3ColumnPropertiesFromName(p, pCol);
if( pType->n==0 ){
/* If there is no type specified, columns have the default affinity
** 'BLOB' with a default size of 4 bytes. */
pCol->affinity = SQLITE_AFF_BLOB;
pCol->szEst = 1;
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( 4>=sqlite3GlobalConfig.szSorterRef ){
pCol->colFlags |= COLFLAG_SORTERREF;
}
#endif
}else{
zType = z + sqlite3Strlen30(z) + 1;
memcpy(zType, pType->z, pType->n);
zType[pType->n] = 0;
sqlite3Dequote(zType);
pCol->affinity = sqlite3AffinityType(zType, pCol);
pCol->colFlags |= COLFLAG_HASTYPE;
}
p->nCol++;
p->nNVCol++;
pParse->constraintName.n = 0;
}
/*
** This routine is called by the parser while in the middle of
** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
** been seen on a column. This routine sets the notNull flag on
** the column currently under construction.
*/
void sqlite3AddNotNull(Parse *pParse, int onError){
Table *p;
Column *pCol;
p = pParse->pNewTable;
if( p==0 || NEVER(p->nCol<1) ) return;
pCol = &p->aCol[p->nCol-1];
pCol->notNull = (u8)onError;
p->tabFlags |= TF_HasNotNull;
/* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
** on this column. */
if( pCol->colFlags & COLFLAG_UNIQUE ){
Index *pIdx;
for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
if( pIdx->aiColumn[0]==p->nCol-1 ){
pIdx->uniqNotNull = 1;
}
}
}
}
/*
** Scan the column type name zType (length nType) and return the
** associated affinity type.
**
** This routine does a case-independent search of zType for the
** substrings in the following table. If one of the substrings is
** found, the corresponding affinity is returned. If zType contains
** more than one of the substrings, entries toward the top of
** the table take priority. For example, if zType is 'BLOBINT',
** SQLITE_AFF_INTEGER is returned.
**
** Substring | Affinity
** --------------------------------
** 'INT' | SQLITE_AFF_INTEGER
** 'CHAR' | SQLITE_AFF_TEXT
** 'CLOB' | SQLITE_AFF_TEXT
** 'TEXT' | SQLITE_AFF_TEXT
** 'BLOB' | SQLITE_AFF_BLOB
** 'REAL' | SQLITE_AFF_REAL
** 'FLOA' | SQLITE_AFF_REAL
** 'DOUB' | SQLITE_AFF_REAL
**
** If none of the substrings in the above table are found,
** SQLITE_AFF_NUMERIC is returned.
*/
char sqlite3AffinityType(const char *zIn, Column *pCol){
u32 h = 0;
char aff = SQLITE_AFF_NUMERIC;
const char *zChar = 0;
assert( zIn!=0 );
while( zIn[0] ){
h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
zIn++;
if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
aff = SQLITE_AFF_TEXT;
zChar = zIn;
}else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
aff = SQLITE_AFF_TEXT;
}else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
aff = SQLITE_AFF_TEXT;
}else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
&& (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
aff = SQLITE_AFF_BLOB;
if( zIn[0]=='(' ) zChar = zIn;
#ifndef SQLITE_OMIT_FLOATING_POINT
}else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
&& aff==SQLITE_AFF_NUMERIC ){
aff = SQLITE_AFF_REAL;
}else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
&& aff==SQLITE_AFF_NUMERIC ){
aff = SQLITE_AFF_REAL;
}else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
&& aff==SQLITE_AFF_NUMERIC ){
aff = SQLITE_AFF_REAL;
#endif
}else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
aff = SQLITE_AFF_INTEGER;
break;
}
}
/* If pCol is not NULL, store an estimate of the field size. The
** estimate is scaled so that the size of an integer is 1. */
if( pCol ){
int v = 0; /* default size is approx 4 bytes */
if( aff<SQLITE_AFF_NUMERIC ){
if( zChar ){
while( zChar[0] ){
if( sqlite3Isdigit(zChar[0]) ){
/* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
sqlite3GetInt32(zChar, &v);
break;
}
zChar++;
}
}else{
v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
}
}
#ifdef SQLITE_ENABLE_SORTER_REFERENCES
if( v>=sqlite3GlobalConfig.szSorterRef ){
pCol->colFlags |= COLFLAG_SORTERREF;
}
#endif
v = v/4 + 1;
if( v>255 ) v = 255;
pCol->szEst = v;
}
return aff;
}
/*
** The expression is the default value for the most recently added column
** of the table currently under construction.
**
** Default value expressions must be constant. Raise an exception if this
** is not the case.
**
** This routine is called by the parser while in the middle of
** parsing a CREATE TABLE statement.
*/
void sqlite3AddDefaultValue(
Parse *pParse, /* Parsing context */
Expr *pExpr, /* The parsed expression of the default value */
const char *zStart, /* Start of the default value text */
const char *zEnd /* First character past end of defaut value text */
){
Table *p;
Column *pCol;
sqlite3 *db = pParse->db;
p = pParse->pNewTable;
if( p!=0 ){
pCol = &(p->aCol[p->nCol-1]);
if( !sqlite3ExprIsConstantOrFunction(pExpr, db->init.busy) ){
sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
pCol->zName);
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
}else if( pCol->colFlags & COLFLAG_GENERATED ){
testcase( pCol->colFlags & COLFLAG_VIRTUAL );
testcase( pCol->colFlags & COLFLAG_STORED );
sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column");
#endif
}else{
/* A copy of pExpr is used instead of the original, as pExpr contains
** tokens that point to volatile memory.
*/
Expr x;
sqlite3ExprDelete(db, pCol->pDflt);
memset(&x, 0, sizeof(x));
x.op = TK_SPAN;
x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
x.pLeft = pExpr;
x.flags = EP_Skip;
pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
sqlite3DbFree(db, x.u.zToken);
}
}
if( IN_RENAME_OBJECT ){
sqlite3RenameExprUnmap(pParse, pExpr);
}
sqlite3ExprDelete(db, pExpr);
}
/*
** Backwards Compatibility Hack:
**
** Historical versions of SQLite accepted strings as column names in
** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
**
** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
**
** This is goofy. But to preserve backwards compatibility we continue to
** accept it. This routine does the necessary conversion. It converts
** the expression given in its argument from a TK_STRING into a TK_ID
** if the expression is just a TK_STRING with an optional COLLATE clause.
** If the expression is anything other than TK_STRING, the expression is
** unchanged.
*/
static void sqlite3StringToId(Expr *p){
if( p->op==TK_STRING ){
p->op = TK_ID;
}else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
p->pLeft->op = TK_ID;
}
}
/*
** Tag the given column as being part of the PRIMARY KEY
*/
static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){
pCol->colFlags |= COLFLAG_PRIMKEY;
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
if( pCol->colFlags & COLFLAG_GENERATED ){
testcase( pCol->colFlags & COLFLAG_VIRTUAL );
testcase( pCol->colFlags & COLFLAG_STORED );
sqlite3ErrorMsg(pParse,
"generated columns cannot be part of the PRIMARY KEY");
}
#endif
}
/*
** Designate the PRIMARY KEY for the table. pList is a list of names
** of columns that form the primary key. If pList is NULL, then the
** most recently added column of the table is the primary key.
**
** A table can have at most one primary key. If the table already has
** a primary key (and this is the second primary key) then create an
** error.
**
** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
** then we will try to use that column as the rowid. Set the Table.iPKey
** field of the table under construction to be the index of the
** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
** no INTEGER PRIMARY KEY.
**
** If the key is not an INTEGER PRIMARY KEY, then create a unique
** index for the key. No index is created for INTEGER PRIMARY KEYs.
*/
void sqlite3AddPrimaryKey(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List of field names to be indexed */
int onError, /* What to do with a uniqueness conflict */
int autoInc, /* True if the AUTOINCREMENT keyword is present */
int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
){
Table *pTab = pParse->pNewTable;
Column *pCol = 0;
int iCol = -1, i;
int nTerm;
if( pTab==0 ) goto primary_key_exit;
if( pTab->tabFlags & TF_HasPrimaryKey ){
sqlite3ErrorMsg(pParse,
"table \"%s\" has more than one primary key", pTab->zName);
goto primary_key_exit;
}
pTab->tabFlags |= TF_HasPrimaryKey;
if( pList==0 ){
iCol = pTab->nCol - 1;
pCol = &pTab->aCol[iCol];
makeColumnPartOfPrimaryKey(pParse, pCol);
nTerm = 1;
}else{
nTerm = pList->nExpr;
for(i=0; i<nTerm; i++){
Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
assert( pCExpr!=0 );
sqlite3StringToId(pCExpr);
if( pCExpr->op==TK_ID ){
const char *zCName = pCExpr->u.zToken;
for(iCol=0; iCol<pTab->nCol; iCol++){
if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
pCol = &pTab->aCol[iCol];
makeColumnPartOfPrimaryKey(pParse, pCol);
break;
}
}
}
}
}
if( nTerm==1
&& pCol
&& sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
&& sortOrder!=SQLITE_SO_DESC
){
if( IN_RENAME_OBJECT && pList ){
Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
}
pTab->iPKey = iCol;
pTab->keyConf = (u8)onError;
assert( autoInc==0 || autoInc==1 );
pTab->tabFlags |= autoInc*TF_Autoincrement;
if( pList ) pParse->iPkSortOrder = pList->a[0].sortFlags;
}else if( autoInc ){
#ifndef SQLITE_OMIT_AUTOINCREMENT
sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
"INTEGER PRIMARY KEY");
#endif
}else{
sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
pList = 0;
}
primary_key_exit:
sqlite3ExprListDelete(pParse->db, pList);
return;
}
/*
** Add a new CHECK constraint to the table currently under construction.
*/
void sqlite3AddCheckConstraint(
Parse *pParse, /* Parsing context */
Expr *pCheckExpr /* The check expression */
){
#ifndef SQLITE_OMIT_CHECK
Table *pTab = pParse->pNewTable;
sqlite3 *db = pParse->db;
if( pTab && !IN_DECLARE_VTAB
&& !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
){
pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
if( pParse->constraintName.n ){
sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
}
}else
#endif
{
sqlite3ExprDelete(pParse->db, pCheckExpr);
}
}
/*
** Set the collation function of the most recently parsed table column
** to the CollSeq given.
*/
void sqlite3AddCollateType(Parse *pParse, Token *pToken){
Table *p;
int i;
char *zColl; /* Dequoted name of collation sequence */
sqlite3 *db;
if( (p = pParse->pNewTable)==0 ) return;
i = p->nCol-1;
db = pParse->db;
zColl = sqlite3NameFromToken(db, pToken);
if( !zColl ) return;
if( sqlite3LocateCollSeq(pParse, zColl) ){
Index *pIdx;
sqlite3DbFree(db, p->aCol[i].zColl);
p->aCol[i].zColl = zColl;
/* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
** then an index may have been created on this column before the
** collation type was added. Correct this if it is the case.
*/
for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
assert( pIdx->nKeyCol==1 );
if( pIdx->aiColumn[0]==i ){
pIdx->azColl[0] = p->aCol[i].zColl;
}
}
}else{
sqlite3DbFree(db, zColl);
}
}
/* Change the most recently parsed column to be a GENERATED ALWAYS AS
** column.
*/
void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
u8 eType = COLFLAG_VIRTUAL;
Table *pTab = pParse->pNewTable;
Column *pCol;
if( pTab==0 ){
/* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
goto generated_done;
}
pCol = &(pTab->aCol[pTab->nCol-1]);
if( IN_DECLARE_VTAB ){
sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns");
goto generated_done;
}
if( pCol->pDflt ) goto generated_error;
if( pType ){
if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
/* no-op */
}else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
eType = COLFLAG_STORED;
}else{
goto generated_error;
}
}
if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
pCol->colFlags |= eType;
assert( TF_HasVirtual==COLFLAG_VIRTUAL );
assert( TF_HasStored==COLFLAG_STORED );
pTab->tabFlags |= eType;
if( pCol->colFlags & COLFLAG_PRIMKEY ){
makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */
}
pCol->pDflt = pExpr;
pExpr = 0;
goto generated_done;
generated_error:
sqlite3ErrorMsg(pParse, "error in generated column \"%s\"",
pCol->zName);
generated_done:
sqlite3ExprDelete(pParse->db, pExpr);
#else
/* Throw and error for the GENERATED ALWAYS AS clause if the
** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
sqlite3ErrorMsg(pParse, "generated columns not supported");
sqlite3ExprDelete(pParse->db, pExpr);
#endif
}
/*
** Generate code that will increment the schema cookie.
**
** The schema cookie is used to determine when the schema for the
** database changes. After each schema change, the cookie value
** changes. When a process first reads the schema it records the
** cookie. Thereafter, whenever it goes to access the database,
** it checks the cookie to make sure the schema has not changed
** since it was last read.
**
** This plan is not completely bullet-proof. It is possible for
** the schema to change multiple times and for the cookie to be
** set back to prior value. But schema changes are infrequent
** and the probability of hitting the same cookie value is only
** 1 chance in 2^32. So we're safe enough.
**
** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
** the schema-version whenever the schema changes.
*/
void sqlite3ChangeCookie(Parse *pParse, int iDb){
sqlite3 *db = pParse->db;
Vdbe *v = pParse->pVdbe;
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
(int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
}
/*
** Measure the number of characters needed to output the given
** identifier. The number returned includes any quotes used
** but does not include the null terminator.
**
** The estimate is conservative. It might be larger that what is
** really needed.
*/
static int identLength(const char *z){
int n;
for(n=0; *z; n++, z++){
if( *z=='"' ){ n++; }
}
return n + 2;
}
/*
** The first parameter is a pointer to an output buffer. The second
** parameter is a pointer to an integer that contains the offset at
** which to write into the output buffer. This function copies the
** nul-terminated string pointed to by the third parameter, zSignedIdent,
** to the specified offset in the buffer and updates *pIdx to refer
** to the first byte after the last byte written before returning.
**
** If the string zSignedIdent consists entirely of alpha-numeric
** characters, does not begin with a digit and is not an SQL keyword,
** then it is copied to the output buffer exactly as it is. Otherwise,
** it is quoted using double-quotes.
*/
static void identPut(char *z, int *pIdx, char *zSignedIdent){
unsigned char *zIdent = (unsigned char*)zSignedIdent;
int i, j, needQuote;
i = *pIdx;
for(j=0; zIdent[j]; j++){
if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
}
needQuote = sqlite3Isdigit(zIdent[0])
|| sqlite3KeywordCode(zIdent, j)!=TK_ID
|| zIdent[j]!=0
|| j==0;
if( needQuote ) z[i++] = '"';
for(j=0; zIdent[j]; j++){
z[i++] = zIdent[j];
if( zIdent[j]=='"' ) z[i++] = '"';
}
if( needQuote ) z[i++] = '"';
z[i] = 0;
*pIdx = i;
}
/*
** Generate a CREATE TABLE statement appropriate for the given
** table. Memory to hold the text of the statement is obtained
** from sqliteMalloc() and must be freed by the calling function.
*/
static char *createTableStmt(sqlite3 *db, Table *p){
int i, k, n;
char *zStmt;
char *zSep, *zSep2, *zEnd;
Column *pCol;
n = 0;
for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
n += identLength(pCol->zName) + 5;
}
n += identLength(p->zName);
if( n<50 ){
zSep = "";
zSep2 = ",";
zEnd = ")";
}else{
zSep = "\n ";
zSep2 = ",\n ";
zEnd = "\n)";
}
n += 35 + 6*p->nCol;
zStmt = sqlite3DbMallocRaw(0, n);
if( zStmt==0 ){
sqlite3OomFault(db);
return 0;
}
sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
k = sqlite3Strlen30(zStmt);
identPut(zStmt, &k, p->zName);
zStmt[k++] = '(';
for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
static const char * const azType[] = {
/* SQLITE_AFF_BLOB */ "",
/* SQLITE_AFF_TEXT */ " TEXT",
/* SQLITE_AFF_NUMERIC */ " NUM",
/* SQLITE_AFF_INTEGER */ " INT",
/* SQLITE_AFF_REAL */ " REAL"
};
int len;
const char *zType;
sqlite3_snprintf(n-k, &zStmt[k], zSep);
k += sqlite3Strlen30(&zStmt[k]);
zSep = zSep2;
identPut(zStmt, &k, pCol->zName);
assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
testcase( pCol->affinity==SQLITE_AFF_BLOB );
testcase( pCol->affinity==SQLITE_AFF_TEXT );
testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
testcase( pCol->affinity==SQLITE_AFF_INTEGER );
testcase( pCol->affinity==SQLITE_AFF_REAL );
zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
len = sqlite3Strlen30(zType);
assert( pCol->affinity==SQLITE_AFF_BLOB
|| pCol->affinity==sqlite3AffinityType(zType, 0) );
memcpy(&zStmt[k], zType, len);
k += len;
assert( k<=n );
}
sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
return zStmt;
}
/*
** Resize an Index object to hold N columns total. Return SQLITE_OK
** on success and SQLITE_NOMEM on an OOM error.
*/
static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
char *zExtra;
int nByte;
if( pIdx->nColumn>=N ) return SQLITE_OK;
assert( pIdx->isResized==0 );
nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
zExtra = sqlite3DbMallocZero(db, nByte);
if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
pIdx->azColl = (const char**)zExtra;
zExtra += sizeof(char*)*N;
memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
pIdx->aiColumn = (i16*)zExtra;
zExtra += sizeof(i16)*N;
memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
pIdx->aSortOrder = (u8*)zExtra;
pIdx->nColumn = N;
pIdx->isResized = 1;
return SQLITE_OK;
}
/*
** Estimate the total row width for a table.
*/
static void estimateTableWidth(Table *pTab){
unsigned wTable = 0;
const Column *pTabCol;
int i;
for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
wTable += pTabCol->szEst;
}
if( pTab->iPKey<0 ) wTable++;
pTab->szTabRow = sqlite3LogEst(wTable*4);
}
/*
** Estimate the average size of a row for an index.
*/
static void estimateIndexWidth(Index *pIdx){
unsigned wIndex = 0;
int i;
const Column *aCol = pIdx->pTable->aCol;
for(i=0; i<pIdx->nColumn; i++){
i16 x = pIdx->aiColumn[i];
assert( x<pIdx->pTable->nCol );
wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
}
pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
}
/* Return true if column number x is any of the first nCol entries of aiCol[].
** This is used to determine if the column number x appears in any of the
** first nCol entries of an index.
*/
static int hasColumn(const i16 *aiCol, int nCol, int x){
while( nCol-- > 0 ){
assert( aiCol[0]>=0 );
if( x==*(aiCol++) ){
return 1;
}
}
return 0;
}
/*
** Return true if any of the first nKey entries of index pIdx exactly
** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID
** PRIMARY KEY index. pIdx is an index on the same table. pIdx may
** or may not be the same index as pPk.
**
** The first nKey entries of pIdx are guaranteed to be ordinary columns,
** not a rowid or expression.
**
** This routine differs from hasColumn() in that both the column and the
** collating sequence must match for this routine, but for hasColumn() only
** the column name must match.
*/
static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
int i, j;
assert( nKey<=pIdx->nColumn );
assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
assert( pPk->pTable->tabFlags & TF_WithoutRowid );
assert( pPk->pTable==pIdx->pTable );
testcase( pPk==pIdx );
j = pPk->aiColumn[iCol];
assert( j!=XN_ROWID && j!=XN_EXPR );
for(i=0; i<nKey; i++){
assert( pIdx->aiColumn[i]>=0 || j>=0 );
if( pIdx->aiColumn[i]==j
&& sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
){
return 1;
}
}
return 0;
}
/* Recompute the colNotIdxed field of the Index.
**
** colNotIdxed is a bitmask that has a 0 bit representing each indexed
** columns that are within the first 63 columns of the table. The
** high-order bit of colNotIdxed is always 1. All unindexed columns
** of the table have a 1.
**
** 2019-10-24: For the purpose of this computation, virtual columns are
** not considered to be covered by the index, even if they are in the
** index, because we do not trust the logic in whereIndexExprTrans() to be
** able to find all instances of a reference to the indexed table column
** and convert them into references to the index. Hence we always want
** the actual table at hand in order to recompute the virtual column, if
** necessary.
**
** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
** to determine if the index is covering index.
*/
static void recomputeColumnsNotIndexed(Index *pIdx){
Bitmask m = 0;
int j;
Table *pTab = pIdx->pTable;
for(j=pIdx->nColumn-1; j>=0; j--){
int x = pIdx->aiColumn[j];
if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
testcase( x==BMS-1 );
testcase( x==BMS-2 );
if( x<BMS-1 ) m |= MASKBIT(x);
}
}
pIdx->colNotIdxed = ~m;
assert( (pIdx->colNotIdxed>>63)==1 );
}
/*
** This routine runs at the end of parsing a CREATE TABLE statement that
** has a WITHOUT ROWID clause. The job of this routine is to convert both
** internal schema data structures and the generated VDBE code so that they
** are appropriate for a WITHOUT ROWID table instead of a rowid table.
** Changes include:
**
** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
** into BTREE_BLOBKEY.
** (3) Bypass the creation of the sqlite_master table entry
** for the PRIMARY KEY as the primary key index is now
** identified by the sqlite_master table entry of the table itself.
** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
** schema to the rootpage from the main table.
** (5) Add all table columns to the PRIMARY KEY Index object
** so that the PRIMARY KEY is a covering index. The surplus
** columns are part of KeyInfo.nAllField and are not used for
** sorting or lookup or uniqueness checks.
** (6) Replace the rowid tail on all automatically generated UNIQUE
** indices with the PRIMARY KEY columns.
**
** For virtual tables, only (1) is performed.
*/
static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
Index *pIdx;
Index *pPk;
int nPk;
int nExtra;
int i, j;
sqlite3 *db = pParse->db;
Vdbe *v = pParse->pVdbe;
/* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
*/
if( !db->init.imposterTable ){
for(i=0; i<pTab->nCol; i++){
if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0 ){
pTab->aCol[i].notNull = OE_Abort;
}
}
pTab->tabFlags |= TF_HasNotNull;
}
/* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
** into BTREE_BLOBKEY.
*/
if( pParse->addrCrTab ){
assert( v );
sqlite3VdbeChangeP3(v, pParse->addrCrTab, BTREE_BLOBKEY);
}
/* Locate the PRIMARY KEY index. Or, if this table was originally
** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
*/
if( pTab->iPKey>=0 ){
ExprList *pList;
Token ipkToken;
sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
pList = sqlite3ExprListAppend(pParse, 0,
sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
if( pList==0 ) return;
if( IN_RENAME_OBJECT ){
sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
}
pList->a[0].sortFlags = pParse->iPkSortOrder;
assert( pParse->pNewTable==pTab );
pTab->iPKey = -1;
sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
SQLITE_IDXTYPE_PRIMARYKEY);
if( db->mallocFailed || pParse->nErr ) return;
pPk = sqlite3PrimaryKeyIndex(pTab);
assert( pPk->nKeyCol==1 );
}else{
pPk = sqlite3PrimaryKeyIndex(pTab);
assert( pPk!=0 );
/*
** Remove all redundant columns from the PRIMARY KEY. For example, change
** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
** code assumes the PRIMARY KEY contains no repeated columns.
*/
for(i=j=1; i<pPk->nKeyCol; i++){
if( isDupColumn(pPk, j, pPk, i) ){
pPk->nColumn--;
}else{
testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
pPk->azColl[j] = pPk->azColl[i];
pPk->aSortOrder[j] = pPk->aSortOrder[i];
pPk->aiColumn[j++] = pPk->aiColumn[i];
}
}
pPk->nKeyCol = j;
}
assert( pPk!=0 );
pPk->isCovering = 1;
if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
nPk = pPk->nColumn = pPk->nKeyCol;
/* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
** table entry. This is only required if currently generating VDBE
** code for a CREATE TABLE (not when parsing one as part of reading
** a database schema). */
if( v && pPk->tnum>0 ){
assert( db->init.busy==0 );
sqlite3VdbeChangeOpcode(v, pPk->tnum, OP_Goto);
}
/* The root page of the PRIMARY KEY is the table root page */
pPk->tnum = pTab->tnum;
/* Update the in-memory representation of all UNIQUE indices by converting
** the final rowid column into one or more columns of the PRIMARY KEY.
*/
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
int n;
if( IsPrimaryKeyIndex(pIdx) ) continue;
for(i=n=0; i<nPk; i++){
if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
n++;
}
}
if( n==0 ){
/* This index is a superset of the primary key */
pIdx->nColumn = pIdx->nKeyCol;
continue;
}
if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
pIdx->aiColumn[j] = pPk->aiColumn[i];
pIdx->azColl[j] = pPk->azColl[i];
if( pPk->aSortOrder[i] ){
/* See ticket https://www.sqlite.org/src/info/bba7b69f9849b5bf */
pIdx->bAscKeyBug = 1;
}
j++;
}
}
assert( pIdx->nColumn>=pIdx->nKeyCol+n );
assert( pIdx->nColumn>=j );
}
/* Add all table columns to the PRIMARY KEY index
*/
nExtra = 0;
for(i=0; i<pTab->nCol; i++){
if( !hasColumn(pPk->aiColumn, nPk, i)
&& (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
}
if( resizeIndexObject(db, pPk, nPk+nExtra) ) return;
for(i=0, j=nPk; i<pTab->nCol; i++){
if( !hasColumn(pPk->aiColumn, j, i)
&& (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
){
assert( j<pPk->nColumn );
pPk->aiColumn[j] = i;
pPk->azColl[j] = sqlite3StrBINARY;
j++;
}
}
assert( pPk->nColumn==j );
assert( pTab->nNVCol<=j );
recomputeColumnsNotIndexed(pPk);
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
/*
** Return true if zName is a shadow table name in the current database
** connection.
**
** zName is temporarily modified while this routine is running, but is
** restored to its original value prior to this routine returning.
*/
int sqlite3ShadowTableName(sqlite3 *db, const char *zName){
char *zTail; /* Pointer to the last "_" in zName */
Table *pTab; /* Table that zName is a shadow of */
Module *pMod; /* Module for the virtual table */
zTail = strrchr(zName, '_');
if( zTail==0 ) return 0;
*zTail = 0;
pTab = sqlite3FindTable(db, zName, 0);
*zTail = '_';
if( pTab==0 ) return 0;
if( !IsVirtual(pTab) ) return 0;
pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->azModuleArg[0]);
if( pMod==0 ) return 0;
if( pMod->pModule->iVersion<3 ) return 0;
if( pMod->pModule->xShadowName==0 ) return 0;
return pMod->pModule->xShadowName(zTail+1);
}
#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
/*
** This routine is called to report the final ")" that terminates
** a CREATE TABLE statement.
**
** The table structure that other action routines have been building
** is added to the internal hash tables, assuming no errors have
** occurred.
**
** An entry for the table is made in the master table on disk, unless
** this is a temporary table or db->init.busy==1. When db->init.busy==1
** it means we are reading the sqlite_master table because we just
** connected to the database or because the sqlite_master table has
** recently changed, so the entry for this table already exists in
** the sqlite_master table. We do not want to create it again.
**
** If the pSelect argument is not NULL, it means that this routine
** was called to create a table generated from a
** "CREATE TABLE ... AS SELECT ..." statement. The column names of
** the new table will match the result set of the SELECT.
*/
void sqlite3EndTable(
Parse *pParse, /* Parse context */
Token *pCons, /* The ',' token after the last column defn. */
Token *pEnd, /* The ')' before options in the CREATE TABLE */
u8 tabOpts, /* Extra table options. Usually 0. */
Select *pSelect /* Select from a "CREATE ... AS SELECT" */
){
Table *p; /* The new table */
sqlite3 *db = pParse->db; /* The database connection */
int iDb; /* Database in which the table lives */
Index *pIdx; /* An implied index of the table */
if( pEnd==0 && pSelect==0 ){
return;
}
assert( !db->mallocFailed );
p = pParse->pNewTable;
if( p==0 ) return;
if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
p->tabFlags |= TF_Shadow;
}
/* If the db->init.busy is 1 it means we are reading the SQL off the
** "sqlite_master" or "sqlite_temp_master" table on the disk.
** So do not write to the disk again. Extract the root page number
** for the table from the db->init.newTnum field. (The page number
** should have been put there by the sqliteOpenCb routine.)
**
** If the root page number is 1, that means this is the sqlite_master
** table itself. So mark it read-only.
*/
if( db->init.busy ){
if( pSelect ){
sqlite3ErrorMsg(pParse, "");
return;
}
p->tnum = db->init.newTnum;
if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
}
assert( (p->tabFlags & TF_HasPrimaryKey)==0
|| p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
assert( (p->tabFlags & TF_HasPrimaryKey)!=0
|| (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
/* Special processing for WITHOUT ROWID Tables */
if( tabOpts & TF_WithoutRowid ){
if( (p->tabFlags & TF_Autoincrement) ){
sqlite3ErrorMsg(pParse,
"AUTOINCREMENT not allowed on WITHOUT ROWID tables");
return;
}
if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
return;
}
p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
convertToWithoutRowidTable(pParse, p);
}
iDb = sqlite3SchemaToIndex(db, p->pSchema);
#ifndef SQLITE_OMIT_CHECK
/* Resolve names in all CHECK constraint expressions.
*/
if( p->pCheck ){
sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
}
#endif /* !defined(SQLITE_OMIT_CHECK) */
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
if( p->tabFlags & TF_HasGenerated ){
int ii, nNG = 0;
testcase( p->tabFlags & TF_HasVirtual );
testcase( p->tabFlags & TF_HasStored );
for(ii=0; ii<p->nCol; ii++){
u32 colFlags = p->aCol[ii].colFlags;
if( (colFlags & COLFLAG_GENERATED)!=0 ){
testcase( colFlags & COLFLAG_VIRTUAL );
testcase( colFlags & COLFLAG_STORED );
sqlite3ResolveSelfReference(pParse, p, NC_GenCol,
p->aCol[ii].pDflt, 0);
}else{
nNG++;
}
}
if( nNG==0 ){
sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
return;
}
}
#endif
/* Estimate the average row size for the table and for all implied indices */
estimateTableWidth(p);
for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
estimateIndexWidth(pIdx);
}
/* If not initializing, then create a record for the new table
** in the SQLITE_MASTER table of the database.
**
** If this is a TEMPORARY table, write the entry into the auxiliary
** file instead of into the main database file.
*/
if( !db->init.busy ){
int n;
Vdbe *v;
char *zType; /* "view" or "table" */
char *zType2; /* "VIEW" or "TABLE" */
char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
v = sqlite3GetVdbe(pParse);
if( NEVER(v==0) ) return;
sqlite3VdbeAddOp1(v, OP_Close, 0);
/*
** Initialize zType for the new view or table.
*/
if( p->pSelect==0 ){
/* A regular table */
zType = "table";
zType2 = "TABLE";
#ifndef SQLITE_OMIT_VIEW
}else{
/* A view */
zType = "view";
zType2 = "VIEW";
#endif
}
/* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
** statement to populate the new table. The root-page number for the
** new table is in register pParse->regRoot.
**
** Once the SELECT has been coded by sqlite3Select(), it is in a
** suitable state to query for the column names and types to be used
** by the new table.
**
** A shared-cache write-lock is not required to write to the new table,
** as a schema-lock must have already been obtained to create it. Since
** a schema-lock excludes all other database users, the write-lock would
** be redundant.
*/
if( pSelect ){
SelectDest dest; /* Where the SELECT should store results */
int regYield; /* Register holding co-routine entry-point */
int addrTop; /* Top of the co-routine */
int regRec; /* A record to be insert into the new table */
int regRowid; /* Rowid of the next row to insert */
int addrInsLoop; /* Top of the loop for inserting rows */
Table *pSelTab; /* A table that describes the SELECT results */
regYield = ++pParse->nMem;
regRec = ++pParse->nMem;
regRowid = ++pParse->nMem;
assert(pParse->nTab==1);
sqlite3MayAbort(pParse);
sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
pParse->nTab = 2;
addrTop = sqlite3VdbeCurrentAddr(v) + 1;
sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
if( pParse->nErr ) return;
pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB);
if( pSelTab==0 ) return;
assert( p->aCol==0 );
p->nCol = p->nNVCol = pSelTab->nCol;
p->aCol = pSelTab->aCol;
pSelTab->nCol = 0;
pSelTab->aCol = 0;
sqlite3DeleteTable(db, pSelTab);
sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
sqlite3Select(pParse, pSelect, &dest);
if( pParse->nErr ) return;
sqlite3VdbeEndCoroutine(v, regYield);
sqlite3VdbeJumpHere(v, addrTop - 1);
addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
sqlite3TableAffinity(v, p, 0);
sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
sqlite3VdbeGoto(v, addrInsLoop);
sqlite3VdbeJumpHere(v, addrInsLoop);
sqlite3VdbeAddOp1(v, OP_Close, 1);
}
/* Compute the complete text of the CREATE statement */
if( pSelect ){
zStmt = createTableStmt(db, p);
}else{
Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
n = (int)(pEnd2->z - pParse->sNameToken.z);
if( pEnd2->z[0]!=';' ) n += pEnd2->n;
zStmt = sqlite3MPrintf(db,
"CREATE %s %.*s", zType2, n, pParse->sNameToken.z
);
}
/* A slot for the record has already been allocated in the
** SQLITE_MASTER table. We just need to update that slot with all
** the information we've collected.
*/
sqlite3NestedParse(pParse,
"UPDATE %Q.%s "
"SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
"WHERE rowid=#%d",
db->aDb[iDb].zDbSName, MASTER_NAME,
zType,
p->zName,
p->zName,
pParse->regRoot,
zStmt,
pParse->regRowid
);
sqlite3DbFree(db, zStmt);
sqlite3ChangeCookie(pParse, iDb);
#ifndef SQLITE_OMIT_AUTOINCREMENT
/* Check to see if we need to create an sqlite_sequence table for
** keeping track of autoincrement keys.
*/
if( (p->tabFlags & TF_Autoincrement)!=0 ){
Db *pDb = &db->aDb[iDb];
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
if( pDb->pSchema->pSeqTab==0 ){
sqlite3NestedParse(pParse,
"CREATE TABLE %Q.sqlite_sequence(name,seq)",
pDb->zDbSName
);
}
}
#endif
/* Reparse everything to update our internal data structures */
sqlite3VdbeAddParseSchemaOp(v, iDb,
sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
}
/* Add the table to the in-memory representation of the database.
*/
if( db->init.busy ){
Table *pOld;
Schema *pSchema = p->pSchema;
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
if( pOld ){
assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
sqlite3OomFault(db);
return;
}
pParse->pNewTable = 0;
db->mDbFlags |= DBFLAG_SchemaChange;
#ifndef SQLITE_OMIT_ALTERTABLE
if( !p->pSelect ){
const char *zName = (const char *)pParse->sNameToken.z;
int nName;
assert( !pSelect && pCons && pEnd );
if( pCons->z==0 ){
pCons = pEnd;
}
nName = (int)((const char *)pCons->z - zName);
p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
}
#endif
}
}
#ifndef SQLITE_OMIT_VIEW
/*
** The parser calls this routine in order to create a new VIEW
*/
void sqlite3CreateView(
Parse *pParse, /* The parsing context */
Token *pBegin, /* The CREATE token that begins the statement */
Token *pName1, /* The token that holds the name of the view */
Token *pName2, /* The token that holds the name of the view */
ExprList *pCNames, /* Optional list of view column names */
Select *pSelect, /* A SELECT statement that will become the new view */
int isTemp, /* TRUE for a TEMPORARY view */
int noErr /* Suppress error messages if VIEW already exists */
){
Table *p;
int n;
const char *z;
Token sEnd;
DbFixer sFix;
Token *pName = 0;
int iDb;
sqlite3 *db = pParse->db;
if( pParse->nVar>0 ){
sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
goto create_view_fail;
}
sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
p = pParse->pNewTable;
if( p==0 || pParse->nErr ) goto create_view_fail;
sqlite3TwoPartName(pParse, pName1, pName2, &pName);
iDb = sqlite3SchemaToIndex(db, p->pSchema);
sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
/* Make a copy of the entire SELECT statement that defines the view.
** This will force all the Expr.token.z values to be dynamically
** allocated rather than point to the input string - which means that
** they will persist after the current sqlite3_exec() call returns.
*/
if( IN_RENAME_OBJECT ){
p->pSelect = pSelect;
pSelect = 0;
}else{
p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
}
p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
if( db->mallocFailed ) goto create_view_fail;
/* Locate the end of the CREATE VIEW statement. Make sEnd point to
** the end.
*/
sEnd = pParse->sLastToken;
assert( sEnd.z[0]!=0 || sEnd.n==0 );
if( sEnd.z[0]!=';' ){
sEnd.z += sEnd.n;
}
sEnd.n = 0;
n = (int)(sEnd.z - pBegin->z);
assert( n>0 );
z = pBegin->z;
while( sqlite3Isspace(z[n-1]) ){ n--; }
sEnd.z = &z[n-1];
sEnd.n = 1;
/* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
create_view_fail:
sqlite3SelectDelete(db, pSelect);
if( IN_RENAME_OBJECT ){
sqlite3RenameExprlistUnmap(pParse, pCNames);
}
sqlite3ExprListDelete(db, pCNames);
return;
}
#endif /* SQLITE_OMIT_VIEW */
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
/*
** The Table structure pTable is really a VIEW. Fill in the names of
** the columns of the view in the pTable structure. Return the number
** of errors. If an error is seen leave an error message in pParse->zErrMsg.
*/
int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
Table *pSelTab; /* A fake table from which we get the result set */
Select *pSel; /* Copy of the SELECT that implements the view */
int nErr = 0; /* Number of errors encountered */
int n; /* Temporarily holds the number of cursors assigned */
sqlite3 *db = pParse->db; /* Database connection for malloc errors */
#ifndef SQLITE_OMIT_VIRTUALTABLE
int rc;
#endif
#ifndef SQLITE_OMIT_AUTHORIZATION
sqlite3_xauth xAuth; /* Saved xAuth pointer */
#endif
assert( pTable );
#ifndef SQLITE_OMIT_VIRTUALTABLE
db->nSchemaLock++;
rc = sqlite3VtabCallConnect(pParse, pTable);
db->nSchemaLock--;
if( rc ){
return 1;
}
if( IsVirtual(pTable) ) return 0;
#endif
#ifndef SQLITE_OMIT_VIEW
/* A positive nCol means the columns names for this view are
** already known.
*/
if( pTable->nCol>0 ) return 0;
/* A negative nCol is a special marker meaning that we are currently
** trying to compute the column names. If we enter this routine with
** a negative nCol, it means two or more views form a loop, like this:
**
** CREATE VIEW one AS SELECT * FROM two;
** CREATE VIEW two AS SELECT * FROM one;
**
** Actually, the error above is now caught prior to reaching this point.
** But the following test is still important as it does come up
** in the following:
**
** CREATE TABLE main.ex1(a);
** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
** SELECT * FROM temp.ex1;
*/
if( pTable->nCol<0 ){
sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
return 1;
}
assert( pTable->nCol>=0 );
/* If we get this far, it means we need to compute the table names.
** Note that the call to sqlite3ResultSetOfSelect() will expand any
** "*" elements in the results set of the view and will assign cursors
** to the elements of the FROM clause. But we do not want these changes
** to be permanent. So the computation is done on a copy of the SELECT
** statement that defines the view.
*/
assert( pTable->pSelect );
pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
if( pSel ){
#ifndef SQLITE_OMIT_ALTERTABLE
u8 eParseMode = pParse->eParseMode;
pParse->eParseMode = PARSE_MODE_NORMAL;
#endif
n = pParse->nTab;
sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
pTable->nCol = -1;
DisableLookaside;
#ifndef SQLITE_OMIT_AUTHORIZATION
xAuth = db->xAuth;
db->xAuth = 0;
pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
db->xAuth = xAuth;
#else
pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
#endif
pParse->nTab = n;
if( pTable->pCheck ){
/* CREATE VIEW name(arglist) AS ...
** The names of the columns in the table are taken from
** arglist which is stored in pTable->pCheck. The pCheck field
** normally holds CHECK constraints on an ordinary table, but for
** a VIEW it holds the list of column names.
*/
sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
&pTable->nCol, &pTable->aCol);
if( db->mallocFailed==0
&& pParse->nErr==0
&& pTable->nCol==pSel->pEList->nExpr
){
sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel,
SQLITE_AFF_NONE);
}
}else if( pSelTab ){
/* CREATE VIEW name AS... without an argument list. Construct
** the column names from the SELECT statement that defines the view.
*/
assert( pTable->aCol==0 );
pTable->nCol = pSelTab->nCol;
pTable->aCol = pSelTab->aCol;
pSelTab->nCol = 0;
pSelTab->aCol = 0;
assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
}else{
pTable->nCol = 0;
nErr++;
}
pTable->nNVCol = pTable->nCol;
sqlite3DeleteTable(db, pSelTab);
sqlite3SelectDelete(db, pSel);
EnableLookaside;
#ifndef SQLITE_OMIT_ALTERTABLE
pParse->eParseMode = eParseMode;
#endif
} else {
nErr++;
}
pTable->pSchema->schemaFlags |= DB_UnresetViews;
if( db->mallocFailed ){
sqlite3DeleteColumnNames(db, pTable);
pTable->aCol = 0;
pTable->nCol = 0;
}
#endif /* SQLITE_OMIT_VIEW */
return nErr;
}
#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
#ifndef SQLITE_OMIT_VIEW
/*
** Clear the column names from every VIEW in database idx.
*/
static void sqliteViewResetAll(sqlite3 *db, int idx){
HashElem *i;
assert( sqlite3SchemaMutexHeld(db, idx, 0) );
if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
Table *pTab = sqliteHashData(i);
if( pTab->pSelect ){
sqlite3DeleteColumnNames(db, pTab);
pTab->aCol = 0;
pTab->nCol = 0;
}
}
DbClearProperty(db, idx, DB_UnresetViews);
}
#else
# define sqliteViewResetAll(A,B)
#endif /* SQLITE_OMIT_VIEW */
/*
** This function is called by the VDBE to adjust the internal schema
** used by SQLite when the btree layer moves a table root page. The
** root-page of a table or index in database iDb has changed from iFrom
** to iTo.
**
** Ticket #1728: The symbol table might still contain information
** on tables and/or indices that are the process of being deleted.
** If you are unlucky, one of those deleted indices or tables might
** have the same rootpage number as the real table or index that is
** being moved. So we cannot stop searching after the first match
** because the first match might be for one of the deleted indices
** or tables and not the table/index that is actually being moved.
** We must continue looping until all tables and indices with
** rootpage==iFrom have been converted to have a rootpage of iTo
** in order to be certain that we got the right one.
*/
#ifndef SQLITE_OMIT_AUTOVACUUM
void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
HashElem *pElem;
Hash *pHash;
Db *pDb;
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
pDb = &db->aDb[iDb];
pHash = &pDb->pSchema->tblHash;
for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
Table *pTab = sqliteHashData(pElem);
if( pTab->tnum==iFrom ){
pTab->tnum = iTo;
}
}
pHash = &pDb->pSchema->idxHash;
for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
Index *pIdx = sqliteHashData(pElem);
if( pIdx->tnum==iFrom ){
pIdx->tnum = iTo;
}
}
}
#endif
/*
** Write code to erase the table with root-page iTable from database iDb.
** Also write code to modify the sqlite_master table and internal schema
** if a root-page of another table is moved by the btree-layer whilst
** erasing iTable (this can happen with an auto-vacuum database).
*/
static void destroyRootPage(Parse *pParse, int iTable, int iDb){
Vdbe *v = sqlite3GetVdbe(pParse);
int r1 = sqlite3GetTempReg(pParse);
if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
sqlite3MayAbort(pParse);
#ifndef SQLITE_OMIT_AUTOVACUUM
/* OP_Destroy stores an in integer r1. If this integer
** is non-zero, then it is the root page number of a table moved to
** location iTable. The following code modifies the sqlite_master table to
** reflect this.
**
** The "#NNN" in the SQL is a special constant that means whatever value
** is in register NNN. See grammar rules associated with the TK_REGISTER
** token for additional information.
*/
sqlite3NestedParse(pParse,
"UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
pParse->db->aDb[iDb].zDbSName, MASTER_NAME, iTable, r1, r1);
#endif
sqlite3ReleaseTempReg(pParse, r1);
}
/*
** Write VDBE code to erase table pTab and all associated indices on disk.
** Code to update the sqlite_master tables and internal schema definitions
** in case a root-page belonging to another table is moved by the btree layer
** is also added (this can happen with an auto-vacuum database).
*/
static void destroyTable(Parse *pParse, Table *pTab){
/* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
** is not defined), then it is important to call OP_Destroy on the
** table and index root-pages in order, starting with the numerically
** largest root-page number. This guarantees that none of the root-pages
** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
** following were coded:
**
** OP_Destroy 4 0
** ...
** OP_Destroy 5 0
**
** and root page 5 happened to be the largest root-page number in the
** database, then root page 5 would be moved to page 4 by the
** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
** a free-list page.
*/
int iTab = pTab->tnum;
int iDestroyed = 0;
while( 1 ){
Index *pIdx;
int iLargest = 0;
if( iDestroyed==0 || iTab<iDestroyed ){
iLargest = iTab;
}
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
int iIdx = pIdx->tnum;
assert( pIdx->pSchema==pTab->pSchema );
if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
iLargest = iIdx;
}
}
if( iLargest==0 ){
return;
}else{
int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
assert( iDb>=0 && iDb<pParse->db->nDb );
destroyRootPage(pParse, iLargest, iDb);
iDestroyed = iLargest;
}
}
}
/*
** Remove entries from the sqlite_statN tables (for N in (1,2,3))
** after a DROP INDEX or DROP TABLE command.
*/
static void sqlite3ClearStatTables(
Parse *pParse, /* The parsing context */
int iDb, /* The database number */
const char *zType, /* "idx" or "tbl" */
const char *zName /* Name of index or table */
){
int i;
const char *zDbName = pParse->db->aDb[iDb].zDbSName;
for(i=1; i<=4; i++){
char zTab[24];
sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
sqlite3NestedParse(pParse,
"DELETE FROM %Q.%s WHERE %s=%Q",
zDbName, zTab, zType, zName
);
}
}
}
/*
** Generate code to drop a table.
*/
void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
Vdbe *v;
sqlite3 *db = pParse->db;
Trigger *pTrigger;
Db *pDb = &db->aDb[iDb];
v = sqlite3GetVdbe(pParse);
assert( v!=0 );
sqlite3BeginWriteOperation(pParse, 1, iDb);
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( IsVirtual(pTab) ){
sqlite3VdbeAddOp0(v, OP_VBegin);
}
#endif
/* Drop all triggers associated with the table being dropped. Code
** is generated to remove entries from sqlite_master and/or
** sqlite_temp_master if required.
*/
pTrigger = sqlite3TriggerList(pParse, pTab);
while( pTrigger ){
assert( pTrigger->pSchema==pTab->pSchema ||
pTrigger->pSchema==db->aDb[1].pSchema );
sqlite3DropTriggerPtr(pParse, pTrigger);
pTrigger = pTrigger->pNext;
}
#ifndef SQLITE_OMIT_AUTOINCREMENT
/* Remove any entries of the sqlite_sequence table associated with
** the table being dropped. This is done before the table is dropped
** at the btree level, in case the sqlite_sequence table needs to
** move as a result of the drop (can happen in auto-vacuum mode).
*/
if( pTab->tabFlags & TF_Autoincrement ){
sqlite3NestedParse(pParse,
"DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
pDb->zDbSName, pTab->zName
);
}
#endif
/* Drop all SQLITE_MASTER table and index entries that refer to the
** table. The program name loops through the master table and deletes
** every row that refers to a table of the same name as the one being
** dropped. Triggers are handled separately because a trigger can be
** created in the temp database that refers to a table in another
** database.
*/
sqlite3NestedParse(pParse,
"DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
pDb->zDbSName, MASTER_NAME, pTab->zName);
if( !isView && !IsVirtual(pTab) ){
destroyTable(pParse, pTab);
}
/* Remove the table entry from SQLite's internal schema and modify
** the schema cookie.
*/
if( IsVirtual(pTab) ){
sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
sqlite3MayAbort(pParse);
}
sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
sqlite3ChangeCookie(pParse, iDb);
sqliteViewResetAll(db, iDb);
}
/*
** Return TRUE if shadow tables should be read-only in the current
** context.
*/
int sqlite3ReadOnlyShadowTables(sqlite3 *db){
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( (db->flags & SQLITE_Defensive)!=0
&& db->pVtabCtx==0
&& db->nVdbeExec==0
){
return 1;
}
#endif
return 0;
}
/*
** Return true if it is not allowed to drop the given table
*/
static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){
if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
return 1;
}
if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
return 1;
}
return 0;
}
/*
** This routine is called to do the work of a DROP TABLE statement.
** pName is the name of the table to be dropped.
*/
void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
Table *pTab;
Vdbe *v;
sqlite3 *db = pParse->db;
int iDb;
if( db->mallocFailed ){
goto exit_drop_table;
}
assert( pParse->nErr==0 );
assert( pName->nSrc==1 );
if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
if( noErr ) db->suppressErr++;
assert( isView==0 || isView==LOCATE_VIEW );
pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
if( noErr ) db->suppressErr--;
if( pTab==0 ){
if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
goto exit_drop_table;
}
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
assert( iDb>=0 && iDb<db->nDb );
/* If pTab is a virtual table, call ViewGetColumnNames() to ensure
** it is initialized.
*/
if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
goto exit_drop_table;
}
#ifndef SQLITE_OMIT_AUTHORIZATION
{
int code;
const char *zTab = SCHEMA_TABLE(iDb);
const char *zDb = db->aDb[iDb].zDbSName;
const char *zArg2 = 0;
if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
goto exit_drop_table;
}
if( isView ){
if( !OMIT_TEMPDB && iDb==1 ){
code = SQLITE_DROP_TEMP_VIEW;
}else{
code = SQLITE_DROP_VIEW;
}
#ifndef SQLITE_OMIT_VIRTUALTABLE
}else if( IsVirtual(pTab) ){
code = SQLITE_DROP_VTABLE;
zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
#endif
}else{
if( !OMIT_TEMPDB && iDb==1 ){
code = SQLITE_DROP_TEMP_TABLE;
}else{
code = SQLITE_DROP_TABLE;
}
}
if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
goto exit_drop_table;
}
if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
goto exit_drop_table;
}
}
#endif
if( tableMayNotBeDropped(db, pTab) ){
sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
goto exit_drop_table;
}
#ifndef SQLITE_OMIT_VIEW
/* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
** on a table.
*/
if( isView && pTab->pSelect==0 ){
sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
goto exit_drop_table;
}
if( !isView && pTab->pSelect ){
sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
goto exit_drop_table;
}
#endif
/* Generate code to remove the table from the master table
** on disk.
*/
v = sqlite3GetVdbe(pParse);
if( v ){
sqlite3BeginWriteOperation(pParse, 1, iDb);
if( !isView ){
sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
sqlite3FkDropTable(pParse, pName, pTab);
}
sqlite3CodeDropTable(pParse, pTab, iDb, isView);
}
exit_drop_table:
sqlite3SrcListDelete(db, pName);
}
/*
** This routine is called to create a new foreign key on the table
** currently under construction. pFromCol determines which columns
** in the current table point to the foreign key. If pFromCol==0 then
** connect the key to the last column inserted. pTo is the name of
** the table referred to (a.k.a the "parent" table). pToCol is a list
** of tables in the parent pTo table. flags contains all
** information about the conflict resolution algorithms specified
** in the ON DELETE, ON UPDATE and ON INSERT clauses.
**
** An FKey structure is created and added to the table currently
** under construction in the pParse->pNewTable field.
**
** The foreign key is set for IMMEDIATE processing. A subsequent call
** to sqlite3DeferForeignKey() might change this to DEFERRED.
*/
void sqlite3CreateForeignKey(
Parse *pParse, /* Parsing context */
ExprList *pFromCol, /* Columns in this table that point to other table */
Token *pTo, /* Name of the other table */
ExprList *pToCol, /* Columns in the other table */
int flags /* Conflict resolution algorithms. */
){
sqlite3 *db = pParse->db;
#ifndef SQLITE_OMIT_FOREIGN_KEY
FKey *pFKey = 0;
FKey *pNextTo;
Table *p = pParse->pNewTable;
int nByte;
int i;
int nCol;
char *z;
assert( pTo!=0 );
if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
if( pFromCol==0 ){
int iCol = p->nCol-1;
if( NEVER(iCol<0) ) goto fk_end;
if( pToCol && pToCol->nExpr!=1 ){
sqlite3ErrorMsg(pParse, "foreign key on %s"
" should reference only one column of table %T",
p->aCol[iCol].zName, pTo);
goto fk_end;
}
nCol = 1;
}else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
sqlite3ErrorMsg(pParse,
"number of columns in foreign key does not match the number of "
"columns in the referenced table");
goto fk_end;
}else{
nCol = pFromCol->nExpr;
}
nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
if( pToCol ){
for(i=0; i<pToCol->nExpr; i++){
nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
}
}
pFKey = sqlite3DbMallocZero(db, nByte );
if( pFKey==0 ){
goto fk_end;
}
pFKey->pFrom = p;
pFKey->pNextFrom = p->pFKey;
z = (char*)&pFKey->aCol[nCol];
pFKey->zTo = z;
if( IN_RENAME_OBJECT ){
sqlite3RenameTokenMap(pParse, (void*)z, pTo);
}
memcpy(z, pTo->z, pTo->n);
z[pTo->n] = 0;
sqlite3Dequote(z);
z += pTo->n+1;
pFKey->nCol = nCol;
if( pFromCol==0 ){
pFKey->aCol[0].iFrom = p->nCol-1;
}else{
for(i=0; i<nCol; i++){
int j;
for(j=0; j<p->nCol; j++){
if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
pFKey->aCol[i].iFrom = j;
break;
}
}
if( j>=p->nCol ){
sqlite3ErrorMsg(pParse,
"unknown column \"%s\" in foreign key definition",
pFromCol->a[i].zName);
goto fk_end;
}
if( IN_RENAME_OBJECT ){
sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zName);
}
}
}
if( pToCol ){
for(i=0; i<nCol; i++){
int n = sqlite3Strlen30(pToCol->a[i].zName);
pFKey->aCol[i].zCol = z;
if( IN_RENAME_OBJECT ){
sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zName);
}
memcpy(z, pToCol->a[i].zName, n);
z[n] = 0;
z += n+1;
}
}
pFKey->isDeferred = 0;
pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
pFKey->zTo, (void *)pFKey
);
if( pNextTo==pFKey ){
sqlite3OomFault(db);
goto fk_end;
}
if( pNextTo ){
assert( pNextTo->pPrevTo==0 );
pFKey->pNextTo = pNextTo;
pNextTo->pPrevTo = pFKey;
}
/* Link the foreign key to the table as the last step.
*/
p->pFKey = pFKey;
pFKey = 0;
fk_end:
sqlite3DbFree(db, pFKey);
#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
sqlite3ExprListDelete(db, pFromCol);
sqlite3ExprListDelete(db, pToCol);
}
/*
** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
** clause is seen as part of a foreign key definition. The isDeferred
** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
** The behavior of the most recently created foreign key is adjusted
** accordingly.
*/
void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
#ifndef SQLITE_OMIT_FOREIGN_KEY
Table *pTab;
FKey *pFKey;
if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
pFKey->isDeferred = (u8)isDeferred;
#endif
}
/*
** Generate code that will erase and refill index *pIdx. This is
** used to initialize a newly created index or to recompute the
** content of an index in response to a REINDEX command.
**
** if memRootPage is not negative, it means that the index is newly
** created. The register specified by memRootPage contains the
** root page number of the index. If memRootPage is negative, then
** the index already exists and must be cleared before being refilled and
** the root page number of the index is taken from pIndex->tnum.
*/
static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
Table *pTab = pIndex->pTable; /* The table that is indexed */
int iTab = pParse->nTab++; /* Btree cursor used for pTab */
int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
int iSorter; /* Cursor opened by OpenSorter (if in use) */
int addr1; /* Address of top of loop */
int addr2; /* Address to jump to for next iteration */
int tnum; /* Root page of index */
int iPartIdxLabel; /* Jump to this label to skip a row */
Vdbe *v; /* Generate code into this virtual machine */
KeyInfo *pKey; /* KeyInfo for index */
int regRecord; /* Register holding assembled index record */
sqlite3 *db = pParse->db; /* The database connection */
int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
#ifndef SQLITE_OMIT_AUTHORIZATION
if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
db->aDb[iDb].zDbSName ) ){
return;
}
#endif
/* Require a write-lock on the table to perform this operation */
sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
v = sqlite3GetVdbe(pParse);
if( v==0 ) return;
if( memRootPage>=0 ){
tnum = memRootPage;
}else{
tnum = pIndex->tnum;
}
pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
assert( pKey!=0 || db->mallocFailed || pParse->nErr );
/* Open the sorter cursor if we are to use one. */
iSorter = pParse->nTab++;
sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
sqlite3KeyInfoRef(pKey), P4_KEYINFO);
/* Open the table. Loop through all rows of the table, inserting index
** records into the sorter. */
sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
regRecord = sqlite3GetTempReg(pParse);
sqlite3MultiWrite(pParse);
sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
sqlite3VdbeJumpHere(v, addr1);
if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
(char *)pKey, P4_KEYINFO);
sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
if( IsUniqueIndex(pIndex) ){
int j2 = sqlite3VdbeGoto(v, 1);
addr2 = sqlite3VdbeCurrentAddr(v);
sqlite3VdbeVerifyAbortable(v, OE_Abort);
sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
pIndex->nKeyCol); VdbeCoverage(v);
sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
sqlite3VdbeJumpHere(v, j2);
}else{
/* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
** abort. The exception is if one of the indexed expressions contains a
** user function that throws an exception when it is evaluated. But the
** overhead of adding a statement journal to a CREATE INDEX statement is
** very small (since most of the pages written do not contain content that
** needs to be restored if the statement aborts), so we call
** sqlite3MayAbort() for all CREATE INDEX statements. */
sqlite3MayAbort(pParse);
addr2 = sqlite3VdbeCurrentAddr(v);
}
sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
if( !pIndex->bAscKeyBug ){
/* This OP_SeekEnd opcode makes index insert for a REINDEX go much
** faster by avoiding unnecessary seeks. But the optimization does
** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
** with DESC primary keys, since those indexes have there keys in
** a different order from the main table.
** See ticket: https://www.sqlite.org/src/info/bba7b69f9849b5bf
*/
sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
}
sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
sqlite3ReleaseTempReg(pParse, regRecord);
sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
sqlite3VdbeJumpHere(v, addr1);
sqlite3VdbeAddOp1(v, OP_Close, iTab);
sqlite3VdbeAddOp1(v, OP_Close, iIdx);
sqlite3VdbeAddOp1(v, OP_Close, iSorter);
}
/*
** Allocate heap space to hold an Index object with nCol columns.
**
** Increase the allocation size to provide an extra nExtra bytes
** of 8-byte aligned space after the Index object and return a
** pointer to this extra space in *ppExtra.
*/
Index *sqlite3AllocateIndexObject(
sqlite3 *db, /* Database connection */
i16 nCol, /* Total number of columns in the index */
int nExtra, /* Number of bytes of extra space to alloc */
char **ppExtra /* Pointer to the "extra" space */
){
Index *p; /* Allocated index object */
int nByte; /* Bytes of space for Index object + arrays */
nByte = ROUND8(sizeof(Index)) + /* Index structure */
ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
sizeof(i16)*nCol + /* Index.aiColumn */
sizeof(u8)*nCol); /* Index.aSortOrder */
p = sqlite3DbMallocZero(db, nByte + nExtra);
if( p ){
char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
p->aSortOrder = (u8*)pExtra;
p->nColumn = nCol;
p->nKeyCol = nCol - 1;
*ppExtra = ((char*)p) + nByte;
}
return p;
}
/*
** If expression list pList contains an expression that was parsed with
** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
** pParse and return non-zero. Otherwise, return zero.
*/
int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
if( pList ){
int i;
for(i=0; i<pList->nExpr; i++){
if( pList->a[i].bNulls ){
u8 sf = pList->a[i].sortFlags;
sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s",
(sf==0 || sf==3) ? "FIRST" : "LAST"
);
return 1;
}
}
}
return 0;
}
/*
** Create a new index for an SQL table. pName1.pName2 is the name of the index
** and pTblList is the name of the table that is to be indexed. Both will
** be NULL for a primary key or an index that is created to satisfy a
** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
** as the table to be indexed. pParse->pNewTable is a table that is
** currently being constructed by a CREATE TABLE statement.
**
** pList is a list of columns to be indexed. pList will be NULL if this
** is a primary key or unique-constraint on the most recent column added
** to the table currently under construction.
*/
void sqlite3CreateIndex(
Parse *pParse, /* All information about this parse */
Token *pName1, /* First part of index name. May be NULL */
Token *pName2, /* Second part of index name. May be NULL */
SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
ExprList *pList, /* A list of columns to be indexed */
int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
Token *pStart, /* The CREATE token that begins this statement */
Expr *pPIWhere, /* WHERE clause for partial indices */
int sortOrder, /* Sort order of primary key when pList==NULL */
int ifNotExist, /* Omit error if index already exists */
u8 idxType /* The index type */
){
Table *pTab = 0; /* Table to be indexed */
Index *pIndex = 0; /* The index to be created */
char *zName = 0; /* Name of the index */
int nName; /* Number of characters in zName */
int i, j;
DbFixer sFix; /* For assigning database names to pTable */
int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
sqlite3 *db = pParse->db;
Db *pDb; /* The specific table containing the indexed database */
int iDb; /* Index of the database that is being written */
Token *pName = 0; /* Unqualified name of the index to create */
struct ExprList_item *pListItem; /* For looping over pList */
int nExtra = 0; /* Space allocated for zExtra[] */
int nExtraCol; /* Number of extra columns needed */
char *zExtra = 0; /* Extra space after the Index object */
Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
if( db->mallocFailed || pParse->nErr>0 ){
goto exit_create_index;
}
if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
goto exit_create_index;
}
if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
goto exit_create_index;
}
if( sqlite3HasExplicitNulls(pParse, pList) ){
goto exit_create_index;
}
/*
** Find the table that is to be indexed. Return early if not found.
*/
if( pTblName!=0 ){
/* Use the two-part index name to determine the database
** to search for the table. 'Fix' the table name to this db
** before looking up the table.
*/
assert( pName1 && pName2 );
iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
if( iDb<0 ) goto exit_create_index;
assert( pName && pName->z );
#ifndef SQLITE_OMIT_TEMPDB
/* If the index name was unqualified, check if the table
** is a temp table. If so, set the database to 1. Do not do this
** if initialising a database schema.
*/
if( !db->init.busy ){
pTab = sqlite3SrcListLookup(pParse, pTblName);
if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
iDb = 1;
}
}
#endif
sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
if( sqlite3FixSrcList(&sFix, pTblName) ){
/* Because the parser constructs pTblName from a single identifier,
** sqlite3FixSrcList can never fail. */
assert(0);
}
pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
assert( db->mallocFailed==0 || pTab==0 );
if( pTab==0 ) goto exit_create_index;
if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
sqlite3ErrorMsg(pParse,
"cannot create a TEMP index on non-TEMP table \"%s\"",
pTab->zName);
goto exit_create_index;
}
if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
}else{
assert( pName==0 );
assert( pStart==0 );
pTab = pParse->pNewTable;
if( !pTab ) goto exit_create_index;
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
}
pDb = &db->aDb[iDb];
assert( pTab!=0 );
assert( pParse->nErr==0 );
if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
&& db->init.busy==0
&& pTblName!=0
#if SQLITE_USER_AUTHENTICATION
&& sqlite3UserAuthTable(pTab->zName)==0
#endif
#ifdef SQLITE_ALLOW_SQLITE_MASTER_INDEX
&& sqlite3StrICmp(&pTab->zName[7],"master")!=0
#endif
){
sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
goto exit_create_index;
}
#ifndef SQLITE_OMIT_VIEW
if( pTab->pSelect ){
sqlite3ErrorMsg(pParse, "views may not be indexed");
goto exit_create_index;
}
#endif
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( IsVirtual(pTab) ){
sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
goto exit_create_index;
}
#endif
/*
** Find the name of the index. Make sure there is not already another
** index or table with the same name.
**
** Exception: If we are reading the names of permanent indices from the
** sqlite_master table (because some other process changed the schema) and
** one of the index names collides with the name of a temporary table or
** index, then we will continue to process this index.
**
** If pName==0 it means that we are
** dealing with a primary key or UNIQUE constraint. We have to invent our
** own name.
*/
if( pName ){
zName = sqlite3NameFromToken(db, pName);
if( zName==0 ) goto exit_create_index;
assert( pName->z!=0 );
if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
goto exit_create_index;
}
if( !IN_RENAME_OBJECT ){
if( !db->init.busy ){
if( sqlite3FindTable(db, zName, 0)!=0 ){
sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
goto exit_create_index;
}
}
if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
if( !ifNotExist ){
sqlite3ErrorMsg(pParse, "index %s already exists", zName);
}else{
assert( !db->init.busy );
sqlite3CodeVerifySchema(pParse, iDb);
}
goto exit_create_index;
}
}
}else{
int n;
Index *pLoop;
for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
if( zName==0 ){
goto exit_create_index;
}
/* Automatic index names generated from within sqlite3_declare_vtab()
** must have names that are distinct from normal automatic index names.
** The following statement converts "sqlite3_autoindex..." into
** "sqlite3_butoindex..." in order to make the names distinct.
** The "vtab_err.test" test demonstrates the need of this statement. */
if( IN_SPECIAL_PARSE ) zName[7]++;
}
/* Check for authorization to create an index.
*/
#ifndef SQLITE_OMIT_AUTHORIZATION
if( !IN_RENAME_OBJECT ){
const char *zDb = pDb->zDbSName;
if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
goto exit_create_index;
}
i = SQLITE_CREATE_INDEX;
if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
goto exit_create_index;
}
}
#endif
/* If pList==0, it means this routine was called to make a primary
** key out of the last column added to the table under construction.
** So create a fake list to simulate this.
*/
if( pList==0 ){
Token prevCol;
Column *pCol = &pTab->aCol[pTab->nCol-1];
pCol->colFlags |= COLFLAG_UNIQUE;
sqlite3TokenInit(&prevCol, pCol->zName);
pList = sqlite3ExprListAppend(pParse, 0,
sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
if( pList==0 ) goto exit_create_index;
assert( pList->nExpr==1 );
sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED);
}else{
sqlite3ExprListCheckLength(pParse, pList, "index");
if( pParse->nErr ) goto exit_create_index;
}
/* Figure out how many bytes of space are required to store explicitly
** specified collation sequence names.
*/
for(i=0; i<pList->nExpr; i++){
Expr *pExpr = pList->a[i].pExpr;
assert( pExpr!=0 );
if( pExpr->op==TK_COLLATE ){
nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
}
}
/*
** Allocate the index structure.
*/
nName = sqlite3Strlen30(zName);
nExtraCol = pPk ? pPk->nKeyCol : 1;
assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
nName + nExtra + 1, &zExtra);
if( db->mallocFailed ){
goto exit_create_index;
}
assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
pIndex->zName = zExtra;
zExtra += nName + 1;
memcpy(pIndex->zName, zName, nName+1);
pIndex->pTable = pTab;
pIndex->onError = (u8)onError;
pIndex->uniqNotNull = onError!=OE_None;
pIndex->idxType = idxType;
pIndex->pSchema = db->aDb[iDb].pSchema;
pIndex->nKeyCol = pList->nExpr;
if( pPIWhere ){
sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
pIndex->pPartIdxWhere = pPIWhere;
pPIWhere = 0;
}
assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
/* Check to see if we should honor DESC requests on index columns
*/
if( pDb->pSchema->file_format>=4 ){
sortOrderMask = -1; /* Honor DESC */
}else{
sortOrderMask = 0; /* Ignore DESC */
}
/* Analyze the list of expressions that form the terms of the index and
** report any errors. In the common case where the expression is exactly
** a table column, store that column in aiColumn[]. For general expressions,
** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
**
** TODO: Issue a warning if two or more columns of the index are identical.
** TODO: Issue a warning if the table primary key is used as part of the
** index key.
*/
pListItem = pList->a;
if( IN_RENAME_OBJECT ){
pIndex->aColExpr = pList;
pList = 0;
}
for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
Expr *pCExpr; /* The i-th index expression */
int requestedSortOrder; /* ASC or DESC on the i-th expression */
const char *zColl; /* Collation sequence name */
sqlite3StringToId(pListItem->pExpr);
sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
if( pParse->nErr ) goto exit_create_index;
pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
if( pCExpr->op!=TK_COLUMN ){
if( pTab==pParse->pNewTable ){
sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
"UNIQUE constraints");
goto exit_create_index;
}
if( pIndex->aColExpr==0 ){
pIndex->aColExpr = pList;
pList = 0;
}
j = XN_EXPR;
pIndex->aiColumn[i] = XN_EXPR;
pIndex->uniqNotNull = 0;
}else{
j = pCExpr->iColumn;
assert( j<=0x7fff );
if( j<0 ){
j = pTab->iPKey;
}else{
if( pTab->aCol[j].notNull==0 ){
pIndex->uniqNotNull = 0;
}
if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
pIndex->bHasVCol = 1;
}
}
pIndex->aiColumn[i] = (i16)j;
}
zColl = 0;
if( pListItem->pExpr->op==TK_COLLATE ){
int nColl;
zColl = pListItem->pExpr->u.zToken;
nColl = sqlite3Strlen30(zColl) + 1;
assert( nExtra>=nColl );
memcpy(zExtra, zColl, nColl);
zColl = zExtra;
zExtra += nColl;
nExtra -= nColl;
}else if( j>=0 ){
zColl = pTab->aCol[j].zColl;
}
if( !zColl ) zColl = sqlite3StrBINARY;
if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
goto exit_create_index;
}
pIndex->azColl[i] = zColl;
requestedSortOrder = pListItem->sortFlags & sortOrderMask;
pIndex->aSortOrder[i] = (u8)requestedSortOrder;
}
/* Append the table key to the end of the index. For WITHOUT ROWID
** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
** normal tables (when pPk==0) this will be the rowid.
*/
if( pPk ){
for(j=0; j<pPk->nKeyCol; j++){
int x = pPk->aiColumn[j];
assert( x>=0 );
if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
pIndex->nColumn--;
}else{
testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
pIndex->aiColumn[i] = x;
pIndex->azColl[i] = pPk->azColl[j];
pIndex->aSortOrder[i] = pPk->aSortOrder[j];
i++;
}
}
assert( i==pIndex->nColumn );
}else{
pIndex->aiColumn[i] = XN_ROWID;
pIndex->azColl[i] = sqlite3StrBINARY;
}
sqlite3DefaultRowEst(pIndex);
if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
/* If this index contains every column of its table, then mark
** it as a covering index */
assert( HasRowid(pTab)
|| pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
recomputeColumnsNotIndexed(pIndex);
if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
pIndex->isCovering = 1;
for(j=0; j<pTab->nCol; j++){
if( j==pTab->iPKey ) continue;
if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue;
pIndex->isCovering = 0;
break;
}
}
if( pTab==pParse->pNewTable ){
/* This routine has been called to create an automatic index as a
** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
** a PRIMARY KEY or UNIQUE clause following the column definitions.
** i.e. one of:
**
** CREATE TABLE t(x PRIMARY KEY, y);
** CREATE TABLE t(x, y, UNIQUE(x, y));
**
** Either way, check to see if the table already has such an index. If
** so, don't bother creating this one. This only applies to
** automatically created indices. Users can do as they wish with
** explicit indices.
**
** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
** (and thus suppressing the second one) even if they have different
** sort orders.
**
** If there are different collating sequences or if the columns of
** the constraint occur in different orders, then the constraints are
** considered distinct and both result in separate indices.
*/
Index *pIdx;
for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
int k;
assert( IsUniqueIndex(pIdx) );
assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
assert( IsUniqueIndex(pIndex) );
if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
for(k=0; k<pIdx->nKeyCol; k++){
const char *z1;
const char *z2;
assert( pIdx->aiColumn[k]>=0 );
if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
z1 = pIdx->azColl[k];
z2 = pIndex->azColl[k];
if( sqlite3StrICmp(z1, z2) ) break;
}
if( k==pIdx->nKeyCol ){
if( pIdx->onError!=pIndex->onError ){
/* This constraint creates the same index as a previous
** constraint specified somewhere in the CREATE TABLE statement.
** However the ON CONFLICT clauses are different. If both this
** constraint and the previous equivalent constraint have explicit
** ON CONFLICT clauses this is an error. Otherwise, use the
** explicitly specified behavior for the index.
*/
if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
sqlite3ErrorMsg(pParse,
"conflicting ON CONFLICT clauses specified", 0);
}
if( pIdx->onError==OE_Default ){
pIdx->onError = pIndex->onError;
}
}
if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
if( IN_RENAME_OBJECT ){
pIndex->pNext = pParse->pNewIndex;
pParse->pNewIndex = pIndex;
pIndex = 0;
}
goto exit_create_index;
}
}
}
if( !IN_RENAME_OBJECT ){
/* Link the new Index structure to its table and to the other
** in-memory database structures.
*/
assert( pParse->nErr==0 );
if( db->init.busy ){
Index *p;
assert( !IN_SPECIAL_PARSE );
assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
if( pTblName!=0 ){
pIndex->tnum = db->init.newTnum;
if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
sqlite3ErrorMsg(pParse, "invalid rootpage");
pParse->rc = SQLITE_CORRUPT_BKPT;
goto exit_create_index;
}
}
p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
pIndex->zName, pIndex);
if( p ){
assert( p==pIndex ); /* Malloc must have failed */
sqlite3OomFault(db);
goto exit_create_index;
}
db->mDbFlags |= DBFLAG_SchemaChange;
}
/* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
** emit code to allocate the index rootpage on disk and make an entry for
** the index in the sqlite_master table and populate the index with
** content. But, do not do this if we are simply reading the sqlite_master
** table to parse the schema, or if this index is the PRIMARY KEY index
** of a WITHOUT ROWID table.
**
** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
** or UNIQUE index in a CREATE TABLE statement. Since the table
** has just been created, it contains no data and the index initialization
** step can be skipped.
*/
else if( HasRowid(pTab) || pTblName!=0 ){
Vdbe *v;
char *zStmt;
int iMem = ++pParse->nMem;
v = sqlite3GetVdbe(pParse);
if( v==0 ) goto exit_create_index;
sqlite3BeginWriteOperation(pParse, 1, iDb);
/* Create the rootpage for the index using CreateIndex. But before
** doing so, code a Noop instruction and store its address in
** Index.tnum. This is required in case this index is actually a
** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
** that case the convertToWithoutRowidTable() routine will replace
** the Noop with a Goto to jump over the VDBE code generated below. */
pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
/* Gather the complete text of the CREATE INDEX statement into
** the zStmt variable
*/
assert( pName!=0 || pStart==0 );
if( pStart ){
int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
if( pName->z[n-1]==';' ) n--;
/* A named index with an explicit CREATE INDEX statement */
zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
onError==OE_None ? "" : " UNIQUE", n, pName->z);
}else{
/* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
/* zStmt = sqlite3MPrintf(""); */
zStmt = 0;
}
/* Add an entry in sqlite_master for this index
*/
sqlite3NestedParse(pParse,
"INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
db->aDb[iDb].zDbSName, MASTER_NAME,
pIndex->zName,
pTab->zName,
iMem,
zStmt
);
sqlite3DbFree(db, zStmt);
/* Fill the index with data and reparse the schema. Code an OP_Expire
** to invalidate all pre-compiled statements.
*/
if( pTblName ){
sqlite3RefillIndex(pParse, pIndex, iMem);
sqlite3ChangeCookie(pParse, iDb);
sqlite3VdbeAddParseSchemaOp(v, iDb,
sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
}
sqlite3VdbeJumpHere(v, pIndex->tnum);
}
}
/* When adding an index to the list of indices for a table, make
** sure all indices labeled OE_Replace come after all those labeled
** OE_Ignore. This is necessary for the correct constraint check
** processing (in sqlite3GenerateConstraintChecks()) as part of
** UPDATE and INSERT statements.
*/
if( db->init.busy || pTblName==0 ){
if( onError!=OE_Replace || pTab->pIndex==0
|| pTab->pIndex->onError==OE_Replace){
pIndex->pNext = pTab->pIndex;
pTab->pIndex = pIndex;
}else{
Index *pOther = pTab->pIndex;
while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
pOther = pOther->pNext;
}
pIndex->pNext = pOther->pNext;
pOther->pNext = pIndex;
}
pIndex = 0;
}
else if( IN_RENAME_OBJECT ){
assert( pParse->pNewIndex==0 );
pParse->pNewIndex = pIndex;
pIndex = 0;
}
/* Clean up before exiting */
exit_create_index:
if( pIndex ) sqlite3FreeIndex(db, pIndex);
sqlite3ExprDelete(db, pPIWhere);
sqlite3ExprListDelete(db, pList);
sqlite3SrcListDelete(db, pTblName);
sqlite3DbFree(db, zName);
}
/*
** Fill the Index.aiRowEst[] array with default information - information
** to be used when we have not run the ANALYZE command.
**
** aiRowEst[0] is supposed to contain the number of elements in the index.
** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
** number of rows in the table that match any particular value of the
** first column of the index. aiRowEst[2] is an estimate of the number
** of rows that match any particular combination of the first 2 columns
** of the index. And so forth. It must always be the case that
*
** aiRowEst[N]<=aiRowEst[N-1]
** aiRowEst[N]>=1
**
** Apart from that, we have little to go on besides intuition as to
** how aiRowEst[] should be initialized. The numbers generated here
** are based on typical values found in actual indices.
*/
void sqlite3DefaultRowEst(Index *pIdx){
/* 10, 9, 8, 7, 6 */
LogEst aVal[] = { 33, 32, 30, 28, 26 };
LogEst *a = pIdx->aiRowLogEst;
int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
int i;
/* Indexes with default row estimates should not have stat1 data */
assert( !pIdx->hasStat1 );
/* Set the first entry (number of rows in the index) to the estimated
** number of rows in the table, or half the number of rows in the table
** for a partial index. But do not let the estimate drop below 10. */
a[0] = pIdx->pTable->nRowLogEst;
if( pIdx->pPartIdxWhere!=0 ) a[0] -= 10; assert( 10==sqlite3LogEst(2) );
if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
/* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
** 6 and each subsequent value (if any) is 5. */
memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
a[i] = 23; assert( 23==sqlite3LogEst(5) );
}
assert( 0==sqlite3LogEst(1) );
if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
}
/*
** This routine will drop an existing named index. This routine
** implements the DROP INDEX statement.
*/
void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
Index *pIndex;
Vdbe *v;
sqlite3 *db = pParse->db;
int iDb;
assert( pParse->nErr==0 ); /* Never called with prior errors */
if( db->mallocFailed ){
goto exit_drop_index;
}
assert( pName->nSrc==1 );
if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
goto exit_drop_index;
}
pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
if( pIndex==0 ){
if( !ifExists ){
sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
}else{
sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
}
pParse->checkSchema = 1;
goto exit_drop_index;
}
if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
"or PRIMARY KEY constraint cannot be dropped", 0);
goto exit_drop_index;
}
iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
#ifndef SQLITE_OMIT_AUTHORIZATION
{
int code = SQLITE_DROP_INDEX;
Table *pTab = pIndex->pTable;
const char *zDb = db->aDb[iDb].zDbSName;
const char *zTab = SCHEMA_TABLE(iDb);
if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
goto exit_drop_index;
}
if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
goto exit_drop_index;
}
}
#endif
/* Generate code to remove the index and from the master table */
v = sqlite3GetVdbe(pParse);
if( v ){
sqlite3BeginWriteOperation(pParse, 1, iDb);
sqlite3NestedParse(pParse,
"DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
db->aDb[iDb].zDbSName, MASTER_NAME, pIndex->zName
);
sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
sqlite3ChangeCookie(pParse, iDb);
destroyRootPage(pParse, pIndex->tnum, iDb);
sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
}
exit_drop_index:
sqlite3SrcListDelete(db, pName);
}
/*
** pArray is a pointer to an array of objects. Each object in the
** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
** to extend the array so that there is space for a new object at the end.
**
** When this function is called, *pnEntry contains the current size of
** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
** in total).
**
** If the realloc() is successful (i.e. if no OOM condition occurs), the
** space allocated for the new object is zeroed, *pnEntry updated to
** reflect the new size of the array and a pointer to the new allocation
** returned. *pIdx is set to the index of the new array entry in this case.
**
** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
** unchanged and a copy of pArray returned.
*/
void *sqlite3ArrayAllocate(
sqlite3 *db, /* Connection to notify of malloc failures */
void *pArray, /* Array of objects. Might be reallocated */
int szEntry, /* Size of each object in the array */
int *pnEntry, /* Number of objects currently in use */
int *pIdx /* Write the index of a new slot here */
){
char *z;
sqlite3_int64 n = *pIdx = *pnEntry;
if( (n & (n-1))==0 ){
sqlite3_int64 sz = (n==0) ? 1 : 2*n;
void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
if( pNew==0 ){
*pIdx = -1;
return pArray;
}
pArray = pNew;
}
z = (char*)pArray;
memset(&z[n * szEntry], 0, szEntry);
++*pnEntry;
return pArray;
}
/*
** Append a new element to the given IdList. Create a new IdList if
** need be.
**
** A new IdList is returned, or NULL if malloc() fails.
*/
IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
sqlite3 *db = pParse->db;
int i;
if( pList==0 ){
pList = sqlite3DbMallocZero(db, sizeof(IdList) );
if( pList==0 ) return 0;
}
pList->a = sqlite3ArrayAllocate(
db,
pList->a,
sizeof(pList->a[0]),
&pList->nId,
&i
);
if( i<0 ){
sqlite3IdListDelete(db, pList);
return 0;
}
pList->a[i].zName = sqlite3NameFromToken(db, pToken);
if( IN_RENAME_OBJECT && pList->a[i].zName ){
sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
}
return pList;
}
/*
** Delete an IdList.
*/
void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
int i;
if( pList==0 ) return;
for(i=0; i<pList->nId; i++){
sqlite3DbFree(db, pList->a[i].zName);
}
sqlite3DbFree(db, pList->a);
sqlite3DbFreeNN(db, pList);
}
/*
** Return the index in pList of the identifier named zId. Return -1
** if not found.
*/
int sqlite3IdListIndex(IdList *pList, const char *zName){
int i;
if( pList==0 ) return -1;
for(i=0; i<pList->nId; i++){
if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
}
return -1;
}
/*
** Maximum size of a SrcList object.
** The SrcList object is used to represent the FROM clause of a
** SELECT statement, and the query planner cannot deal with more
** than 64 tables in a join. So any value larger than 64 here
** is sufficient for most uses. Smaller values, like say 10, are
** appropriate for small and memory-limited applications.
*/
#ifndef SQLITE_MAX_SRCLIST
# define SQLITE_MAX_SRCLIST 200
#endif
/*
** Expand the space allocated for the given SrcList object by
** creating nExtra new slots beginning at iStart. iStart is zero based.
** New slots are zeroed.
**
** For example, suppose a SrcList initially contains two entries: A,B.
** To append 3 new entries onto the end, do this:
**
** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
**
** After the call above it would contain: A, B, nil, nil, nil.
** If the iStart argument had been 1 instead of 2, then the result
** would have been: A, nil, nil, nil, B. To prepend the new slots,
** the iStart value would be 0. The result then would
** be: nil, nil, nil, A, B.
**
** If a memory allocation fails or the SrcList becomes too large, leave
** the original SrcList unchanged, return NULL, and leave an error message
** in pParse.
*/
SrcList *sqlite3SrcListEnlarge(
Parse *pParse, /* Parsing context into which errors are reported */
SrcList *pSrc, /* The SrcList to be enlarged */
int nExtra, /* Number of new slots to add to pSrc->a[] */
int iStart /* Index in pSrc->a[] of first new slot */
){
int i;
/* Sanity checking on calling parameters */
assert( iStart>=0 );
assert( nExtra>=1 );
assert( pSrc!=0 );
assert( iStart<=pSrc->nSrc );
/* Allocate additional space if needed */
if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
SrcList *pNew;
sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
sqlite3 *db = pParse->db;
if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
SQLITE_MAX_SRCLIST);
return 0;
}
if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
pNew = sqlite3DbRealloc(db, pSrc,
sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
if( pNew==0 ){
assert( db->mallocFailed );
return 0;
}
pSrc = pNew;
pSrc->nAlloc = nAlloc;
}
/* Move existing slots that come after the newly inserted slots
** out of the way */
for(i=pSrc->nSrc-1; i>=iStart; i--){
pSrc->a[i+nExtra] = pSrc->a[i];
}
pSrc->nSrc += nExtra;
/* Zero the newly allocated slots */
memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
for(i=iStart; i<iStart+nExtra; i++){
pSrc->a[i].iCursor = -1;
}
/* Return a pointer to the enlarged SrcList */
return pSrc;
}
/*
** Append a new table name to the given SrcList. Create a new SrcList if
** need be. A new entry is created in the SrcList even if pTable is NULL.
**
** A SrcList is returned, or NULL if there is an OOM error or if the
** SrcList grows to large. The returned
** SrcList might be the same as the SrcList that was input or it might be
** a new one. If an OOM error does occurs, then the prior value of pList
** that is input to this routine is automatically freed.
**
** If pDatabase is not null, it means that the table has an optional
** database name prefix. Like this: "database.table". The pDatabase
** points to the table name and the pTable points to the database name.
** The SrcList.a[].zName field is filled with the table name which might
** come from pTable (if pDatabase is NULL) or from pDatabase.
** SrcList.a[].zDatabase is filled with the database name from pTable,
** or with NULL if no database is specified.
**
** In other words, if call like this:
**
** sqlite3SrcListAppend(D,A,B,0);
**
** Then B is a table name and the database name is unspecified. If called
** like this:
**
** sqlite3SrcListAppend(D,A,B,C);
**
** Then C is the table name and B is the database name. If C is defined
** then so is B. In other words, we never have a case where:
**
** sqlite3SrcListAppend(D,A,0,C);
**
** Both pTable and pDatabase are assumed to be quoted. They are dequoted
** before being added to the SrcList.
*/
SrcList *sqlite3SrcListAppend(
Parse *pParse, /* Parsing context, in which errors are reported */
SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
Token *pTable, /* Table to append */
Token *pDatabase /* Database of the table */
){
struct SrcList_item *pItem;
sqlite3 *db;
assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
assert( pParse!=0 );
assert( pParse->db!=0 );
db = pParse->db;
if( pList==0 ){
pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
if( pList==0 ) return 0;
pList->nAlloc = 1;
pList->nSrc = 1;
memset(&pList->a[0], 0, sizeof(pList->a[0]));
pList->a[0].iCursor = -1;
}else{
SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
if( pNew==0 ){
sqlite3SrcListDelete(db, pList);
return 0;
}else{
pList = pNew;
}
}
pItem = &pList->a[pList->nSrc-1];
if( pDatabase && pDatabase->z==0 ){
pDatabase = 0;
}
if( pDatabase ){
pItem->zName = sqlite3NameFromToken(db, pDatabase);
pItem->zDatabase = sqlite3NameFromToken(db, pTable);
}else{
pItem->zName = sqlite3NameFromToken(db, pTable);
pItem->zDatabase = 0;
}
return pList;
}
/*
** Assign VdbeCursor index numbers to all tables in a SrcList
*/
void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
int i;
struct SrcList_item *pItem;
assert(pList || pParse->db->mallocFailed );
if( pList ){
for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
if( pItem->iCursor>=0 ) break;
pItem->iCursor = pParse->nTab++;
if( pItem->pSelect ){
sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
}
}
}
}
/*
** Delete an entire SrcList including all its substructure.
*/
void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
int i;
struct SrcList_item *pItem;
if( pList==0 ) return;
for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
sqlite3DbFree(db, pItem->zDatabase);
sqlite3DbFree(db, pItem->zName);
sqlite3DbFree(db, pItem->zAlias);
if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
sqlite3DeleteTable(db, pItem->pTab);
sqlite3SelectDelete(db, pItem->pSelect);
sqlite3ExprDelete(db, pItem->pOn);
sqlite3IdListDelete(db, pItem->pUsing);
}
sqlite3DbFreeNN(db, pList);
}
/*
** This routine is called by the parser to add a new term to the
** end of a growing FROM clause. The "p" parameter is the part of
** the FROM clause that has already been constructed. "p" is NULL
** if this is the first term of the FROM clause. pTable and pDatabase
** are the name of the table and database named in the FROM clause term.
** pDatabase is NULL if the database name qualifier is missing - the
** usual case. If the term has an alias, then pAlias points to the
** alias token. If the term is a subquery, then pSubquery is the
** SELECT statement that the subquery encodes. The pTable and
** pDatabase parameters are NULL for subqueries. The pOn and pUsing
** parameters are the content of the ON and USING clauses.
**
** Return a new SrcList which encodes is the FROM with the new
** term added.
*/
SrcList *sqlite3SrcListAppendFromTerm(
Parse *pParse, /* Parsing context */
SrcList *p, /* The left part of the FROM clause already seen */
Token *pTable, /* Name of the table to add to the FROM clause */
Token *pDatabase, /* Name of the database containing pTable */
Token *pAlias, /* The right-hand side of the AS subexpression */
Select *pSubquery, /* A subquery used in place of a table name */
Expr *pOn, /* The ON clause of a join */
IdList *pUsing /* The USING clause of a join */
){
struct SrcList_item *pItem;
sqlite3 *db = pParse->db;
if( !p && (pOn || pUsing) ){
sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
(pOn ? "ON" : "USING")
);
goto append_from_error;
}
p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
if( p==0 ){
goto append_from_error;
}
assert( p->nSrc>0 );
pItem = &p->a[p->nSrc-1];
assert( (pTable==0)==(pDatabase==0) );
assert( pItem->zName==0 || pDatabase!=0 );
if( IN_RENAME_OBJECT && pItem->zName ){
Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
}
assert( pAlias!=0 );
if( pAlias->n ){
pItem->zAlias = sqlite3NameFromToken(db, pAlias);
}
pItem->pSelect = pSubquery;
pItem->pOn = pOn;
pItem->pUsing = pUsing;
return p;
append_from_error:
assert( p==0 );
sqlite3ExprDelete(db, pOn);
sqlite3IdListDelete(db, pUsing);
sqlite3SelectDelete(db, pSubquery);
return 0;
}
/*
** Add an INDEXED BY or NOT INDEXED clause to the most recently added
** element of the source-list passed as the second argument.
*/
void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
assert( pIndexedBy!=0 );
if( p && pIndexedBy->n>0 ){
struct SrcList_item *pItem;
assert( p->nSrc>0 );
pItem = &p->a[p->nSrc-1];
assert( pItem->fg.notIndexed==0 );
assert( pItem->fg.isIndexedBy==0 );
assert( pItem->fg.isTabFunc==0 );
if( pIndexedBy->n==1 && !pIndexedBy->z ){
/* A "NOT INDEXED" clause was supplied. See parse.y
** construct "indexed_opt" for details. */
pItem->fg.notIndexed = 1;
}else{
pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
pItem->fg.isIndexedBy = 1;
}
}
}
/*
** Add the list of function arguments to the SrcList entry for a
** table-valued-function.
*/
void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
if( p ){
struct SrcList_item *pItem = &p->a[p->nSrc-1];
assert( pItem->fg.notIndexed==0 );
assert( pItem->fg.isIndexedBy==0 );
assert( pItem->fg.isTabFunc==0 );
pItem->u1.pFuncArg = pList;
pItem->fg.isTabFunc = 1;
}else{
sqlite3ExprListDelete(pParse->db, pList);
}
}
/*
** When building up a FROM clause in the parser, the join operator
** is initially attached to the left operand. But the code generator
** expects the join operator to be on the right operand. This routine
** Shifts all join operators from left to right for an entire FROM
** clause.
**
** Example: Suppose the join is like this:
**
** A natural cross join B
**
** The operator is "natural cross join". The A and B operands are stored
** in p->a[0] and p->a[1], respectively. The parser initially stores the
** operator with A. This routine shifts that operator over to B.
*/
void sqlite3SrcListShiftJoinType(SrcList *p){
if( p ){
int i;
for(i=p->nSrc-1; i>0; i--){
p->a[i].fg.jointype = p->a[i-1].fg.jointype;
}
p->a[0].fg.jointype = 0;
}
}
/*
** Generate VDBE code for a BEGIN statement.
*/
void sqlite3BeginTransaction(Parse *pParse, int type){
sqlite3 *db;
Vdbe *v;
int i;
assert( pParse!=0 );
db = pParse->db;
assert( db!=0 );
if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
return;
}
v = sqlite3GetVdbe(pParse);
if( !v ) return;
if( type!=TK_DEFERRED ){
for(i=0; i<db->nDb; i++){
sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
sqlite3VdbeUsesBtree(v, i);
}
}
sqlite3VdbeAddOp0(v, OP_AutoCommit);
}
/*
** Generate VDBE code for a COMMIT or ROLLBACK statement.
** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
** code is generated for a COMMIT.
*/
void sqlite3EndTransaction(Parse *pParse, int eType){
Vdbe *v;
int isRollback;
assert( pParse!=0 );
assert( pParse->db!=0 );
assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
isRollback = eType==TK_ROLLBACK;
if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
return;
}
v = sqlite3GetVdbe(pParse);
if( v ){
sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
}
}
/*
** This function is called by the parser when it parses a command to create,
** release or rollback an SQL savepoint.
*/
void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
char *zName = sqlite3NameFromToken(pParse->db, pName);
if( zName ){
Vdbe *v = sqlite3GetVdbe(pParse);
#ifndef SQLITE_OMIT_AUTHORIZATION
static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
#endif
if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
sqlite3DbFree(pParse->db, zName);
return;
}
sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
}
}
/*
** Make sure the TEMP database is open and available for use. Return
** the number of errors. Leave any error messages in the pParse structure.
*/
int sqlite3OpenTempDatabase(Parse *pParse){
sqlite3 *db = pParse->db;
if( db->aDb[1].pBt==0 && !pParse->explain ){
int rc;
Btree *pBt;
static const int flags =
SQLITE_OPEN_READWRITE |
SQLITE_OPEN_CREATE |
SQLITE_OPEN_EXCLUSIVE |
SQLITE_OPEN_DELETEONCLOSE |
SQLITE_OPEN_TEMP_DB;
rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
if( rc!=SQLITE_OK ){
sqlite3ErrorMsg(pParse, "unable to open a temporary database "
"file for storing temporary tables");
pParse->rc = rc;
return 1;
}
db->aDb[1].pBt = pBt;
assert( db->aDb[1].pSchema );
if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
sqlite3OomFault(db);
return 1;
}
}
return 0;
}
/*
** Record the fact that the schema cookie will need to be verified
** for database iDb. The code to actually verify the schema cookie
** will occur at the end of the top-level VDBE and will be generated
** later, by sqlite3FinishCoding().
*/
void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
Parse *pToplevel = sqlite3ParseToplevel(pParse);
assert( iDb>=0 && iDb<pParse->db->nDb );
assert( pParse->db->aDb[iDb].pBt!=0 || iDb==1 );
assert( iDb<SQLITE_MAX_ATTACHED+2 );
assert( sqlite3SchemaMutexHeld(pParse->db, iDb, 0) );
if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
DbMaskSet(pToplevel->cookieMask, iDb);
if( !OMIT_TEMPDB && iDb==1 ){
sqlite3OpenTempDatabase(pToplevel);
}
}
}
/*
** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
** attached database. Otherwise, invoke it for the database named zDb only.
*/
void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
sqlite3 *db = pParse->db;
int i;
for(i=0; i<db->nDb; i++){
Db *pDb = &db->aDb[i];
if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
sqlite3CodeVerifySchema(pParse, i);
}
}
}
/*
** Generate VDBE code that prepares for doing an operation that
** might change the database.
**
** This routine starts a new transaction if we are not already within
** a transaction. If we are already within a transaction, then a checkpoint
** is set if the setStatement parameter is true. A checkpoint should
** be set for operations that might fail (due to a constraint) part of
** the way through and which will need to undo some writes without having to
** rollback the whole transaction. For operations where all constraints
** can be checked before any changes are made to the database, it is never
** necessary to undo a write and the checkpoint should not be set.
*/
void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
Parse *pToplevel = sqlite3ParseToplevel(pParse);
sqlite3CodeVerifySchema(pParse, iDb);
DbMaskSet(pToplevel->writeMask, iDb);
pToplevel->isMultiWrite |= setStatement;
}
/*
** Indicate that the statement currently under construction might write
** more than one entry (example: deleting one row then inserting another,
** inserting multiple rows in a table, or inserting a row and index entries.)
** If an abort occurs after some of these writes have completed, then it will
** be necessary to undo the completed writes.
*/
void sqlite3MultiWrite(Parse *pParse){
Parse *pToplevel = sqlite3ParseToplevel(pParse);
pToplevel->isMultiWrite = 1;
}
/*
** The code generator calls this routine if is discovers that it is
** possible to abort a statement prior to completion. In order to
** perform this abort without corrupting the database, we need to make
** sure that the statement is protected by a statement transaction.
**
** Technically, we only need to set the mayAbort flag if the
** isMultiWrite flag was previously set. There is a time dependency
** such that the abort must occur after the multiwrite. This makes
** some statements involving the REPLACE conflict resolution algorithm
** go a little faster. But taking advantage of this time dependency
** makes it more difficult to prove that the code is correct (in
** particular, it prevents us from writing an effective
** implementation of sqlite3AssertMayAbort()) and so we have chosen
** to take the safe route and skip the optimization.
*/
void sqlite3MayAbort(Parse *pParse){
Parse *pToplevel = sqlite3ParseToplevel(pParse);
pToplevel->mayAbort = 1;
}
/*
** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
** error. The onError parameter determines which (if any) of the statement
** and/or current transaction is rolled back.
*/
void sqlite3HaltConstraint(
Parse *pParse, /* Parsing context */
int errCode, /* extended error code */
int onError, /* Constraint type */
char *p4, /* Error message */
i8 p4type, /* P4_STATIC or P4_TRANSIENT */
u8 p5Errmsg /* P5_ErrMsg type */
){
Vdbe *v = sqlite3GetVdbe(pParse);
assert( (errCode&0xff)==SQLITE_CONSTRAINT );
if( onError==OE_Abort ){
sqlite3MayAbort(pParse);
}
sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
sqlite3VdbeChangeP5(v, p5Errmsg);
}
/*
** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
*/
void sqlite3UniqueConstraint(
Parse *pParse, /* Parsing context */
int onError, /* Constraint type */
Index *pIdx /* The index that triggers the constraint */
){
char *zErr;
int j;
StrAccum errMsg;
Table *pTab = pIdx->pTable;
sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
if( pIdx->aColExpr ){
sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
}else{
for(j=0; j<pIdx->nKeyCol; j++){
char *zCol;
assert( pIdx->aiColumn[j]>=0 );
zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
if( j ) sqlite3_str_append(&errMsg, ", ", 2);
sqlite3_str_appendall(&errMsg, pTab->zName);
sqlite3_str_append(&errMsg, ".", 1);
sqlite3_str_appendall(&errMsg, zCol);
}
}
zErr = sqlite3StrAccumFinish(&errMsg);
sqlite3HaltConstraint(pParse,
IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
: SQLITE_CONSTRAINT_UNIQUE,
onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
}
/*
** Code an OP_Halt due to non-unique rowid.
*/
void sqlite3RowidConstraint(
Parse *pParse, /* Parsing context */
int onError, /* Conflict resolution algorithm */
Table *pTab /* The table with the non-unique rowid */
){
char *zMsg;
int rc;
if( pTab->iPKey>=0 ){
zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
pTab->aCol[pTab->iPKey].zName);
rc = SQLITE_CONSTRAINT_PRIMARYKEY;
}else{
zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
rc = SQLITE_CONSTRAINT_ROWID;
}
sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
P5_ConstraintUnique);
}
/*
** Check to see if pIndex uses the collating sequence pColl. Return
** true if it does and false if it does not.
*/
#ifndef SQLITE_OMIT_REINDEX
static int collationMatch(const char *zColl, Index *pIndex){
int i;
assert( zColl!=0 );
for(i=0; i<pIndex->nColumn; i++){
const char *z = pIndex->azColl[i];
assert( z!=0 || pIndex->aiColumn[i]<0 );
if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
return 1;
}
}
return 0;
}
#endif
/*
** Recompute all indices of pTab that use the collating sequence pColl.
** If pColl==0 then recompute all indices of pTab.
*/
#ifndef SQLITE_OMIT_REINDEX
static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
if( !IsVirtual(pTab) ){
Index *pIndex; /* An index associated with pTab */
for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
if( zColl==0 || collationMatch(zColl, pIndex) ){
int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
sqlite3BeginWriteOperation(pParse, 0, iDb);
sqlite3RefillIndex(pParse, pIndex, -1);
}
}
}
}
#endif
/*
** Recompute all indices of all tables in all databases where the
** indices use the collating sequence pColl. If pColl==0 then recompute
** all indices everywhere.
*/
#ifndef SQLITE_OMIT_REINDEX
static void reindexDatabases(Parse *pParse, char const *zColl){
Db *pDb; /* A single database */
int iDb; /* The database index number */
sqlite3 *db = pParse->db; /* The database connection */
HashElem *k; /* For looping over tables in pDb */
Table *pTab; /* A table in the database */
assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
assert( pDb!=0 );
for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
pTab = (Table*)sqliteHashData(k);
reindexTable(pParse, pTab, zColl);
}
}
}
#endif
/*
** Generate code for the REINDEX command.
**
** REINDEX -- 1
** REINDEX <collation> -- 2
** REINDEX ?<database>.?<tablename> -- 3
** REINDEX ?<database>.?<indexname> -- 4
**
** Form 1 causes all indices in all attached databases to be rebuilt.
** Form 2 rebuilds all indices in all databases that use the named
** collating function. Forms 3 and 4 rebuild the named index or all
** indices associated with the named table.
*/
#ifndef SQLITE_OMIT_REINDEX
void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
char *z; /* Name of a table or index */
const char *zDb; /* Name of the database */
Table *pTab; /* A table in the database */
Index *pIndex; /* An index associated with pTab */
int iDb; /* The database index number */
sqlite3 *db = pParse->db; /* The database connection */
Token *pObjName; /* Name of the table or index to be reindexed */
/* Read the database schema. If an error occurs, leave an error message
** and code in pParse and return NULL. */
if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
return;
}
if( pName1==0 ){
reindexDatabases(pParse, 0);
return;
}else if( NEVER(pName2==0) || pName2->z==0 ){
char *zColl;
assert( pName1->z );
zColl = sqlite3NameFromToken(pParse->db, pName1);
if( !zColl ) return;
pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
if( pColl ){
reindexDatabases(pParse, zColl);
sqlite3DbFree(db, zColl);
return;
}
sqlite3DbFree(db, zColl);
}
iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
if( iDb<0 ) return;
z = sqlite3NameFromToken(db, pObjName);
if( z==0 ) return;
zDb = db->aDb[iDb].zDbSName;
pTab = sqlite3FindTable(db, z, zDb);
if( pTab ){
reindexTable(pParse, pTab, 0);
sqlite3DbFree(db, z);
return;
}
pIndex = sqlite3FindIndex(db, z, zDb);
sqlite3DbFree(db, z);
if( pIndex ){
sqlite3BeginWriteOperation(pParse, 0, iDb);
sqlite3RefillIndex(pParse, pIndex, -1);
return;
}
sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
}
#endif
/*
** Return a KeyInfo structure that is appropriate for the given Index.
**
** The caller should invoke sqlite3KeyInfoUnref() on the returned object
** when it has finished using it.
*/
KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
int i;
int nCol = pIdx->nColumn;
int nKey = pIdx->nKeyCol;
KeyInfo *pKey;
if( pParse->nErr ) return 0;
if( pIdx->uniqNotNull ){
pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
}else{
pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
}
if( pKey ){
assert( sqlite3KeyInfoIsWriteable(pKey) );
for(i=0; i<nCol; i++){
const char *zColl = pIdx->azColl[i];
pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
sqlite3LocateCollSeq(pParse, zColl);
pKey->aSortFlags[i] = pIdx->aSortOrder[i];
assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
}
if( pParse->nErr ){
assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
if( pIdx->bNoQuery==0 ){
/* Deactivate the index because it contains an unknown collating
** sequence. The only way to reactive the index is to reload the
** schema. Adding the missing collating sequence later does not
** reactive the index. The application had the chance to register
** the missing index using the collation-needed callback. For
** simplicity, SQLite will not give the application a second chance.
*/
pIdx->bNoQuery = 1;
pParse->rc = SQLITE_ERROR_RETRY;
}
sqlite3KeyInfoUnref(pKey);
pKey = 0;
}
}
return pKey;
}
#ifndef SQLITE_OMIT_CTE
/*
** This routine is invoked once per CTE by the parser while parsing a
** WITH clause.
*/
With *sqlite3WithAdd(
Parse *pParse, /* Parsing context */
With *pWith, /* Existing WITH clause, or NULL */
Token *pName, /* Name of the common-table */
ExprList *pArglist, /* Optional column name list for the table */
Select *pQuery /* Query used to initialize the table */
){
sqlite3 *db = pParse->db;
With *pNew;
char *zName;
/* Check that the CTE name is unique within this WITH clause. If
** not, store an error in the Parse structure. */
zName = sqlite3NameFromToken(pParse->db, pName);
if( zName && pWith ){
int i;
for(i=0; i<pWith->nCte; i++){
if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
}
}
}
if( pWith ){
sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
pNew = sqlite3DbRealloc(db, pWith, nByte);
}else{
pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
}
assert( (pNew!=0 && zName!=0) || db->mallocFailed );
if( db->mallocFailed ){
sqlite3ExprListDelete(db, pArglist);
sqlite3SelectDelete(db, pQuery);
sqlite3DbFree(db, zName);
pNew = pWith;
}else{
pNew->a[pNew->nCte].pSelect = pQuery;
pNew->a[pNew->nCte].pCols = pArglist;
pNew->a[pNew->nCte].zName = zName;
pNew->a[pNew->nCte].zCteErr = 0;
pNew->nCte++;
}
return pNew;
}
/*
** Free the contents of the With object passed as the second argument.
*/
void sqlite3WithDelete(sqlite3 *db, With *pWith){
if( pWith ){
int i;
for(i=0; i<pWith->nCte; i++){
struct Cte *pCte = &pWith->a[i];
sqlite3ExprListDelete(db, pCte->pCols);
sqlite3SelectDelete(db, pCte->pSelect);
sqlite3DbFree(db, pCte->zName);
}
sqlite3DbFree(db, pWith);
}
}
#endif /* !defined(SQLITE_OMIT_CTE) */
| ./CrossVul/dataset_final_sorted/CWE-674/c/bad_1310_3 |
crossvul-cpp_data_good_354_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;
ND_TCHECK2(*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++;
/* Not sure how this relates with the protocol specification,
* but in order to avoid stack exhaustion recurse at most that
* many levels.
*/
if (depth == 10)
ND_PRINT((ndo, "(too many nested levels, not recursing)"));
else
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-674/c/good_354_0 |
crossvul-cpp_data_good_3382_2 | /*
Copyright (c) 2013. The YARA Authors. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
This module implements a regular expressions engine based on Thompson's
algorithm as described by Russ Cox in http://swtch.com/~rsc/regexp/regexp2.html.
What the article names a "thread" has been named a "fiber" in this code, in
order to avoid confusion with operating system threads.
*/
#include <assert.h>
#include <string.h>
#include <limits.h>
#include <yara/limits.h>
#include <yara/globals.h>
#include <yara/utils.h>
#include <yara/mem.h>
#include <yara/re.h>
#include <yara/error.h>
#include <yara/threading.h>
#include <yara/re_lexer.h>
#include <yara/hex_lexer.h>
#define EMIT_BACKWARDS 0x01
#define EMIT_DONT_SET_FORWARDS_CODE 0x02
#define EMIT_DONT_SET_BACKWARDS_CODE 0x04
typedef struct _RE_REPEAT_ARGS
{
uint16_t min;
uint16_t max;
int32_t offset;
} RE_REPEAT_ARGS;
typedef struct _RE_REPEAT_ANY_ARGS
{
uint16_t min;
uint16_t max;
} RE_REPEAT_ANY_ARGS;
typedef struct _RE_EMIT_CONTEXT {
YR_ARENA* arena;
RE_SPLIT_ID_TYPE next_split_id;
} RE_EMIT_CONTEXT;
typedef struct _RE_FIBER
{
uint8_t* ip; // instruction pointer
int32_t sp; // stack pointer
int32_t rc; // repeat counter
uint16_t stack[RE_MAX_STACK];
struct _RE_FIBER* prev;
struct _RE_FIBER* next;
} RE_FIBER;
typedef struct _RE_FIBER_LIST
{
RE_FIBER* head;
RE_FIBER* tail;
} RE_FIBER_LIST;
typedef struct _RE_FIBER_POOL
{
int fiber_count;
RE_FIBER_LIST fibers;
} RE_FIBER_POOL;
typedef struct _RE_THREAD_STORAGE
{
RE_FIBER_POOL fiber_pool;
} RE_THREAD_STORAGE;
YR_THREAD_STORAGE_KEY thread_storage_key = 0;
#define CHAR_IN_CLASS(chr, cls) \
((cls)[(chr) / 8] & 1 << ((chr) % 8))
int _yr_re_is_word_char(
uint8_t* input,
uint8_t character_size)
{
int result = ((isalnum(*input) || (*input) == '_'));
if (character_size == 2)
result = result && (*(input + 1) == 0);
return result;
}
//
// yr_re_initialize
//
// Should be called by main thread before any other
// function from this module.
//
int yr_re_initialize(void)
{
return yr_thread_storage_create(&thread_storage_key);
}
//
// yr_re_finalize
//
// Should be called by main thread after every other thread
// stopped using functions from this module.
//
int yr_re_finalize(void)
{
yr_thread_storage_destroy(&thread_storage_key);
thread_storage_key = 0;
return ERROR_SUCCESS;
}
//
// yr_re_finalize_thread
//
// Should be called by every thread using this module
// before exiting.
//
int yr_re_finalize_thread(void)
{
RE_FIBER* fiber;
RE_FIBER* next_fiber;
RE_THREAD_STORAGE* storage;
if (thread_storage_key != 0)
storage = (RE_THREAD_STORAGE*) yr_thread_storage_get_value(
&thread_storage_key);
else
return ERROR_SUCCESS;
if (storage != NULL)
{
fiber = storage->fiber_pool.fibers.head;
while (fiber != NULL)
{
next_fiber = fiber->next;
yr_free(fiber);
fiber = next_fiber;
}
yr_free(storage);
}
return yr_thread_storage_set_value(&thread_storage_key, NULL);
}
RE_NODE* yr_re_node_create(
int type,
RE_NODE* left,
RE_NODE* right)
{
RE_NODE* result = (RE_NODE*) yr_malloc(sizeof(RE_NODE));
if (result != NULL)
{
result->type = type;
result->left = left;
result->right = right;
result->greedy = TRUE;
result->forward_code = NULL;
result->backward_code = NULL;
}
return result;
}
void yr_re_node_destroy(
RE_NODE* node)
{
if (node->left != NULL)
yr_re_node_destroy(node->left);
if (node->right != NULL)
yr_re_node_destroy(node->right);
if (node->type == RE_NODE_CLASS)
yr_free(node->class_vector);
yr_free(node);
}
int yr_re_ast_create(
RE_AST** re_ast)
{
*re_ast = (RE_AST*) yr_malloc(sizeof(RE_AST));
if (*re_ast == NULL)
return ERROR_INSUFFICIENT_MEMORY;
(*re_ast)->flags = 0;
(*re_ast)->levels = 0;
(*re_ast)->root_node = NULL;
return ERROR_SUCCESS;
}
void yr_re_ast_destroy(
RE_AST* re_ast)
{
if (re_ast->root_node != NULL)
yr_re_node_destroy(re_ast->root_node);
yr_free(re_ast);
}
//
// yr_re_parse
//
// Parses a regexp but don't emit its code. A further call to
// yr_re_emit_code is required to get the code.
//
int yr_re_parse(
const char* re_string,
RE_AST** re_ast,
RE_ERROR* error)
{
return yr_parse_re_string(re_string, re_ast, error);
}
//
// yr_re_parse_hex
//
// Parses a hex string but don't emit its code. A further call to
// yr_re_emit_code is required to get the code.
//
int yr_re_parse_hex(
const char* hex_string,
RE_AST** re_ast,
RE_ERROR* error)
{
return yr_parse_hex_string(hex_string, re_ast, error);
}
//
// yr_re_compile
//
// Parses the regexp and emit its code to the provided code_arena.
//
int yr_re_compile(
const char* re_string,
int flags,
YR_ARENA* code_arena,
RE** re,
RE_ERROR* error)
{
RE_AST* re_ast;
RE _re;
FAIL_ON_ERROR(yr_arena_reserve_memory(
code_arena, sizeof(int64_t) + RE_MAX_CODE_SIZE));
FAIL_ON_ERROR(yr_re_parse(re_string, &re_ast, error));
_re.flags = flags;
FAIL_ON_ERROR_WITH_CLEANUP(
yr_arena_write_data(
code_arena,
&_re,
sizeof(_re),
(void**) re),
yr_re_ast_destroy(re_ast));
FAIL_ON_ERROR_WITH_CLEANUP(
yr_re_ast_emit_code(re_ast, code_arena, FALSE),
yr_re_ast_destroy(re_ast));
yr_re_ast_destroy(re_ast);
return ERROR_SUCCESS;
}
//
// yr_re_match
//
// Verifies if the target string matches the pattern
//
// Args:
// RE* re - A pointer to a compiled regexp
// char* target - Target string
//
// Returns:
// See return codes for yr_re_exec
int yr_re_match(
RE* re,
const char* target)
{
int result;
yr_re_exec(
re->code,
(uint8_t*) target,
strlen(target),
0,
re->flags | RE_FLAGS_SCAN,
NULL,
NULL,
&result);
return result;
}
//
// yr_re_ast_extract_literal
//
// Verifies if the provided regular expression is just a literal string
// like "abc", "12345", without any wildcard, operator, etc. In that case
// returns the string as a SIZED_STRING, or returns NULL if otherwise.
//
// The caller is responsible for deallocating the returned SIZED_STRING by
// calling yr_free.
//
SIZED_STRING* yr_re_ast_extract_literal(
RE_AST* re_ast)
{
SIZED_STRING* string;
RE_NODE* node = re_ast->root_node;
int i, length = 0;
char tmp;
while (node != NULL)
{
length++;
if (node->type == RE_NODE_LITERAL)
break;
if (node->type != RE_NODE_CONCAT)
return NULL;
if (node->right == NULL ||
node->right->type != RE_NODE_LITERAL)
return NULL;
node = node->left;
}
string = (SIZED_STRING*) yr_malloc(sizeof(SIZED_STRING) + length);
if (string == NULL)
return NULL;
string->length = 0;
node = re_ast->root_node;
while (node->type == RE_NODE_CONCAT)
{
string->c_string[string->length++] = node->right->value;
node = node->left;
}
string->c_string[string->length++] = node->value;
// The string ends up reversed. Reverse it back to its original value.
for (i = 0; i < length / 2; i++)
{
tmp = string->c_string[i];
string->c_string[i] = string->c_string[length - i - 1];
string->c_string[length - i - 1] = tmp;
}
return string;
}
int _yr_re_node_contains_dot_star(
RE_NODE* re_node)
{
if (re_node->type == RE_NODE_STAR && re_node->left->type == RE_NODE_ANY)
return TRUE;
if (re_node->left != NULL && _yr_re_node_contains_dot_star(re_node->left))
return TRUE;
if (re_node->right != NULL && _yr_re_node_contains_dot_star(re_node->right))
return TRUE;
return FALSE;
}
int yr_re_ast_contains_dot_star(
RE_AST* re_ast)
{
return _yr_re_node_contains_dot_star(re_ast->root_node);
}
//
// yr_re_ast_split_at_chaining_point
//
// In some cases splitting a regular expression in two is more efficient that
// having a single regular expression. This happens when the regular expression
// contains a large repetition of any character, for example: /foo.{0,1000}bar/
// In this case the regexp is split in /foo/ and /bar/ where /bar/ is "chained"
// to /foo/. This means that /foo/ and /bar/ are handled as individual regexps
// and when both matches YARA verifies if the distance between the matches
// complies with the {0,1000} restriction.
// This function traverses the regexp's tree looking for nodes where the regxp
// should be split. It expects a left-unbalanced tree where the right child of
// a RE_NODE_CONCAT can't be another RE_NODE_CONCAT. A RE_NODE_CONCAT must be
// always the left child of its parent if the parent is also a RE_NODE_CONCAT.
//
int yr_re_ast_split_at_chaining_point(
RE_AST* re_ast,
RE_AST** result_re_ast,
RE_AST** remainder_re_ast,
int32_t* min_gap,
int32_t* max_gap)
{
RE_NODE* node = re_ast->root_node;
RE_NODE* child = re_ast->root_node->left;
RE_NODE* parent = NULL;
int result;
*result_re_ast = re_ast;
*remainder_re_ast = NULL;
*min_gap = 0;
*max_gap = 0;
while (child != NULL && child->type == RE_NODE_CONCAT)
{
if (child->right != NULL &&
child->right->type == RE_NODE_RANGE_ANY &&
child->right->greedy == FALSE &&
(child->right->start > STRING_CHAINING_THRESHOLD ||
child->right->end > STRING_CHAINING_THRESHOLD))
{
result = yr_re_ast_create(remainder_re_ast);
if (result != ERROR_SUCCESS)
return result;
(*remainder_re_ast)->root_node = child->left;
(*remainder_re_ast)->flags = re_ast->flags;
child->left = NULL;
if (parent != NULL)
parent->left = node->right;
else
(*result_re_ast)->root_node = node->right;
node->right = NULL;
*min_gap = child->right->start;
*max_gap = child->right->end;
yr_re_node_destroy(node);
return ERROR_SUCCESS;
}
parent = node;
node = child;
child = child->left;
}
return ERROR_SUCCESS;
}
int _yr_emit_inst(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint8_t** instruction_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
*code_size = sizeof(uint8_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_uint8(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint8_t argument,
uint8_t** instruction_addr,
uint8_t** argument_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(uint8_t),
(void**) argument_addr));
*code_size = 2 * sizeof(uint8_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_uint16(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint16_t argument,
uint8_t** instruction_addr,
uint16_t** argument_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(uint16_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(uint16_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_uint32(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint32_t argument,
uint8_t** instruction_addr,
uint32_t** argument_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(uint32_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(uint32_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_int16(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
int16_t argument,
uint8_t** instruction_addr,
int16_t** argument_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(int16_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(int16_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_struct(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
void* structure,
size_t structure_size,
uint8_t** instruction_addr,
void** argument_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
structure,
structure_size,
(void**) argument_addr));
*code_size = sizeof(uint8_t) + structure_size;
return ERROR_SUCCESS;
}
int _yr_emit_split(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
int16_t argument,
uint8_t** instruction_addr,
int16_t** argument_addr,
size_t* code_size)
{
assert(opcode == RE_OPCODE_SPLIT_A || opcode == RE_OPCODE_SPLIT_B);
if (emit_context->next_split_id == RE_MAX_SPLIT_ID)
return ERROR_REGULAR_EXPRESSION_TOO_COMPLEX;
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&emit_context->next_split_id,
sizeof(RE_SPLIT_ID_TYPE),
NULL));
emit_context->next_split_id++;
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(int16_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(RE_SPLIT_ID_TYPE) + sizeof(int16_t);
return ERROR_SUCCESS;
}
int _yr_re_emit(
RE_EMIT_CONTEXT* emit_context,
RE_NODE* re_node,
int flags,
uint8_t** code_addr,
size_t* code_size)
{
size_t branch_size;
size_t split_size;
size_t inst_size;
size_t jmp_size;
int emit_split;
int emit_repeat;
int emit_prolog;
int emit_epilog;
RE_REPEAT_ARGS repeat_args;
RE_REPEAT_ARGS* repeat_start_args_addr;
RE_REPEAT_ANY_ARGS repeat_any_args;
RE_NODE* left;
RE_NODE* right;
int16_t* split_offset_addr = NULL;
int16_t* jmp_offset_addr = NULL;
uint8_t* instruction_addr = NULL;
*code_size = 0;
switch(re_node->type)
{
case RE_NODE_LITERAL:
FAIL_ON_ERROR(_yr_emit_inst_arg_uint8(
emit_context,
RE_OPCODE_LITERAL,
re_node->value,
&instruction_addr,
NULL,
code_size));
break;
case RE_NODE_MASKED_LITERAL:
FAIL_ON_ERROR(_yr_emit_inst_arg_uint16(
emit_context,
RE_OPCODE_MASKED_LITERAL,
re_node->mask << 8 | re_node->value,
&instruction_addr,
NULL,
code_size));
break;
case RE_NODE_WORD_CHAR:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_WORD_CHAR,
&instruction_addr,
code_size));
break;
case RE_NODE_NON_WORD_CHAR:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_NON_WORD_CHAR,
&instruction_addr,
code_size));
break;
case RE_NODE_WORD_BOUNDARY:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_WORD_BOUNDARY,
&instruction_addr,
code_size));
break;
case RE_NODE_NON_WORD_BOUNDARY:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_NON_WORD_BOUNDARY,
&instruction_addr,
code_size));
break;
case RE_NODE_SPACE:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_SPACE,
&instruction_addr,
code_size));
break;
case RE_NODE_NON_SPACE:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_NON_SPACE,
&instruction_addr,
code_size));
break;
case RE_NODE_DIGIT:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_DIGIT,
&instruction_addr,
code_size));
break;
case RE_NODE_NON_DIGIT:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_NON_DIGIT,
&instruction_addr,
code_size));
break;
case RE_NODE_ANY:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_ANY,
&instruction_addr,
code_size));
break;
case RE_NODE_CLASS:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_CLASS,
&instruction_addr,
code_size));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
re_node->class_vector,
32,
NULL));
*code_size += 32;
break;
case RE_NODE_ANCHOR_START:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_MATCH_AT_START,
&instruction_addr,
code_size));
break;
case RE_NODE_ANCHOR_END:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_MATCH_AT_END,
&instruction_addr,
code_size));
break;
case RE_NODE_CONCAT:
if (flags & EMIT_BACKWARDS)
{
left = re_node->right;
right = re_node->left;
}
else
{
left = re_node->left;
right = re_node->right;
}
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
left,
flags,
&instruction_addr,
&branch_size));
*code_size += branch_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
right,
flags,
NULL,
&branch_size));
*code_size += branch_size;
break;
case RE_NODE_PLUS:
// Code for e+ looks like:
//
// L1: code for e
// split L1, L2
// L2:
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags,
&instruction_addr,
&branch_size));
*code_size += branch_size;
FAIL_ON_ERROR(_yr_emit_split(
emit_context,
re_node->greedy ? RE_OPCODE_SPLIT_B : RE_OPCODE_SPLIT_A,
-((int16_t) branch_size),
NULL,
&split_offset_addr,
&split_size));
*code_size += split_size;
break;
case RE_NODE_STAR:
// Code for e* looks like:
//
// L1: split L1, L2
// code for e
// jmp L1
// L2:
FAIL_ON_ERROR(_yr_emit_split(
emit_context,
re_node->greedy ? RE_OPCODE_SPLIT_A : RE_OPCODE_SPLIT_B,
0,
&instruction_addr,
&split_offset_addr,
&split_size));
*code_size += split_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags,
NULL,
&branch_size));
*code_size += branch_size;
// Emit jump with offset set to 0.
FAIL_ON_ERROR(_yr_emit_inst_arg_int16(
emit_context,
RE_OPCODE_JUMP,
-((uint16_t)(branch_size + split_size)),
NULL,
&jmp_offset_addr,
&jmp_size));
*code_size += jmp_size;
assert(split_size + branch_size + jmp_size < INT16_MAX);
// Update split offset.
*split_offset_addr = (int16_t) (split_size + branch_size + jmp_size);
break;
case RE_NODE_ALT:
// Code for e1|e2 looks like:
//
// split L1, L2
// L1: code for e1
// jmp L3
// L2: code for e2
// L3:
// Emit a split instruction with offset set to 0 temporarily. Offset
// will be updated after we know the size of the code generated for
// the left node (e1).
FAIL_ON_ERROR(_yr_emit_split(
emit_context,
RE_OPCODE_SPLIT_A,
0,
&instruction_addr,
&split_offset_addr,
&split_size));
*code_size += split_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags,
NULL,
&branch_size));
*code_size += branch_size;
// Emit jump with offset set to 0.
FAIL_ON_ERROR(_yr_emit_inst_arg_int16(
emit_context,
RE_OPCODE_JUMP,
0,
NULL,
&jmp_offset_addr,
&jmp_size));
*code_size += jmp_size;
assert(split_size + branch_size + jmp_size < INT16_MAX);
// Update split offset.
*split_offset_addr = (int16_t) (split_size + branch_size + jmp_size);
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->right,
flags,
NULL,
&branch_size));
*code_size += branch_size;
assert(branch_size + jmp_size < INT16_MAX);
// Update offset for jmp instruction.
*jmp_offset_addr = (int16_t) (branch_size + jmp_size);
break;
case RE_NODE_RANGE_ANY:
repeat_any_args.min = re_node->start;
repeat_any_args.max = re_node->end;
FAIL_ON_ERROR(_yr_emit_inst_arg_struct(
emit_context,
re_node->greedy ?
RE_OPCODE_REPEAT_ANY_GREEDY :
RE_OPCODE_REPEAT_ANY_UNGREEDY,
&repeat_any_args,
sizeof(repeat_any_args),
&instruction_addr,
NULL,
&inst_size));
*code_size += inst_size;
break;
case RE_NODE_RANGE:
// Code for e{n,m} looks like:
//
// code for e --- prolog
// repeat_start n, m, L1 --+
// L0: code for e | repeat
// repeat_end n, m, L0 --+
// L1: split L2, L3 --- split
// L2: code for e --- epilog
// L3:
//
// Not all sections (prolog, repeat, split and epilog) are generated in all
// cases, it depends on the values of n and m. The following table shows
// which sections are generated for the first few values of n and m.
//
// n,m prolog repeat split epilog
// (min,max)
// ---------------------------------------
// 0,0 - - - -
// 0,1 - - X X
// 0,2 - 0,1 X X
// 0,3 - 0,2 X X
// 0,M - 0,M-1 X X
//
// 1,1 X - - -
// 1,2 X - X X
// 1,3 X 0,1 X X
// 1,4 X 1,2 X X
// 1,M X 1,M-2 X X
//
// 2,2 X - - X
// 2,3 X 1,1 X X
// 2,4 X 1,2 X X
// 2,M X 1,M-2 X X
//
// 3,3 X 1,1 - X
// 3,4 X 2,2 X X
// 3,M X 2,M-1 X X
//
// The code can't consists simply in the repeat section, the prolog and
// epilog are required because we can't have atoms pointing to code inside
// the repeat loop. Atoms' forwards_code will point to code in the prolog
// and backwards_code will point to code in the epilog (or in prolog if
// epilog wasn't generated, like in n=1,m=1)
emit_prolog = re_node->start > 0;
emit_repeat = re_node->end > re_node->start + 1 || re_node->end > 2;
emit_split = re_node->end > re_node->start;
emit_epilog = re_node->end > re_node->start || re_node->end > 1;
if (emit_prolog)
{
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags,
&instruction_addr,
&branch_size));
*code_size += branch_size;
}
if (emit_repeat)
{
repeat_args.min = re_node->start;
repeat_args.max = re_node->end;
if (emit_prolog)
{
repeat_args.max--;
repeat_args.min--;
}
if (emit_split)
repeat_args.max--;
else
repeat_args.min--;
repeat_args.offset = 0;
FAIL_ON_ERROR(_yr_emit_inst_arg_struct(
emit_context,
re_node->greedy ?
RE_OPCODE_REPEAT_START_GREEDY :
RE_OPCODE_REPEAT_START_UNGREEDY,
&repeat_args,
sizeof(repeat_args),
emit_prolog ? NULL : &instruction_addr,
(void**) &repeat_start_args_addr,
&inst_size));
*code_size += inst_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags | EMIT_DONT_SET_FORWARDS_CODE | EMIT_DONT_SET_BACKWARDS_CODE,
NULL,
&branch_size));
*code_size += branch_size;
repeat_start_args_addr->offset = (int32_t)(2 * inst_size + branch_size);
repeat_args.offset = -((int32_t) branch_size);
FAIL_ON_ERROR(_yr_emit_inst_arg_struct(
emit_context,
re_node->greedy ?
RE_OPCODE_REPEAT_END_GREEDY :
RE_OPCODE_REPEAT_END_UNGREEDY,
&repeat_args,
sizeof(repeat_args),
NULL,
NULL,
&inst_size));
*code_size += inst_size;
}
if (emit_split)
{
FAIL_ON_ERROR(_yr_emit_split(
emit_context,
re_node->greedy ?
RE_OPCODE_SPLIT_A :
RE_OPCODE_SPLIT_B,
0,
NULL,
&split_offset_addr,
&split_size));
*code_size += split_size;
}
if (emit_epilog)
{
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
emit_prolog ? flags | EMIT_DONT_SET_FORWARDS_CODE : flags,
emit_prolog || emit_repeat ? NULL : &instruction_addr,
&branch_size));
*code_size += branch_size;
}
if (emit_split)
{
assert(split_size + branch_size < INT16_MAX);
*split_offset_addr = (int16_t) (split_size + branch_size);
}
break;
}
if (flags & EMIT_BACKWARDS)
{
if (!(flags & EMIT_DONT_SET_BACKWARDS_CODE))
re_node->backward_code = instruction_addr + *code_size;
}
else
{
if (!(flags & EMIT_DONT_SET_FORWARDS_CODE))
re_node->forward_code = instruction_addr;
}
if (code_addr != NULL)
*code_addr = instruction_addr;
return ERROR_SUCCESS;
}
int yr_re_ast_emit_code(
RE_AST* re_ast,
YR_ARENA* arena,
int backwards_code)
{
RE_EMIT_CONTEXT emit_context;
size_t code_size;
size_t total_size;
// Ensure that we have enough contiguous memory space in the arena to
// contain the regular expression code. The code can't span over multiple
// non-contiguous pages.
FAIL_ON_ERROR(yr_arena_reserve_memory(arena, RE_MAX_CODE_SIZE));
// Emit code for matching the regular expressions forwards.
total_size = 0;
emit_context.arena = arena;
emit_context.next_split_id = 0;
FAIL_ON_ERROR(_yr_re_emit(
&emit_context,
re_ast->root_node,
backwards_code ? EMIT_BACKWARDS : 0,
NULL,
&code_size));
total_size += code_size;
FAIL_ON_ERROR(_yr_emit_inst(
&emit_context,
RE_OPCODE_MATCH,
NULL,
&code_size));
total_size += code_size;
if (total_size > RE_MAX_CODE_SIZE)
return ERROR_REGULAR_EXPRESSION_TOO_LARGE;
return ERROR_SUCCESS;
}
int _yr_re_alloc_storage(
RE_THREAD_STORAGE** storage)
{
*storage = (RE_THREAD_STORAGE*) yr_thread_storage_get_value(
&thread_storage_key);
if (*storage == NULL)
{
*storage = (RE_THREAD_STORAGE*) yr_malloc(sizeof(RE_THREAD_STORAGE));
if (*storage == NULL)
return ERROR_INSUFFICIENT_MEMORY;
(*storage)->fiber_pool.fiber_count = 0;
(*storage)->fiber_pool.fibers.head = NULL;
(*storage)->fiber_pool.fibers.tail = NULL;
FAIL_ON_ERROR(
yr_thread_storage_set_value(&thread_storage_key, *storage));
}
return ERROR_SUCCESS;
}
int _yr_re_fiber_create(
RE_FIBER_POOL* fiber_pool,
RE_FIBER** new_fiber)
{
RE_FIBER* fiber;
if (fiber_pool->fibers.head != NULL)
{
fiber = fiber_pool->fibers.head;
fiber_pool->fibers.head = fiber->next;
if (fiber_pool->fibers.tail == fiber)
fiber_pool->fibers.tail = NULL;
}
else
{
if (fiber_pool->fiber_count == RE_MAX_FIBERS)
return ERROR_TOO_MANY_RE_FIBERS;
fiber = (RE_FIBER*) yr_malloc(sizeof(RE_FIBER));
if (fiber == NULL)
return ERROR_INSUFFICIENT_MEMORY;
fiber_pool->fiber_count++;
}
fiber->ip = NULL;
fiber->sp = -1;
fiber->rc = -1;
fiber->next = NULL;
fiber->prev = NULL;
*new_fiber = fiber;
return ERROR_SUCCESS;
}
//
// _yr_re_fiber_append
//
// Appends 'fiber' to 'fiber_list'
//
void _yr_re_fiber_append(
RE_FIBER_LIST* fiber_list,
RE_FIBER* fiber)
{
assert(fiber->prev == NULL);
assert(fiber->next == NULL);
fiber->prev = fiber_list->tail;
if (fiber_list->tail != NULL)
fiber_list->tail->next = fiber;
fiber_list->tail = fiber;
if (fiber_list->head == NULL)
fiber_list->head = fiber;
assert(fiber_list->tail->next == NULL);
assert(fiber_list->head->prev == NULL);
}
//
// _yr_re_fiber_exists
//
// Verifies if a fiber with the same properties (ip, rc, sp, and stack values)
// than 'target_fiber' exists in 'fiber_list'. The list is iterated from
// the start until 'last_fiber' (inclusive). Fibers past 'last_fiber' are not
// taken into account.
//
int _yr_re_fiber_exists(
RE_FIBER_LIST* fiber_list,
RE_FIBER* target_fiber,
RE_FIBER* last_fiber)
{
RE_FIBER* fiber = fiber_list->head;
int equal_stacks;
int i;
if (last_fiber == NULL)
return FALSE;
while (fiber != last_fiber->next)
{
if (fiber->ip == target_fiber->ip &&
fiber->sp == target_fiber->sp &&
fiber->rc == target_fiber->rc)
{
equal_stacks = TRUE;
for (i = 0; i <= fiber->sp; i++)
{
if (fiber->stack[i] != target_fiber->stack[i])
{
equal_stacks = FALSE;
break;
}
}
if (equal_stacks)
return TRUE;
}
fiber = fiber->next;
}
return FALSE;
}
//
// _yr_re_fiber_split
//
// Clones a fiber in fiber_list and inserts the cloned fiber just after.
// the original one. If fiber_list is:
//
// f1 -> f2 -> f3 -> f4
//
// Splitting f2 will result in:
//
// f1 -> f2 -> cloned f2 -> f3 -> f4
//
int _yr_re_fiber_split(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool,
RE_FIBER* fiber,
RE_FIBER** new_fiber)
{
int32_t i;
FAIL_ON_ERROR(_yr_re_fiber_create(fiber_pool, new_fiber));
(*new_fiber)->sp = fiber->sp;
(*new_fiber)->ip = fiber->ip;
(*new_fiber)->rc = fiber->rc;
for (i = 0; i <= fiber->sp; i++)
(*new_fiber)->stack[i] = fiber->stack[i];
(*new_fiber)->next = fiber->next;
(*new_fiber)->prev = fiber;
if (fiber->next != NULL)
fiber->next->prev = *new_fiber;
fiber->next = *new_fiber;
if (fiber_list->tail == fiber)
fiber_list->tail = *new_fiber;
assert(fiber_list->tail->next == NULL);
assert(fiber_list->head->prev == NULL);
return ERROR_SUCCESS;
}
//
// _yr_re_fiber_kill
//
// Kills a given fiber by removing it from the fiber list and putting it
// in the fiber pool.
//
RE_FIBER* _yr_re_fiber_kill(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool,
RE_FIBER* fiber)
{
RE_FIBER* next_fiber = fiber->next;
if (fiber->prev != NULL)
fiber->prev->next = next_fiber;
if (next_fiber != NULL)
next_fiber->prev = fiber->prev;
if (fiber_pool->fibers.tail != NULL)
fiber_pool->fibers.tail->next = fiber;
if (fiber_list->tail == fiber)
fiber_list->tail = fiber->prev;
if (fiber_list->head == fiber)
fiber_list->head = next_fiber;
fiber->next = NULL;
fiber->prev = fiber_pool->fibers.tail;
fiber_pool->fibers.tail = fiber;
if (fiber_pool->fibers.head == NULL)
fiber_pool->fibers.head = fiber;
return next_fiber;
}
//
// _yr_re_fiber_kill_tail
//
// Kills all fibers from the given one up to the end of the fiber list.
//
void _yr_re_fiber_kill_tail(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool,
RE_FIBER* fiber)
{
RE_FIBER* prev_fiber = fiber->prev;
if (prev_fiber != NULL)
prev_fiber->next = NULL;
fiber->prev = fiber_pool->fibers.tail;
if (fiber_pool->fibers.tail != NULL)
fiber_pool->fibers.tail->next = fiber;
fiber_pool->fibers.tail = fiber_list->tail;
fiber_list->tail = prev_fiber;
if (fiber_list->head == fiber)
fiber_list->head = NULL;
if (fiber_pool->fibers.head == NULL)
fiber_pool->fibers.head = fiber;
}
//
// _yr_re_fiber_kill_all
//
// Kills all fibers in the fiber list.
//
void _yr_re_fiber_kill_all(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool)
{
if (fiber_list->head != NULL)
_yr_re_fiber_kill_tail(fiber_list, fiber_pool, fiber_list->head);
}
//
// _yr_re_fiber_sync
//
// Executes a fiber until reaching an "matching" instruction. A "matching"
// instruction is one that actually reads a byte from the input and performs
// some matching. If the fiber reaches a split instruction, the new fiber is
// also synced.
//
int _yr_re_fiber_sync(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool,
RE_FIBER* fiber_to_sync)
{
// A array for keeping track of which split instructions has been already
// executed. Each split instruction within a regexp has an associated ID
// between 0 and RE_MAX_SPLIT_ID. Keeping track of executed splits is
// required to avoid infinite loops in regexps like (a*)* or (a|)*
RE_SPLIT_ID_TYPE splits_executed[RE_MAX_SPLIT_ID];
RE_SPLIT_ID_TYPE splits_executed_count = 0;
RE_SPLIT_ID_TYPE split_id, splits_executed_idx;
int split_already_executed;
RE_REPEAT_ARGS* repeat_args;
RE_REPEAT_ANY_ARGS* repeat_any_args;
RE_FIBER* fiber;
RE_FIBER* last;
RE_FIBER* prev;
RE_FIBER* next;
RE_FIBER* branch_a;
RE_FIBER* branch_b;
fiber = fiber_to_sync;
prev = fiber_to_sync->prev;
last = fiber_to_sync->next;
while(fiber != last)
{
uint8_t opcode = *fiber->ip;
switch(opcode)
{
case RE_OPCODE_SPLIT_A:
case RE_OPCODE_SPLIT_B:
split_id = *(RE_SPLIT_ID_TYPE*)(fiber->ip + 1);
split_already_executed = FALSE;
for (splits_executed_idx = 0;
splits_executed_idx < splits_executed_count;
splits_executed_idx++)
{
if (split_id == splits_executed[splits_executed_idx])
{
split_already_executed = TRUE;
break;
}
}
if (split_already_executed)
{
fiber = _yr_re_fiber_kill(fiber_list, fiber_pool, fiber);
}
else
{
branch_a = fiber;
FAIL_ON_ERROR(_yr_re_fiber_split(
fiber_list, fiber_pool, branch_a, &branch_b));
// With RE_OPCODE_SPLIT_A the current fiber continues at the next
// instruction in the stream (branch A), while the newly created
// fiber starts at the address indicated by the instruction (branch B)
// RE_OPCODE_SPLIT_B has the opposite behavior.
if (opcode == RE_OPCODE_SPLIT_B)
yr_swap(branch_a, branch_b, RE_FIBER*);
// Branch A continues at the next instruction
branch_a->ip += (sizeof(RE_SPLIT_ID_TYPE) + 3);
// Branch B adds the offset encoded in the opcode to its instruction
// pointer.
branch_b->ip += *(int16_t*)(
branch_b->ip
+ 1 // opcode size
+ sizeof(RE_SPLIT_ID_TYPE));
splits_executed[splits_executed_count] = split_id;
splits_executed_count++;
}
break;
case RE_OPCODE_REPEAT_START_GREEDY:
case RE_OPCODE_REPEAT_START_UNGREEDY:
repeat_args = (RE_REPEAT_ARGS*)(fiber->ip + 1);
assert(repeat_args->max > 0);
branch_a = fiber;
if (repeat_args->min == 0)
{
FAIL_ON_ERROR(_yr_re_fiber_split(
fiber_list, fiber_pool, branch_a, &branch_b));
if (opcode == RE_OPCODE_REPEAT_START_UNGREEDY)
yr_swap(branch_a, branch_b, RE_FIBER*);
branch_b->ip += repeat_args->offset;
}
branch_a->stack[++branch_a->sp] = 0;
branch_a->ip += (1 + sizeof(RE_REPEAT_ARGS));
break;
case RE_OPCODE_REPEAT_END_GREEDY:
case RE_OPCODE_REPEAT_END_UNGREEDY:
repeat_args = (RE_REPEAT_ARGS*)(fiber->ip + 1);
fiber->stack[fiber->sp]++;
if (fiber->stack[fiber->sp] < repeat_args->min)
{
fiber->ip += repeat_args->offset;
break;
}
branch_a = fiber;
if (fiber->stack[fiber->sp] < repeat_args->max)
{
FAIL_ON_ERROR(_yr_re_fiber_split(
fiber_list, fiber_pool, branch_a, &branch_b));
if (opcode == RE_OPCODE_REPEAT_END_GREEDY)
yr_swap(branch_a, branch_b, RE_FIBER*);
branch_a->sp--;
branch_b->ip += repeat_args->offset;
}
branch_a->ip += (1 + sizeof(RE_REPEAT_ARGS));
break;
case RE_OPCODE_REPEAT_ANY_GREEDY:
case RE_OPCODE_REPEAT_ANY_UNGREEDY:
repeat_any_args = (RE_REPEAT_ANY_ARGS*)(fiber->ip + 1);
// If repetition counter (rc) is -1 it means that we are reaching this
// instruction from the previous one in the instructions stream. In
// this case let's initialize the counter to 0 and start looping.
if (fiber->rc == -1)
fiber->rc = 0;
if (fiber->rc < repeat_any_args->min)
{
// Increase repetition counter and continue with next fiber. The
// instruction pointer for this fiber is not incremented yet, this
// fiber spins in this same instruction until reaching the minimum
// number of repetitions.
fiber->rc++;
fiber = fiber->next;
}
else if (fiber->rc < repeat_any_args->max)
{
// Once the minimum number of repetitions are matched one fiber
// remains spinning in this instruction until reaching the maximum
// number of repetitions while new fibers are created. New fibers
// start executing at the next instruction.
next = fiber->next;
branch_a = fiber;
FAIL_ON_ERROR(_yr_re_fiber_split(
fiber_list, fiber_pool, branch_a, &branch_b));
if (opcode == RE_OPCODE_REPEAT_ANY_UNGREEDY)
yr_swap(branch_a, branch_b, RE_FIBER*);
branch_a->rc++;
branch_b->ip += (1 + sizeof(RE_REPEAT_ANY_ARGS));
branch_b->rc = -1;
FAIL_ON_ERROR(_yr_re_fiber_sync(
fiber_list, fiber_pool, branch_b));
fiber = next;
}
else
{
// When the maximum number of repetitions is reached the fiber keeps
// executing at the next instruction. The repetition counter is set
// to -1 indicating that we are not spinning in a repeat instruction
// anymore.
fiber->ip += (1 + sizeof(RE_REPEAT_ANY_ARGS));
fiber->rc = -1;
}
break;
case RE_OPCODE_JUMP:
fiber->ip += *(int16_t*)(fiber->ip + 1);
break;
default:
if (_yr_re_fiber_exists(fiber_list, fiber, prev))
fiber = _yr_re_fiber_kill(fiber_list, fiber_pool, fiber);
else
fiber = fiber->next;
}
}
return ERROR_SUCCESS;
}
//
// yr_re_exec
//
// Executes a regular expression. The specified regular expression will try to
// match the data starting at the address specified by "input". The "input"
// pointer can point to any address inside a memory buffer. Arguments
// "input_forwards_size" and "input_backwards_size" indicate how many bytes
// can be accesible starting at "input" and going forwards and backwards
// respectively.
//
// <--- input_backwards_size -->|<----------- input_forwards_size -------->
// |-------- memory buffer -----------------------------------------------|
// ^
// input
//
// Args:
// uint8_t* re_code - Regexp code be executed
// uint8_t* input - Pointer to input data
// size_t input_forwards_size - Number of accessible bytes starting at
// "input" and going forwards.
// size_t input_backwards_size - Number of accessible bytes starting at
// "input" and going backwards
// int flags - Flags:
// RE_FLAGS_SCAN
// RE_FLAGS_BACKWARDS
// RE_FLAGS_EXHAUSTIVE
// RE_FLAGS_WIDE
// RE_FLAGS_NO_CASE
// RE_FLAGS_DOT_ALL
// RE_MATCH_CALLBACK_FUNC callback - Callback function
// void* callback_args - Callback argument
// int* matches - Pointer to an integer receiving the
// number of matching bytes. Notice that
// 0 means a zero-length match, while no
// matches is -1.
// Returns:
// ERROR_SUCCESS or any other error code.
int yr_re_exec(
uint8_t* re_code,
uint8_t* input_data,
size_t input_forwards_size,
size_t input_backwards_size,
int flags,
RE_MATCH_CALLBACK_FUNC callback,
void* callback_args,
int* matches)
{
uint8_t* ip;
uint8_t* input;
uint8_t mask;
uint8_t value;
uint8_t character_size;
RE_FIBER_LIST fibers;
RE_THREAD_STORAGE* storage;
RE_FIBER* fiber;
RE_FIBER* next_fiber;
int bytes_matched;
int max_bytes_matched;
int match;
int input_incr;
int kill;
int action;
#define ACTION_NONE 0
#define ACTION_CONTINUE 1
#define ACTION_KILL 2
#define ACTION_KILL_TAIL 3
#define prolog { \
if ((bytes_matched >= max_bytes_matched) || \
(character_size == 2 && *(input + 1) != 0)) \
{ \
action = ACTION_KILL; \
break; \
} \
}
if (matches != NULL)
*matches = -1;
if (_yr_re_alloc_storage(&storage) != ERROR_SUCCESS)
return -2;
if (flags & RE_FLAGS_WIDE)
character_size = 2;
else
character_size = 1;
input = input_data;
input_incr = character_size;
if (flags & RE_FLAGS_BACKWARDS)
{
max_bytes_matched = (int) yr_min(input_backwards_size, RE_SCAN_LIMIT);
input -= character_size;
input_incr = -input_incr;
}
else
{
max_bytes_matched = (int) yr_min(input_forwards_size, RE_SCAN_LIMIT);
}
// Round down max_bytes_matched to a multiple of character_size, this way if
// character_size is 2 and max_bytes_matched is odd we are ignoring the
// extra byte which can't match anyways.
max_bytes_matched = max_bytes_matched - max_bytes_matched % character_size;
bytes_matched = 0;
FAIL_ON_ERROR(_yr_re_fiber_create(&storage->fiber_pool, &fiber));
fiber->ip = re_code;
fibers.head = fiber;
fibers.tail = fiber;
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
while (fibers.head != NULL)
{
fiber = fibers.head;
while(fiber != NULL)
{
ip = fiber->ip;
action = ACTION_NONE;
switch(*ip)
{
case RE_OPCODE_ANY:
prolog;
match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_REPEAT_ANY_GREEDY:
case RE_OPCODE_REPEAT_ANY_UNGREEDY:
prolog;
match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A);
action = match ? ACTION_NONE : ACTION_KILL;
// The instruction pointer is not incremented here. The current fiber
// spins in this instruction until reaching the required number of
// repetitions. The code controlling the number of repetitions is in
// _yr_re_fiber_sync.
break;
case RE_OPCODE_LITERAL:
prolog;
if (flags & RE_FLAGS_NO_CASE)
match = yr_lowercase[*input] == yr_lowercase[*(ip + 1)];
else
match = (*input == *(ip + 1));
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 2;
break;
case RE_OPCODE_MASKED_LITERAL:
prolog;
value = *(int16_t*)(ip + 1) & 0xFF;
mask = *(int16_t*)(ip + 1) >> 8;
// We don't need to take into account the case-insensitive
// case because this opcode is only used with hex strings,
// which can't be case-insensitive.
match = ((*input & mask) == value);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 3;
break;
case RE_OPCODE_CLASS:
prolog;
match = CHAR_IN_CLASS(*input, ip + 1);
if (!match && (flags & RE_FLAGS_NO_CASE))
match = CHAR_IN_CLASS(yr_altercase[*input], ip + 1);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 33;
break;
case RE_OPCODE_WORD_CHAR:
prolog;
match = _yr_re_is_word_char(input, character_size);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_NON_WORD_CHAR:
prolog;
match = !_yr_re_is_word_char(input, character_size);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_SPACE:
case RE_OPCODE_NON_SPACE:
prolog;
switch(*input)
{
case ' ':
case '\t':
case '\r':
case '\n':
case '\v':
case '\f':
match = TRUE;
break;
default:
match = FALSE;
}
if (*ip == RE_OPCODE_NON_SPACE)
match = !match;
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_DIGIT:
prolog;
match = isdigit(*input);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_NON_DIGIT:
prolog;
match = !isdigit(*input);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_WORD_BOUNDARY:
case RE_OPCODE_NON_WORD_BOUNDARY:
if (bytes_matched == 0 && input_backwards_size < character_size)
{
match = TRUE;
}
else if (bytes_matched >= max_bytes_matched)
{
match = TRUE;
}
else
{
assert(input < input_data + input_forwards_size);
assert(input >= input_data - input_backwards_size);
assert(input - input_incr < input_data + input_forwards_size);
assert(input - input_incr >= input_data - input_backwards_size);
match = _yr_re_is_word_char(input, character_size) != \
_yr_re_is_word_char(input - input_incr, character_size);
}
if (*ip == RE_OPCODE_NON_WORD_BOUNDARY)
match = !match;
action = match ? ACTION_CONTINUE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_MATCH_AT_START:
if (flags & RE_FLAGS_BACKWARDS)
kill = input_backwards_size > (size_t) bytes_matched;
else
kill = input_backwards_size > 0 || (bytes_matched != 0);
action = kill ? ACTION_KILL : ACTION_CONTINUE;
fiber->ip += 1;
break;
case RE_OPCODE_MATCH_AT_END:
kill = flags & RE_FLAGS_BACKWARDS ||
input_forwards_size > (size_t) bytes_matched;
action = kill ? ACTION_KILL : ACTION_CONTINUE;
fiber->ip += 1;
break;
case RE_OPCODE_MATCH:
if (matches != NULL)
*matches = bytes_matched;
if (flags & RE_FLAGS_EXHAUSTIVE)
{
if (callback != NULL)
{
if (flags & RE_FLAGS_BACKWARDS)
{
FAIL_ON_ERROR_WITH_CLEANUP(
callback(
input + character_size,
bytes_matched,
flags,
callback_args),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
}
else
{
FAIL_ON_ERROR_WITH_CLEANUP(
callback(
input_data,
bytes_matched,
flags,
callback_args),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
}
}
action = ACTION_KILL;
}
else
{
action = ACTION_KILL_TAIL;
}
break;
default:
assert(FALSE);
}
switch(action)
{
case ACTION_KILL:
fiber = _yr_re_fiber_kill(&fibers, &storage->fiber_pool, fiber);
break;
case ACTION_KILL_TAIL:
_yr_re_fiber_kill_tail(&fibers, &storage->fiber_pool, fiber);
fiber = NULL;
break;
case ACTION_CONTINUE:
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
break;
default:
next_fiber = fiber->next;
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
fiber = next_fiber;
}
}
input += input_incr;
bytes_matched += character_size;
if (flags & RE_FLAGS_SCAN && bytes_matched < max_bytes_matched)
{
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_re_fiber_create(&storage->fiber_pool, &fiber),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
fiber->ip = re_code;
_yr_re_fiber_append(&fibers, fiber);
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
}
}
return ERROR_SUCCESS;
}
int yr_re_fast_exec(
uint8_t* code,
uint8_t* input_data,
size_t input_forwards_size,
size_t input_backwards_size,
int flags,
RE_MATCH_CALLBACK_FUNC callback,
void* callback_args,
int* matches)
{
RE_REPEAT_ANY_ARGS* repeat_any_args;
uint8_t* code_stack[MAX_FAST_RE_STACK];
uint8_t* input_stack[MAX_FAST_RE_STACK];
int matches_stack[MAX_FAST_RE_STACK];
uint8_t* ip = code;
uint8_t* input = input_data;
uint8_t* next_input;
uint8_t* next_opcode;
uint8_t mask;
uint8_t value;
int i;
int stop;
int input_incr;
int sp = 0;
int bytes_matched;
int max_bytes_matched;
max_bytes_matched = flags & RE_FLAGS_BACKWARDS ?
(int) input_backwards_size :
(int) input_forwards_size;
input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1;
if (flags & RE_FLAGS_BACKWARDS)
input--;
code_stack[sp] = code;
input_stack[sp] = input;
matches_stack[sp] = 0;
sp++;
while (sp > 0)
{
sp--;
ip = code_stack[sp];
input = input_stack[sp];
bytes_matched = matches_stack[sp];
stop = FALSE;
while(!stop)
{
if (*ip == RE_OPCODE_MATCH)
{
if (flags & RE_FLAGS_EXHAUSTIVE)
{
FAIL_ON_ERROR(callback(
flags & RE_FLAGS_BACKWARDS ? input + 1 : input_data,
bytes_matched,
flags,
callback_args));
break;
}
else
{
if (matches != NULL)
*matches = bytes_matched;
return ERROR_SUCCESS;
}
}
if (bytes_matched >= max_bytes_matched)
break;
switch(*ip)
{
case RE_OPCODE_LITERAL:
if (*input == *(ip + 1))
{
bytes_matched++;
input += input_incr;
ip += 2;
}
else
{
stop = TRUE;
}
break;
case RE_OPCODE_MASKED_LITERAL:
value = *(int16_t*)(ip + 1) & 0xFF;
mask = *(int16_t*)(ip + 1) >> 8;
if ((*input & mask) == value)
{
bytes_matched++;
input += input_incr;
ip += 3;
}
else
{
stop = TRUE;
}
break;
case RE_OPCODE_ANY:
bytes_matched++;
input += input_incr;
ip += 1;
break;
case RE_OPCODE_REPEAT_ANY_UNGREEDY:
repeat_any_args = (RE_REPEAT_ANY_ARGS*)(ip + 1);
next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS);
for (i = repeat_any_args->min + 1; i <= repeat_any_args->max; i++)
{
next_input = input + i * input_incr;
if (bytes_matched + i >= max_bytes_matched)
break;
if ( *(next_opcode) != RE_OPCODE_LITERAL ||
(*(next_opcode) == RE_OPCODE_LITERAL &&
*(next_opcode + 1) == *next_input))
{
if (sp >= MAX_FAST_RE_STACK)
return -4;
code_stack[sp] = next_opcode;
input_stack[sp] = next_input;
matches_stack[sp] = bytes_matched + i;
sp++;
}
}
input += input_incr * repeat_any_args->min;
bytes_matched += repeat_any_args->min;
ip = next_opcode;
break;
default:
assert(FALSE);
}
}
}
if (matches != NULL)
*matches = -1;
return ERROR_SUCCESS;
}
void _yr_re_print_node(
RE_NODE* re_node)
{
int i;
if (re_node == NULL)
return;
switch(re_node->type)
{
case RE_NODE_ALT:
printf("Alt(");
_yr_re_print_node(re_node->left);
printf(", ");
_yr_re_print_node(re_node->right);
printf(")");
break;
case RE_NODE_CONCAT:
printf("Cat(");
_yr_re_print_node(re_node->left);
printf(", ");
_yr_re_print_node(re_node->right);
printf(")");
break;
case RE_NODE_STAR:
printf("Star(");
_yr_re_print_node(re_node->left);
printf(")");
break;
case RE_NODE_PLUS:
printf("Plus(");
_yr_re_print_node(re_node->left);
printf(")");
break;
case RE_NODE_LITERAL:
printf("Lit(%02X)", re_node->value);
break;
case RE_NODE_MASKED_LITERAL:
printf("MaskedLit(%02X,%02X)", re_node->value, re_node->mask);
break;
case RE_NODE_WORD_CHAR:
printf("WordChar");
break;
case RE_NODE_NON_WORD_CHAR:
printf("NonWordChar");
break;
case RE_NODE_SPACE:
printf("Space");
break;
case RE_NODE_NON_SPACE:
printf("NonSpace");
break;
case RE_NODE_DIGIT:
printf("Digit");
break;
case RE_NODE_NON_DIGIT:
printf("NonDigit");
break;
case RE_NODE_ANY:
printf("Any");
break;
case RE_NODE_RANGE:
printf("Range(%d-%d, ", re_node->start, re_node->end);
_yr_re_print_node(re_node->left);
printf(")");
break;
case RE_NODE_CLASS:
printf("Class(");
for (i = 0; i < 256; i++)
if (CHAR_IN_CLASS(i, re_node->class_vector))
printf("%02X,", i);
printf(")");
break;
default:
printf("???");
break;
}
}
void yr_re_print(
RE_AST* re_ast)
{
_yr_re_print_node(re_ast->root_node);
}
| ./CrossVul/dataset_final_sorted/CWE-674/c/good_3382_2 |
crossvul-cpp_data_good_162_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;
}
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);
}
JsVar *jspFindPrototypeFor(const char *className) {
JsVar *obj = jsvObjectGetChild(execInfo.root, className, 0);
if (!obj) return 0;
JsVar *proto = jsvObjectGetChild(obj, JSPARSE_PROTOTYPE_VAR, 0);
jsvUnLock(obj);
return proto;
}
/** 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)
inheritsFrom = jspFindPrototypeFor("Object");
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 that references the object we actually requested the
* member from..
*/
if (child && returnName) {
// Get rid of existing name
if (jsvIsName(child)) {
JsVar *t = jsvGetValueOfName(child);
jsvUnLock(child);
child = t;
}
// 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);
}
#ifndef SAVE_ON_FLASH
/* If we've got something that we care about the parent of (eg. a getter/setter)
* then we repackage it into a 'NewChild' name that references the parent before
* we leave. Note: You can't do this on everything because normally NewChild
* forces a new child to be blindly created. It works on Getters/Setters because
* we *always* run those rather than adding them.
*/
if (parent && jsvIsName(a) && !jsvIsNewChild(a)) {
JsVar *value = jsvGetValueOfName(a);
if (jsvIsGetterOrSetter(value)) { // no need to do this for functions since we've just executed whatever we needed to
JsVar *nameVar = jsvCopyNameOnly(a,false,true);
JsVar *newChild = jsvCreateNewChild(parent, nameVar, value);
jsvUnLock2(nameVar, a);
a = newChild;
}
jsvUnLock(value);
}
#endif
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);
}
#ifndef SAVE_ON_FLASH
bool isGetter, isSetter;
if (lex->tk==LEX_ID && jsvIsString(varName)) {
isGetter = jsvIsStringEqual(varName, "get");
isSetter = jsvIsStringEqual(varName, "set");
if (isGetter || isSetter) {
jsvUnLock(varName);
varName = jslGetTokenValueAsVar(lex);
JSP_ASSERT_MATCH(LEX_ID);
JsVar *method = jspeFunctionDefinition(false);
jsvAddGetterOrSetter(contents, varName, isGetter, method);
jsvUnLock(method);
}
} else
#endif
{
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,jsvUnLock4(funcName,classFunction,classInternalName,classPrototype),0);
#ifndef SAVE_ON_FLASH
bool isGetter, isSetter;
if (lex->tk==LEX_ID) {
isGetter = jsvIsStringEqual(funcName, "get");
isSetter = jsvIsStringEqual(funcName, "set");
if (isGetter || isSetter) {
jsvUnLock(funcName);
funcName = jslGetTokenValueAsVar(lex);
JSP_ASSERT_MATCH(LEX_ID);
}
}
#endif
JsVar *method = jspeFunctionDefinition(false);
if (classFunction && classPrototype) {
JsVar *obj = isStatic ? classFunction : classPrototype;
if (jsvIsStringEqual(funcName, "constructor")) {
jswrap_function_replaceWith(classFunction, method);
#ifndef SAVE_ON_FLASH
} else if (isGetter || isSetter) {
jsvAddGetterOrSetter(obj, funcName, isGetter, method);
#endif
} else {
funcName = jsvMakeIntoVariableName(funcName, 0);
jsvSetValueOfName(funcName, method);
jsvAddName(obj, 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
jsvReplaceWith(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
jsvReplaceWith(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=='=') {
jsvReplaceWithOrAddToRoot(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);
jsvReplaceWith(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 `{ ... }` */
NO_INLINE void jspeSkipBlock() {
// fast skip of blocks
int brackets = 1;
while (lex->tk && brackets) {
if (lex->tk == '{') brackets++;
else if (lex->tk == '}') {
brackets--;
if (!brackets) return;
}
JSP_ASSERT_MATCH(lex->tk);
}
}
/** 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;
if (!JSP_SHOULD_EXECUTE) {
jspeSkipBlock();
return;
}
}
} else {
jspeSkipBlock();
}
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)
jsvReplaceWith(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 *jspGetBuiltinPrototype(JsVar *obj) {
if (jsvIsArray(obj)) {
JsVar *v = jspFindPrototypeFor("Array");
if (v) return v;
}
if (jsvIsObject(obj) || jsvIsArray(obj)) {
JsVar *v = jspFindPrototypeFor("Object");
if (v==obj) { // don't return ourselves
jsvUnLock(v);
v = 0;
}
return v;
}
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 || lex->tk == LEX_R_OF) {
bool isForOf = lex->tk == LEX_R_OF;
// for (i in array) or for (i of array)
// where i = forStatement
if (JSP_SHOULD_EXECUTE && !jsvIsName(forStatement)) {
jsvUnLock(forStatement);
jsExceptionHere(JSET_ERROR, "for(a %s b) - 'a' must be a variable name, not %t", isForOf?"of":"in", forStatement);
return 0;
}
JSP_ASSERT_MATCH(lex->tk); // skip over in/of
JsVar *array = jsvSkipNameAndUnLock(jspeExpression());
JSP_MATCH_WITH_CLEANUP_AND_RETURN(')', jsvUnLock2(forStatement, array), 0);
JslCharPos forBodyStart = jslCharPosClone(&lex->tokenStart);
// Simply scan over the loop the first time without executing to figure out where it ends
// OPT: we could skip the first parse and actually execute the first time
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();
// Now start executing properly
if (JSP_SHOULD_EXECUTE) {
if (jsvIsIterable(array)) {
JsvIsInternalChecker checkerFunction = jsvGetInternalFunctionCheckerFor(array);
JsVar *foundPrototype = 0;
if (!isForOf) // for..in
foundPrototype = jspGetBuiltinPrototype(array);
JsvIterator it;
jsvIteratorNew(&it, array, isForOf ?
/* for of */ JSIF_EVERY_ARRAY_ELEMENT :
/* for in */ 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 *iteratorValue;
if (isForOf) { // for (... of ...)
iteratorValue = jsvIteratorGetValue(&it);
} else { // for (... in ...)
iteratorValue = jsvIsName(loopIndexVar) ?
jsvCopyNameOnly(loopIndexVar, false/*no copy children*/, false/*not a name*/) :
loopIndexVar;
assert(jsvGetRefs(iteratorValue)==0);
}
if (isForOf || iteratorValue) { // could be out of memory
assert(!jsvIsName(iteratorValue));
jsvReplaceWithOrAddToRoot(forStatement, iteratorValue);
if (iteratorValue!=loopIndexVar) jsvUnLock(iteratorValue);
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;
}
}
}
jsvIteratorNext(&it);
jsvUnLock(loopIndexVar);
// if using for..in we'll skip down the prototype chain when we reach the end of the current one
if (!jsvIteratorHasElement(&it) && !isForOf && foundPrototype) {
jsvIteratorFree(&it);
JsVar *iterable = foundPrototype;
jsvIteratorNew(&it, iterable, JSIF_DEFINED_ARRAY_ElEMENTS);
checkerFunction = jsvGetInternalFunctionCheckerFor(iterable);
foundPrototype = jspGetBuiltinPrototype(iterable);
jsvUnLock(iterable);
}
}
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) {
jsvReplaceWith(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 {
jsvReplaceWith(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 */
if (!jspCheckStackPosition()) return 0;
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-674/c/good_162_1 |
crossvul-cpp_data_good_1310_2 | /*
** 2005 February 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that used to generate VDBE code
** that implements the ALTER TABLE command.
*/
#include "sqliteInt.h"
/*
** The code in this file only exists if we are not omitting the
** ALTER TABLE logic from the build.
*/
#ifndef SQLITE_OMIT_ALTERTABLE
/*
** Parameter zName is the name of a table that is about to be altered
** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
** If the table is a system table, this function leaves an error message
** in pParse->zErr (system tables may not be altered) and returns non-zero.
**
** Or, if zName is not a system table, zero is returned.
*/
static int isAlterableTable(Parse *pParse, Table *pTab){
if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
#ifndef SQLITE_OMIT_VIRTUALTABLE
|| ( (pTab->tabFlags & TF_Shadow)!=0
&& sqlite3ReadOnlyShadowTables(pParse->db)
)
#endif
){
sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
return 1;
}
return 0;
}
/*
** Generate code to verify that the schemas of database zDb and, if
** bTemp is not true, database "temp", can still be parsed. This is
** called at the end of the generation of an ALTER TABLE ... RENAME ...
** statement to ensure that the operation has not rendered any schema
** objects unusable.
*/
static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){
sqlite3NestedParse(pParse,
"SELECT 1 "
"FROM \"%w\".%s "
"WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
" AND sql NOT LIKE 'create virtual%%'"
" AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ",
zDb, MASTER_NAME,
zDb, bTemp
);
if( bTemp==0 ){
sqlite3NestedParse(pParse,
"SELECT 1 "
"FROM temp.%s "
"WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
" AND sql NOT LIKE 'create virtual%%'"
" AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ",
MASTER_NAME, zDb
);
}
}
/*
** Generate code to reload the schema for database iDb. And, if iDb!=1, for
** the temp database as well.
*/
static void renameReloadSchema(Parse *pParse, int iDb){
Vdbe *v = pParse->pVdbe;
if( v ){
sqlite3ChangeCookie(pParse, iDb);
sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0);
if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0);
}
}
/*
** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
** command.
*/
void sqlite3AlterRenameTable(
Parse *pParse, /* Parser context. */
SrcList *pSrc, /* The table to rename. */
Token *pName /* The new table name. */
){
int iDb; /* Database that contains the table */
char *zDb; /* Name of database iDb */
Table *pTab; /* Table being renamed */
char *zName = 0; /* NULL-terminated version of pName */
sqlite3 *db = pParse->db; /* Database connection */
int nTabName; /* Number of UTF-8 characters in zTabName */
const char *zTabName; /* Original name of the table */
Vdbe *v;
VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
u32 savedDbFlags; /* Saved value of db->mDbFlags */
savedDbFlags = db->mDbFlags;
if( NEVER(db->mallocFailed) ) goto exit_rename_table;
assert( pSrc->nSrc==1 );
assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
if( !pTab ) goto exit_rename_table;
iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
zDb = db->aDb[iDb].zDbSName;
db->mDbFlags |= DBFLAG_PreferBuiltin;
/* Get a NULL terminated version of the new table name. */
zName = sqlite3NameFromToken(db, pName);
if( !zName ) goto exit_rename_table;
/* Check that a table or index named 'zName' does not already exist
** in database iDb. If so, this is an error.
*/
if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
sqlite3ErrorMsg(pParse,
"there is already another table or index with this name: %s", zName);
goto exit_rename_table;
}
/* Make sure it is not a system table being altered, or a reserved name
** that the table is being renamed to.
*/
if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
goto exit_rename_table;
}
if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){
goto exit_rename_table;
}
#ifndef SQLITE_OMIT_VIEW
if( pTab->pSelect ){
sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
goto exit_rename_table;
}
#endif
#ifndef SQLITE_OMIT_AUTHORIZATION
/* Invoke the authorization callback. */
if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
goto exit_rename_table;
}
#endif
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( sqlite3ViewGetColumnNames(pParse, pTab) ){
goto exit_rename_table;
}
if( IsVirtual(pTab) ){
pVTab = sqlite3GetVTable(db, pTab);
if( pVTab->pVtab->pModule->xRename==0 ){
pVTab = 0;
}
}
#endif
/* Begin a transaction for database iDb. Then modify the schema cookie
** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
** nested SQL may raise an exception. */
v = sqlite3GetVdbe(pParse);
if( v==0 ){
goto exit_rename_table;
}
sqlite3MayAbort(pParse);
/* figure out how many UTF-8 characters are in zName */
zTabName = pTab->zName;
nTabName = sqlite3Utf8CharLen(zTabName, -1);
/* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
** the schema to use the new table name. */
sqlite3NestedParse(pParse,
"UPDATE \"%w\".%s SET "
"sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
"WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
"AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
, zDb, MASTER_NAME, zDb, zTabName, zName, (iDb==1), zTabName
);
/* Update the tbl_name and name columns of the sqlite_master table
** as required. */
sqlite3NestedParse(pParse,
"UPDATE %Q.%s SET "
"tbl_name = %Q, "
"name = CASE "
"WHEN type='table' THEN %Q "
"WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
" AND type='index' THEN "
"'sqlite_autoindex_' || %Q || substr(name,%d+18) "
"ELSE name END "
"WHERE tbl_name=%Q COLLATE nocase AND "
"(type='table' OR type='index' OR type='trigger');",
zDb, MASTER_NAME,
zName, zName, zName,
nTabName, zTabName
);
#ifndef SQLITE_OMIT_AUTOINCREMENT
/* If the sqlite_sequence table exists in this database, then update
** it with the new table name.
*/
if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
sqlite3NestedParse(pParse,
"UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
zDb, zName, pTab->zName);
}
#endif
/* If the table being renamed is not itself part of the temp database,
** edit view and trigger definitions within the temp database
** as required. */
if( iDb!=1 ){
sqlite3NestedParse(pParse,
"UPDATE sqlite_temp_master SET "
"sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
"tbl_name = "
"CASE WHEN tbl_name=%Q COLLATE nocase AND "
" sqlite_rename_test(%Q, sql, type, name, 1) "
"THEN %Q ELSE tbl_name END "
"WHERE type IN ('view', 'trigger')"
, zDb, zTabName, zName, zTabName, zDb, zName);
}
/* If this is a virtual table, invoke the xRename() function if
** one is defined. The xRename() callback will modify the names
** of any resources used by the v-table implementation (including other
** SQLite tables) that are identified by the name of the virtual table.
*/
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( pVTab ){
int i = ++pParse->nMem;
sqlite3VdbeLoadString(v, i, zName);
sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
}
#endif
renameReloadSchema(pParse, iDb);
renameTestSchema(pParse, zDb, iDb==1);
exit_rename_table:
sqlite3SrcListDelete(db, pSrc);
sqlite3DbFree(db, zName);
db->mDbFlags = savedDbFlags;
}
/*
** This function is called after an "ALTER TABLE ... ADD" statement
** has been parsed. Argument pColDef contains the text of the new
** column definition.
**
** The Table structure pParse->pNewTable was extended to include
** the new column during parsing.
*/
void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
Table *pNew; /* Copy of pParse->pNewTable */
Table *pTab; /* Table being altered */
int iDb; /* Database number */
const char *zDb; /* Database name */
const char *zTab; /* Table name */
char *zCol; /* Null-terminated column definition */
Column *pCol; /* The new column */
Expr *pDflt; /* Default value for the new column */
sqlite3 *db; /* The database connection; */
Vdbe *v; /* The prepared statement under construction */
int r1; /* Temporary registers */
db = pParse->db;
if( pParse->nErr || db->mallocFailed ) return;
pNew = pParse->pNewTable;
assert( pNew );
assert( sqlite3BtreeHoldsAllMutexes(db) );
iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
zDb = db->aDb[iDb].zDbSName;
zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
pCol = &pNew->aCol[pNew->nCol-1];
pDflt = pCol->pDflt;
pTab = sqlite3FindTable(db, zTab, zDb);
assert( pTab );
#ifndef SQLITE_OMIT_AUTHORIZATION
/* Invoke the authorization callback. */
if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
return;
}
#endif
/* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
** If there is a NOT NULL constraint, then the default value for the
** column must not be NULL.
*/
if( pCol->colFlags & COLFLAG_PRIMKEY ){
sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
return;
}
if( pNew->pIndex ){
sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
return;
}
if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
/* If the default value for the new column was specified with a
** literal NULL, then set pDflt to 0. This simplifies checking
** for an SQL NULL default below.
*/
assert( pDflt==0 || pDflt->op==TK_SPAN );
if( pDflt && pDflt->pLeft->op==TK_NULL ){
pDflt = 0;
}
if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
sqlite3ErrorMsg(pParse,
"Cannot add a REFERENCES column with non-NULL default value");
return;
}
if( pCol->notNull && !pDflt ){
sqlite3ErrorMsg(pParse,
"Cannot add a NOT NULL column with default value NULL");
return;
}
/* Ensure the default expression is something that sqlite3ValueFromExpr()
** can handle (i.e. not CURRENT_TIME etc.)
*/
if( pDflt ){
sqlite3_value *pVal = 0;
int rc;
rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
if( rc!=SQLITE_OK ){
assert( db->mallocFailed == 1 );
return;
}
if( !pVal ){
sqlite3ErrorMsg(pParse,"Cannot add a column with non-constant default");
return;
}
sqlite3ValueFree(pVal);
}
}else if( pCol->colFlags & COLFLAG_STORED ){
sqlite3ErrorMsg(pParse, "cannot add a STORED column");
return;
}
/* Modify the CREATE TABLE statement. */
zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
if( zCol ){
char *zEnd = &zCol[pColDef->n-1];
u32 savedDbFlags = db->mDbFlags;
while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
*zEnd-- = '\0';
}
db->mDbFlags |= DBFLAG_PreferBuiltin;
sqlite3NestedParse(pParse,
"UPDATE \"%w\".%s SET "
"sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
"WHERE type = 'table' AND name = %Q",
zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
zTab
);
sqlite3DbFree(db, zCol);
db->mDbFlags = savedDbFlags;
}
/* Make sure the schema version is at least 3. But do not upgrade
** from less than 3 to 4, as that will corrupt any preexisting DESC
** index.
*/
v = sqlite3GetVdbe(pParse);
if( v ){
r1 = sqlite3GetTempReg(pParse);
sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
sqlite3VdbeUsesBtree(v, iDb);
sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
VdbeCoverage(v);
sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
sqlite3ReleaseTempReg(pParse, r1);
}
/* Reload the table definition */
renameReloadSchema(pParse, iDb);
}
/*
** This function is called by the parser after the table-name in
** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
** pSrc is the full-name of the table being altered.
**
** This routine makes a (partial) copy of the Table structure
** for the table being altered and sets Parse.pNewTable to point
** to it. Routines called by the parser as the column definition
** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
** the copy. The copy of the Table structure is deleted by tokenize.c
** after parsing is finished.
**
** Routine sqlite3AlterFinishAddColumn() will be called to complete
** coding the "ALTER TABLE ... ADD" statement.
*/
void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
Table *pNew;
Table *pTab;
int iDb;
int i;
int nAlloc;
sqlite3 *db = pParse->db;
/* Look up the table being altered. */
assert( pParse->pNewTable==0 );
assert( sqlite3BtreeHoldsAllMutexes(db) );
if( db->mallocFailed ) goto exit_begin_add_column;
pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
if( !pTab ) goto exit_begin_add_column;
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( IsVirtual(pTab) ){
sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
goto exit_begin_add_column;
}
#endif
/* Make sure this is not an attempt to ALTER a view. */
if( pTab->pSelect ){
sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
goto exit_begin_add_column;
}
if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
goto exit_begin_add_column;
}
sqlite3MayAbort(pParse);
assert( pTab->addColOffset>0 );
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
/* Put a copy of the Table struct in Parse.pNewTable for the
** sqlite3AddColumn() function and friends to modify. But modify
** the name by adding an "sqlite_altertab_" prefix. By adding this
** prefix, we insure that the name will not collide with an existing
** table because user table are not allowed to have the "sqlite_"
** prefix on their name.
*/
pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
if( !pNew ) goto exit_begin_add_column;
pParse->pNewTable = pNew;
pNew->nTabRef = 1;
pNew->nCol = pTab->nCol;
assert( pNew->nCol>0 );
nAlloc = (((pNew->nCol-1)/8)*8)+8;
assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
if( !pNew->aCol || !pNew->zName ){
assert( db->mallocFailed );
goto exit_begin_add_column;
}
memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
for(i=0; i<pNew->nCol; i++){
Column *pCol = &pNew->aCol[i];
pCol->zName = sqlite3DbStrDup(db, pCol->zName);
pCol->zColl = 0;
pCol->pDflt = 0;
}
pNew->pSchema = db->aDb[iDb].pSchema;
pNew->addColOffset = pTab->addColOffset;
pNew->nTabRef = 1;
exit_begin_add_column:
sqlite3SrcListDelete(db, pSrc);
return;
}
/*
** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
** command. This function checks if the table is a view or virtual
** table (columns of views or virtual tables may not be renamed). If so,
** it loads an error message into pParse and returns non-zero.
**
** Or, if pTab is not a view or virtual table, zero is returned.
*/
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
static int isRealTable(Parse *pParse, Table *pTab){
const char *zType = 0;
#ifndef SQLITE_OMIT_VIEW
if( pTab->pSelect ){
zType = "view";
}
#endif
#ifndef SQLITE_OMIT_VIRTUALTABLE
if( IsVirtual(pTab) ){
zType = "virtual table";
}
#endif
if( zType ){
sqlite3ErrorMsg(
pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
);
return 1;
}
return 0;
}
#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
# define isRealTable(x,y) (0)
#endif
/*
** Handles the following parser reduction:
**
** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
*/
void sqlite3AlterRenameColumn(
Parse *pParse, /* Parsing context */
SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
Token *pOld, /* Name of column being changed */
Token *pNew /* New column name */
){
sqlite3 *db = pParse->db; /* Database connection */
Table *pTab; /* Table being updated */
int iCol; /* Index of column being renamed */
char *zOld = 0; /* Old column name */
char *zNew = 0; /* New column name */
const char *zDb; /* Name of schema containing the table */
int iSchema; /* Index of the schema */
int bQuote; /* True to quote the new name */
/* Locate the table to be altered */
pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
if( !pTab ) goto exit_rename_column;
/* Cannot alter a system table */
if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
/* Which schema holds the table to be altered */
iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
assert( iSchema>=0 );
zDb = db->aDb[iSchema].zDbSName;
#ifndef SQLITE_OMIT_AUTHORIZATION
/* Invoke the authorization callback. */
if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
goto exit_rename_column;
}
#endif
/* Make sure the old name really is a column name in the table to be
** altered. Set iCol to be the index of the column being renamed */
zOld = sqlite3NameFromToken(db, pOld);
if( !zOld ) goto exit_rename_column;
for(iCol=0; iCol<pTab->nCol; iCol++){
if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
}
if( iCol==pTab->nCol ){
sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
goto exit_rename_column;
}
/* Do the rename operation using a recursive UPDATE statement that
** uses the sqlite_rename_column() SQL function to compute the new
** CREATE statement text for the sqlite_master table.
*/
sqlite3MayAbort(pParse);
zNew = sqlite3NameFromToken(db, pNew);
if( !zNew ) goto exit_rename_column;
assert( pNew->n>0 );
bQuote = sqlite3Isquote(pNew->z[0]);
sqlite3NestedParse(pParse,
"UPDATE \"%w\".%s SET "
"sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
"WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
" AND (type != 'index' OR tbl_name = %Q)"
" AND sql NOT LIKE 'create virtual%%'",
zDb, MASTER_NAME,
zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
pTab->zName
);
sqlite3NestedParse(pParse,
"UPDATE temp.%s SET "
"sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
"WHERE type IN ('trigger', 'view')",
MASTER_NAME,
zDb, pTab->zName, iCol, zNew, bQuote
);
/* Drop and reload the database schema. */
renameReloadSchema(pParse, iSchema);
renameTestSchema(pParse, zDb, iSchema==1);
exit_rename_column:
sqlite3SrcListDelete(db, pSrc);
sqlite3DbFree(db, zOld);
sqlite3DbFree(db, zNew);
return;
}
/*
** Each RenameToken object maps an element of the parse tree into
** the token that generated that element. The parse tree element
** might be one of:
**
** * A pointer to an Expr that represents an ID
** * The name of a table column in Column.zName
**
** A list of RenameToken objects can be constructed during parsing.
** Each new object is created by sqlite3RenameTokenMap().
** As the parse tree is transformed, the sqlite3RenameTokenRemap()
** routine is used to keep the mapping current.
**
** After the parse finishes, renameTokenFind() routine can be used
** to look up the actual token value that created some element in
** the parse tree.
*/
struct RenameToken {
void *p; /* Parse tree element created by token t */
Token t; /* The token that created parse tree element p */
RenameToken *pNext; /* Next is a list of all RenameToken objects */
};
/*
** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
** down into the Walker.
*/
typedef struct RenameCtx RenameCtx;
struct RenameCtx {
RenameToken *pList; /* List of tokens to overwrite */
int nList; /* Number of tokens in pList */
int iCol; /* Index of column being renamed */
Table *pTab; /* Table being ALTERed */
const char *zOld; /* Old column name */
};
#ifdef SQLITE_DEBUG
/*
** This function is only for debugging. It performs two tasks:
**
** 1. Checks that pointer pPtr does not already appear in the
** rename-token list.
**
** 2. Dereferences each pointer in the rename-token list.
**
** The second is most effective when debugging under valgrind or
** address-sanitizer or similar. If any of these pointers no longer
** point to valid objects, an exception is raised by the memory-checking
** tool.
**
** The point of this is to prevent comparisons of invalid pointer values.
** Even though this always seems to work, it is undefined according to the
** C standard. Example of undefined comparison:
**
** sqlite3_free(x);
** if( x==y ) ...
**
** Technically, as x no longer points into a valid object or to the byte
** following a valid object, it may not be used in comparison operations.
*/
static void renameTokenCheckAll(Parse *pParse, void *pPtr){
if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
RenameToken *p;
u8 i = 0;
for(p=pParse->pRename; p; p=p->pNext){
if( p->p ){
assert( p->p!=pPtr );
i += *(u8*)(p->p);
}
}
}
}
#else
# define renameTokenCheckAll(x,y)
#endif
/*
** Remember that the parser tree element pPtr was created using
** the token pToken.
**
** In other words, construct a new RenameToken object and add it
** to the list of RenameToken objects currently being built up
** in pParse->pRename.
**
** The pPtr argument is returned so that this routine can be used
** with tail recursion in tokenExpr() routine, for a small performance
** improvement.
*/
void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
RenameToken *pNew;
assert( pPtr || pParse->db->mallocFailed );
renameTokenCheckAll(pParse, pPtr);
if( pParse->eParseMode!=PARSE_MODE_UNMAP ){
pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
if( pNew ){
pNew->p = pPtr;
pNew->t = *pToken;
pNew->pNext = pParse->pRename;
pParse->pRename = pNew;
}
}
return pPtr;
}
/*
** It is assumed that there is already a RenameToken object associated
** with parse tree element pFrom. This function remaps the associated token
** to parse tree element pTo.
*/
void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
RenameToken *p;
renameTokenCheckAll(pParse, pTo);
for(p=pParse->pRename; p; p=p->pNext){
if( p->p==pFrom ){
p->p = pTo;
break;
}
}
}
/*
** Walker callback used by sqlite3RenameExprUnmap().
*/
static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
Parse *pParse = pWalker->pParse;
sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
return WRC_Continue;
}
/*
** Iterate through the Select objects that are part of WITH clauses attached
** to select statement pSelect.
*/
static void renameWalkWith(Walker *pWalker, Select *pSelect){
if( pSelect->pWith ){
int i;
for(i=0; i<pSelect->pWith->nCte; i++){
Select *p = pSelect->pWith->a[i].pSelect;
NameContext sNC;
memset(&sNC, 0, sizeof(sNC));
sNC.pParse = pWalker->pParse;
sqlite3SelectPrep(sNC.pParse, p, &sNC);
sqlite3WalkSelect(pWalker, p);
}
}
}
/*
** Walker callback used by sqlite3RenameExprUnmap().
*/
static int renameUnmapSelectCb(Walker *pWalker, Select *p){
Parse *pParse = pWalker->pParse;
int i;
if( pParse->nErr ) return WRC_Abort;
if( p->selFlags & SF_View ) return WRC_Prune;
if( ALWAYS(p->pEList) ){
ExprList *pList = p->pEList;
for(i=0; i<pList->nExpr; i++){
if( pList->a[i].zName ){
sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zName);
}
}
}
if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
SrcList *pSrc = p->pSrc;
for(i=0; i<pSrc->nSrc; i++){
sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
}
}
renameWalkWith(pWalker, p);
return WRC_Continue;
}
/*
** Remove all nodes that are part of expression pExpr from the rename list.
*/
void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
u8 eMode = pParse->eParseMode;
Walker sWalker;
memset(&sWalker, 0, sizeof(Walker));
sWalker.pParse = pParse;
sWalker.xExprCallback = renameUnmapExprCb;
sWalker.xSelectCallback = renameUnmapSelectCb;
pParse->eParseMode = PARSE_MODE_UNMAP;
sqlite3WalkExpr(&sWalker, pExpr);
pParse->eParseMode = eMode;
}
/*
** Remove all nodes that are part of expression-list pEList from the
** rename list.
*/
void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
if( pEList ){
int i;
Walker sWalker;
memset(&sWalker, 0, sizeof(Walker));
sWalker.pParse = pParse;
sWalker.xExprCallback = renameUnmapExprCb;
sqlite3WalkExprList(&sWalker, pEList);
for(i=0; i<pEList->nExpr; i++){
sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zName);
}
}
}
/*
** Free the list of RenameToken objects given in the second argument
*/
static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
RenameToken *pNext;
RenameToken *p;
for(p=pToken; p; p=pNext){
pNext = p->pNext;
sqlite3DbFree(db, p);
}
}
/*
** Search the Parse object passed as the first argument for a RenameToken
** object associated with parse tree element pPtr. If found, remove it
** from the Parse object and add it to the list maintained by the
** RenameCtx object passed as the second argument.
*/
static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
RenameToken **pp;
assert( pPtr!=0 );
for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
if( (*pp)->p==pPtr ){
RenameToken *pToken = *pp;
*pp = pToken->pNext;
pToken->pNext = pCtx->pList;
pCtx->pList = pToken;
pCtx->nList++;
break;
}
}
}
/*
** This is a Walker select callback. It does nothing. It is only required
** because without a dummy callback, sqlite3WalkExpr() and similar do not
** descend into sub-select statements.
*/
static int renameColumnSelectCb(Walker *pWalker, Select *p){
if( p->selFlags & SF_View ) return WRC_Prune;
renameWalkWith(pWalker, p);
return WRC_Continue;
}
/*
** This is a Walker expression callback.
**
** For every TK_COLUMN node in the expression tree, search to see
** if the column being references is the column being renamed by an
** ALTER TABLE statement. If it is, then attach its associated
** RenameToken object to the list of RenameToken objects being
** constructed in RenameCtx object at pWalker->u.pRename.
*/
static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
RenameCtx *p = pWalker->u.pRename;
if( pExpr->op==TK_TRIGGER
&& pExpr->iColumn==p->iCol
&& pWalker->pParse->pTriggerTab==p->pTab
){
renameTokenFind(pWalker->pParse, p, (void*)pExpr);
}else if( pExpr->op==TK_COLUMN
&& pExpr->iColumn==p->iCol
&& p->pTab==pExpr->y.pTab
){
renameTokenFind(pWalker->pParse, p, (void*)pExpr);
}
return WRC_Continue;
}
/*
** The RenameCtx contains a list of tokens that reference a column that
** is being renamed by an ALTER TABLE statement. Return the "last"
** RenameToken in the RenameCtx and remove that RenameToken from the
** RenameContext. "Last" means the last RenameToken encountered when
** the input SQL is parsed from left to right. Repeated calls to this routine
** return all column name tokens in the order that they are encountered
** in the SQL statement.
*/
static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
RenameToken *pBest = pCtx->pList;
RenameToken *pToken;
RenameToken **pp;
for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
if( pToken->t.z>pBest->t.z ) pBest = pToken;
}
for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
*pp = pBest->pNext;
return pBest;
}
/*
** An error occured while parsing or otherwise processing a database
** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
** ALTER TABLE RENAME COLUMN program. The error message emitted by the
** sub-routine is currently stored in pParse->zErrMsg. This function
** adds context to the error message and then stores it in pCtx.
*/
static void renameColumnParseError(
sqlite3_context *pCtx,
int bPost,
sqlite3_value *pType,
sqlite3_value *pObject,
Parse *pParse
){
const char *zT = (const char*)sqlite3_value_text(pType);
const char *zN = (const char*)sqlite3_value_text(pObject);
char *zErr;
zErr = sqlite3_mprintf("error in %s %s%s: %s",
zT, zN, (bPost ? " after rename" : ""),
pParse->zErrMsg
);
sqlite3_result_error(pCtx, zErr, -1);
sqlite3_free(zErr);
}
/*
** For each name in the the expression-list pEList (i.e. each
** pEList->a[i].zName) that matches the string in zOld, extract the
** corresponding rename-token from Parse object pParse and add it
** to the RenameCtx pCtx.
*/
static void renameColumnElistNames(
Parse *pParse,
RenameCtx *pCtx,
ExprList *pEList,
const char *zOld
){
if( pEList ){
int i;
for(i=0; i<pEList->nExpr; i++){
char *zName = pEList->a[i].zName;
if( 0==sqlite3_stricmp(zName, zOld) ){
renameTokenFind(pParse, pCtx, (void*)zName);
}
}
}
}
/*
** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
** that matches the string in zOld, extract the corresponding rename-token
** from Parse object pParse and add it to the RenameCtx pCtx.
*/
static void renameColumnIdlistNames(
Parse *pParse,
RenameCtx *pCtx,
IdList *pIdList,
const char *zOld
){
if( pIdList ){
int i;
for(i=0; i<pIdList->nId; i++){
char *zName = pIdList->a[i].zName;
if( 0==sqlite3_stricmp(zName, zOld) ){
renameTokenFind(pParse, pCtx, (void*)zName);
}
}
}
}
/*
** Parse the SQL statement zSql using Parse object (*p). The Parse object
** is initialized by this function before it is used.
*/
static int renameParseSql(
Parse *p, /* Memory to use for Parse object */
const char *zDb, /* Name of schema SQL belongs to */
int bTable, /* 1 -> RENAME TABLE, 0 -> RENAME COLUMN */
sqlite3 *db, /* Database handle */
const char *zSql, /* SQL to parse */
int bTemp /* True if SQL is from temp schema */
){
int rc;
char *zErr = 0;
db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
/* Parse the SQL statement passed as the first argument. If no error
** occurs and the parse does not result in a new table, index or
** trigger object, the database must be corrupt. */
memset(p, 0, sizeof(Parse));
p->eParseMode = PARSE_MODE_RENAME;
p->db = db;
p->nQueryLoop = 1;
rc = sqlite3RunParser(p, zSql, &zErr);
assert( p->zErrMsg==0 );
assert( rc!=SQLITE_OK || zErr==0 );
p->zErrMsg = zErr;
if( db->mallocFailed ) rc = SQLITE_NOMEM;
if( rc==SQLITE_OK
&& p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
){
rc = SQLITE_CORRUPT_BKPT;
}
#ifdef SQLITE_DEBUG
/* Ensure that all mappings in the Parse.pRename list really do map to
** a part of the input string. */
if( rc==SQLITE_OK ){
int nSql = sqlite3Strlen30(zSql);
RenameToken *pToken;
for(pToken=p->pRename; pToken; pToken=pToken->pNext){
assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
}
}
#endif
db->init.iDb = 0;
return rc;
}
/*
** This function edits SQL statement zSql, replacing each token identified
** by the linked list pRename with the text of zNew. If argument bQuote is
** true, then zNew is always quoted first. If no error occurs, the result
** is loaded into context object pCtx as the result.
**
** Or, if an error occurs (i.e. an OOM condition), an error is left in
** pCtx and an SQLite error code returned.
*/
static int renameEditSql(
sqlite3_context *pCtx, /* Return result here */
RenameCtx *pRename, /* Rename context */
const char *zSql, /* SQL statement to edit */
const char *zNew, /* New token text */
int bQuote /* True to always quote token */
){
int nNew = sqlite3Strlen30(zNew);
int nSql = sqlite3Strlen30(zSql);
sqlite3 *db = sqlite3_context_db_handle(pCtx);
int rc = SQLITE_OK;
char *zQuot;
char *zOut;
int nQuot;
/* Set zQuot to point to a buffer containing a quoted copy of the
** identifier zNew. If the corresponding identifier in the original
** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
** point to zQuot so that all substitutions are made using the
** quoted version of the new column name. */
zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
if( zQuot==0 ){
return SQLITE_NOMEM;
}else{
nQuot = sqlite3Strlen30(zQuot);
}
if( bQuote ){
zNew = zQuot;
nNew = nQuot;
}
/* At this point pRename->pList contains a list of RenameToken objects
** corresponding to all tokens in the input SQL that must be replaced
** with the new column name. All that remains is to construct and
** return the edited SQL string. */
assert( nQuot>=nNew );
zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
if( zOut ){
int nOut = nSql;
memcpy(zOut, zSql, nSql);
while( pRename->pList ){
int iOff; /* Offset of token to replace in zOut */
RenameToken *pBest = renameColumnTokenNext(pRename);
u32 nReplace;
const char *zReplace;
if( sqlite3IsIdChar(*pBest->t.z) ){
nReplace = nNew;
zReplace = zNew;
}else{
nReplace = nQuot;
zReplace = zQuot;
}
iOff = pBest->t.z - zSql;
if( pBest->t.n!=nReplace ){
memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
nOut - (iOff + pBest->t.n)
);
nOut += nReplace - pBest->t.n;
zOut[nOut] = '\0';
}
memcpy(&zOut[iOff], zReplace, nReplace);
sqlite3DbFree(db, pBest);
}
sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
sqlite3DbFree(db, zOut);
}else{
rc = SQLITE_NOMEM;
}
sqlite3_free(zQuot);
return rc;
}
/*
** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
** it was read from the schema of database zDb. Return SQLITE_OK if
** successful. Otherwise, return an SQLite error code and leave an error
** message in the Parse object.
*/
static int renameResolveTrigger(Parse *pParse, const char *zDb){
sqlite3 *db = pParse->db;
Trigger *pNew = pParse->pNewTrigger;
TriggerStep *pStep;
NameContext sNC;
int rc = SQLITE_OK;
memset(&sNC, 0, sizeof(sNC));
sNC.pParse = pParse;
assert( pNew->pTabSchema );
pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
);
pParse->eTriggerOp = pNew->op;
/* ALWAYS() because if the table of the trigger does not exist, the
** error would have been hit before this point */
if( ALWAYS(pParse->pTriggerTab) ){
rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
}
/* Resolve symbols in WHEN clause */
if( rc==SQLITE_OK && pNew->pWhen ){
rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
}
for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
if( pStep->pSelect ){
sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
if( pParse->nErr ) rc = pParse->rc;
}
if( rc==SQLITE_OK && pStep->zTarget ){
Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
if( pTarget==0 ){
rc = SQLITE_ERROR;
}else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
SrcList sSrc;
memset(&sSrc, 0, sizeof(sSrc));
sSrc.nSrc = 1;
sSrc.a[0].zName = pStep->zTarget;
sSrc.a[0].pTab = pTarget;
sNC.pSrcList = &sSrc;
if( pStep->pWhere ){
rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
}
if( rc==SQLITE_OK ){
rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
}
assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
if( pStep->pUpsert ){
Upsert *pUpsert = pStep->pUpsert;
assert( rc==SQLITE_OK );
pUpsert->pUpsertSrc = &sSrc;
sNC.uNC.pUpsert = pUpsert;
sNC.ncFlags = NC_UUpsert;
rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
if( rc==SQLITE_OK ){
ExprList *pUpsertSet = pUpsert->pUpsertSet;
rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
}
if( rc==SQLITE_OK ){
rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
}
if( rc==SQLITE_OK ){
rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
}
sNC.ncFlags = 0;
}
sNC.pSrcList = 0;
}
}
}
return rc;
}
/*
** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
** objects that are part of the trigger passed as the second argument.
*/
static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
TriggerStep *pStep;
/* Find tokens to edit in WHEN clause */
sqlite3WalkExpr(pWalker, pTrigger->pWhen);
/* Find tokens to edit in trigger steps */
for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
sqlite3WalkSelect(pWalker, pStep->pSelect);
sqlite3WalkExpr(pWalker, pStep->pWhere);
sqlite3WalkExprList(pWalker, pStep->pExprList);
if( pStep->pUpsert ){
Upsert *pUpsert = pStep->pUpsert;
sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
}
}
}
/*
** Free the contents of Parse object (*pParse). Do not free the memory
** occupied by the Parse object itself.
*/
static void renameParseCleanup(Parse *pParse){
sqlite3 *db = pParse->db;
Index *pIdx;
if( pParse->pVdbe ){
sqlite3VdbeFinalize(pParse->pVdbe);
}
sqlite3DeleteTable(db, pParse->pNewTable);
while( (pIdx = pParse->pNewIndex)!=0 ){
pParse->pNewIndex = pIdx->pNext;
sqlite3FreeIndex(db, pIdx);
}
sqlite3DeleteTrigger(db, pParse->pNewTrigger);
sqlite3DbFree(db, pParse->zErrMsg);
renameTokenFree(db, pParse->pRename);
sqlite3ParserReset(pParse);
}
/*
** SQL function:
**
** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
**
** 0. zSql: SQL statement to rewrite
** 1. type: Type of object ("table", "view" etc.)
** 2. object: Name of object
** 3. Database: Database name (e.g. "main")
** 4. Table: Table name
** 5. iCol: Index of column to rename
** 6. zNew: New column name
** 7. bQuote: Non-zero if the new column name should be quoted.
** 8. bTemp: True if zSql comes from temp schema
**
** Do a column rename operation on the CREATE statement given in zSql.
** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
** into zNew. The name should be quoted if bQuote is true.
**
** This function is used internally by the ALTER TABLE RENAME COLUMN command.
** It is only accessible to SQL created using sqlite3NestedParse(). It is
** not reachable from ordinary SQL passed into sqlite3_prepare().
*/
static void renameColumnFunc(
sqlite3_context *context,
int NotUsed,
sqlite3_value **argv
){
sqlite3 *db = sqlite3_context_db_handle(context);
RenameCtx sCtx;
const char *zSql = (const char*)sqlite3_value_text(argv[0]);
const char *zDb = (const char*)sqlite3_value_text(argv[3]);
const char *zTable = (const char*)sqlite3_value_text(argv[4]);
int iCol = sqlite3_value_int(argv[5]);
const char *zNew = (const char*)sqlite3_value_text(argv[6]);
int bQuote = sqlite3_value_int(argv[7]);
int bTemp = sqlite3_value_int(argv[8]);
const char *zOld;
int rc;
Parse sParse;
Walker sWalker;
Index *pIdx;
int i;
Table *pTab;
#ifndef SQLITE_OMIT_AUTHORIZATION
sqlite3_xauth xAuth = db->xAuth;
#endif
UNUSED_PARAMETER(NotUsed);
if( zSql==0 ) return;
if( zTable==0 ) return;
if( zNew==0 ) return;
if( iCol<0 ) return;
sqlite3BtreeEnterAll(db);
pTab = sqlite3FindTable(db, zTable, zDb);
if( pTab==0 || iCol>=pTab->nCol ){
sqlite3BtreeLeaveAll(db);
return;
}
zOld = pTab->aCol[iCol].zName;
memset(&sCtx, 0, sizeof(sCtx));
sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
#ifndef SQLITE_OMIT_AUTHORIZATION
db->xAuth = 0;
#endif
rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp);
/* Find tokens that need to be replaced. */
memset(&sWalker, 0, sizeof(Walker));
sWalker.pParse = &sParse;
sWalker.xExprCallback = renameColumnExprCb;
sWalker.xSelectCallback = renameColumnSelectCb;
sWalker.u.pRename = &sCtx;
sCtx.pTab = pTab;
if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
if( sParse.pNewTable ){
Select *pSelect = sParse.pNewTable->pSelect;
if( pSelect ){
pSelect->selFlags &= ~SF_View;
sParse.rc = SQLITE_OK;
sqlite3SelectPrep(&sParse, pSelect, 0);
rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
if( rc==SQLITE_OK ){
sqlite3WalkSelect(&sWalker, pSelect);
}
if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
}else{
/* A regular table */
int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
FKey *pFKey;
assert( sParse.pNewTable->pSelect==0 );
sCtx.pTab = sParse.pNewTable;
if( bFKOnly==0 ){
renameTokenFind(
&sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
);
if( sCtx.iCol<0 ){
renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
}
sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
}
for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
}
}
#ifndef SQLITE_OMIT_GENERATED_COLUMNS
for(i=0; i<sParse.pNewTable->nCol; i++){
sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
}
#endif
for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
for(i=0; i<pFKey->nCol; i++){
if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
}
if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
&& 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
){
renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
}
}
}
}
}else if( sParse.pNewIndex ){
sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
}else{
/* A trigger */
TriggerStep *pStep;
rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
if( pStep->zTarget ){
Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
if( pTarget==pTab ){
if( pStep->pUpsert ){
ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
}
renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
}
}
}
/* Find tokens to edit in UPDATE OF clause */
if( sParse.pTriggerTab==pTab ){
renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
}
/* Find tokens to edit in various expressions and selects */
renameWalkTrigger(&sWalker, sParse.pNewTrigger);
}
assert( rc==SQLITE_OK );
rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
renameColumnFunc_done:
if( rc!=SQLITE_OK ){
if( sParse.zErrMsg ){
renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
}else{
sqlite3_result_error_code(context, rc);
}
}
renameParseCleanup(&sParse);
renameTokenFree(db, sCtx.pList);
#ifndef SQLITE_OMIT_AUTHORIZATION
db->xAuth = xAuth;
#endif
sqlite3BtreeLeaveAll(db);
}
/*
** Walker expression callback used by "RENAME TABLE".
*/
static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
RenameCtx *p = pWalker->u.pRename;
if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
}
return WRC_Continue;
}
/*
** Walker select callback used by "RENAME TABLE".
*/
static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
int i;
RenameCtx *p = pWalker->u.pRename;
SrcList *pSrc = pSelect->pSrc;
if( pSelect->selFlags & SF_View ) return WRC_Prune;
if( pSrc==0 ){
assert( pWalker->pParse->db->mallocFailed );
return WRC_Abort;
}
for(i=0; i<pSrc->nSrc; i++){
struct SrcList_item *pItem = &pSrc->a[i];
if( pItem->pTab==p->pTab ){
renameTokenFind(pWalker->pParse, p, pItem->zName);
}
}
renameWalkWith(pWalker, pSelect);
return WRC_Continue;
}
/*
** This C function implements an SQL user function that is used by SQL code
** generated by the ALTER TABLE ... RENAME command to modify the definition
** of any foreign key constraints that use the table being renamed as the
** parent table. It is passed three arguments:
**
** 0: The database containing the table being renamed.
** 1. type: Type of object ("table", "view" etc.)
** 2. object: Name of object
** 3: The complete text of the schema statement being modified,
** 4: The old name of the table being renamed, and
** 5: The new name of the table being renamed.
** 6: True if the schema statement comes from the temp db.
**
** It returns the new schema statement. For example:
**
** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
** -> 'CREATE TABLE t1(a REFERENCES t3)'
*/
static void renameTableFunc(
sqlite3_context *context,
int NotUsed,
sqlite3_value **argv
){
sqlite3 *db = sqlite3_context_db_handle(context);
const char *zDb = (const char*)sqlite3_value_text(argv[0]);
const char *zInput = (const char*)sqlite3_value_text(argv[3]);
const char *zOld = (const char*)sqlite3_value_text(argv[4]);
const char *zNew = (const char*)sqlite3_value_text(argv[5]);
int bTemp = sqlite3_value_int(argv[6]);
UNUSED_PARAMETER(NotUsed);
if( zInput && zOld && zNew ){
Parse sParse;
int rc;
int bQuote = 1;
RenameCtx sCtx;
Walker sWalker;
#ifndef SQLITE_OMIT_AUTHORIZATION
sqlite3_xauth xAuth = db->xAuth;
db->xAuth = 0;
#endif
sqlite3BtreeEnterAll(db);
memset(&sCtx, 0, sizeof(RenameCtx));
sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
memset(&sWalker, 0, sizeof(Walker));
sWalker.pParse = &sParse;
sWalker.xExprCallback = renameTableExprCb;
sWalker.xSelectCallback = renameTableSelectCb;
sWalker.u.pRename = &sCtx;
rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
if( rc==SQLITE_OK ){
int isLegacy = (db->flags & SQLITE_LegacyAlter);
if( sParse.pNewTable ){
Table *pTab = sParse.pNewTable;
if( pTab->pSelect ){
if( isLegacy==0 ){
Select *pSelect = pTab->pSelect;
NameContext sNC;
memset(&sNC, 0, sizeof(sNC));
sNC.pParse = &sParse;
assert( pSelect->selFlags & SF_View );
pSelect->selFlags &= ~SF_View;
sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
if( sParse.nErr ) rc = sParse.rc;
sqlite3WalkSelect(&sWalker, pTab->pSelect);
}
}else{
/* Modify any FK definitions to point to the new table. */
#ifndef SQLITE_OMIT_FOREIGN_KEY
if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
FKey *pFKey;
for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
}
}
}
#endif
/* If this is the table being altered, fix any table refs in CHECK
** expressions. Also update the name that appears right after the
** "CREATE [VIRTUAL] TABLE" bit. */
if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
sCtx.pTab = pTab;
if( isLegacy==0 ){
sqlite3WalkExprList(&sWalker, pTab->pCheck);
}
renameTokenFind(&sParse, &sCtx, pTab->zName);
}
}
}
else if( sParse.pNewIndex ){
renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
if( isLegacy==0 ){
sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
}
}
#ifndef SQLITE_OMIT_TRIGGER
else{
Trigger *pTrigger = sParse.pNewTrigger;
TriggerStep *pStep;
if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
&& sCtx.pTab->pSchema==pTrigger->pTabSchema
){
renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
}
if( isLegacy==0 ){
rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
if( rc==SQLITE_OK ){
renameWalkTrigger(&sWalker, pTrigger);
for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
renameTokenFind(&sParse, &sCtx, pStep->zTarget);
}
}
}
}
}
#endif
}
if( rc==SQLITE_OK ){
rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
}
if( rc!=SQLITE_OK ){
if( sParse.zErrMsg ){
renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
}else{
sqlite3_result_error_code(context, rc);
}
}
renameParseCleanup(&sParse);
renameTokenFree(db, sCtx.pList);
sqlite3BtreeLeaveAll(db);
#ifndef SQLITE_OMIT_AUTHORIZATION
db->xAuth = xAuth;
#endif
}
return;
}
/*
** An SQL user function that checks that there are no parse or symbol
** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
** After an ALTER TABLE .. RENAME operation is performed and the schema
** reloaded, this function is called on each SQL statement in the schema
** to ensure that it is still usable.
**
** 0: Database name ("main", "temp" etc.).
** 1: SQL statement.
** 2: Object type ("view", "table", "trigger" or "index").
** 3: Object name.
** 4: True if object is from temp schema.
**
** Unless it finds an error, this function normally returns NULL. However, it
** returns integer value 1 if:
**
** * the SQL argument creates a trigger, and
** * the table that the trigger is attached to is in database zDb.
*/
static void renameTableTest(
sqlite3_context *context,
int NotUsed,
sqlite3_value **argv
){
sqlite3 *db = sqlite3_context_db_handle(context);
char const *zDb = (const char*)sqlite3_value_text(argv[0]);
char const *zInput = (const char*)sqlite3_value_text(argv[1]);
int bTemp = sqlite3_value_int(argv[4]);
int isLegacy = (db->flags & SQLITE_LegacyAlter);
#ifndef SQLITE_OMIT_AUTHORIZATION
sqlite3_xauth xAuth = db->xAuth;
db->xAuth = 0;
#endif
UNUSED_PARAMETER(NotUsed);
if( zDb && zInput ){
int rc;
Parse sParse;
rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
if( rc==SQLITE_OK ){
if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
NameContext sNC;
memset(&sNC, 0, sizeof(sNC));
sNC.pParse = &sParse;
sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
if( sParse.nErr ) rc = sParse.rc;
}
else if( sParse.pNewTrigger ){
if( isLegacy==0 ){
rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
}
if( rc==SQLITE_OK ){
int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
int i2 = sqlite3FindDbName(db, zDb);
if( i1==i2 ) sqlite3_result_int(context, 1);
}
}
}
if( rc!=SQLITE_OK ){
renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
}
renameParseCleanup(&sParse);
}
#ifndef SQLITE_OMIT_AUTHORIZATION
db->xAuth = xAuth;
#endif
}
/*
** Register built-in functions used to help implement ALTER TABLE
*/
void sqlite3AlterFunctions(void){
static FuncDef aAlterTableFuncs[] = {
INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
INTERNAL_FUNCTION(sqlite_rename_test, 5, renameTableTest),
};
sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
}
#endif /* SQLITE_ALTER_TABLE */
| ./CrossVul/dataset_final_sorted/CWE-674/c/good_1310_2 |
crossvul-cpp_data_bad_354_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;
ND_TCHECK2(*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-674/c/bad_354_0 |
crossvul-cpp_data_bad_3392_0 | /* A Bison parser, made by GNU Bison 3.0.4. */
/* Bison implementation for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc.
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/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* C LALR(1) parser skeleton written by Richard Stallman, by
simplifying the original so-called "semantic" parser. */
/* All symbols defined below should begin with yy or YY, to avoid
infringing on user name space. This should be done even for local
variables, as they might otherwise be expanded by user macros.
There are some unavoidable exceptions within include files to
define necessary library symbols; they are noted "INFRINGES ON
USER NAME SPACE" below. */
/* Identify Bison output. */
#define YYBISON 1
/* Bison version. */
#define YYBISON_VERSION "3.0.4"
/* Skeleton name. */
#define YYSKELETON_NAME "yacc.c"
/* Pure parsers. */
#define YYPURE 1
/* Push parsers. */
#define YYPUSH 0
/* Pull parsers. */
#define YYPULL 1
/* Substitute the variable and function names. */
#define yyparse hex_yyparse
#define yylex hex_yylex
#define yyerror hex_yyerror
#define yydebug hex_yydebug
#define yynerrs hex_yynerrs
/* Copy the first part of user declarations. */
#line 30 "hex_grammar.y" /* yacc.c:339 */
#include <string.h>
#include <limits.h>
#include <yara/integers.h>
#include <yara/utils.h>
#include <yara/hex_lexer.h>
#include <yara/limits.h>
#include <yara/mem.h>
#include <yara/error.h>
#define STR_EXPAND(tok) #tok
#define STR(tok) STR_EXPAND(tok)
#define YYERROR_VERBOSE
#define YYMALLOC yr_malloc
#define YYFREE yr_free
#define mark_as_not_fast_regexp() \
((RE_AST*) yyget_extra(yyscanner))->flags &= ~RE_FLAGS_FAST_REGEXP
#define ERROR_IF(x, error) \
if (x) \
{ \
lex_env->last_error_code = error; \
YYABORT; \
} \
#define DESTROY_NODE_IF(x, node) \
if (x) \
{ \
yr_re_node_destroy(node); \
} \
#line 111 "hex_grammar.c" /* yacc.c:339 */
# ifndef YY_NULLPTR
# if defined __cplusplus && 201103L <= __cplusplus
# define YY_NULLPTR nullptr
# else
# define YY_NULLPTR 0
# endif
# endif
/* Enabling verbose error messages. */
#ifdef YYERROR_VERBOSE
# undef YYERROR_VERBOSE
# define YYERROR_VERBOSE 1
#else
# define YYERROR_VERBOSE 0
#endif
/* In a future release of Bison, this section will be replaced
by #include "y.tab.h". */
#ifndef YY_HEX_YY_HEX_GRAMMAR_H_INCLUDED
# define YY_HEX_YY_HEX_GRAMMAR_H_INCLUDED
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
#if YYDEBUG
extern int hex_yydebug;
#endif
/* Token type. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
enum yytokentype
{
_BYTE_ = 258,
_MASKED_BYTE_ = 259,
_NUMBER_ = 260
};
#endif
/* Tokens. */
#define _BYTE_ 258
#define _MASKED_BYTE_ 259
#define _NUMBER_ 260
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
union YYSTYPE
{
#line 78 "hex_grammar.y" /* yacc.c:355 */
int64_t integer;
RE_NODE *re_node;
#line 166 "hex_grammar.c" /* yacc.c:355 */
};
typedef union YYSTYPE YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#endif
int hex_yyparse (void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env);
#endif /* !YY_HEX_YY_HEX_GRAMMAR_H_INCLUDED */
/* Copy the second part of user declarations. */
#line 182 "hex_grammar.c" /* yacc.c:358 */
#ifdef short
# undef short
#endif
#ifdef YYTYPE_UINT8
typedef YYTYPE_UINT8 yytype_uint8;
#else
typedef unsigned char yytype_uint8;
#endif
#ifdef YYTYPE_INT8
typedef YYTYPE_INT8 yytype_int8;
#else
typedef signed char yytype_int8;
#endif
#ifdef YYTYPE_UINT16
typedef YYTYPE_UINT16 yytype_uint16;
#else
typedef unsigned short int yytype_uint16;
#endif
#ifdef YYTYPE_INT16
typedef YYTYPE_INT16 yytype_int16;
#else
typedef short int yytype_int16;
#endif
#ifndef YYSIZE_T
# ifdef __SIZE_TYPE__
# define YYSIZE_T __SIZE_TYPE__
# elif defined size_t
# define YYSIZE_T size_t
# elif ! defined YYSIZE_T
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# define YYSIZE_T size_t
# else
# define YYSIZE_T unsigned int
# endif
#endif
#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
#ifndef YY_
# if defined YYENABLE_NLS && YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
# define YY_(Msgid) dgettext ("bison-runtime", Msgid)
# endif
# endif
# ifndef YY_
# define YY_(Msgid) Msgid
# endif
#endif
#ifndef YY_ATTRIBUTE
# if (defined __GNUC__ \
&& (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \
|| defined __SUNPRO_C && 0x5110 <= __SUNPRO_C
# define YY_ATTRIBUTE(Spec) __attribute__(Spec)
# else
# define YY_ATTRIBUTE(Spec) /* empty */
# endif
#endif
#ifndef YY_ATTRIBUTE_PURE
# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__))
#endif
#ifndef YY_ATTRIBUTE_UNUSED
# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__))
#endif
#if !defined _Noreturn \
&& (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112)
# if defined _MSC_VER && 1200 <= _MSC_VER
# define _Noreturn __declspec (noreturn)
# else
# define _Noreturn YY_ATTRIBUTE ((__noreturn__))
# endif
#endif
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YYUSE(E) ((void) (E))
#else
# define YYUSE(E) /* empty */
#endif
#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__
/* Suppress an incorrect diagnostic about yylval being uninitialized. */
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\
_Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
# define YY_IGNORE_MAYBE_UNINITIALIZED_END \
_Pragma ("GCC diagnostic pop")
#else
# define YY_INITIAL_VALUE(Value) Value
#endif
#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_END
#endif
#ifndef YY_INITIAL_VALUE
# define YY_INITIAL_VALUE(Value) /* Nothing. */
#endif
#if ! defined yyoverflow || YYERROR_VERBOSE
/* The parser invokes alloca or malloc; define the necessary symbols. */
# ifdef YYSTACK_USE_ALLOCA
# if YYSTACK_USE_ALLOCA
# ifdef __GNUC__
# define YYSTACK_ALLOC __builtin_alloca
# elif defined __BUILTIN_VA_ARG_INCR
# include <alloca.h> /* INFRINGES ON USER NAME SPACE */
# elif defined _AIX
# define YYSTACK_ALLOC __alloca
# elif defined _MSC_VER
# include <malloc.h> /* INFRINGES ON USER NAME SPACE */
# define alloca _alloca
# else
# define YYSTACK_ALLOC alloca
# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
/* Use EXIT_SUCCESS as a witness for stdlib.h. */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# endif
# endif
# endif
# ifdef YYSTACK_ALLOC
/* Pacify GCC's 'empty if-body' warning. */
# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0)
# ifndef YYSTACK_ALLOC_MAXIMUM
/* The OS might guarantee only one guard page at the bottom of the stack,
and a page size can be as small as 4096 bytes. So we cannot safely
invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
to allow for a few compiler-allocated temporary stack slots. */
# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
# endif
# else
# define YYSTACK_ALLOC YYMALLOC
# define YYSTACK_FREE YYFREE
# ifndef YYSTACK_ALLOC_MAXIMUM
# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
# endif
# if (defined __cplusplus && ! defined EXIT_SUCCESS \
&& ! ((defined YYMALLOC || defined malloc) \
&& (defined YYFREE || defined free)))
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# ifndef YYMALLOC
# define YYMALLOC malloc
# if ! defined malloc && ! defined EXIT_SUCCESS
void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# ifndef YYFREE
# define YYFREE free
# if ! defined free && ! defined EXIT_SUCCESS
void free (void *); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# endif
#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
#if (! defined yyoverflow \
&& (! defined __cplusplus \
|| (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
/* A type that is properly aligned for any stack member. */
union yyalloc
{
yytype_int16 yyss_alloc;
YYSTYPE yyvs_alloc;
};
/* The size of the maximum gap between one aligned stack and the next. */
# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
/* The size of an array large to enough to hold all stacks, each with
N elements. */
# define YYSTACK_BYTES(N) \
((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
+ YYSTACK_GAP_MAXIMUM)
# define YYCOPY_NEEDED 1
/* Relocate STACK from its old location to the new one. The
local variables YYSIZE and YYSTACKSIZE give the old and new number of
elements in the stack, and YYPTR gives the new location of the
stack. Advance YYPTR to a properly aligned location for the next
stack. */
# define YYSTACK_RELOCATE(Stack_alloc, Stack) \
do \
{ \
YYSIZE_T yynewbytes; \
YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \
Stack = &yyptr->Stack_alloc; \
yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
yyptr += yynewbytes / sizeof (*yyptr); \
} \
while (0)
#endif
#if defined YYCOPY_NEEDED && YYCOPY_NEEDED
/* Copy COUNT objects from SRC to DST. The source and destination do
not overlap. */
# ifndef YYCOPY
# if defined __GNUC__ && 1 < __GNUC__
# define YYCOPY(Dst, Src, Count) \
__builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src)))
# else
# define YYCOPY(Dst, Src, Count) \
do \
{ \
YYSIZE_T yyi; \
for (yyi = 0; yyi < (Count); yyi++) \
(Dst)[yyi] = (Src)[yyi]; \
} \
while (0)
# endif
# endif
#endif /* !YYCOPY_NEEDED */
/* YYFINAL -- State number of the termination state. */
#define YYFINAL 9
/* YYLAST -- Last index in YYTABLE. */
#define YYLAST 30
/* YYNTOKENS -- Number of terminals. */
#define YYNTOKENS 14
/* YYNNTS -- Number of nonterminals. */
#define YYNNTS 10
/* YYNRULES -- Number of rules. */
#define YYNRULES 20
/* YYNSTATES -- Number of states. */
#define YYNSTATES 32
/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned
by yylex, with out-of-bounds checking. */
#define YYUNDEFTOK 2
#define YYMAXUTOK 260
#define YYTRANSLATE(YYX) \
((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM
as returned by yylex, without out-of-bounds checking. */
static const yytype_uint8 yytranslate[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
8, 9, 2, 2, 2, 12, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 10, 2, 11, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 6, 13, 7, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
5
};
#if YYDEBUG
/* YYRLINE[YYN] -- Source line where rule number YYN was defined. */
static const yytype_uint16 yyrline[] =
{
0, 105, 105, 114, 118, 127, 189, 193, 206, 210,
219, 233, 232, 245, 268, 300, 322, 342, 346, 360,
368
};
#endif
#if YYDEBUG || YYERROR_VERBOSE || 0
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
First, the terminals, then, starting at YYNTOKENS, nonterminals. */
static const char *const yytname[] =
{
"$end", "error", "$undefined", "_BYTE_", "_MASKED_BYTE_", "_NUMBER_",
"'{'", "'}'", "'('", "')'", "'['", "']'", "'-'", "'|'", "$accept",
"hex_string", "tokens", "token_sequence", "token_or_range", "token",
"$@1", "range", "alternatives", "byte", YY_NULLPTR
};
#endif
# ifdef YYPRINT
/* YYTOKNUM[NUM] -- (External) token number corresponding to the
(internal) symbol number NUM (which must be that of a token). */
static const yytype_uint16 yytoknum[] =
{
0, 256, 257, 258, 259, 260, 123, 125, 40, 41,
91, 93, 45, 124
};
# endif
#define YYPACT_NINF -11
#define yypact_value_is_default(Yystate) \
(!!((Yystate) == (-11)))
#define YYTABLE_NINF -6
#define yytable_value_is_error(Yytable_value) \
0
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
static const yytype_int8 yypact[] =
{
20, 14, 27, -11, -11, -11, 21, -2, -11, -11,
14, -11, -1, -2, -11, -4, -11, -11, 10, 13,
9, -11, 3, -11, 14, -11, 2, -11, -11, 18,
-11, -11
};
/* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
Performed when YYTABLE does not specify something else to do. Zero
means the default is an error. */
static const yytype_uint8 yydefact[] =
{
0, 0, 0, 19, 20, 11, 0, 3, 10, 1,
0, 2, 0, 0, 6, 8, 9, 17, 0, 0,
0, 7, 8, 12, 0, 13, 0, 16, 18, 0,
15, 14
};
/* YYPGOTO[NTERM-NUM]. */
static const yytype_int8 yypgoto[] =
{
-11, -11, -10, -11, 17, 8, -11, -11, -11, -11
};
/* YYDEFGOTO[NTERM-NUM]. */
static const yytype_int8 yydefgoto[] =
{
-1, 2, 6, 13, 14, 7, 10, 16, 18, 8
};
/* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule whose
number is the opposite. If YYTABLE_NINF, syntax error. */
static const yytype_int8 yytable[] =
{
17, 3, 4, -4, 19, -4, 5, 29, 12, -4,
-5, 20, -5, 30, 28, 15, -5, 3, 4, 23,
27, 22, 5, 24, 25, 26, 1, 9, 11, 31,
21
};
static const yytype_uint8 yycheck[] =
{
10, 3, 4, 7, 5, 9, 8, 5, 10, 13,
7, 12, 9, 11, 24, 7, 13, 3, 4, 9,
11, 13, 8, 13, 11, 12, 6, 0, 7, 11,
13
};
/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
symbol of state STATE-NUM. */
static const yytype_uint8 yystos[] =
{
0, 6, 15, 3, 4, 8, 16, 19, 23, 0,
20, 7, 10, 17, 18, 19, 21, 16, 22, 5,
12, 18, 19, 9, 13, 11, 12, 11, 16, 5,
11, 11
};
/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
static const yytype_uint8 yyr1[] =
{
0, 14, 15, 16, 16, 16, 17, 17, 18, 18,
19, 20, 19, 21, 21, 21, 21, 22, 22, 23,
23
};
/* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */
static const yytype_uint8 yyr2[] =
{
0, 2, 3, 1, 2, 3, 1, 2, 1, 1,
1, 0, 4, 3, 5, 4, 3, 1, 3, 1,
1
};
#define yyerrok (yyerrstatus = 0)
#define yyclearin (yychar = YYEMPTY)
#define YYEMPTY (-2)
#define YYEOF 0
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrorlab
#define YYRECOVERING() (!!yyerrstatus)
#define YYBACKUP(Token, Value) \
do \
if (yychar == YYEMPTY) \
{ \
yychar = (Token); \
yylval = (Value); \
YYPOPSTACK (yylen); \
yystate = *yyssp; \
goto yybackup; \
} \
else \
{ \
yyerror (yyscanner, lex_env, YY_("syntax error: cannot back up")); \
YYERROR; \
} \
while (0)
/* Error token number */
#define YYTERROR 1
#define YYERRCODE 256
/* Enable debugging if requested. */
#if YYDEBUG
# ifndef YYFPRINTF
# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
# define YYFPRINTF fprintf
# endif
# define YYDPRINTF(Args) \
do { \
if (yydebug) \
YYFPRINTF Args; \
} while (0)
/* This macro is provided for backward compatibility. */
#ifndef YY_LOCATION_PRINT
# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
#endif
# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
do { \
if (yydebug) \
{ \
YYFPRINTF (stderr, "%s ", Title); \
yy_symbol_print (stderr, \
Type, Value, yyscanner, lex_env); \
YYFPRINTF (stderr, "\n"); \
} \
} while (0)
/*----------------------------------------.
| Print this symbol's value on YYOUTPUT. |
`----------------------------------------*/
static void
yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env)
{
FILE *yyo = yyoutput;
YYUSE (yyo);
YYUSE (yyscanner);
YYUSE (lex_env);
if (!yyvaluep)
return;
# ifdef YYPRINT
if (yytype < YYNTOKENS)
YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
# endif
YYUSE (yytype);
}
/*--------------------------------.
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
static void
yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env)
{
YYFPRINTF (yyoutput, "%s %s (",
yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]);
yy_symbol_value_print (yyoutput, yytype, yyvaluep, yyscanner, lex_env);
YYFPRINTF (yyoutput, ")");
}
/*------------------------------------------------------------------.
| yy_stack_print -- Print the state stack from its BOTTOM up to its |
| TOP (included). |
`------------------------------------------------------------------*/
static void
yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
{
YYFPRINTF (stderr, "Stack now");
for (; yybottom <= yytop; yybottom++)
{
int yybot = *yybottom;
YYFPRINTF (stderr, " %d", yybot);
}
YYFPRINTF (stderr, "\n");
}
# define YY_STACK_PRINT(Bottom, Top) \
do { \
if (yydebug) \
yy_stack_print ((Bottom), (Top)); \
} while (0)
/*------------------------------------------------.
| Report that the YYRULE is going to be reduced. |
`------------------------------------------------*/
static void
yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule, void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env)
{
unsigned long int yylno = yyrline[yyrule];
int yynrhs = yyr2[yyrule];
int yyi;
YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
yyrule - 1, yylno);
/* The symbols being reduced. */
for (yyi = 0; yyi < yynrhs; yyi++)
{
YYFPRINTF (stderr, " $%d = ", yyi + 1);
yy_symbol_print (stderr,
yystos[yyssp[yyi + 1 - yynrhs]],
&(yyvsp[(yyi + 1) - (yynrhs)])
, yyscanner, lex_env);
YYFPRINTF (stderr, "\n");
}
}
# define YY_REDUCE_PRINT(Rule) \
do { \
if (yydebug) \
yy_reduce_print (yyssp, yyvsp, Rule, yyscanner, lex_env); \
} while (0)
/* Nonzero means print parse trace. It is left uninitialized so that
multiple parsers can coexist. */
int yydebug;
#else /* !YYDEBUG */
# define YYDPRINTF(Args)
# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
# define YY_STACK_PRINT(Bottom, Top)
# define YY_REDUCE_PRINT(Rule)
#endif /* !YYDEBUG */
/* YYINITDEPTH -- initial size of the parser's stacks. */
#ifndef YYINITDEPTH
# define YYINITDEPTH 200
#endif
/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
if the built-in stack extension method is used).
Do not make this value too large; the results are undefined if
YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
evaluated with infinite-precision integer arithmetic. */
#ifndef YYMAXDEPTH
# define YYMAXDEPTH 10000
#endif
#if YYERROR_VERBOSE
# ifndef yystrlen
# if defined __GLIBC__ && defined _STRING_H
# define yystrlen strlen
# else
/* Return the length of YYSTR. */
static YYSIZE_T
yystrlen (const char *yystr)
{
YYSIZE_T yylen;
for (yylen = 0; yystr[yylen]; yylen++)
continue;
return yylen;
}
# endif
# endif
# ifndef yystpcpy
# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
# define yystpcpy stpcpy
# else
/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
YYDEST. */
static char *
yystpcpy (char *yydest, const char *yysrc)
{
char *yyd = yydest;
const char *yys = yysrc;
while ((*yyd++ = *yys++) != '\0')
continue;
return yyd - 1;
}
# endif
# endif
# ifndef yytnamerr
/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
quotes and backslashes, so that it's suitable for yyerror. The
heuristic is that double-quoting is unnecessary unless the string
contains an apostrophe, a comma, or backslash (other than
backslash-backslash). YYSTR is taken from yytname. If YYRES is
null, do not copy; instead, return the length of what the result
would have been. */
static YYSIZE_T
yytnamerr (char *yyres, const char *yystr)
{
if (*yystr == '"')
{
YYSIZE_T yyn = 0;
char const *yyp = yystr;
for (;;)
switch (*++yyp)
{
case '\'':
case ',':
goto do_not_strip_quotes;
case '\\':
if (*++yyp != '\\')
goto do_not_strip_quotes;
/* Fall through. */
default:
if (yyres)
yyres[yyn] = *yyp;
yyn++;
break;
case '"':
if (yyres)
yyres[yyn] = '\0';
return yyn;
}
do_not_strip_quotes: ;
}
if (! yyres)
return yystrlen (yystr);
return yystpcpy (yyres, yystr) - yyres;
}
# endif
/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message
about the unexpected token YYTOKEN for the state stack whose top is
YYSSP.
Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is
not large enough to hold the message. In that case, also set
*YYMSG_ALLOC to the required number of bytes. Return 2 if the
required number of bytes is too large to store. */
static int
yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
yytype_int16 *yyssp, int yytoken)
{
YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]);
YYSIZE_T yysize = yysize0;
enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
/* Internationalized format string. */
const char *yyformat = YY_NULLPTR;
/* Arguments of yyformat. */
char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
/* Number of reported tokens (one for the "unexpected", one per
"expected"). */
int yycount = 0;
/* There are many possibilities here to consider:
- If this state is a consistent state with a default action, then
the only way this function was invoked is if the default action
is an error action. In that case, don't check for expected
tokens because there are none.
- The only way there can be no lookahead present (in yychar) is if
this state is a consistent state with a default action. Thus,
detecting the absence of a lookahead is sufficient to determine
that there is no unexpected or expected token to report. In that
case, just report a simple "syntax error".
- Don't assume there isn't a lookahead just because this state is a
consistent state with a default action. There might have been a
previous inconsistent state, consistent state with a non-default
action, or user semantic action that manipulated yychar.
- Of course, the expected token list depends on states to have
correct lookahead information, and it depends on the parser not
to perform extra reductions after fetching a lookahead from the
scanner and before detecting a syntax error. Thus, state merging
(from LALR or IELR) and default reductions corrupt the expected
token list. However, the list is correct for canonical LR with
one exception: it will still contain any token that will not be
accepted due to an error action in a later state.
*/
if (yytoken != YYEMPTY)
{
int yyn = yypact[*yyssp];
yyarg[yycount++] = yytname[yytoken];
if (!yypact_value_is_default (yyn))
{
/* Start YYX at -YYN if negative to avoid negative indexes in
YYCHECK. In other words, skip the first -YYN actions for
this state because they are default actions. */
int yyxbegin = yyn < 0 ? -yyn : 0;
/* Stay within bounds of both yycheck and yytname. */
int yychecklim = YYLAST - yyn + 1;
int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
int yyx;
for (yyx = yyxbegin; yyx < yyxend; ++yyx)
if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR
&& !yytable_value_is_error (yytable[yyx + yyn]))
{
if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
{
yycount = 1;
yysize = yysize0;
break;
}
yyarg[yycount++] = yytname[yyx];
{
YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]);
if (! (yysize <= yysize1
&& yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
yysize = yysize1;
}
}
}
}
switch (yycount)
{
# define YYCASE_(N, S) \
case N: \
yyformat = S; \
break
YYCASE_(0, YY_("syntax error"));
YYCASE_(1, YY_("syntax error, unexpected %s"));
YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s"));
YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s"));
YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
# undef YYCASE_
}
{
YYSIZE_T yysize1 = yysize + yystrlen (yyformat);
if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
yysize = yysize1;
}
if (*yymsg_alloc < yysize)
{
*yymsg_alloc = 2 * yysize;
if (! (yysize <= *yymsg_alloc
&& *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM))
*yymsg_alloc = YYSTACK_ALLOC_MAXIMUM;
return 1;
}
/* Avoid sprintf, as that infringes on the user's name space.
Don't have undefined behavior even if the translation
produced a string with the wrong number of "%s"s. */
{
char *yyp = *yymsg;
int yyi = 0;
while ((*yyp = *yyformat) != '\0')
if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount)
{
yyp += yytnamerr (yyp, yyarg[yyi++]);
yyformat += 2;
}
else
{
yyp++;
yyformat++;
}
}
return 0;
}
#endif /* YYERROR_VERBOSE */
/*-----------------------------------------------.
| Release the memory associated to this symbol. |
`-----------------------------------------------*/
static void
yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env)
{
YYUSE (yyvaluep);
YYUSE (yyscanner);
YYUSE (lex_env);
if (!yymsg)
yymsg = "Deleting";
YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
switch (yytype)
{
case 16: /* tokens */
#line 94 "hex_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1023 "hex_grammar.c" /* yacc.c:1257 */
break;
case 17: /* token_sequence */
#line 95 "hex_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1029 "hex_grammar.c" /* yacc.c:1257 */
break;
case 18: /* token_or_range */
#line 96 "hex_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1035 "hex_grammar.c" /* yacc.c:1257 */
break;
case 19: /* token */
#line 97 "hex_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1041 "hex_grammar.c" /* yacc.c:1257 */
break;
case 21: /* range */
#line 100 "hex_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1047 "hex_grammar.c" /* yacc.c:1257 */
break;
case 22: /* alternatives */
#line 99 "hex_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1053 "hex_grammar.c" /* yacc.c:1257 */
break;
case 23: /* byte */
#line 98 "hex_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1059 "hex_grammar.c" /* yacc.c:1257 */
break;
default:
break;
}
YY_IGNORE_MAYBE_UNINITIALIZED_END
}
/*----------.
| yyparse. |
`----------*/
int
yyparse (void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env)
{
/* The lookahead symbol. */
int yychar;
/* The semantic value of the lookahead symbol. */
/* Default value used for initialization, for pacifying older GCCs
or non-GCC compilers. */
YY_INITIAL_VALUE (static YYSTYPE yyval_default;)
YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default);
/* Number of syntax errors so far. */
int yynerrs;
int yystate;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus;
/* The stacks and their tools:
'yyss': related to states.
'yyvs': related to semantic values.
Refer to the stacks through separate pointers, to allow yyoverflow
to reallocate them elsewhere. */
/* The state stack. */
yytype_int16 yyssa[YYINITDEPTH];
yytype_int16 *yyss;
yytype_int16 *yyssp;
/* The semantic value stack. */
YYSTYPE yyvsa[YYINITDEPTH];
YYSTYPE *yyvs;
YYSTYPE *yyvsp;
YYSIZE_T yystacksize;
int yyn;
int yyresult;
/* Lookahead token as an internal (translated) token number. */
int yytoken = 0;
/* The variables used to return semantic value and location from the
action routines. */
YYSTYPE yyval;
#if YYERROR_VERBOSE
/* Buffer for error messages, and its allocated size. */
char yymsgbuf[128];
char *yymsg = yymsgbuf;
YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
#endif
#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))
/* The number of symbols on the RHS of the reduced rule.
Keep to zero when no symbol should be popped. */
int yylen = 0;
yyssp = yyss = yyssa;
yyvsp = yyvs = yyvsa;
yystacksize = YYINITDEPTH;
YYDPRINTF ((stderr, "Starting parse\n"));
yystate = 0;
yyerrstatus = 0;
yynerrs = 0;
yychar = YYEMPTY; /* Cause a token to be read. */
goto yysetstate;
/*------------------------------------------------------------.
| yynewstate -- Push a new state, which is found in yystate. |
`------------------------------------------------------------*/
yynewstate:
/* In all cases, when you get here, the value and location stacks
have just been pushed. So pushing a state here evens the stacks. */
yyssp++;
yysetstate:
*yyssp = yystate;
if (yyss + yystacksize - 1 <= yyssp)
{
/* Get the current used size of the three stacks, in elements. */
YYSIZE_T yysize = yyssp - yyss + 1;
#ifdef yyoverflow
{
/* Give user a chance to reallocate the stack. Use copies of
these so that the &'s don't force the real ones into
memory. */
YYSTYPE *yyvs1 = yyvs;
yytype_int16 *yyss1 = yyss;
/* Each stack pointer address is followed by the size of the
data in use in that stack, in bytes. This used to be a
conditional around just the two extra args, but that might
be undefined if yyoverflow is a macro. */
yyoverflow (YY_("memory exhausted"),
&yyss1, yysize * sizeof (*yyssp),
&yyvs1, yysize * sizeof (*yyvsp),
&yystacksize);
yyss = yyss1;
yyvs = yyvs1;
}
#else /* no yyoverflow */
# ifndef YYSTACK_RELOCATE
goto yyexhaustedlab;
# else
/* Extend the stack our own way. */
if (YYMAXDEPTH <= yystacksize)
goto yyexhaustedlab;
yystacksize *= 2;
if (YYMAXDEPTH < yystacksize)
yystacksize = YYMAXDEPTH;
{
yytype_int16 *yyss1 = yyss;
union yyalloc *yyptr =
(union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
if (! yyptr)
goto yyexhaustedlab;
YYSTACK_RELOCATE (yyss_alloc, yyss);
YYSTACK_RELOCATE (yyvs_alloc, yyvs);
# undef YYSTACK_RELOCATE
if (yyss1 != yyssa)
YYSTACK_FREE (yyss1);
}
# endif
#endif /* no yyoverflow */
yyssp = yyss + yysize - 1;
yyvsp = yyvs + yysize - 1;
YYDPRINTF ((stderr, "Stack size increased to %lu\n",
(unsigned long int) yystacksize));
if (yyss + yystacksize - 1 <= yyssp)
YYABORT;
}
YYDPRINTF ((stderr, "Entering state %d\n", yystate));
if (yystate == YYFINAL)
YYACCEPT;
goto yybackup;
/*-----------.
| yybackup. |
`-----------*/
yybackup:
/* Do appropriate processing given the current state. Read a
lookahead token if we need one and don't already have one. */
/* First try to decide what to do without reference to lookahead token. */
yyn = yypact[yystate];
if (yypact_value_is_default (yyn))
goto yydefault;
/* Not known => get a lookahead token if don't already have one. */
/* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */
if (yychar == YYEMPTY)
{
YYDPRINTF ((stderr, "Reading a token: "));
yychar = yylex (&yylval, yyscanner, lex_env);
}
if (yychar <= YYEOF)
{
yychar = yytoken = YYEOF;
YYDPRINTF ((stderr, "Now at end of input.\n"));
}
else
{
yytoken = YYTRANSLATE (yychar);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
goto yydefault;
yyn = yytable[yyn];
if (yyn <= 0)
{
if (yytable_value_is_error (yyn))
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
/* Count tokens shifted since error; after three, turn off error
status. */
if (yyerrstatus)
yyerrstatus--;
/* Shift the lookahead token. */
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
/* Discard the shifted token. */
yychar = YYEMPTY;
yystate = yyn;
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact[yystate];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- Do a reduction. |
`-----------------------------*/
yyreduce:
/* yyn is the number of a rule to reduce with. */
yylen = yyr2[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
'$$ = $1'.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. Assigning to YYVAL
unconditionally makes the parser a bit smaller, and it avoids a
GCC warning that YYVAL may be used uninitialized. */
yyval = yyvsp[1-yylen];
YY_REDUCE_PRINT (yyn);
switch (yyn)
{
case 2:
#line 106 "hex_grammar.y" /* yacc.c:1646 */
{
RE_AST* re_ast = yyget_extra(yyscanner);
re_ast->root_node = (yyvsp[-1].re_node);
}
#line 1330 "hex_grammar.c" /* yacc.c:1646 */
break;
case 3:
#line 115 "hex_grammar.y" /* yacc.c:1646 */
{
(yyval.re_node) = (yyvsp[0].re_node);
}
#line 1338 "hex_grammar.c" /* yacc.c:1646 */
break;
case 4:
#line 119 "hex_grammar.y" /* yacc.c:1646 */
{
(yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, (yyvsp[-1].re_node), (yyvsp[0].re_node));
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node));
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node));
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
}
#line 1351 "hex_grammar.c" /* yacc.c:1646 */
break;
case 5:
#line 128 "hex_grammar.y" /* yacc.c:1646 */
{
RE_NODE* new_concat;
RE_NODE* leftmost_concat = NULL;
RE_NODE* leftmost_node = (yyvsp[-1].re_node);
(yyval.re_node) = NULL;
/*
Some portions of the code (i.e: yr_re_split_at_chaining_point)
expect a left-unbalanced tree where the right child of a concat node
can't be another concat node. A concat node must be always the left
child of its parent if the parent is also a concat. For this reason
the can't simply create two new concat nodes arranged like this:
concat
/ \
/ \
token's \
subtree concat
/ \
/ \
/ \
token_sequence's token's
subtree subtree
Instead we must insert the subtree for the first token as the
leftmost node of the token_sequence subtree.
*/
while (leftmost_node->type == RE_NODE_CONCAT)
{
leftmost_concat = leftmost_node;
leftmost_node = leftmost_node->left;
}
new_concat = yr_re_node_create(
RE_NODE_CONCAT, (yyvsp[-2].re_node), leftmost_node);
if (new_concat != NULL)
{
if (leftmost_concat != NULL)
{
leftmost_concat->left = new_concat;
(yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, (yyvsp[-1].re_node), (yyvsp[0].re_node));
}
else
{
(yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, new_concat, (yyvsp[0].re_node));
}
}
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-2].re_node));
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node));
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node));
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
}
#line 1413 "hex_grammar.c" /* yacc.c:1646 */
break;
case 6:
#line 190 "hex_grammar.y" /* yacc.c:1646 */
{
(yyval.re_node) = (yyvsp[0].re_node);
}
#line 1421 "hex_grammar.c" /* yacc.c:1646 */
break;
case 7:
#line 194 "hex_grammar.y" /* yacc.c:1646 */
{
(yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, (yyvsp[-1].re_node), (yyvsp[0].re_node));
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node));
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node));
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
}
#line 1434 "hex_grammar.c" /* yacc.c:1646 */
break;
case 8:
#line 207 "hex_grammar.y" /* yacc.c:1646 */
{
(yyval.re_node) = (yyvsp[0].re_node);
}
#line 1442 "hex_grammar.c" /* yacc.c:1646 */
break;
case 9:
#line 211 "hex_grammar.y" /* yacc.c:1646 */
{
(yyval.re_node) = (yyvsp[0].re_node);
(yyval.re_node)->greedy = FALSE;
}
#line 1451 "hex_grammar.c" /* yacc.c:1646 */
break;
case 10:
#line 220 "hex_grammar.y" /* yacc.c:1646 */
{
lex_env->token_count++;
if (lex_env->token_count > MAX_HEX_STRING_TOKENS)
{
yr_re_node_destroy((yyvsp[0].re_node));
yyerror(yyscanner, lex_env, "string too long");
YYABORT;
}
(yyval.re_node) = (yyvsp[0].re_node);
}
#line 1468 "hex_grammar.c" /* yacc.c:1646 */
break;
case 11:
#line 233 "hex_grammar.y" /* yacc.c:1646 */
{
lex_env->inside_or++;
}
#line 1476 "hex_grammar.c" /* yacc.c:1646 */
break;
case 12:
#line 237 "hex_grammar.y" /* yacc.c:1646 */
{
(yyval.re_node) = (yyvsp[-1].re_node);
lex_env->inside_or--;
}
#line 1485 "hex_grammar.c" /* yacc.c:1646 */
break;
case 13:
#line 246 "hex_grammar.y" /* yacc.c:1646 */
{
if ((yyvsp[-1].integer) <= 0)
{
yyerror(yyscanner, lex_env, "invalid jump length");
YYABORT;
}
if (lex_env->inside_or && (yyvsp[-1].integer) > STRING_CHAINING_THRESHOLD)
{
yyerror(yyscanner, lex_env, "jumps over "
STR(STRING_CHAINING_THRESHOLD)
" now allowed inside alternation (|)");
YYABORT;
}
(yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL);
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
(yyval.re_node)->start = (int) (yyvsp[-1].integer);
(yyval.re_node)->end = (int) (yyvsp[-1].integer);
}
#line 1512 "hex_grammar.c" /* yacc.c:1646 */
break;
case 14:
#line 269 "hex_grammar.y" /* yacc.c:1646 */
{
if (lex_env->inside_or &&
((yyvsp[-3].integer) > STRING_CHAINING_THRESHOLD ||
(yyvsp[-1].integer) > STRING_CHAINING_THRESHOLD) )
{
yyerror(yyscanner, lex_env, "jumps over "
STR(STRING_CHAINING_THRESHOLD)
" now allowed inside alternation (|)");
YYABORT;
}
if ((yyvsp[-3].integer) < 0 || (yyvsp[-1].integer) < 0)
{
yyerror(yyscanner, lex_env, "invalid negative jump length");
YYABORT;
}
if ((yyvsp[-3].integer) > (yyvsp[-1].integer))
{
yyerror(yyscanner, lex_env, "invalid jump range");
YYABORT;
}
(yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL);
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
(yyval.re_node)->start = (int) (yyvsp[-3].integer);
(yyval.re_node)->end = (int) (yyvsp[-1].integer);
}
#line 1548 "hex_grammar.c" /* yacc.c:1646 */
break;
case 15:
#line 301 "hex_grammar.y" /* yacc.c:1646 */
{
if (lex_env->inside_or)
{
yyerror(yyscanner, lex_env,
"unbounded jumps not allowed inside alternation (|)");
YYABORT;
}
if ((yyvsp[-2].integer) < 0)
{
yyerror(yyscanner, lex_env, "invalid negative jump length");
YYABORT;
}
(yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL);
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
(yyval.re_node)->start = (int) (yyvsp[-2].integer);
(yyval.re_node)->end = INT_MAX;
}
#line 1574 "hex_grammar.c" /* yacc.c:1646 */
break;
case 16:
#line 323 "hex_grammar.y" /* yacc.c:1646 */
{
if (lex_env->inside_or)
{
yyerror(yyscanner, lex_env,
"unbounded jumps not allowed inside alternation (|)");
YYABORT;
}
(yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL);
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
(yyval.re_node)->start = 0;
(yyval.re_node)->end = INT_MAX;
}
#line 1594 "hex_grammar.c" /* yacc.c:1646 */
break;
case 17:
#line 343 "hex_grammar.y" /* yacc.c:1646 */
{
(yyval.re_node) = (yyvsp[0].re_node);
}
#line 1602 "hex_grammar.c" /* yacc.c:1646 */
break;
case 18:
#line 347 "hex_grammar.y" /* yacc.c:1646 */
{
mark_as_not_fast_regexp();
(yyval.re_node) = yr_re_node_create(RE_NODE_ALT, (yyvsp[-2].re_node), (yyvsp[0].re_node));
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-2].re_node));
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node));
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
}
#line 1617 "hex_grammar.c" /* yacc.c:1646 */
break;
case 19:
#line 361 "hex_grammar.y" /* yacc.c:1646 */
{
(yyval.re_node) = yr_re_node_create(RE_NODE_LITERAL, NULL, NULL);
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
(yyval.re_node)->value = (int) (yyvsp[0].integer);
}
#line 1629 "hex_grammar.c" /* yacc.c:1646 */
break;
case 20:
#line 369 "hex_grammar.y" /* yacc.c:1646 */
{
uint8_t mask = (uint8_t) ((yyvsp[0].integer) >> 8);
if (mask == 0x00)
{
(yyval.re_node) = yr_re_node_create(RE_NODE_ANY, NULL, NULL);
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
}
else
{
(yyval.re_node) = yr_re_node_create(RE_NODE_MASKED_LITERAL, NULL, NULL);
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
(yyval.re_node)->value = (yyvsp[0].integer) & 0xFF;
(yyval.re_node)->mask = mask;
}
}
#line 1653 "hex_grammar.c" /* yacc.c:1646 */
break;
#line 1657 "hex_grammar.c" /* yacc.c:1646 */
default: break;
}
/* User semantic actions sometimes alter yychar, and that requires
that yytoken be updated with the new translation. We take the
approach of translating immediately before every use of yytoken.
One alternative is translating here after every semantic action,
but that translation would be missed if the semantic action invokes
YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an
incorrect destructor might then be invoked immediately. In the
case of YYERROR or YYBACKUP, subsequent parser actions might lead
to an incorrect destructor call or verbose syntax error message
before the lookahead is translated. */
YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
*++yyvsp = yyval;
/* Now 'shift' the result of the reduction. Determine what state
that goes to, based on the state we popped back to and the rule
number reduced by. */
yyn = yyr1[yyn];
yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
yystate = yytable[yystate];
else
yystate = yydefgoto[yyn - YYNTOKENS];
goto yynewstate;
/*--------------------------------------.
| yyerrlab -- here on detecting error. |
`--------------------------------------*/
yyerrlab:
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);
/* If not already recovering from an error, report this error. */
if (!yyerrstatus)
{
++yynerrs;
#if ! YYERROR_VERBOSE
yyerror (yyscanner, lex_env, YY_("syntax error"));
#else
# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \
yyssp, yytoken)
{
char const *yymsgp = YY_("syntax error");
int yysyntax_error_status;
yysyntax_error_status = YYSYNTAX_ERROR;
if (yysyntax_error_status == 0)
yymsgp = yymsg;
else if (yysyntax_error_status == 1)
{
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);
if (!yymsg)
{
yymsg = yymsgbuf;
yymsg_alloc = sizeof yymsgbuf;
yysyntax_error_status = 2;
}
else
{
yysyntax_error_status = YYSYNTAX_ERROR;
yymsgp = yymsg;
}
}
yyerror (yyscanner, lex_env, yymsgp);
if (yysyntax_error_status == 2)
goto yyexhaustedlab;
}
# undef YYSYNTAX_ERROR
#endif
}
if (yyerrstatus == 3)
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
if (yychar <= YYEOF)
{
/* Return failure if at end of input. */
if (yychar == YYEOF)
YYABORT;
}
else
{
yydestruct ("Error: discarding",
yytoken, &yylval, yyscanner, lex_env);
yychar = YYEMPTY;
}
}
/* Else will try to reuse lookahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers like GCC when the user code never invokes
YYERROR and the label yyerrorlab therefore never appears in user
code. */
if (/*CONSTCOND*/ 0)
goto yyerrorlab;
/* Do not reclaim the symbols of the rule whose action triggered
this YYERROR. */
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
yystate = *yyssp;
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus = 3; /* Each real token shifted decrements this. */
for (;;)
{
yyn = yypact[yystate];
if (!yypact_value_is_default (yyn))
{
yyn += YYTERROR;
if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
{
yyn = yytable[yyn];
if (0 < yyn)
break;
}
}
/* Pop the current state because it cannot handle the error token. */
if (yyssp == yyss)
YYABORT;
yydestruct ("Error: popping",
yystos[yystate], yyvsp, yyscanner, lex_env);
YYPOPSTACK (1);
yystate = *yyssp;
YY_STACK_PRINT (yyss, yyssp);
}
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
/* Shift the error token. */
YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
yystate = yyn;
goto yynewstate;
/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here. |
`-------------------------------------*/
yyacceptlab:
yyresult = 0;
goto yyreturn;
/*-----------------------------------.
| yyabortlab -- YYABORT comes here. |
`-----------------------------------*/
yyabortlab:
yyresult = 1;
goto yyreturn;
#if !defined yyoverflow || YYERROR_VERBOSE
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here. |
`-------------------------------------------------*/
yyexhaustedlab:
yyerror (yyscanner, lex_env, YY_("memory exhausted"));
yyresult = 2;
/* Fall through. */
#endif
yyreturn:
if (yychar != YYEMPTY)
{
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = YYTRANSLATE (yychar);
yydestruct ("Cleanup: discarding lookahead",
yytoken, &yylval, yyscanner, lex_env);
}
/* Do not reclaim the symbols of the rule whose action triggered
this YYABORT or YYACCEPT. */
YYPOPSTACK (yylen);
YY_STACK_PRINT (yyss, yyssp);
while (yyssp != yyss)
{
yydestruct ("Cleanup: popping",
yystos[*yyssp], yyvsp, yyscanner, lex_env);
YYPOPSTACK (1);
}
#ifndef yyoverflow
if (yyss != yyssa)
YYSTACK_FREE (yyss);
#endif
#if YYERROR_VERBOSE
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
#endif
return yyresult;
}
#line 390 "hex_grammar.y" /* yacc.c:1906 */
| ./CrossVul/dataset_final_sorted/CWE-674/c/bad_3392_0 |
crossvul-cpp_data_good_3392_0 | /* A Bison parser, made by GNU Bison 3.0.4. */
/* Bison implementation for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc.
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/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* C LALR(1) parser skeleton written by Richard Stallman, by
simplifying the original so-called "semantic" parser. */
/* All symbols defined below should begin with yy or YY, to avoid
infringing on user name space. This should be done even for local
variables, as they might otherwise be expanded by user macros.
There are some unavoidable exceptions within include files to
define necessary library symbols; they are noted "INFRINGES ON
USER NAME SPACE" below. */
/* Identify Bison output. */
#define YYBISON 1
/* Bison version. */
#define YYBISON_VERSION "3.0.4"
/* Skeleton name. */
#define YYSKELETON_NAME "yacc.c"
/* Pure parsers. */
#define YYPURE 1
/* Push parsers. */
#define YYPUSH 0
/* Pull parsers. */
#define YYPULL 1
/* Substitute the variable and function names. */
#define yyparse hex_yyparse
#define yylex hex_yylex
#define yyerror hex_yyerror
#define yydebug hex_yydebug
#define yynerrs hex_yynerrs
/* Copy the first part of user declarations. */
#line 30 "hex_grammar.y" /* yacc.c:339 */
#include <string.h>
#include <limits.h>
#include <yara/integers.h>
#include <yara/utils.h>
#include <yara/hex_lexer.h>
#include <yara/limits.h>
#include <yara/mem.h>
#include <yara/error.h>
#define STR_EXPAND(tok) #tok
#define STR(tok) STR_EXPAND(tok)
#define YYERROR_VERBOSE
#define YYMALLOC yr_malloc
#define YYFREE yr_free
#define mark_as_not_fast_regexp() \
((RE_AST*) yyget_extra(yyscanner))->flags &= ~RE_FLAGS_FAST_REGEXP
#define incr_ast_levels() \
if (((RE_AST*) yyget_extra(yyscanner))->levels++ > RE_MAX_AST_LEVELS) \
{ \
lex_env->last_error_code = ERROR_INVALID_HEX_STRING; \
YYABORT; \
}
#define ERROR_IF(x, error) \
if (x) \
{ \
lex_env->last_error_code = error; \
YYABORT; \
} \
#define DESTROY_NODE_IF(x, node) \
if (x) \
{ \
yr_re_node_destroy(node); \
} \
#line 118 "hex_grammar.c" /* yacc.c:339 */
# ifndef YY_NULLPTR
# if defined __cplusplus && 201103L <= __cplusplus
# define YY_NULLPTR nullptr
# else
# define YY_NULLPTR 0
# endif
# endif
/* Enabling verbose error messages. */
#ifdef YYERROR_VERBOSE
# undef YYERROR_VERBOSE
# define YYERROR_VERBOSE 1
#else
# define YYERROR_VERBOSE 0
#endif
/* In a future release of Bison, this section will be replaced
by #include "y.tab.h". */
#ifndef YY_HEX_YY_HEX_GRAMMAR_H_INCLUDED
# define YY_HEX_YY_HEX_GRAMMAR_H_INCLUDED
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
#if YYDEBUG
extern int hex_yydebug;
#endif
/* Token type. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
enum yytokentype
{
_BYTE_ = 258,
_MASKED_BYTE_ = 259,
_NUMBER_ = 260
};
#endif
/* Tokens. */
#define _BYTE_ 258
#define _MASKED_BYTE_ 259
#define _NUMBER_ 260
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
union YYSTYPE
{
#line 85 "hex_grammar.y" /* yacc.c:355 */
int64_t integer;
RE_NODE *re_node;
#line 173 "hex_grammar.c" /* yacc.c:355 */
};
typedef union YYSTYPE YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#endif
int hex_yyparse (void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env);
#endif /* !YY_HEX_YY_HEX_GRAMMAR_H_INCLUDED */
/* Copy the second part of user declarations. */
#line 189 "hex_grammar.c" /* yacc.c:358 */
#ifdef short
# undef short
#endif
#ifdef YYTYPE_UINT8
typedef YYTYPE_UINT8 yytype_uint8;
#else
typedef unsigned char yytype_uint8;
#endif
#ifdef YYTYPE_INT8
typedef YYTYPE_INT8 yytype_int8;
#else
typedef signed char yytype_int8;
#endif
#ifdef YYTYPE_UINT16
typedef YYTYPE_UINT16 yytype_uint16;
#else
typedef unsigned short int yytype_uint16;
#endif
#ifdef YYTYPE_INT16
typedef YYTYPE_INT16 yytype_int16;
#else
typedef short int yytype_int16;
#endif
#ifndef YYSIZE_T
# ifdef __SIZE_TYPE__
# define YYSIZE_T __SIZE_TYPE__
# elif defined size_t
# define YYSIZE_T size_t
# elif ! defined YYSIZE_T
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# define YYSIZE_T size_t
# else
# define YYSIZE_T unsigned int
# endif
#endif
#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
#ifndef YY_
# if defined YYENABLE_NLS && YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
# define YY_(Msgid) dgettext ("bison-runtime", Msgid)
# endif
# endif
# ifndef YY_
# define YY_(Msgid) Msgid
# endif
#endif
#ifndef YY_ATTRIBUTE
# if (defined __GNUC__ \
&& (2 < __GNUC__ || (__GNUC__ == 2 && 96 <= __GNUC_MINOR__))) \
|| defined __SUNPRO_C && 0x5110 <= __SUNPRO_C
# define YY_ATTRIBUTE(Spec) __attribute__(Spec)
# else
# define YY_ATTRIBUTE(Spec) /* empty */
# endif
#endif
#ifndef YY_ATTRIBUTE_PURE
# define YY_ATTRIBUTE_PURE YY_ATTRIBUTE ((__pure__))
#endif
#ifndef YY_ATTRIBUTE_UNUSED
# define YY_ATTRIBUTE_UNUSED YY_ATTRIBUTE ((__unused__))
#endif
#if !defined _Noreturn \
&& (!defined __STDC_VERSION__ || __STDC_VERSION__ < 201112)
# if defined _MSC_VER && 1200 <= _MSC_VER
# define _Noreturn __declspec (noreturn)
# else
# define _Noreturn YY_ATTRIBUTE ((__noreturn__))
# endif
#endif
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YYUSE(E) ((void) (E))
#else
# define YYUSE(E) /* empty */
#endif
#if defined __GNUC__ && 407 <= __GNUC__ * 100 + __GNUC_MINOR__
/* Suppress an incorrect diagnostic about yylval being uninitialized. */
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN \
_Pragma ("GCC diagnostic push") \
_Pragma ("GCC diagnostic ignored \"-Wuninitialized\"")\
_Pragma ("GCC diagnostic ignored \"-Wmaybe-uninitialized\"")
# define YY_IGNORE_MAYBE_UNINITIALIZED_END \
_Pragma ("GCC diagnostic pop")
#else
# define YY_INITIAL_VALUE(Value) Value
#endif
#ifndef YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
# define YY_IGNORE_MAYBE_UNINITIALIZED_END
#endif
#ifndef YY_INITIAL_VALUE
# define YY_INITIAL_VALUE(Value) /* Nothing. */
#endif
#if ! defined yyoverflow || YYERROR_VERBOSE
/* The parser invokes alloca or malloc; define the necessary symbols. */
# ifdef YYSTACK_USE_ALLOCA
# if YYSTACK_USE_ALLOCA
# ifdef __GNUC__
# define YYSTACK_ALLOC __builtin_alloca
# elif defined __BUILTIN_VA_ARG_INCR
# include <alloca.h> /* INFRINGES ON USER NAME SPACE */
# elif defined _AIX
# define YYSTACK_ALLOC __alloca
# elif defined _MSC_VER
# include <malloc.h> /* INFRINGES ON USER NAME SPACE */
# define alloca _alloca
# else
# define YYSTACK_ALLOC alloca
# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
/* Use EXIT_SUCCESS as a witness for stdlib.h. */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# endif
# endif
# endif
# ifdef YYSTACK_ALLOC
/* Pacify GCC's 'empty if-body' warning. */
# define YYSTACK_FREE(Ptr) do { /* empty */; } while (0)
# ifndef YYSTACK_ALLOC_MAXIMUM
/* The OS might guarantee only one guard page at the bottom of the stack,
and a page size can be as small as 4096 bytes. So we cannot safely
invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
to allow for a few compiler-allocated temporary stack slots. */
# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
# endif
# else
# define YYSTACK_ALLOC YYMALLOC
# define YYSTACK_FREE YYFREE
# ifndef YYSTACK_ALLOC_MAXIMUM
# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
# endif
# if (defined __cplusplus && ! defined EXIT_SUCCESS \
&& ! ((defined YYMALLOC || defined malloc) \
&& (defined YYFREE || defined free)))
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# ifndef YYMALLOC
# define YYMALLOC malloc
# if ! defined malloc && ! defined EXIT_SUCCESS
void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# ifndef YYFREE
# define YYFREE free
# if ! defined free && ! defined EXIT_SUCCESS
void free (void *); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# endif
#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
#if (! defined yyoverflow \
&& (! defined __cplusplus \
|| (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
/* A type that is properly aligned for any stack member. */
union yyalloc
{
yytype_int16 yyss_alloc;
YYSTYPE yyvs_alloc;
};
/* The size of the maximum gap between one aligned stack and the next. */
# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
/* The size of an array large to enough to hold all stacks, each with
N elements. */
# define YYSTACK_BYTES(N) \
((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
+ YYSTACK_GAP_MAXIMUM)
# define YYCOPY_NEEDED 1
/* Relocate STACK from its old location to the new one. The
local variables YYSIZE and YYSTACKSIZE give the old and new number of
elements in the stack, and YYPTR gives the new location of the
stack. Advance YYPTR to a properly aligned location for the next
stack. */
# define YYSTACK_RELOCATE(Stack_alloc, Stack) \
do \
{ \
YYSIZE_T yynewbytes; \
YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \
Stack = &yyptr->Stack_alloc; \
yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
yyptr += yynewbytes / sizeof (*yyptr); \
} \
while (0)
#endif
#if defined YYCOPY_NEEDED && YYCOPY_NEEDED
/* Copy COUNT objects from SRC to DST. The source and destination do
not overlap. */
# ifndef YYCOPY
# if defined __GNUC__ && 1 < __GNUC__
# define YYCOPY(Dst, Src, Count) \
__builtin_memcpy (Dst, Src, (Count) * sizeof (*(Src)))
# else
# define YYCOPY(Dst, Src, Count) \
do \
{ \
YYSIZE_T yyi; \
for (yyi = 0; yyi < (Count); yyi++) \
(Dst)[yyi] = (Src)[yyi]; \
} \
while (0)
# endif
# endif
#endif /* !YYCOPY_NEEDED */
/* YYFINAL -- State number of the termination state. */
#define YYFINAL 9
/* YYLAST -- Last index in YYTABLE. */
#define YYLAST 30
/* YYNTOKENS -- Number of terminals. */
#define YYNTOKENS 14
/* YYNNTS -- Number of nonterminals. */
#define YYNNTS 10
/* YYNRULES -- Number of rules. */
#define YYNRULES 20
/* YYNSTATES -- Number of states. */
#define YYNSTATES 32
/* YYTRANSLATE[YYX] -- Symbol number corresponding to YYX as returned
by yylex, with out-of-bounds checking. */
#define YYUNDEFTOK 2
#define YYMAXUTOK 260
#define YYTRANSLATE(YYX) \
((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
/* YYTRANSLATE[TOKEN-NUM] -- Symbol number corresponding to TOKEN-NUM
as returned by yylex, without out-of-bounds checking. */
static const yytype_uint8 yytranslate[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
8, 9, 2, 2, 2, 12, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 10, 2, 11, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 6, 13, 7, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
5
};
#if YYDEBUG
/* YYRLINE[YYN] -- Source line where rule number YYN was defined. */
static const yytype_uint16 yyrline[] =
{
0, 112, 112, 121, 125, 136, 200, 204, 219, 223,
232, 246, 245, 258, 281, 313, 335, 355, 359, 374,
382
};
#endif
#if YYDEBUG || YYERROR_VERBOSE || 0
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
First, the terminals, then, starting at YYNTOKENS, nonterminals. */
static const char *const yytname[] =
{
"$end", "error", "$undefined", "_BYTE_", "_MASKED_BYTE_", "_NUMBER_",
"'{'", "'}'", "'('", "')'", "'['", "']'", "'-'", "'|'", "$accept",
"hex_string", "tokens", "token_sequence", "token_or_range", "token",
"$@1", "range", "alternatives", "byte", YY_NULLPTR
};
#endif
# ifdef YYPRINT
/* YYTOKNUM[NUM] -- (External) token number corresponding to the
(internal) symbol number NUM (which must be that of a token). */
static const yytype_uint16 yytoknum[] =
{
0, 256, 257, 258, 259, 260, 123, 125, 40, 41,
91, 93, 45, 124
};
# endif
#define YYPACT_NINF -11
#define yypact_value_is_default(Yystate) \
(!!((Yystate) == (-11)))
#define YYTABLE_NINF -6
#define yytable_value_is_error(Yytable_value) \
0
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
static const yytype_int8 yypact[] =
{
20, 14, 27, -11, -11, -11, 21, -2, -11, -11,
14, -11, -1, -2, -11, -4, -11, -11, 10, 13,
9, -11, 3, -11, 14, -11, 2, -11, -11, 18,
-11, -11
};
/* YYDEFACT[STATE-NUM] -- Default reduction number in state STATE-NUM.
Performed when YYTABLE does not specify something else to do. Zero
means the default is an error. */
static const yytype_uint8 yydefact[] =
{
0, 0, 0, 19, 20, 11, 0, 3, 10, 1,
0, 2, 0, 0, 6, 8, 9, 17, 0, 0,
0, 7, 8, 12, 0, 13, 0, 16, 18, 0,
15, 14
};
/* YYPGOTO[NTERM-NUM]. */
static const yytype_int8 yypgoto[] =
{
-11, -11, -10, -11, 17, 8, -11, -11, -11, -11
};
/* YYDEFGOTO[NTERM-NUM]. */
static const yytype_int8 yydefgoto[] =
{
-1, 2, 6, 13, 14, 7, 10, 16, 18, 8
};
/* YYTABLE[YYPACT[STATE-NUM]] -- What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule whose
number is the opposite. If YYTABLE_NINF, syntax error. */
static const yytype_int8 yytable[] =
{
17, 3, 4, -4, 19, -4, 5, 29, 12, -4,
-5, 20, -5, 30, 28, 15, -5, 3, 4, 23,
27, 22, 5, 24, 25, 26, 1, 9, 11, 31,
21
};
static const yytype_uint8 yycheck[] =
{
10, 3, 4, 7, 5, 9, 8, 5, 10, 13,
7, 12, 9, 11, 24, 7, 13, 3, 4, 9,
11, 13, 8, 13, 11, 12, 6, 0, 7, 11,
13
};
/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
symbol of state STATE-NUM. */
static const yytype_uint8 yystos[] =
{
0, 6, 15, 3, 4, 8, 16, 19, 23, 0,
20, 7, 10, 17, 18, 19, 21, 16, 22, 5,
12, 18, 19, 9, 13, 11, 12, 11, 16, 5,
11, 11
};
/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
static const yytype_uint8 yyr1[] =
{
0, 14, 15, 16, 16, 16, 17, 17, 18, 18,
19, 20, 19, 21, 21, 21, 21, 22, 22, 23,
23
};
/* YYR2[YYN] -- Number of symbols on the right hand side of rule YYN. */
static const yytype_uint8 yyr2[] =
{
0, 2, 3, 1, 2, 3, 1, 2, 1, 1,
1, 0, 4, 3, 5, 4, 3, 1, 3, 1,
1
};
#define yyerrok (yyerrstatus = 0)
#define yyclearin (yychar = YYEMPTY)
#define YYEMPTY (-2)
#define YYEOF 0
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrorlab
#define YYRECOVERING() (!!yyerrstatus)
#define YYBACKUP(Token, Value) \
do \
if (yychar == YYEMPTY) \
{ \
yychar = (Token); \
yylval = (Value); \
YYPOPSTACK (yylen); \
yystate = *yyssp; \
goto yybackup; \
} \
else \
{ \
yyerror (yyscanner, lex_env, YY_("syntax error: cannot back up")); \
YYERROR; \
} \
while (0)
/* Error token number */
#define YYTERROR 1
#define YYERRCODE 256
/* Enable debugging if requested. */
#if YYDEBUG
# ifndef YYFPRINTF
# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
# define YYFPRINTF fprintf
# endif
# define YYDPRINTF(Args) \
do { \
if (yydebug) \
YYFPRINTF Args; \
} while (0)
/* This macro is provided for backward compatibility. */
#ifndef YY_LOCATION_PRINT
# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
#endif
# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
do { \
if (yydebug) \
{ \
YYFPRINTF (stderr, "%s ", Title); \
yy_symbol_print (stderr, \
Type, Value, yyscanner, lex_env); \
YYFPRINTF (stderr, "\n"); \
} \
} while (0)
/*----------------------------------------.
| Print this symbol's value on YYOUTPUT. |
`----------------------------------------*/
static void
yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env)
{
FILE *yyo = yyoutput;
YYUSE (yyo);
YYUSE (yyscanner);
YYUSE (lex_env);
if (!yyvaluep)
return;
# ifdef YYPRINT
if (yytype < YYNTOKENS)
YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
# endif
YYUSE (yytype);
}
/*--------------------------------.
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
static void
yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env)
{
YYFPRINTF (yyoutput, "%s %s (",
yytype < YYNTOKENS ? "token" : "nterm", yytname[yytype]);
yy_symbol_value_print (yyoutput, yytype, yyvaluep, yyscanner, lex_env);
YYFPRINTF (yyoutput, ")");
}
/*------------------------------------------------------------------.
| yy_stack_print -- Print the state stack from its BOTTOM up to its |
| TOP (included). |
`------------------------------------------------------------------*/
static void
yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
{
YYFPRINTF (stderr, "Stack now");
for (; yybottom <= yytop; yybottom++)
{
int yybot = *yybottom;
YYFPRINTF (stderr, " %d", yybot);
}
YYFPRINTF (stderr, "\n");
}
# define YY_STACK_PRINT(Bottom, Top) \
do { \
if (yydebug) \
yy_stack_print ((Bottom), (Top)); \
} while (0)
/*------------------------------------------------.
| Report that the YYRULE is going to be reduced. |
`------------------------------------------------*/
static void
yy_reduce_print (yytype_int16 *yyssp, YYSTYPE *yyvsp, int yyrule, void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env)
{
unsigned long int yylno = yyrline[yyrule];
int yynrhs = yyr2[yyrule];
int yyi;
YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
yyrule - 1, yylno);
/* The symbols being reduced. */
for (yyi = 0; yyi < yynrhs; yyi++)
{
YYFPRINTF (stderr, " $%d = ", yyi + 1);
yy_symbol_print (stderr,
yystos[yyssp[yyi + 1 - yynrhs]],
&(yyvsp[(yyi + 1) - (yynrhs)])
, yyscanner, lex_env);
YYFPRINTF (stderr, "\n");
}
}
# define YY_REDUCE_PRINT(Rule) \
do { \
if (yydebug) \
yy_reduce_print (yyssp, yyvsp, Rule, yyscanner, lex_env); \
} while (0)
/* Nonzero means print parse trace. It is left uninitialized so that
multiple parsers can coexist. */
int yydebug;
#else /* !YYDEBUG */
# define YYDPRINTF(Args)
# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
# define YY_STACK_PRINT(Bottom, Top)
# define YY_REDUCE_PRINT(Rule)
#endif /* !YYDEBUG */
/* YYINITDEPTH -- initial size of the parser's stacks. */
#ifndef YYINITDEPTH
# define YYINITDEPTH 200
#endif
/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
if the built-in stack extension method is used).
Do not make this value too large; the results are undefined if
YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
evaluated with infinite-precision integer arithmetic. */
#ifndef YYMAXDEPTH
# define YYMAXDEPTH 10000
#endif
#if YYERROR_VERBOSE
# ifndef yystrlen
# if defined __GLIBC__ && defined _STRING_H
# define yystrlen strlen
# else
/* Return the length of YYSTR. */
static YYSIZE_T
yystrlen (const char *yystr)
{
YYSIZE_T yylen;
for (yylen = 0; yystr[yylen]; yylen++)
continue;
return yylen;
}
# endif
# endif
# ifndef yystpcpy
# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
# define yystpcpy stpcpy
# else
/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
YYDEST. */
static char *
yystpcpy (char *yydest, const char *yysrc)
{
char *yyd = yydest;
const char *yys = yysrc;
while ((*yyd++ = *yys++) != '\0')
continue;
return yyd - 1;
}
# endif
# endif
# ifndef yytnamerr
/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
quotes and backslashes, so that it's suitable for yyerror. The
heuristic is that double-quoting is unnecessary unless the string
contains an apostrophe, a comma, or backslash (other than
backslash-backslash). YYSTR is taken from yytname. If YYRES is
null, do not copy; instead, return the length of what the result
would have been. */
static YYSIZE_T
yytnamerr (char *yyres, const char *yystr)
{
if (*yystr == '"')
{
YYSIZE_T yyn = 0;
char const *yyp = yystr;
for (;;)
switch (*++yyp)
{
case '\'':
case ',':
goto do_not_strip_quotes;
case '\\':
if (*++yyp != '\\')
goto do_not_strip_quotes;
/* Fall through. */
default:
if (yyres)
yyres[yyn] = *yyp;
yyn++;
break;
case '"':
if (yyres)
yyres[yyn] = '\0';
return yyn;
}
do_not_strip_quotes: ;
}
if (! yyres)
return yystrlen (yystr);
return yystpcpy (yyres, yystr) - yyres;
}
# endif
/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message
about the unexpected token YYTOKEN for the state stack whose top is
YYSSP.
Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is
not large enough to hold the message. In that case, also set
*YYMSG_ALLOC to the required number of bytes. Return 2 if the
required number of bytes is too large to store. */
static int
yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
yytype_int16 *yyssp, int yytoken)
{
YYSIZE_T yysize0 = yytnamerr (YY_NULLPTR, yytname[yytoken]);
YYSIZE_T yysize = yysize0;
enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
/* Internationalized format string. */
const char *yyformat = YY_NULLPTR;
/* Arguments of yyformat. */
char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
/* Number of reported tokens (one for the "unexpected", one per
"expected"). */
int yycount = 0;
/* There are many possibilities here to consider:
- If this state is a consistent state with a default action, then
the only way this function was invoked is if the default action
is an error action. In that case, don't check for expected
tokens because there are none.
- The only way there can be no lookahead present (in yychar) is if
this state is a consistent state with a default action. Thus,
detecting the absence of a lookahead is sufficient to determine
that there is no unexpected or expected token to report. In that
case, just report a simple "syntax error".
- Don't assume there isn't a lookahead just because this state is a
consistent state with a default action. There might have been a
previous inconsistent state, consistent state with a non-default
action, or user semantic action that manipulated yychar.
- Of course, the expected token list depends on states to have
correct lookahead information, and it depends on the parser not
to perform extra reductions after fetching a lookahead from the
scanner and before detecting a syntax error. Thus, state merging
(from LALR or IELR) and default reductions corrupt the expected
token list. However, the list is correct for canonical LR with
one exception: it will still contain any token that will not be
accepted due to an error action in a later state.
*/
if (yytoken != YYEMPTY)
{
int yyn = yypact[*yyssp];
yyarg[yycount++] = yytname[yytoken];
if (!yypact_value_is_default (yyn))
{
/* Start YYX at -YYN if negative to avoid negative indexes in
YYCHECK. In other words, skip the first -YYN actions for
this state because they are default actions. */
int yyxbegin = yyn < 0 ? -yyn : 0;
/* Stay within bounds of both yycheck and yytname. */
int yychecklim = YYLAST - yyn + 1;
int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
int yyx;
for (yyx = yyxbegin; yyx < yyxend; ++yyx)
if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR
&& !yytable_value_is_error (yytable[yyx + yyn]))
{
if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
{
yycount = 1;
yysize = yysize0;
break;
}
yyarg[yycount++] = yytname[yyx];
{
YYSIZE_T yysize1 = yysize + yytnamerr (YY_NULLPTR, yytname[yyx]);
if (! (yysize <= yysize1
&& yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
yysize = yysize1;
}
}
}
}
switch (yycount)
{
# define YYCASE_(N, S) \
case N: \
yyformat = S; \
break
YYCASE_(0, YY_("syntax error"));
YYCASE_(1, YY_("syntax error, unexpected %s"));
YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s"));
YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s"));
YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
# undef YYCASE_
}
{
YYSIZE_T yysize1 = yysize + yystrlen (yyformat);
if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
yysize = yysize1;
}
if (*yymsg_alloc < yysize)
{
*yymsg_alloc = 2 * yysize;
if (! (yysize <= *yymsg_alloc
&& *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM))
*yymsg_alloc = YYSTACK_ALLOC_MAXIMUM;
return 1;
}
/* Avoid sprintf, as that infringes on the user's name space.
Don't have undefined behavior even if the translation
produced a string with the wrong number of "%s"s. */
{
char *yyp = *yymsg;
int yyi = 0;
while ((*yyp = *yyformat) != '\0')
if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount)
{
yyp += yytnamerr (yyp, yyarg[yyi++]);
yyformat += 2;
}
else
{
yyp++;
yyformat++;
}
}
return 0;
}
#endif /* YYERROR_VERBOSE */
/*-----------------------------------------------.
| Release the memory associated to this symbol. |
`-----------------------------------------------*/
static void
yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env)
{
YYUSE (yyvaluep);
YYUSE (yyscanner);
YYUSE (lex_env);
if (!yymsg)
yymsg = "Deleting";
YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
switch (yytype)
{
case 16: /* tokens */
#line 101 "hex_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1030 "hex_grammar.c" /* yacc.c:1257 */
break;
case 17: /* token_sequence */
#line 102 "hex_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1036 "hex_grammar.c" /* yacc.c:1257 */
break;
case 18: /* token_or_range */
#line 103 "hex_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1042 "hex_grammar.c" /* yacc.c:1257 */
break;
case 19: /* token */
#line 104 "hex_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1048 "hex_grammar.c" /* yacc.c:1257 */
break;
case 21: /* range */
#line 107 "hex_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1054 "hex_grammar.c" /* yacc.c:1257 */
break;
case 22: /* alternatives */
#line 106 "hex_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1060 "hex_grammar.c" /* yacc.c:1257 */
break;
case 23: /* byte */
#line 105 "hex_grammar.y" /* yacc.c:1257 */
{ yr_re_node_destroy(((*yyvaluep).re_node)); }
#line 1066 "hex_grammar.c" /* yacc.c:1257 */
break;
default:
break;
}
YY_IGNORE_MAYBE_UNINITIALIZED_END
}
/*----------.
| yyparse. |
`----------*/
int
yyparse (void *yyscanner, HEX_LEX_ENVIRONMENT *lex_env)
{
/* The lookahead symbol. */
int yychar;
/* The semantic value of the lookahead symbol. */
/* Default value used for initialization, for pacifying older GCCs
or non-GCC compilers. */
YY_INITIAL_VALUE (static YYSTYPE yyval_default;)
YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default);
/* Number of syntax errors so far. */
int yynerrs;
int yystate;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus;
/* The stacks and their tools:
'yyss': related to states.
'yyvs': related to semantic values.
Refer to the stacks through separate pointers, to allow yyoverflow
to reallocate them elsewhere. */
/* The state stack. */
yytype_int16 yyssa[YYINITDEPTH];
yytype_int16 *yyss;
yytype_int16 *yyssp;
/* The semantic value stack. */
YYSTYPE yyvsa[YYINITDEPTH];
YYSTYPE *yyvs;
YYSTYPE *yyvsp;
YYSIZE_T yystacksize;
int yyn;
int yyresult;
/* Lookahead token as an internal (translated) token number. */
int yytoken = 0;
/* The variables used to return semantic value and location from the
action routines. */
YYSTYPE yyval;
#if YYERROR_VERBOSE
/* Buffer for error messages, and its allocated size. */
char yymsgbuf[128];
char *yymsg = yymsgbuf;
YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
#endif
#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))
/* The number of symbols on the RHS of the reduced rule.
Keep to zero when no symbol should be popped. */
int yylen = 0;
yyssp = yyss = yyssa;
yyvsp = yyvs = yyvsa;
yystacksize = YYINITDEPTH;
YYDPRINTF ((stderr, "Starting parse\n"));
yystate = 0;
yyerrstatus = 0;
yynerrs = 0;
yychar = YYEMPTY; /* Cause a token to be read. */
goto yysetstate;
/*------------------------------------------------------------.
| yynewstate -- Push a new state, which is found in yystate. |
`------------------------------------------------------------*/
yynewstate:
/* In all cases, when you get here, the value and location stacks
have just been pushed. So pushing a state here evens the stacks. */
yyssp++;
yysetstate:
*yyssp = yystate;
if (yyss + yystacksize - 1 <= yyssp)
{
/* Get the current used size of the three stacks, in elements. */
YYSIZE_T yysize = yyssp - yyss + 1;
#ifdef yyoverflow
{
/* Give user a chance to reallocate the stack. Use copies of
these so that the &'s don't force the real ones into
memory. */
YYSTYPE *yyvs1 = yyvs;
yytype_int16 *yyss1 = yyss;
/* Each stack pointer address is followed by the size of the
data in use in that stack, in bytes. This used to be a
conditional around just the two extra args, but that might
be undefined if yyoverflow is a macro. */
yyoverflow (YY_("memory exhausted"),
&yyss1, yysize * sizeof (*yyssp),
&yyvs1, yysize * sizeof (*yyvsp),
&yystacksize);
yyss = yyss1;
yyvs = yyvs1;
}
#else /* no yyoverflow */
# ifndef YYSTACK_RELOCATE
goto yyexhaustedlab;
# else
/* Extend the stack our own way. */
if (YYMAXDEPTH <= yystacksize)
goto yyexhaustedlab;
yystacksize *= 2;
if (YYMAXDEPTH < yystacksize)
yystacksize = YYMAXDEPTH;
{
yytype_int16 *yyss1 = yyss;
union yyalloc *yyptr =
(union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
if (! yyptr)
goto yyexhaustedlab;
YYSTACK_RELOCATE (yyss_alloc, yyss);
YYSTACK_RELOCATE (yyvs_alloc, yyvs);
# undef YYSTACK_RELOCATE
if (yyss1 != yyssa)
YYSTACK_FREE (yyss1);
}
# endif
#endif /* no yyoverflow */
yyssp = yyss + yysize - 1;
yyvsp = yyvs + yysize - 1;
YYDPRINTF ((stderr, "Stack size increased to %lu\n",
(unsigned long int) yystacksize));
if (yyss + yystacksize - 1 <= yyssp)
YYABORT;
}
YYDPRINTF ((stderr, "Entering state %d\n", yystate));
if (yystate == YYFINAL)
YYACCEPT;
goto yybackup;
/*-----------.
| yybackup. |
`-----------*/
yybackup:
/* Do appropriate processing given the current state. Read a
lookahead token if we need one and don't already have one. */
/* First try to decide what to do without reference to lookahead token. */
yyn = yypact[yystate];
if (yypact_value_is_default (yyn))
goto yydefault;
/* Not known => get a lookahead token if don't already have one. */
/* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */
if (yychar == YYEMPTY)
{
YYDPRINTF ((stderr, "Reading a token: "));
yychar = yylex (&yylval, yyscanner, lex_env);
}
if (yychar <= YYEOF)
{
yychar = yytoken = YYEOF;
YYDPRINTF ((stderr, "Now at end of input.\n"));
}
else
{
yytoken = YYTRANSLATE (yychar);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
goto yydefault;
yyn = yytable[yyn];
if (yyn <= 0)
{
if (yytable_value_is_error (yyn))
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
/* Count tokens shifted since error; after three, turn off error
status. */
if (yyerrstatus)
yyerrstatus--;
/* Shift the lookahead token. */
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
/* Discard the shifted token. */
yychar = YYEMPTY;
yystate = yyn;
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact[yystate];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- Do a reduction. |
`-----------------------------*/
yyreduce:
/* yyn is the number of a rule to reduce with. */
yylen = yyr2[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
'$$ = $1'.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. Assigning to YYVAL
unconditionally makes the parser a bit smaller, and it avoids a
GCC warning that YYVAL may be used uninitialized. */
yyval = yyvsp[1-yylen];
YY_REDUCE_PRINT (yyn);
switch (yyn)
{
case 2:
#line 113 "hex_grammar.y" /* yacc.c:1661 */
{
RE_AST* re_ast = yyget_extra(yyscanner);
re_ast->root_node = (yyvsp[-1].re_node);
}
#line 1337 "hex_grammar.c" /* yacc.c:1661 */
break;
case 3:
#line 122 "hex_grammar.y" /* yacc.c:1661 */
{
(yyval.re_node) = (yyvsp[0].re_node);
}
#line 1345 "hex_grammar.c" /* yacc.c:1661 */
break;
case 4:
#line 126 "hex_grammar.y" /* yacc.c:1661 */
{
incr_ast_levels();
(yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, (yyvsp[-1].re_node), (yyvsp[0].re_node));
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node));
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node));
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
}
#line 1360 "hex_grammar.c" /* yacc.c:1661 */
break;
case 5:
#line 137 "hex_grammar.y" /* yacc.c:1661 */
{
RE_NODE* new_concat;
RE_NODE* leftmost_concat = NULL;
RE_NODE* leftmost_node = (yyvsp[-1].re_node);
incr_ast_levels();
(yyval.re_node) = NULL;
/*
Some portions of the code (i.e: yr_re_split_at_chaining_point)
expect a left-unbalanced tree where the right child of a concat node
can't be another concat node. A concat node must be always the left
child of its parent if the parent is also a concat. For this reason
the can't simply create two new concat nodes arranged like this:
concat
/ \
/ \
token's \
subtree concat
/ \
/ \
/ \
token_sequence's token's
subtree subtree
Instead we must insert the subtree for the first token as the
leftmost node of the token_sequence subtree.
*/
while (leftmost_node->type == RE_NODE_CONCAT)
{
leftmost_concat = leftmost_node;
leftmost_node = leftmost_node->left;
}
new_concat = yr_re_node_create(
RE_NODE_CONCAT, (yyvsp[-2].re_node), leftmost_node);
if (new_concat != NULL)
{
if (leftmost_concat != NULL)
{
leftmost_concat->left = new_concat;
(yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, (yyvsp[-1].re_node), (yyvsp[0].re_node));
}
else
{
(yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, new_concat, (yyvsp[0].re_node));
}
}
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-2].re_node));
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node));
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node));
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
}
#line 1424 "hex_grammar.c" /* yacc.c:1661 */
break;
case 6:
#line 201 "hex_grammar.y" /* yacc.c:1661 */
{
(yyval.re_node) = (yyvsp[0].re_node);
}
#line 1432 "hex_grammar.c" /* yacc.c:1661 */
break;
case 7:
#line 205 "hex_grammar.y" /* yacc.c:1661 */
{
incr_ast_levels();
(yyval.re_node) = yr_re_node_create(RE_NODE_CONCAT, (yyvsp[-1].re_node), (yyvsp[0].re_node));
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-1].re_node));
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node));
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
}
#line 1447 "hex_grammar.c" /* yacc.c:1661 */
break;
case 8:
#line 220 "hex_grammar.y" /* yacc.c:1661 */
{
(yyval.re_node) = (yyvsp[0].re_node);
}
#line 1455 "hex_grammar.c" /* yacc.c:1661 */
break;
case 9:
#line 224 "hex_grammar.y" /* yacc.c:1661 */
{
(yyval.re_node) = (yyvsp[0].re_node);
(yyval.re_node)->greedy = FALSE;
}
#line 1464 "hex_grammar.c" /* yacc.c:1661 */
break;
case 10:
#line 233 "hex_grammar.y" /* yacc.c:1661 */
{
lex_env->token_count++;
if (lex_env->token_count > MAX_HEX_STRING_TOKENS)
{
yr_re_node_destroy((yyvsp[0].re_node));
yyerror(yyscanner, lex_env, "string too long");
YYABORT;
}
(yyval.re_node) = (yyvsp[0].re_node);
}
#line 1481 "hex_grammar.c" /* yacc.c:1661 */
break;
case 11:
#line 246 "hex_grammar.y" /* yacc.c:1661 */
{
lex_env->inside_or++;
}
#line 1489 "hex_grammar.c" /* yacc.c:1661 */
break;
case 12:
#line 250 "hex_grammar.y" /* yacc.c:1661 */
{
(yyval.re_node) = (yyvsp[-1].re_node);
lex_env->inside_or--;
}
#line 1498 "hex_grammar.c" /* yacc.c:1661 */
break;
case 13:
#line 259 "hex_grammar.y" /* yacc.c:1661 */
{
if ((yyvsp[-1].integer) <= 0)
{
yyerror(yyscanner, lex_env, "invalid jump length");
YYABORT;
}
if (lex_env->inside_or && (yyvsp[-1].integer) > STRING_CHAINING_THRESHOLD)
{
yyerror(yyscanner, lex_env, "jumps over "
STR(STRING_CHAINING_THRESHOLD)
" now allowed inside alternation (|)");
YYABORT;
}
(yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL);
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
(yyval.re_node)->start = (int) (yyvsp[-1].integer);
(yyval.re_node)->end = (int) (yyvsp[-1].integer);
}
#line 1525 "hex_grammar.c" /* yacc.c:1661 */
break;
case 14:
#line 282 "hex_grammar.y" /* yacc.c:1661 */
{
if (lex_env->inside_or &&
((yyvsp[-3].integer) > STRING_CHAINING_THRESHOLD ||
(yyvsp[-1].integer) > STRING_CHAINING_THRESHOLD) )
{
yyerror(yyscanner, lex_env, "jumps over "
STR(STRING_CHAINING_THRESHOLD)
" now allowed inside alternation (|)");
YYABORT;
}
if ((yyvsp[-3].integer) < 0 || (yyvsp[-1].integer) < 0)
{
yyerror(yyscanner, lex_env, "invalid negative jump length");
YYABORT;
}
if ((yyvsp[-3].integer) > (yyvsp[-1].integer))
{
yyerror(yyscanner, lex_env, "invalid jump range");
YYABORT;
}
(yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL);
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
(yyval.re_node)->start = (int) (yyvsp[-3].integer);
(yyval.re_node)->end = (int) (yyvsp[-1].integer);
}
#line 1561 "hex_grammar.c" /* yacc.c:1661 */
break;
case 15:
#line 314 "hex_grammar.y" /* yacc.c:1661 */
{
if (lex_env->inside_or)
{
yyerror(yyscanner, lex_env,
"unbounded jumps not allowed inside alternation (|)");
YYABORT;
}
if ((yyvsp[-2].integer) < 0)
{
yyerror(yyscanner, lex_env, "invalid negative jump length");
YYABORT;
}
(yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL);
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
(yyval.re_node)->start = (int) (yyvsp[-2].integer);
(yyval.re_node)->end = INT_MAX;
}
#line 1587 "hex_grammar.c" /* yacc.c:1661 */
break;
case 16:
#line 336 "hex_grammar.y" /* yacc.c:1661 */
{
if (lex_env->inside_or)
{
yyerror(yyscanner, lex_env,
"unbounded jumps not allowed inside alternation (|)");
YYABORT;
}
(yyval.re_node) = yr_re_node_create(RE_NODE_RANGE_ANY, NULL, NULL);
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
(yyval.re_node)->start = 0;
(yyval.re_node)->end = INT_MAX;
}
#line 1607 "hex_grammar.c" /* yacc.c:1661 */
break;
case 17:
#line 356 "hex_grammar.y" /* yacc.c:1661 */
{
(yyval.re_node) = (yyvsp[0].re_node);
}
#line 1615 "hex_grammar.c" /* yacc.c:1661 */
break;
case 18:
#line 360 "hex_grammar.y" /* yacc.c:1661 */
{
mark_as_not_fast_regexp();
incr_ast_levels();
(yyval.re_node) = yr_re_node_create(RE_NODE_ALT, (yyvsp[-2].re_node), (yyvsp[0].re_node));
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[-2].re_node));
DESTROY_NODE_IF((yyval.re_node) == NULL, (yyvsp[0].re_node));
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
}
#line 1631 "hex_grammar.c" /* yacc.c:1661 */
break;
case 19:
#line 375 "hex_grammar.y" /* yacc.c:1661 */
{
(yyval.re_node) = yr_re_node_create(RE_NODE_LITERAL, NULL, NULL);
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
(yyval.re_node)->value = (int) (yyvsp[0].integer);
}
#line 1643 "hex_grammar.c" /* yacc.c:1661 */
break;
case 20:
#line 383 "hex_grammar.y" /* yacc.c:1661 */
{
uint8_t mask = (uint8_t) ((yyvsp[0].integer) >> 8);
if (mask == 0x00)
{
(yyval.re_node) = yr_re_node_create(RE_NODE_ANY, NULL, NULL);
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
}
else
{
(yyval.re_node) = yr_re_node_create(RE_NODE_MASKED_LITERAL, NULL, NULL);
ERROR_IF((yyval.re_node) == NULL, ERROR_INSUFFICIENT_MEMORY);
(yyval.re_node)->value = (yyvsp[0].integer) & 0xFF;
(yyval.re_node)->mask = mask;
}
}
#line 1667 "hex_grammar.c" /* yacc.c:1661 */
break;
#line 1671 "hex_grammar.c" /* yacc.c:1661 */
default: break;
}
/* User semantic actions sometimes alter yychar, and that requires
that yytoken be updated with the new translation. We take the
approach of translating immediately before every use of yytoken.
One alternative is translating here after every semantic action,
but that translation would be missed if the semantic action invokes
YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an
incorrect destructor might then be invoked immediately. In the
case of YYERROR or YYBACKUP, subsequent parser actions might lead
to an incorrect destructor call or verbose syntax error message
before the lookahead is translated. */
YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
*++yyvsp = yyval;
/* Now 'shift' the result of the reduction. Determine what state
that goes to, based on the state we popped back to and the rule
number reduced by. */
yyn = yyr1[yyn];
yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
yystate = yytable[yystate];
else
yystate = yydefgoto[yyn - YYNTOKENS];
goto yynewstate;
/*--------------------------------------.
| yyerrlab -- here on detecting error. |
`--------------------------------------*/
yyerrlab:
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);
/* If not already recovering from an error, report this error. */
if (!yyerrstatus)
{
++yynerrs;
#if ! YYERROR_VERBOSE
yyerror (yyscanner, lex_env, YY_("syntax error"));
#else
# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \
yyssp, yytoken)
{
char const *yymsgp = YY_("syntax error");
int yysyntax_error_status;
yysyntax_error_status = YYSYNTAX_ERROR;
if (yysyntax_error_status == 0)
yymsgp = yymsg;
else if (yysyntax_error_status == 1)
{
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);
if (!yymsg)
{
yymsg = yymsgbuf;
yymsg_alloc = sizeof yymsgbuf;
yysyntax_error_status = 2;
}
else
{
yysyntax_error_status = YYSYNTAX_ERROR;
yymsgp = yymsg;
}
}
yyerror (yyscanner, lex_env, yymsgp);
if (yysyntax_error_status == 2)
goto yyexhaustedlab;
}
# undef YYSYNTAX_ERROR
#endif
}
if (yyerrstatus == 3)
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
if (yychar <= YYEOF)
{
/* Return failure if at end of input. */
if (yychar == YYEOF)
YYABORT;
}
else
{
yydestruct ("Error: discarding",
yytoken, &yylval, yyscanner, lex_env);
yychar = YYEMPTY;
}
}
/* Else will try to reuse lookahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers like GCC when the user code never invokes
YYERROR and the label yyerrorlab therefore never appears in user
code. */
if (/*CONSTCOND*/ 0)
goto yyerrorlab;
/* Do not reclaim the symbols of the rule whose action triggered
this YYERROR. */
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
yystate = *yyssp;
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus = 3; /* Each real token shifted decrements this. */
for (;;)
{
yyn = yypact[yystate];
if (!yypact_value_is_default (yyn))
{
yyn += YYTERROR;
if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
{
yyn = yytable[yyn];
if (0 < yyn)
break;
}
}
/* Pop the current state because it cannot handle the error token. */
if (yyssp == yyss)
YYABORT;
yydestruct ("Error: popping",
yystos[yystate], yyvsp, yyscanner, lex_env);
YYPOPSTACK (1);
yystate = *yyssp;
YY_STACK_PRINT (yyss, yyssp);
}
YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN
*++yyvsp = yylval;
YY_IGNORE_MAYBE_UNINITIALIZED_END
/* Shift the error token. */
YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
yystate = yyn;
goto yynewstate;
/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here. |
`-------------------------------------*/
yyacceptlab:
yyresult = 0;
goto yyreturn;
/*-----------------------------------.
| yyabortlab -- YYABORT comes here. |
`-----------------------------------*/
yyabortlab:
yyresult = 1;
goto yyreturn;
#if !defined yyoverflow || YYERROR_VERBOSE
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here. |
`-------------------------------------------------*/
yyexhaustedlab:
yyerror (yyscanner, lex_env, YY_("memory exhausted"));
yyresult = 2;
/* Fall through. */
#endif
yyreturn:
if (yychar != YYEMPTY)
{
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = YYTRANSLATE (yychar);
yydestruct ("Cleanup: discarding lookahead",
yytoken, &yylval, yyscanner, lex_env);
}
/* Do not reclaim the symbols of the rule whose action triggered
this YYABORT or YYACCEPT. */
YYPOPSTACK (yylen);
YY_STACK_PRINT (yyss, yyssp);
while (yyssp != yyss)
{
yydestruct ("Cleanup: popping",
yystos[*yyssp], yyvsp, yyscanner, lex_env);
YYPOPSTACK (1);
}
#ifndef yyoverflow
if (yyss != yyssa)
YYSTACK_FREE (yyss);
#endif
#if YYERROR_VERBOSE
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
#endif
return yyresult;
}
#line 404 "hex_grammar.y" /* yacc.c:1906 */
| ./CrossVul/dataset_final_sorted/CWE-674/c/good_3392_0 |
crossvul-cpp_data_bad_3382_2 | /*
Copyright (c) 2013. The YARA Authors. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
This module implements a regular expressions engine based on Thompson's
algorithm as described by Russ Cox in http://swtch.com/~rsc/regexp/regexp2.html.
What the article names a "thread" has been named a "fiber" in this code, in
order to avoid confusion with operating system threads.
*/
#include <assert.h>
#include <string.h>
#include <limits.h>
#include <yara/limits.h>
#include <yara/globals.h>
#include <yara/utils.h>
#include <yara/mem.h>
#include <yara/re.h>
#include <yara/error.h>
#include <yara/threading.h>
#include <yara/re_lexer.h>
#include <yara/hex_lexer.h>
// Maximum allowed split ID, also limiting the number of split instructions
// allowed in a regular expression. This number can't be increased
// over 255 without changing RE_SPLIT_ID_TYPE.
#define RE_MAX_SPLIT_ID 128
// Maximum stack size for regexp evaluation
#define RE_MAX_STACK 1024
// Maximum code size for a compiled regexp
#define RE_MAX_CODE_SIZE 32768
// Maximum input size scanned by yr_re_exec
#define RE_SCAN_LIMIT 4096
// Maximum number of fibers
#define RE_MAX_FIBERS 1024
#define EMIT_BACKWARDS 0x01
#define EMIT_DONT_SET_FORWARDS_CODE 0x02
#define EMIT_DONT_SET_BACKWARDS_CODE 0x04
typedef struct _RE_REPEAT_ARGS
{
uint16_t min;
uint16_t max;
int32_t offset;
} RE_REPEAT_ARGS;
typedef struct _RE_REPEAT_ANY_ARGS
{
uint16_t min;
uint16_t max;
} RE_REPEAT_ANY_ARGS;
typedef struct _RE_EMIT_CONTEXT {
YR_ARENA* arena;
RE_SPLIT_ID_TYPE next_split_id;
} RE_EMIT_CONTEXT;
typedef struct _RE_FIBER
{
uint8_t* ip; // instruction pointer
int32_t sp; // stack pointer
int32_t rc; // repeat counter
uint16_t stack[RE_MAX_STACK];
struct _RE_FIBER* prev;
struct _RE_FIBER* next;
} RE_FIBER;
typedef struct _RE_FIBER_LIST
{
RE_FIBER* head;
RE_FIBER* tail;
} RE_FIBER_LIST;
typedef struct _RE_FIBER_POOL
{
int fiber_count;
RE_FIBER_LIST fibers;
} RE_FIBER_POOL;
typedef struct _RE_THREAD_STORAGE
{
RE_FIBER_POOL fiber_pool;
} RE_THREAD_STORAGE;
YR_THREAD_STORAGE_KEY thread_storage_key = 0;
#define CHAR_IN_CLASS(chr, cls) \
((cls)[(chr) / 8] & 1 << ((chr) % 8))
int _yr_re_is_word_char(
uint8_t* input,
uint8_t character_size)
{
int result = ((isalnum(*input) || (*input) == '_'));
if (character_size == 2)
result = result && (*(input + 1) == 0);
return result;
}
//
// yr_re_initialize
//
// Should be called by main thread before any other
// function from this module.
//
int yr_re_initialize(void)
{
return yr_thread_storage_create(&thread_storage_key);
}
//
// yr_re_finalize
//
// Should be called by main thread after every other thread
// stopped using functions from this module.
//
int yr_re_finalize(void)
{
yr_thread_storage_destroy(&thread_storage_key);
thread_storage_key = 0;
return ERROR_SUCCESS;
}
//
// yr_re_finalize_thread
//
// Should be called by every thread using this module
// before exiting.
//
int yr_re_finalize_thread(void)
{
RE_FIBER* fiber;
RE_FIBER* next_fiber;
RE_THREAD_STORAGE* storage;
if (thread_storage_key != 0)
storage = (RE_THREAD_STORAGE*) yr_thread_storage_get_value(
&thread_storage_key);
else
return ERROR_SUCCESS;
if (storage != NULL)
{
fiber = storage->fiber_pool.fibers.head;
while (fiber != NULL)
{
next_fiber = fiber->next;
yr_free(fiber);
fiber = next_fiber;
}
yr_free(storage);
}
return yr_thread_storage_set_value(&thread_storage_key, NULL);
}
RE_NODE* yr_re_node_create(
int type,
RE_NODE* left,
RE_NODE* right)
{
RE_NODE* result = (RE_NODE*) yr_malloc(sizeof(RE_NODE));
if (result != NULL)
{
result->type = type;
result->left = left;
result->right = right;
result->greedy = TRUE;
result->forward_code = NULL;
result->backward_code = NULL;
}
return result;
}
void yr_re_node_destroy(
RE_NODE* node)
{
if (node->left != NULL)
yr_re_node_destroy(node->left);
if (node->right != NULL)
yr_re_node_destroy(node->right);
if (node->type == RE_NODE_CLASS)
yr_free(node->class_vector);
yr_free(node);
}
int yr_re_ast_create(
RE_AST** re_ast)
{
*re_ast = (RE_AST*) yr_malloc(sizeof(RE_AST));
if (*re_ast == NULL)
return ERROR_INSUFFICIENT_MEMORY;
(*re_ast)->flags = 0;
(*re_ast)->root_node = NULL;
return ERROR_SUCCESS;
}
void yr_re_ast_destroy(
RE_AST* re_ast)
{
if (re_ast->root_node != NULL)
yr_re_node_destroy(re_ast->root_node);
yr_free(re_ast);
}
//
// yr_re_parse
//
// Parses a regexp but don't emit its code. A further call to
// yr_re_emit_code is required to get the code.
//
int yr_re_parse(
const char* re_string,
RE_AST** re_ast,
RE_ERROR* error)
{
return yr_parse_re_string(re_string, re_ast, error);
}
//
// yr_re_parse_hex
//
// Parses a hex string but don't emit its code. A further call to
// yr_re_emit_code is required to get the code.
//
int yr_re_parse_hex(
const char* hex_string,
RE_AST** re_ast,
RE_ERROR* error)
{
return yr_parse_hex_string(hex_string, re_ast, error);
}
//
// yr_re_compile
//
// Parses the regexp and emit its code to the provided code_arena.
//
int yr_re_compile(
const char* re_string,
int flags,
YR_ARENA* code_arena,
RE** re,
RE_ERROR* error)
{
RE_AST* re_ast;
RE _re;
FAIL_ON_ERROR(yr_arena_reserve_memory(
code_arena, sizeof(int64_t) + RE_MAX_CODE_SIZE));
FAIL_ON_ERROR(yr_re_parse(re_string, &re_ast, error));
_re.flags = flags;
FAIL_ON_ERROR_WITH_CLEANUP(
yr_arena_write_data(
code_arena,
&_re,
sizeof(_re),
(void**) re),
yr_re_ast_destroy(re_ast));
FAIL_ON_ERROR_WITH_CLEANUP(
yr_re_ast_emit_code(re_ast, code_arena, FALSE),
yr_re_ast_destroy(re_ast));
yr_re_ast_destroy(re_ast);
return ERROR_SUCCESS;
}
//
// yr_re_match
//
// Verifies if the target string matches the pattern
//
// Args:
// RE* re - A pointer to a compiled regexp
// char* target - Target string
//
// Returns:
// See return codes for yr_re_exec
int yr_re_match(
RE* re,
const char* target)
{
int result;
yr_re_exec(
re->code,
(uint8_t*) target,
strlen(target),
0,
re->flags | RE_FLAGS_SCAN,
NULL,
NULL,
&result);
return result;
}
//
// yr_re_ast_extract_literal
//
// Verifies if the provided regular expression is just a literal string
// like "abc", "12345", without any wildcard, operator, etc. In that case
// returns the string as a SIZED_STRING, or returns NULL if otherwise.
//
// The caller is responsible for deallocating the returned SIZED_STRING by
// calling yr_free.
//
SIZED_STRING* yr_re_ast_extract_literal(
RE_AST* re_ast)
{
SIZED_STRING* string;
RE_NODE* node = re_ast->root_node;
int i, length = 0;
char tmp;
while (node != NULL)
{
length++;
if (node->type == RE_NODE_LITERAL)
break;
if (node->type != RE_NODE_CONCAT)
return NULL;
if (node->right == NULL ||
node->right->type != RE_NODE_LITERAL)
return NULL;
node = node->left;
}
string = (SIZED_STRING*) yr_malloc(sizeof(SIZED_STRING) + length);
if (string == NULL)
return NULL;
string->length = 0;
node = re_ast->root_node;
while (node->type == RE_NODE_CONCAT)
{
string->c_string[string->length++] = node->right->value;
node = node->left;
}
string->c_string[string->length++] = node->value;
// The string ends up reversed. Reverse it back to its original value.
for (i = 0; i < length / 2; i++)
{
tmp = string->c_string[i];
string->c_string[i] = string->c_string[length - i - 1];
string->c_string[length - i - 1] = tmp;
}
return string;
}
int _yr_re_node_contains_dot_star(
RE_NODE* re_node)
{
if (re_node->type == RE_NODE_STAR && re_node->left->type == RE_NODE_ANY)
return TRUE;
if (re_node->left != NULL && _yr_re_node_contains_dot_star(re_node->left))
return TRUE;
if (re_node->right != NULL && _yr_re_node_contains_dot_star(re_node->right))
return TRUE;
return FALSE;
}
int yr_re_ast_contains_dot_star(
RE_AST* re_ast)
{
return _yr_re_node_contains_dot_star(re_ast->root_node);
}
//
// yr_re_ast_split_at_chaining_point
//
// In some cases splitting a regular expression in two is more efficient that
// having a single regular expression. This happens when the regular expression
// contains a large repetition of any character, for example: /foo.{0,1000}bar/
// In this case the regexp is split in /foo/ and /bar/ where /bar/ is "chained"
// to /foo/. This means that /foo/ and /bar/ are handled as individual regexps
// and when both matches YARA verifies if the distance between the matches
// complies with the {0,1000} restriction.
// This function traverses the regexp's tree looking for nodes where the regxp
// should be split. It expects a left-unbalanced tree where the right child of
// a RE_NODE_CONCAT can't be another RE_NODE_CONCAT. A RE_NODE_CONCAT must be
// always the left child of its parent if the parent is also a RE_NODE_CONCAT.
//
int yr_re_ast_split_at_chaining_point(
RE_AST* re_ast,
RE_AST** result_re_ast,
RE_AST** remainder_re_ast,
int32_t* min_gap,
int32_t* max_gap)
{
RE_NODE* node = re_ast->root_node;
RE_NODE* child = re_ast->root_node->left;
RE_NODE* parent = NULL;
int result;
*result_re_ast = re_ast;
*remainder_re_ast = NULL;
*min_gap = 0;
*max_gap = 0;
while (child != NULL && child->type == RE_NODE_CONCAT)
{
if (child->right != NULL &&
child->right->type == RE_NODE_RANGE_ANY &&
child->right->greedy == FALSE &&
(child->right->start > STRING_CHAINING_THRESHOLD ||
child->right->end > STRING_CHAINING_THRESHOLD))
{
result = yr_re_ast_create(remainder_re_ast);
if (result != ERROR_SUCCESS)
return result;
(*remainder_re_ast)->root_node = child->left;
(*remainder_re_ast)->flags = re_ast->flags;
child->left = NULL;
if (parent != NULL)
parent->left = node->right;
else
(*result_re_ast)->root_node = node->right;
node->right = NULL;
*min_gap = child->right->start;
*max_gap = child->right->end;
yr_re_node_destroy(node);
return ERROR_SUCCESS;
}
parent = node;
node = child;
child = child->left;
}
return ERROR_SUCCESS;
}
int _yr_emit_inst(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint8_t** instruction_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
*code_size = sizeof(uint8_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_uint8(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint8_t argument,
uint8_t** instruction_addr,
uint8_t** argument_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(uint8_t),
(void**) argument_addr));
*code_size = 2 * sizeof(uint8_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_uint16(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint16_t argument,
uint8_t** instruction_addr,
uint16_t** argument_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(uint16_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(uint16_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_uint32(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
uint32_t argument,
uint8_t** instruction_addr,
uint32_t** argument_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(uint32_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(uint32_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_int16(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
int16_t argument,
uint8_t** instruction_addr,
int16_t** argument_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(int16_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(int16_t);
return ERROR_SUCCESS;
}
int _yr_emit_inst_arg_struct(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
void* structure,
size_t structure_size,
uint8_t** instruction_addr,
void** argument_addr,
size_t* code_size)
{
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
structure,
structure_size,
(void**) argument_addr));
*code_size = sizeof(uint8_t) + structure_size;
return ERROR_SUCCESS;
}
int _yr_emit_split(
RE_EMIT_CONTEXT* emit_context,
uint8_t opcode,
int16_t argument,
uint8_t** instruction_addr,
int16_t** argument_addr,
size_t* code_size)
{
assert(opcode == RE_OPCODE_SPLIT_A || opcode == RE_OPCODE_SPLIT_B);
if (emit_context->next_split_id == RE_MAX_SPLIT_ID)
return ERROR_REGULAR_EXPRESSION_TOO_COMPLEX;
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&opcode,
sizeof(uint8_t),
(void**) instruction_addr));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&emit_context->next_split_id,
sizeof(RE_SPLIT_ID_TYPE),
NULL));
emit_context->next_split_id++;
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
&argument,
sizeof(int16_t),
(void**) argument_addr));
*code_size = sizeof(uint8_t) + sizeof(RE_SPLIT_ID_TYPE) + sizeof(int16_t);
return ERROR_SUCCESS;
}
int _yr_re_emit(
RE_EMIT_CONTEXT* emit_context,
RE_NODE* re_node,
int flags,
uint8_t** code_addr,
size_t* code_size)
{
size_t branch_size;
size_t split_size;
size_t inst_size;
size_t jmp_size;
int emit_split;
int emit_repeat;
int emit_prolog;
int emit_epilog;
RE_REPEAT_ARGS repeat_args;
RE_REPEAT_ARGS* repeat_start_args_addr;
RE_REPEAT_ANY_ARGS repeat_any_args;
RE_NODE* left;
RE_NODE* right;
int16_t* split_offset_addr = NULL;
int16_t* jmp_offset_addr = NULL;
uint8_t* instruction_addr = NULL;
*code_size = 0;
switch(re_node->type)
{
case RE_NODE_LITERAL:
FAIL_ON_ERROR(_yr_emit_inst_arg_uint8(
emit_context,
RE_OPCODE_LITERAL,
re_node->value,
&instruction_addr,
NULL,
code_size));
break;
case RE_NODE_MASKED_LITERAL:
FAIL_ON_ERROR(_yr_emit_inst_arg_uint16(
emit_context,
RE_OPCODE_MASKED_LITERAL,
re_node->mask << 8 | re_node->value,
&instruction_addr,
NULL,
code_size));
break;
case RE_NODE_WORD_CHAR:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_WORD_CHAR,
&instruction_addr,
code_size));
break;
case RE_NODE_NON_WORD_CHAR:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_NON_WORD_CHAR,
&instruction_addr,
code_size));
break;
case RE_NODE_WORD_BOUNDARY:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_WORD_BOUNDARY,
&instruction_addr,
code_size));
break;
case RE_NODE_NON_WORD_BOUNDARY:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_NON_WORD_BOUNDARY,
&instruction_addr,
code_size));
break;
case RE_NODE_SPACE:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_SPACE,
&instruction_addr,
code_size));
break;
case RE_NODE_NON_SPACE:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_NON_SPACE,
&instruction_addr,
code_size));
break;
case RE_NODE_DIGIT:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_DIGIT,
&instruction_addr,
code_size));
break;
case RE_NODE_NON_DIGIT:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_NON_DIGIT,
&instruction_addr,
code_size));
break;
case RE_NODE_ANY:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_ANY,
&instruction_addr,
code_size));
break;
case RE_NODE_CLASS:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_CLASS,
&instruction_addr,
code_size));
FAIL_ON_ERROR(yr_arena_write_data(
emit_context->arena,
re_node->class_vector,
32,
NULL));
*code_size += 32;
break;
case RE_NODE_ANCHOR_START:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_MATCH_AT_START,
&instruction_addr,
code_size));
break;
case RE_NODE_ANCHOR_END:
FAIL_ON_ERROR(_yr_emit_inst(
emit_context,
RE_OPCODE_MATCH_AT_END,
&instruction_addr,
code_size));
break;
case RE_NODE_CONCAT:
if (flags & EMIT_BACKWARDS)
{
left = re_node->right;
right = re_node->left;
}
else
{
left = re_node->left;
right = re_node->right;
}
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
left,
flags,
&instruction_addr,
&branch_size));
*code_size += branch_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
right,
flags,
NULL,
&branch_size));
*code_size += branch_size;
break;
case RE_NODE_PLUS:
// Code for e+ looks like:
//
// L1: code for e
// split L1, L2
// L2:
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags,
&instruction_addr,
&branch_size));
*code_size += branch_size;
FAIL_ON_ERROR(_yr_emit_split(
emit_context,
re_node->greedy ? RE_OPCODE_SPLIT_B : RE_OPCODE_SPLIT_A,
-((int16_t) branch_size),
NULL,
&split_offset_addr,
&split_size));
*code_size += split_size;
break;
case RE_NODE_STAR:
// Code for e* looks like:
//
// L1: split L1, L2
// code for e
// jmp L1
// L2:
FAIL_ON_ERROR(_yr_emit_split(
emit_context,
re_node->greedy ? RE_OPCODE_SPLIT_A : RE_OPCODE_SPLIT_B,
0,
&instruction_addr,
&split_offset_addr,
&split_size));
*code_size += split_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags,
NULL,
&branch_size));
*code_size += branch_size;
// Emit jump with offset set to 0.
FAIL_ON_ERROR(_yr_emit_inst_arg_int16(
emit_context,
RE_OPCODE_JUMP,
-((uint16_t)(branch_size + split_size)),
NULL,
&jmp_offset_addr,
&jmp_size));
*code_size += jmp_size;
assert(split_size + branch_size + jmp_size < INT16_MAX);
// Update split offset.
*split_offset_addr = (int16_t) (split_size + branch_size + jmp_size);
break;
case RE_NODE_ALT:
// Code for e1|e2 looks like:
//
// split L1, L2
// L1: code for e1
// jmp L3
// L2: code for e2
// L3:
// Emit a split instruction with offset set to 0 temporarily. Offset
// will be updated after we know the size of the code generated for
// the left node (e1).
FAIL_ON_ERROR(_yr_emit_split(
emit_context,
RE_OPCODE_SPLIT_A,
0,
&instruction_addr,
&split_offset_addr,
&split_size));
*code_size += split_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags,
NULL,
&branch_size));
*code_size += branch_size;
// Emit jump with offset set to 0.
FAIL_ON_ERROR(_yr_emit_inst_arg_int16(
emit_context,
RE_OPCODE_JUMP,
0,
NULL,
&jmp_offset_addr,
&jmp_size));
*code_size += jmp_size;
assert(split_size + branch_size + jmp_size < INT16_MAX);
// Update split offset.
*split_offset_addr = (int16_t) (split_size + branch_size + jmp_size);
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->right,
flags,
NULL,
&branch_size));
*code_size += branch_size;
assert(branch_size + jmp_size < INT16_MAX);
// Update offset for jmp instruction.
*jmp_offset_addr = (int16_t) (branch_size + jmp_size);
break;
case RE_NODE_RANGE_ANY:
repeat_any_args.min = re_node->start;
repeat_any_args.max = re_node->end;
FAIL_ON_ERROR(_yr_emit_inst_arg_struct(
emit_context,
re_node->greedy ?
RE_OPCODE_REPEAT_ANY_GREEDY :
RE_OPCODE_REPEAT_ANY_UNGREEDY,
&repeat_any_args,
sizeof(repeat_any_args),
&instruction_addr,
NULL,
&inst_size));
*code_size += inst_size;
break;
case RE_NODE_RANGE:
// Code for e{n,m} looks like:
//
// code for e --- prolog
// repeat_start n, m, L1 --+
// L0: code for e | repeat
// repeat_end n, m, L0 --+
// L1: split L2, L3 --- split
// L2: code for e --- epilog
// L3:
//
// Not all sections (prolog, repeat, split and epilog) are generated in all
// cases, it depends on the values of n and m. The following table shows
// which sections are generated for the first few values of n and m.
//
// n,m prolog repeat split epilog
// (min,max)
// ---------------------------------------
// 0,0 - - - -
// 0,1 - - X X
// 0,2 - 0,1 X X
// 0,3 - 0,2 X X
// 0,M - 0,M-1 X X
//
// 1,1 X - - -
// 1,2 X - X X
// 1,3 X 0,1 X X
// 1,4 X 1,2 X X
// 1,M X 1,M-2 X X
//
// 2,2 X - - X
// 2,3 X 1,1 X X
// 2,4 X 1,2 X X
// 2,M X 1,M-2 X X
//
// 3,3 X 1,1 - X
// 3,4 X 2,2 X X
// 3,M X 2,M-1 X X
//
// The code can't consists simply in the repeat section, the prolog and
// epilog are required because we can't have atoms pointing to code inside
// the repeat loop. Atoms' forwards_code will point to code in the prolog
// and backwards_code will point to code in the epilog (or in prolog if
// epilog wasn't generated, like in n=1,m=1)
emit_prolog = re_node->start > 0;
emit_repeat = re_node->end > re_node->start + 1 || re_node->end > 2;
emit_split = re_node->end > re_node->start;
emit_epilog = re_node->end > re_node->start || re_node->end > 1;
if (emit_prolog)
{
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags,
&instruction_addr,
&branch_size));
*code_size += branch_size;
}
if (emit_repeat)
{
repeat_args.min = re_node->start;
repeat_args.max = re_node->end;
if (emit_prolog)
{
repeat_args.max--;
repeat_args.min--;
}
if (emit_split)
repeat_args.max--;
else
repeat_args.min--;
repeat_args.offset = 0;
FAIL_ON_ERROR(_yr_emit_inst_arg_struct(
emit_context,
re_node->greedy ?
RE_OPCODE_REPEAT_START_GREEDY :
RE_OPCODE_REPEAT_START_UNGREEDY,
&repeat_args,
sizeof(repeat_args),
emit_prolog ? NULL : &instruction_addr,
(void**) &repeat_start_args_addr,
&inst_size));
*code_size += inst_size;
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
flags | EMIT_DONT_SET_FORWARDS_CODE | EMIT_DONT_SET_BACKWARDS_CODE,
NULL,
&branch_size));
*code_size += branch_size;
repeat_start_args_addr->offset = (int32_t)(2 * inst_size + branch_size);
repeat_args.offset = -((int32_t) branch_size);
FAIL_ON_ERROR(_yr_emit_inst_arg_struct(
emit_context,
re_node->greedy ?
RE_OPCODE_REPEAT_END_GREEDY :
RE_OPCODE_REPEAT_END_UNGREEDY,
&repeat_args,
sizeof(repeat_args),
NULL,
NULL,
&inst_size));
*code_size += inst_size;
}
if (emit_split)
{
FAIL_ON_ERROR(_yr_emit_split(
emit_context,
re_node->greedy ?
RE_OPCODE_SPLIT_A :
RE_OPCODE_SPLIT_B,
0,
NULL,
&split_offset_addr,
&split_size));
*code_size += split_size;
}
if (emit_epilog)
{
FAIL_ON_ERROR(_yr_re_emit(
emit_context,
re_node->left,
emit_prolog ? flags | EMIT_DONT_SET_FORWARDS_CODE : flags,
emit_prolog || emit_repeat ? NULL : &instruction_addr,
&branch_size));
*code_size += branch_size;
}
if (emit_split)
{
assert(split_size + branch_size < INT16_MAX);
*split_offset_addr = (int16_t) (split_size + branch_size);
}
break;
}
if (flags & EMIT_BACKWARDS)
{
if (!(flags & EMIT_DONT_SET_BACKWARDS_CODE))
re_node->backward_code = instruction_addr + *code_size;
}
else
{
if (!(flags & EMIT_DONT_SET_FORWARDS_CODE))
re_node->forward_code = instruction_addr;
}
if (code_addr != NULL)
*code_addr = instruction_addr;
return ERROR_SUCCESS;
}
int yr_re_ast_emit_code(
RE_AST* re_ast,
YR_ARENA* arena,
int backwards_code)
{
RE_EMIT_CONTEXT emit_context;
size_t code_size;
size_t total_size;
// Ensure that we have enough contiguous memory space in the arena to
// contain the regular expression code. The code can't span over multiple
// non-contiguous pages.
FAIL_ON_ERROR(yr_arena_reserve_memory(arena, RE_MAX_CODE_SIZE));
// Emit code for matching the regular expressions forwards.
total_size = 0;
emit_context.arena = arena;
emit_context.next_split_id = 0;
FAIL_ON_ERROR(_yr_re_emit(
&emit_context,
re_ast->root_node,
backwards_code ? EMIT_BACKWARDS : 0,
NULL,
&code_size));
total_size += code_size;
FAIL_ON_ERROR(_yr_emit_inst(
&emit_context,
RE_OPCODE_MATCH,
NULL,
&code_size));
total_size += code_size;
if (total_size > RE_MAX_CODE_SIZE)
return ERROR_REGULAR_EXPRESSION_TOO_LARGE;
return ERROR_SUCCESS;
}
int _yr_re_alloc_storage(
RE_THREAD_STORAGE** storage)
{
*storage = (RE_THREAD_STORAGE*) yr_thread_storage_get_value(
&thread_storage_key);
if (*storage == NULL)
{
*storage = (RE_THREAD_STORAGE*) yr_malloc(sizeof(RE_THREAD_STORAGE));
if (*storage == NULL)
return ERROR_INSUFFICIENT_MEMORY;
(*storage)->fiber_pool.fiber_count = 0;
(*storage)->fiber_pool.fibers.head = NULL;
(*storage)->fiber_pool.fibers.tail = NULL;
FAIL_ON_ERROR(
yr_thread_storage_set_value(&thread_storage_key, *storage));
}
return ERROR_SUCCESS;
}
int _yr_re_fiber_create(
RE_FIBER_POOL* fiber_pool,
RE_FIBER** new_fiber)
{
RE_FIBER* fiber;
if (fiber_pool->fibers.head != NULL)
{
fiber = fiber_pool->fibers.head;
fiber_pool->fibers.head = fiber->next;
if (fiber_pool->fibers.tail == fiber)
fiber_pool->fibers.tail = NULL;
}
else
{
if (fiber_pool->fiber_count == RE_MAX_FIBERS)
return ERROR_TOO_MANY_RE_FIBERS;
fiber = (RE_FIBER*) yr_malloc(sizeof(RE_FIBER));
if (fiber == NULL)
return ERROR_INSUFFICIENT_MEMORY;
fiber_pool->fiber_count++;
}
fiber->ip = NULL;
fiber->sp = -1;
fiber->rc = -1;
fiber->next = NULL;
fiber->prev = NULL;
*new_fiber = fiber;
return ERROR_SUCCESS;
}
//
// _yr_re_fiber_append
//
// Appends 'fiber' to 'fiber_list'
//
void _yr_re_fiber_append(
RE_FIBER_LIST* fiber_list,
RE_FIBER* fiber)
{
assert(fiber->prev == NULL);
assert(fiber->next == NULL);
fiber->prev = fiber_list->tail;
if (fiber_list->tail != NULL)
fiber_list->tail->next = fiber;
fiber_list->tail = fiber;
if (fiber_list->head == NULL)
fiber_list->head = fiber;
assert(fiber_list->tail->next == NULL);
assert(fiber_list->head->prev == NULL);
}
//
// _yr_re_fiber_exists
//
// Verifies if a fiber with the same properties (ip, rc, sp, and stack values)
// than 'target_fiber' exists in 'fiber_list'. The list is iterated from
// the start until 'last_fiber' (inclusive). Fibers past 'last_fiber' are not
// taken into account.
//
int _yr_re_fiber_exists(
RE_FIBER_LIST* fiber_list,
RE_FIBER* target_fiber,
RE_FIBER* last_fiber)
{
RE_FIBER* fiber = fiber_list->head;
int equal_stacks;
int i;
if (last_fiber == NULL)
return FALSE;
while (fiber != last_fiber->next)
{
if (fiber->ip == target_fiber->ip &&
fiber->sp == target_fiber->sp &&
fiber->rc == target_fiber->rc)
{
equal_stacks = TRUE;
for (i = 0; i <= fiber->sp; i++)
{
if (fiber->stack[i] != target_fiber->stack[i])
{
equal_stacks = FALSE;
break;
}
}
if (equal_stacks)
return TRUE;
}
fiber = fiber->next;
}
return FALSE;
}
//
// _yr_re_fiber_split
//
// Clones a fiber in fiber_list and inserts the cloned fiber just after.
// the original one. If fiber_list is:
//
// f1 -> f2 -> f3 -> f4
//
// Splitting f2 will result in:
//
// f1 -> f2 -> cloned f2 -> f3 -> f4
//
int _yr_re_fiber_split(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool,
RE_FIBER* fiber,
RE_FIBER** new_fiber)
{
int32_t i;
FAIL_ON_ERROR(_yr_re_fiber_create(fiber_pool, new_fiber));
(*new_fiber)->sp = fiber->sp;
(*new_fiber)->ip = fiber->ip;
(*new_fiber)->rc = fiber->rc;
for (i = 0; i <= fiber->sp; i++)
(*new_fiber)->stack[i] = fiber->stack[i];
(*new_fiber)->next = fiber->next;
(*new_fiber)->prev = fiber;
if (fiber->next != NULL)
fiber->next->prev = *new_fiber;
fiber->next = *new_fiber;
if (fiber_list->tail == fiber)
fiber_list->tail = *new_fiber;
assert(fiber_list->tail->next == NULL);
assert(fiber_list->head->prev == NULL);
return ERROR_SUCCESS;
}
//
// _yr_re_fiber_kill
//
// Kills a given fiber by removing it from the fiber list and putting it
// in the fiber pool.
//
RE_FIBER* _yr_re_fiber_kill(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool,
RE_FIBER* fiber)
{
RE_FIBER* next_fiber = fiber->next;
if (fiber->prev != NULL)
fiber->prev->next = next_fiber;
if (next_fiber != NULL)
next_fiber->prev = fiber->prev;
if (fiber_pool->fibers.tail != NULL)
fiber_pool->fibers.tail->next = fiber;
if (fiber_list->tail == fiber)
fiber_list->tail = fiber->prev;
if (fiber_list->head == fiber)
fiber_list->head = next_fiber;
fiber->next = NULL;
fiber->prev = fiber_pool->fibers.tail;
fiber_pool->fibers.tail = fiber;
if (fiber_pool->fibers.head == NULL)
fiber_pool->fibers.head = fiber;
return next_fiber;
}
//
// _yr_re_fiber_kill_tail
//
// Kills all fibers from the given one up to the end of the fiber list.
//
void _yr_re_fiber_kill_tail(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool,
RE_FIBER* fiber)
{
RE_FIBER* prev_fiber = fiber->prev;
if (prev_fiber != NULL)
prev_fiber->next = NULL;
fiber->prev = fiber_pool->fibers.tail;
if (fiber_pool->fibers.tail != NULL)
fiber_pool->fibers.tail->next = fiber;
fiber_pool->fibers.tail = fiber_list->tail;
fiber_list->tail = prev_fiber;
if (fiber_list->head == fiber)
fiber_list->head = NULL;
if (fiber_pool->fibers.head == NULL)
fiber_pool->fibers.head = fiber;
}
//
// _yr_re_fiber_kill_all
//
// Kills all fibers in the fiber list.
//
void _yr_re_fiber_kill_all(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool)
{
if (fiber_list->head != NULL)
_yr_re_fiber_kill_tail(fiber_list, fiber_pool, fiber_list->head);
}
//
// _yr_re_fiber_sync
//
// Executes a fiber until reaching an "matching" instruction. A "matching"
// instruction is one that actually reads a byte from the input and performs
// some matching. If the fiber reaches a split instruction, the new fiber is
// also synced.
//
int _yr_re_fiber_sync(
RE_FIBER_LIST* fiber_list,
RE_FIBER_POOL* fiber_pool,
RE_FIBER* fiber_to_sync)
{
// A array for keeping track of which split instructions has been already
// executed. Each split instruction within a regexp has an associated ID
// between 0 and RE_MAX_SPLIT_ID. Keeping track of executed splits is
// required to avoid infinite loops in regexps like (a*)* or (a|)*
RE_SPLIT_ID_TYPE splits_executed[RE_MAX_SPLIT_ID];
RE_SPLIT_ID_TYPE splits_executed_count = 0;
RE_SPLIT_ID_TYPE split_id, splits_executed_idx;
int split_already_executed;
RE_REPEAT_ARGS* repeat_args;
RE_REPEAT_ANY_ARGS* repeat_any_args;
RE_FIBER* fiber;
RE_FIBER* last;
RE_FIBER* prev;
RE_FIBER* next;
RE_FIBER* branch_a;
RE_FIBER* branch_b;
fiber = fiber_to_sync;
prev = fiber_to_sync->prev;
last = fiber_to_sync->next;
while(fiber != last)
{
uint8_t opcode = *fiber->ip;
switch(opcode)
{
case RE_OPCODE_SPLIT_A:
case RE_OPCODE_SPLIT_B:
split_id = *(RE_SPLIT_ID_TYPE*)(fiber->ip + 1);
split_already_executed = FALSE;
for (splits_executed_idx = 0;
splits_executed_idx < splits_executed_count;
splits_executed_idx++)
{
if (split_id == splits_executed[splits_executed_idx])
{
split_already_executed = TRUE;
break;
}
}
if (split_already_executed)
{
fiber = _yr_re_fiber_kill(fiber_list, fiber_pool, fiber);
}
else
{
branch_a = fiber;
FAIL_ON_ERROR(_yr_re_fiber_split(
fiber_list, fiber_pool, branch_a, &branch_b));
// With RE_OPCODE_SPLIT_A the current fiber continues at the next
// instruction in the stream (branch A), while the newly created
// fiber starts at the address indicated by the instruction (branch B)
// RE_OPCODE_SPLIT_B has the opposite behavior.
if (opcode == RE_OPCODE_SPLIT_B)
yr_swap(branch_a, branch_b, RE_FIBER*);
// Branch A continues at the next instruction
branch_a->ip += (sizeof(RE_SPLIT_ID_TYPE) + 3);
// Branch B adds the offset encoded in the opcode to its instruction
// pointer.
branch_b->ip += *(int16_t*)(
branch_b->ip
+ 1 // opcode size
+ sizeof(RE_SPLIT_ID_TYPE));
splits_executed[splits_executed_count] = split_id;
splits_executed_count++;
}
break;
case RE_OPCODE_REPEAT_START_GREEDY:
case RE_OPCODE_REPEAT_START_UNGREEDY:
repeat_args = (RE_REPEAT_ARGS*)(fiber->ip + 1);
assert(repeat_args->max > 0);
branch_a = fiber;
if (repeat_args->min == 0)
{
FAIL_ON_ERROR(_yr_re_fiber_split(
fiber_list, fiber_pool, branch_a, &branch_b));
if (opcode == RE_OPCODE_REPEAT_START_UNGREEDY)
yr_swap(branch_a, branch_b, RE_FIBER*);
branch_b->ip += repeat_args->offset;
}
branch_a->stack[++branch_a->sp] = 0;
branch_a->ip += (1 + sizeof(RE_REPEAT_ARGS));
break;
case RE_OPCODE_REPEAT_END_GREEDY:
case RE_OPCODE_REPEAT_END_UNGREEDY:
repeat_args = (RE_REPEAT_ARGS*)(fiber->ip + 1);
fiber->stack[fiber->sp]++;
if (fiber->stack[fiber->sp] < repeat_args->min)
{
fiber->ip += repeat_args->offset;
break;
}
branch_a = fiber;
if (fiber->stack[fiber->sp] < repeat_args->max)
{
FAIL_ON_ERROR(_yr_re_fiber_split(
fiber_list, fiber_pool, branch_a, &branch_b));
if (opcode == RE_OPCODE_REPEAT_END_GREEDY)
yr_swap(branch_a, branch_b, RE_FIBER*);
branch_a->sp--;
branch_b->ip += repeat_args->offset;
}
branch_a->ip += (1 + sizeof(RE_REPEAT_ARGS));
break;
case RE_OPCODE_REPEAT_ANY_GREEDY:
case RE_OPCODE_REPEAT_ANY_UNGREEDY:
repeat_any_args = (RE_REPEAT_ANY_ARGS*)(fiber->ip + 1);
// If repetition counter (rc) is -1 it means that we are reaching this
// instruction from the previous one in the instructions stream. In
// this case let's initialize the counter to 0 and start looping.
if (fiber->rc == -1)
fiber->rc = 0;
if (fiber->rc < repeat_any_args->min)
{
// Increase repetition counter and continue with next fiber. The
// instruction pointer for this fiber is not incremented yet, this
// fiber spins in this same instruction until reaching the minimum
// number of repetitions.
fiber->rc++;
fiber = fiber->next;
}
else if (fiber->rc < repeat_any_args->max)
{
// Once the minimum number of repetitions are matched one fiber
// remains spinning in this instruction until reaching the maximum
// number of repetitions while new fibers are created. New fibers
// start executing at the next instruction.
next = fiber->next;
branch_a = fiber;
FAIL_ON_ERROR(_yr_re_fiber_split(
fiber_list, fiber_pool, branch_a, &branch_b));
if (opcode == RE_OPCODE_REPEAT_ANY_UNGREEDY)
yr_swap(branch_a, branch_b, RE_FIBER*);
branch_a->rc++;
branch_b->ip += (1 + sizeof(RE_REPEAT_ANY_ARGS));
branch_b->rc = -1;
FAIL_ON_ERROR(_yr_re_fiber_sync(
fiber_list, fiber_pool, branch_b));
fiber = next;
}
else
{
// When the maximum number of repetitions is reached the fiber keeps
// executing at the next instruction. The repetition counter is set
// to -1 indicating that we are not spinning in a repeat instruction
// anymore.
fiber->ip += (1 + sizeof(RE_REPEAT_ANY_ARGS));
fiber->rc = -1;
}
break;
case RE_OPCODE_JUMP:
fiber->ip += *(int16_t*)(fiber->ip + 1);
break;
default:
if (_yr_re_fiber_exists(fiber_list, fiber, prev))
fiber = _yr_re_fiber_kill(fiber_list, fiber_pool, fiber);
else
fiber = fiber->next;
}
}
return ERROR_SUCCESS;
}
//
// yr_re_exec
//
// Executes a regular expression. The specified regular expression will try to
// match the data starting at the address specified by "input". The "input"
// pointer can point to any address inside a memory buffer. Arguments
// "input_forwards_size" and "input_backwards_size" indicate how many bytes
// can be accesible starting at "input" and going forwards and backwards
// respectively.
//
// <--- input_backwards_size -->|<----------- input_forwards_size -------->
// |-------- memory buffer -----------------------------------------------|
// ^
// input
//
// Args:
// uint8_t* re_code - Regexp code be executed
// uint8_t* input - Pointer to input data
// size_t input_forwards_size - Number of accessible bytes starting at
// "input" and going forwards.
// size_t input_backwards_size - Number of accessible bytes starting at
// "input" and going backwards
// int flags - Flags:
// RE_FLAGS_SCAN
// RE_FLAGS_BACKWARDS
// RE_FLAGS_EXHAUSTIVE
// RE_FLAGS_WIDE
// RE_FLAGS_NO_CASE
// RE_FLAGS_DOT_ALL
// RE_MATCH_CALLBACK_FUNC callback - Callback function
// void* callback_args - Callback argument
// int* matches - Pointer to an integer receiving the
// number of matching bytes. Notice that
// 0 means a zero-length match, while no
// matches is -1.
// Returns:
// ERROR_SUCCESS or any other error code.
int yr_re_exec(
uint8_t* re_code,
uint8_t* input_data,
size_t input_forwards_size,
size_t input_backwards_size,
int flags,
RE_MATCH_CALLBACK_FUNC callback,
void* callback_args,
int* matches)
{
uint8_t* ip;
uint8_t* input;
uint8_t mask;
uint8_t value;
uint8_t character_size;
RE_FIBER_LIST fibers;
RE_THREAD_STORAGE* storage;
RE_FIBER* fiber;
RE_FIBER* next_fiber;
int bytes_matched;
int max_bytes_matched;
int match;
int input_incr;
int kill;
int action;
#define ACTION_NONE 0
#define ACTION_CONTINUE 1
#define ACTION_KILL 2
#define ACTION_KILL_TAIL 3
#define prolog { \
if ((bytes_matched >= max_bytes_matched) || \
(character_size == 2 && *(input + 1) != 0)) \
{ \
action = ACTION_KILL; \
break; \
} \
}
if (matches != NULL)
*matches = -1;
if (_yr_re_alloc_storage(&storage) != ERROR_SUCCESS)
return -2;
if (flags & RE_FLAGS_WIDE)
character_size = 2;
else
character_size = 1;
input = input_data;
input_incr = character_size;
if (flags & RE_FLAGS_BACKWARDS)
{
max_bytes_matched = (int) yr_min(input_backwards_size, RE_SCAN_LIMIT);
input -= character_size;
input_incr = -input_incr;
}
else
{
max_bytes_matched = (int) yr_min(input_forwards_size, RE_SCAN_LIMIT);
}
// Round down max_bytes_matched to a multiple of character_size, this way if
// character_size is 2 and max_bytes_matched is odd we are ignoring the
// extra byte which can't match anyways.
max_bytes_matched = max_bytes_matched - max_bytes_matched % character_size;
bytes_matched = 0;
FAIL_ON_ERROR(_yr_re_fiber_create(&storage->fiber_pool, &fiber));
fiber->ip = re_code;
fibers.head = fiber;
fibers.tail = fiber;
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
while (fibers.head != NULL)
{
fiber = fibers.head;
while(fiber != NULL)
{
ip = fiber->ip;
action = ACTION_NONE;
switch(*ip)
{
case RE_OPCODE_ANY:
prolog;
match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_REPEAT_ANY_GREEDY:
case RE_OPCODE_REPEAT_ANY_UNGREEDY:
prolog;
match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A);
action = match ? ACTION_NONE : ACTION_KILL;
// The instruction pointer is not incremented here. The current fiber
// spins in this instruction until reaching the required number of
// repetitions. The code controlling the number of repetitions is in
// _yr_re_fiber_sync.
break;
case RE_OPCODE_LITERAL:
prolog;
if (flags & RE_FLAGS_NO_CASE)
match = yr_lowercase[*input] == yr_lowercase[*(ip + 1)];
else
match = (*input == *(ip + 1));
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 2;
break;
case RE_OPCODE_MASKED_LITERAL:
prolog;
value = *(int16_t*)(ip + 1) & 0xFF;
mask = *(int16_t*)(ip + 1) >> 8;
// We don't need to take into account the case-insensitive
// case because this opcode is only used with hex strings,
// which can't be case-insensitive.
match = ((*input & mask) == value);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 3;
break;
case RE_OPCODE_CLASS:
prolog;
match = CHAR_IN_CLASS(*input, ip + 1);
if (!match && (flags & RE_FLAGS_NO_CASE))
match = CHAR_IN_CLASS(yr_altercase[*input], ip + 1);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 33;
break;
case RE_OPCODE_WORD_CHAR:
prolog;
match = _yr_re_is_word_char(input, character_size);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_NON_WORD_CHAR:
prolog;
match = !_yr_re_is_word_char(input, character_size);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_SPACE:
case RE_OPCODE_NON_SPACE:
prolog;
switch(*input)
{
case ' ':
case '\t':
case '\r':
case '\n':
case '\v':
case '\f':
match = TRUE;
break;
default:
match = FALSE;
}
if (*ip == RE_OPCODE_NON_SPACE)
match = !match;
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_DIGIT:
prolog;
match = isdigit(*input);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_NON_DIGIT:
prolog;
match = !isdigit(*input);
action = match ? ACTION_NONE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_WORD_BOUNDARY:
case RE_OPCODE_NON_WORD_BOUNDARY:
if (bytes_matched == 0 && input_backwards_size < character_size)
{
match = TRUE;
}
else if (bytes_matched >= max_bytes_matched)
{
match = TRUE;
}
else
{
assert(input < input_data + input_forwards_size);
assert(input >= input_data - input_backwards_size);
assert(input - input_incr < input_data + input_forwards_size);
assert(input - input_incr >= input_data - input_backwards_size);
match = _yr_re_is_word_char(input, character_size) != \
_yr_re_is_word_char(input - input_incr, character_size);
}
if (*ip == RE_OPCODE_NON_WORD_BOUNDARY)
match = !match;
action = match ? ACTION_CONTINUE : ACTION_KILL;
fiber->ip += 1;
break;
case RE_OPCODE_MATCH_AT_START:
if (flags & RE_FLAGS_BACKWARDS)
kill = input_backwards_size > (size_t) bytes_matched;
else
kill = input_backwards_size > 0 || (bytes_matched != 0);
action = kill ? ACTION_KILL : ACTION_CONTINUE;
fiber->ip += 1;
break;
case RE_OPCODE_MATCH_AT_END:
kill = flags & RE_FLAGS_BACKWARDS ||
input_forwards_size > (size_t) bytes_matched;
action = kill ? ACTION_KILL : ACTION_CONTINUE;
fiber->ip += 1;
break;
case RE_OPCODE_MATCH:
if (matches != NULL)
*matches = bytes_matched;
if (flags & RE_FLAGS_EXHAUSTIVE)
{
if (callback != NULL)
{
if (flags & RE_FLAGS_BACKWARDS)
{
FAIL_ON_ERROR_WITH_CLEANUP(
callback(
input + character_size,
bytes_matched,
flags,
callback_args),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
}
else
{
FAIL_ON_ERROR_WITH_CLEANUP(
callback(
input_data,
bytes_matched,
flags,
callback_args),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
}
}
action = ACTION_KILL;
}
else
{
action = ACTION_KILL_TAIL;
}
break;
default:
assert(FALSE);
}
switch(action)
{
case ACTION_KILL:
fiber = _yr_re_fiber_kill(&fibers, &storage->fiber_pool, fiber);
break;
case ACTION_KILL_TAIL:
_yr_re_fiber_kill_tail(&fibers, &storage->fiber_pool, fiber);
fiber = NULL;
break;
case ACTION_CONTINUE:
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
break;
default:
next_fiber = fiber->next;
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
fiber = next_fiber;
}
}
input += input_incr;
bytes_matched += character_size;
if (flags & RE_FLAGS_SCAN && bytes_matched < max_bytes_matched)
{
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_re_fiber_create(&storage->fiber_pool, &fiber),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
fiber->ip = re_code;
_yr_re_fiber_append(&fibers, fiber);
FAIL_ON_ERROR_WITH_CLEANUP(
_yr_re_fiber_sync(&fibers, &storage->fiber_pool, fiber),
_yr_re_fiber_kill_all(&fibers, &storage->fiber_pool));
}
}
return ERROR_SUCCESS;
}
int yr_re_fast_exec(
uint8_t* code,
uint8_t* input_data,
size_t input_forwards_size,
size_t input_backwards_size,
int flags,
RE_MATCH_CALLBACK_FUNC callback,
void* callback_args,
int* matches)
{
RE_REPEAT_ANY_ARGS* repeat_any_args;
uint8_t* code_stack[MAX_FAST_RE_STACK];
uint8_t* input_stack[MAX_FAST_RE_STACK];
int matches_stack[MAX_FAST_RE_STACK];
uint8_t* ip = code;
uint8_t* input = input_data;
uint8_t* next_input;
uint8_t* next_opcode;
uint8_t mask;
uint8_t value;
int i;
int stop;
int input_incr;
int sp = 0;
int bytes_matched;
int max_bytes_matched;
max_bytes_matched = flags & RE_FLAGS_BACKWARDS ?
(int) input_backwards_size :
(int) input_forwards_size;
input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1;
if (flags & RE_FLAGS_BACKWARDS)
input--;
code_stack[sp] = code;
input_stack[sp] = input;
matches_stack[sp] = 0;
sp++;
while (sp > 0)
{
sp--;
ip = code_stack[sp];
input = input_stack[sp];
bytes_matched = matches_stack[sp];
stop = FALSE;
while(!stop)
{
if (*ip == RE_OPCODE_MATCH)
{
if (flags & RE_FLAGS_EXHAUSTIVE)
{
FAIL_ON_ERROR(callback(
flags & RE_FLAGS_BACKWARDS ? input + 1 : input_data,
bytes_matched,
flags,
callback_args));
break;
}
else
{
if (matches != NULL)
*matches = bytes_matched;
return ERROR_SUCCESS;
}
}
if (bytes_matched >= max_bytes_matched)
break;
switch(*ip)
{
case RE_OPCODE_LITERAL:
if (*input == *(ip + 1))
{
bytes_matched++;
input += input_incr;
ip += 2;
}
else
{
stop = TRUE;
}
break;
case RE_OPCODE_MASKED_LITERAL:
value = *(int16_t*)(ip + 1) & 0xFF;
mask = *(int16_t*)(ip + 1) >> 8;
if ((*input & mask) == value)
{
bytes_matched++;
input += input_incr;
ip += 3;
}
else
{
stop = TRUE;
}
break;
case RE_OPCODE_ANY:
bytes_matched++;
input += input_incr;
ip += 1;
break;
case RE_OPCODE_REPEAT_ANY_UNGREEDY:
repeat_any_args = (RE_REPEAT_ANY_ARGS*)(ip + 1);
next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS);
for (i = repeat_any_args->min + 1; i <= repeat_any_args->max; i++)
{
next_input = input + i * input_incr;
if (bytes_matched + i >= max_bytes_matched)
break;
if ( *(next_opcode) != RE_OPCODE_LITERAL ||
(*(next_opcode) == RE_OPCODE_LITERAL &&
*(next_opcode + 1) == *next_input))
{
if (sp >= MAX_FAST_RE_STACK)
return -4;
code_stack[sp] = next_opcode;
input_stack[sp] = next_input;
matches_stack[sp] = bytes_matched + i;
sp++;
}
}
input += input_incr * repeat_any_args->min;
bytes_matched += repeat_any_args->min;
ip = next_opcode;
break;
default:
assert(FALSE);
}
}
}
if (matches != NULL)
*matches = -1;
return ERROR_SUCCESS;
}
void _yr_re_print_node(
RE_NODE* re_node)
{
int i;
if (re_node == NULL)
return;
switch(re_node->type)
{
case RE_NODE_ALT:
printf("Alt(");
_yr_re_print_node(re_node->left);
printf(", ");
_yr_re_print_node(re_node->right);
printf(")");
break;
case RE_NODE_CONCAT:
printf("Cat(");
_yr_re_print_node(re_node->left);
printf(", ");
_yr_re_print_node(re_node->right);
printf(")");
break;
case RE_NODE_STAR:
printf("Star(");
_yr_re_print_node(re_node->left);
printf(")");
break;
case RE_NODE_PLUS:
printf("Plus(");
_yr_re_print_node(re_node->left);
printf(")");
break;
case RE_NODE_LITERAL:
printf("Lit(%02X)", re_node->value);
break;
case RE_NODE_MASKED_LITERAL:
printf("MaskedLit(%02X,%02X)", re_node->value, re_node->mask);
break;
case RE_NODE_WORD_CHAR:
printf("WordChar");
break;
case RE_NODE_NON_WORD_CHAR:
printf("NonWordChar");
break;
case RE_NODE_SPACE:
printf("Space");
break;
case RE_NODE_NON_SPACE:
printf("NonSpace");
break;
case RE_NODE_DIGIT:
printf("Digit");
break;
case RE_NODE_NON_DIGIT:
printf("NonDigit");
break;
case RE_NODE_ANY:
printf("Any");
break;
case RE_NODE_RANGE:
printf("Range(%d-%d, ", re_node->start, re_node->end);
_yr_re_print_node(re_node->left);
printf(")");
break;
case RE_NODE_CLASS:
printf("Class(");
for (i = 0; i < 256; i++)
if (CHAR_IN_CLASS(i, re_node->class_vector))
printf("%02X,", i);
printf(")");
break;
default:
printf("???");
break;
}
}
void yr_re_print(
RE_AST* re_ast)
{
_yr_re_print_node(re_ast->root_node);
}
| ./CrossVul/dataset_final_sorted/CWE-674/c/bad_3382_2 |
crossvul-cpp_data_bad_4436_0 | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* lib/krb5/asn.1/asn1_encode.c */
/*
* Copyright 1994, 2008 by the Massachusetts Institute of Technology.
* All Rights Reserved.
*
* Export of this software from the United States of America may
* require a specific license from the United States Government.
* It is the responsibility of any person or organization contemplating
* export to obtain such a license before exporting.
*
* WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
* distribute this software and its documentation for any purpose and
* without fee is hereby granted, provided that the above copyright
* notice appear in all copies and that both that copyright notice and
* this permission notice appear in supporting documentation, and that
* the name of M.I.T. not be used in advertising or publicity pertaining
* to distribution of the software without specific, written prior
* permission. Furthermore if you modify this software you must label
* your software as modified software and not distribute it in such a
* fashion that it might be confused with the original M.I.T. software.
* M.I.T. makes no representations about the suitability of
* this software for any purpose. It is provided "as is" without express
* or implied warranty.
*/
#include "asn1_encode.h"
struct asn1buf_st {
uint8_t *ptr; /* Position, moving backwards; may be NULL */
size_t count; /* Count of bytes written so far */
};
/**** Functions for encoding primitive types ****/
/* Insert one byte into buf going backwards. */
static inline void
insert_byte(asn1buf *buf, uint8_t o)
{
if (buf->ptr != NULL) {
buf->ptr--;
*buf->ptr = o;
}
buf->count++;
}
/* Insert a block of bytes into buf going backwards (but without reversing
* bytes). */
static inline void
insert_bytes(asn1buf *buf, const void *bytes, size_t len)
{
if (buf->ptr != NULL) {
memcpy(buf->ptr - len, bytes, len);
buf->ptr -= len;
}
buf->count += len;
}
void
k5_asn1_encode_bool(asn1buf *buf, intmax_t val)
{
insert_byte(buf, val ? 0xFF : 0x00);
}
void
k5_asn1_encode_int(asn1buf *buf, intmax_t val)
{
long valcopy;
int digit;
valcopy = val;
do {
digit = valcopy & 0xFF;
insert_byte(buf, digit);
valcopy = valcopy >> 8;
} while (valcopy != 0 && valcopy != ~0);
/* Make sure the high bit is of the proper signed-ness. */
if (val > 0 && (digit & 0x80) == 0x80)
insert_byte(buf, 0);
else if (val < 0 && (digit & 0x80) != 0x80)
insert_byte(buf, 0xFF);
}
void
k5_asn1_encode_uint(asn1buf *buf, uintmax_t val)
{
uintmax_t valcopy;
int digit;
valcopy = val;
do {
digit = valcopy & 0xFF;
insert_byte(buf, digit);
valcopy = valcopy >> 8;
} while (valcopy != 0);
/* Make sure the high bit is of the proper signed-ness. */
if (digit & 0x80)
insert_byte(buf, 0);
}
krb5_error_code
k5_asn1_encode_bytestring(asn1buf *buf, uint8_t *const *val, size_t len)
{
if (len > 0 && val == NULL)
return ASN1_MISSING_FIELD;
insert_bytes(buf, *val, len);
return 0;
}
krb5_error_code
k5_asn1_encode_generaltime(asn1buf *buf, time_t val)
{
struct tm *gtime, gtimebuf;
char s[16], *sp;
time_t gmt_time = val;
int len;
/*
* Time encoding: YYYYMMDDhhmmssZ
*/
if (gmt_time == 0) {
sp = "19700101000000Z";
} else {
/*
* Sanity check this just to be paranoid, as gmtime can return NULL,
* and some bogus implementations might overrun on the sprintf.
*/
#ifdef HAVE_GMTIME_R
#ifdef GMTIME_R_RETURNS_INT
if (gmtime_r(&gmt_time, >imebuf) != 0)
return ASN1_BAD_GMTIME;
#else
if (gmtime_r(&gmt_time, >imebuf) == NULL)
return ASN1_BAD_GMTIME;
#endif
#else /* HAVE_GMTIME_R */
gtime = gmtime(&gmt_time);
if (gtime == NULL)
return ASN1_BAD_GMTIME;
memcpy(>imebuf, gtime, sizeof(gtimebuf));
#endif /* HAVE_GMTIME_R */
gtime = >imebuf;
if (gtime->tm_year > 8099 || gtime->tm_mon > 11 ||
gtime->tm_mday > 31 || gtime->tm_hour > 23 ||
gtime->tm_min > 59 || gtime->tm_sec > 59)
return ASN1_BAD_GMTIME;
len = snprintf(s, sizeof(s), "%04d%02d%02d%02d%02d%02dZ",
1900 + gtime->tm_year, gtime->tm_mon + 1,
gtime->tm_mday, gtime->tm_hour,
gtime->tm_min, gtime->tm_sec);
if (SNPRINTF_OVERFLOW(len, sizeof(s)))
/* Shouldn't be possible given above tests. */
return ASN1_BAD_GMTIME;
sp = s;
}
insert_bytes(buf, sp, 15);
return 0;
}
krb5_error_code
k5_asn1_encode_bitstring(asn1buf *buf, uint8_t *const *val, size_t len)
{
insert_bytes(buf, *val, len);
insert_byte(buf, 0);
return 0;
}
/**** Functions for decoding primitive types ****/
krb5_error_code
k5_asn1_decode_bool(const uint8_t *asn1, size_t len, intmax_t *val)
{
if (len != 1)
return ASN1_BAD_LENGTH;
*val = (*asn1 != 0);
return 0;
}
/* Decode asn1/len as the contents of a DER integer, placing the signed result
* in val. */
krb5_error_code
k5_asn1_decode_int(const uint8_t *asn1, size_t len, intmax_t *val)
{
intmax_t n;
size_t i;
if (len == 0)
return ASN1_BAD_LENGTH;
n = (asn1[0] & 0x80) ? -1 : 0;
/* Check length; allow extra octet if first octet is 0. */
if (len > sizeof(intmax_t) + (asn1[0] == 0))
return ASN1_OVERFLOW;
for (i = 0; i < len; i++)
n = (n << 8) | asn1[i];
*val = n;
return 0;
}
/* Decode asn1/len as the contents of a DER integer, placing the unsigned
* result in val. */
krb5_error_code
k5_asn1_decode_uint(const uint8_t *asn1, size_t len, uintmax_t *val)
{
uintmax_t n;
size_t i;
if (len == 0)
return ASN1_BAD_LENGTH;
/* Check for negative values and check length. */
if ((asn1[0] & 0x80) || len > sizeof(uintmax_t) + (asn1[0] == 0))
return ASN1_OVERFLOW;
for (i = 0, n = 0; i < len; i++)
n = (n << 8) | asn1[i];
*val = n;
return 0;
}
krb5_error_code
k5_asn1_decode_bytestring(const uint8_t *asn1, size_t len,
uint8_t **str_out, size_t *len_out)
{
uint8_t *str;
*str_out = NULL;
*len_out = 0;
if (len == 0)
return 0;
str = malloc(len);
if (str == NULL)
return ENOMEM;
memcpy(str, asn1, len);
*str_out = str;
*len_out = len;
return 0;
}
krb5_error_code
k5_asn1_decode_generaltime(const uint8_t *asn1, size_t len, time_t *time_out)
{
const char *s = (char *)asn1;
struct tm ts;
time_t t;
*time_out = 0;
if (len != 15)
return ASN1_BAD_LENGTH;
/* Time encoding: YYYYMMDDhhmmssZ */
if (s[14] != 'Z')
return ASN1_BAD_FORMAT;
if (memcmp(s, "19700101000000Z", 15) == 0) {
*time_out = 0;
return 0;
}
#define c2i(c) ((c) - '0')
ts.tm_year = 1000 * c2i(s[0]) + 100 * c2i(s[1]) + 10 * c2i(s[2]) +
c2i(s[3]) - 1900;
ts.tm_mon = 10 * c2i(s[4]) + c2i(s[5]) - 1;
ts.tm_mday = 10 * c2i(s[6]) + c2i(s[7]);
ts.tm_hour = 10 * c2i(s[8]) + c2i(s[9]);
ts.tm_min = 10 * c2i(s[10]) + c2i(s[11]);
ts.tm_sec = 10 * c2i(s[12]) + c2i(s[13]);
ts.tm_isdst = -1;
t = krb5int_gmt_mktime(&ts);
if (t == -1)
return ASN1_BAD_TIMEFORMAT;
*time_out = t;
return 0;
}
/*
* Note: we return the number of bytes, not bits, in the bit string. If the
* number of bits is not a multiple of 8 we effectively round up to the next
* multiple of 8.
*/
krb5_error_code
k5_asn1_decode_bitstring(const uint8_t *asn1, size_t len,
uint8_t **bits_out, size_t *len_out)
{
uint8_t unused, *bits;
*bits_out = NULL;
*len_out = 0;
if (len == 0)
return ASN1_BAD_LENGTH;
unused = *asn1++;
len--;
if (unused > 7)
return ASN1_BAD_FORMAT;
bits = malloc(len);
if (bits == NULL)
return ENOMEM;
memcpy(bits, asn1, len);
if (len > 1)
bits[len - 1] &= (0xff << unused);
*bits_out = bits;
*len_out = len;
return 0;
}
/**** Functions for encoding and decoding tags ****/
/* Encode a DER tag into buf with the tag parameters in t and the content
* length len. Place the length of the encoded tag in *retlen. */
static krb5_error_code
make_tag(asn1buf *buf, const taginfo *t, size_t len)
{
asn1_tagnum tag_copy;
size_t len_copy, oldcount;
if (t->tagnum > ASN1_TAGNUM_MAX)
return ASN1_OVERFLOW;
/* Encode the length of the content within the tag. */
if (len < 128) {
insert_byte(buf, len & 0x7F);
} else {
oldcount = buf->count;
for (len_copy = len; len_copy != 0; len_copy >>= 8)
insert_byte(buf, len_copy & 0xFF);
insert_byte(buf, 0x80 | ((buf->count - oldcount) & 0x7F));
}
/* Encode the tag and construction bit. */
if (t->tagnum < 31) {
insert_byte(buf, t->asn1class | t->construction | t->tagnum);
} else {
tag_copy = t->tagnum;
insert_byte(buf, tag_copy & 0x7F);
tag_copy >>= 7;
for (; tag_copy != 0; tag_copy >>= 7)
insert_byte(buf, 0x80 | (tag_copy & 0x7F));
insert_byte(buf, t->asn1class | t->construction | 0x1F);
}
return 0;
}
/*
* Read a BER tag and length from asn1/len. Place the tag parameters in
* tag_out. Set contents_out/clen_out to the octet range of the tag's
* contents, and remainder_out/rlen_out to the octet range after the end of the
* BER encoding.
*
* (krb5 ASN.1 encodings should be in DER, but for compatibility with some
* really ancient implementations we handle the indefinite length form in tags.
* However, we still insist on the primitive form of string types.)
*/
static krb5_error_code
get_tag(const uint8_t *asn1, size_t len, taginfo *tag_out,
const uint8_t **contents_out, size_t *clen_out,
const uint8_t **remainder_out, size_t *rlen_out)
{
krb5_error_code ret;
uint8_t o;
const uint8_t *c, *p, *tag_start = asn1;
size_t clen, llen, i;
taginfo t;
*contents_out = *remainder_out = NULL;
*clen_out = *rlen_out = 0;
if (len == 0)
return ASN1_OVERRUN;
o = *asn1++;
len--;
tag_out->asn1class = o & 0xC0;
tag_out->construction = o & 0x20;
if ((o & 0x1F) != 0x1F) {
tag_out->tagnum = o & 0x1F;
} else {
tag_out->tagnum = 0;
do {
if (len == 0)
return ASN1_OVERRUN;
o = *asn1++;
len--;
tag_out->tagnum = (tag_out->tagnum << 7) | (o & 0x7F);
} while (o & 0x80);
}
if (len == 0)
return ASN1_OVERRUN;
o = *asn1++;
len--;
if (o == 0x80) {
/* Indefinite form (should not be present in DER, but we accept it). */
if (tag_out->construction != CONSTRUCTED)
return ASN1_MISMATCH_INDEF;
p = asn1;
while (!(len >= 2 && p[0] == 0 && p[1] == 0)) {
ret = get_tag(p, len, &t, &c, &clen, &p, &len);
if (ret)
return ret;
}
tag_out->tag_end_len = 2;
*contents_out = asn1;
*clen_out = p - asn1;
*remainder_out = p + 2;
*rlen_out = len - 2;
} else if ((o & 0x80) == 0) {
/* Short form (first octet gives content length). */
if (o > len)
return ASN1_OVERRUN;
tag_out->tag_end_len = 0;
*contents_out = asn1;
*clen_out = o;
*remainder_out = asn1 + *clen_out;
*rlen_out = len - (*remainder_out - asn1);
} else {
/* Long form (first octet gives number of base-256 length octets). */
llen = o & 0x7F;
if (llen > len)
return ASN1_OVERRUN;
if (llen > sizeof(*clen_out))
return ASN1_OVERFLOW;
for (i = 0, clen = 0; i < llen; i++)
clen = (clen << 8) | asn1[i];
if (clen > len - llen)
return ASN1_OVERRUN;
tag_out->tag_end_len = 0;
*contents_out = asn1 + llen;
*clen_out = clen;
*remainder_out = *contents_out + clen;
*rlen_out = len - (*remainder_out - asn1);
}
tag_out->tag_len = *contents_out - tag_start;
return 0;
}
#ifdef POINTERS_ARE_ALL_THE_SAME
#define LOADPTR(PTR, TYPE) (*(const void *const *)(PTR))
#define STOREPTR(PTR, TYPE, VAL) (*(void **)(VAL) = (PTR))
#else
#define LOADPTR(PTR, PTRINFO) \
(assert((PTRINFO)->loadptr != NULL), (PTRINFO)->loadptr(PTR))
#define STOREPTR(PTR, PTRINFO, VAL) \
(assert((PTRINFO)->storeptr != NULL), (PTRINFO)->storeptr(PTR, VAL))
#endif
static size_t
get_nullterm_sequence_len(const void *valp, const struct atype_info *seq)
{
size_t i;
const struct atype_info *a;
const struct ptr_info *ptr;
const void *elt, *eltptr;
a = seq;
i = 0;
assert(a->type == atype_ptr);
assert(seq->size != 0);
ptr = a->tinfo;
while (1) {
eltptr = (const char *)valp + i * seq->size;
elt = LOADPTR(eltptr, ptr);
if (elt == NULL)
break;
i++;
}
return i;
}
static krb5_error_code
encode_sequence_of(asn1buf *buf, size_t seqlen, const void *val,
const struct atype_info *eltinfo);
static krb5_error_code
encode_nullterm_sequence_of(asn1buf *buf, const void *val,
const struct atype_info *type, int can_be_empty)
{
size_t len = get_nullterm_sequence_len(val, type);
if (!can_be_empty && len == 0)
return ASN1_MISSING_FIELD;
return encode_sequence_of(buf, len, val, type);
}
static intmax_t
load_int(const void *val, size_t size)
{
switch (size) {
case 1: return *(int8_t *)val;
case 2: return *(int16_t *)val;
case 4: return *(int32_t *)val;
case 8: return *(int64_t *)val;
default: abort();
}
}
static uintmax_t
load_uint(const void *val, size_t size)
{
switch (size) {
case 1: return *(uint8_t *)val;
case 2: return *(uint16_t *)val;
case 4: return *(uint32_t *)val;
case 8: return *(uint64_t *)val;
default: abort();
}
}
static krb5_error_code
load_count(const void *val, const struct counted_info *counted,
size_t *count_out)
{
const void *countptr = (const char *)val + counted->lenoff;
assert(sizeof(size_t) <= sizeof(uintmax_t));
if (counted->lensigned) {
intmax_t xlen = load_int(countptr, counted->lensize);
if (xlen < 0 || (uintmax_t)xlen > SIZE_MAX)
return EINVAL;
*count_out = xlen;
} else {
uintmax_t xlen = load_uint(countptr, counted->lensize);
if ((size_t)xlen != xlen || xlen > SIZE_MAX)
return EINVAL;
*count_out = xlen;
}
return 0;
}
static krb5_error_code
store_int(intmax_t intval, size_t size, void *val)
{
switch (size) {
case 1:
if ((int8_t)intval != intval)
return ASN1_OVERFLOW;
*(int8_t *)val = intval;
return 0;
case 2:
if ((int16_t)intval != intval)
return ASN1_OVERFLOW;
*(int16_t *)val = intval;
return 0;
case 4:
if ((int32_t)intval != intval)
return ASN1_OVERFLOW;
*(int32_t *)val = intval;
return 0;
case 8:
if ((int64_t)intval != intval)
return ASN1_OVERFLOW;
*(int64_t *)val = intval;
return 0;
default:
abort();
}
}
static krb5_error_code
store_uint(uintmax_t intval, size_t size, void *val)
{
switch (size) {
case 1:
if ((uint8_t)intval != intval)
return ASN1_OVERFLOW;
*(uint8_t *)val = intval;
return 0;
case 2:
if ((uint16_t)intval != intval)
return ASN1_OVERFLOW;
*(uint16_t *)val = intval;
return 0;
case 4:
if ((uint32_t)intval != intval)
return ASN1_OVERFLOW;
*(uint32_t *)val = intval;
return 0;
case 8:
if ((uint64_t)intval != intval)
return ASN1_OVERFLOW;
*(uint64_t *)val = intval;
return 0;
default:
abort();
}
}
/* Store a count value in an integer field of a structure. If count is
* SIZE_MAX and the target is a signed field, store -1. */
static krb5_error_code
store_count(size_t count, const struct counted_info *counted, void *val)
{
void *countptr = (char *)val + counted->lenoff;
if (counted->lensigned) {
if (count == SIZE_MAX)
return store_int(-1, counted->lensize, countptr);
else if ((intmax_t)count < 0)
return ASN1_OVERFLOW;
else
return store_int(count, counted->lensize, countptr);
} else
return store_uint(count, counted->lensize, countptr);
}
/* Split a DER encoding into tag and contents. Insert the contents into buf,
* then return the length of the contents and the tag. */
static krb5_error_code
split_der(asn1buf *buf, uint8_t *const *der, size_t len, taginfo *tag_out)
{
krb5_error_code ret;
const uint8_t *contents, *remainder;
size_t clen, rlen;
ret = get_tag(*der, len, tag_out, &contents, &clen, &remainder, &rlen);
if (ret)
return ret;
if (rlen != 0)
return ASN1_BAD_LENGTH;
insert_bytes(buf, contents, clen);
return 0;
}
/*
* Store the DER encoding given by t and asn1/len into the char * or
* uint8_t * pointed to by val. Set *count_out to the length of the
* DER encoding.
*/
static krb5_error_code
store_der(const taginfo *t, const uint8_t *asn1, size_t len, void *val,
size_t *count_out)
{
uint8_t *der;
size_t der_len;
*count_out = 0;
der_len = t->tag_len + len + t->tag_end_len;
der = malloc(der_len);
if (der == NULL)
return ENOMEM;
memcpy(der, asn1 - t->tag_len, der_len);
*(uint8_t **)val = der;
*count_out = der_len;
return 0;
}
static krb5_error_code
encode_sequence(asn1buf *buf, const void *val, const struct seq_info *seq);
static krb5_error_code
encode_cntype(asn1buf *buf, const void *val, size_t len,
const struct cntype_info *c, taginfo *tag_out);
/* Encode a value (contents only, no outer tag) according to a type, and return
* its encoded tag information. */
static krb5_error_code
encode_atype(asn1buf *buf, const void *val, const struct atype_info *a,
taginfo *tag_out)
{
krb5_error_code ret;
if (val == NULL)
return ASN1_MISSING_FIELD;
switch (a->type) {
case atype_fn: {
const struct fn_info *fn = a->tinfo;
assert(fn->enc != NULL);
return fn->enc(buf, val, tag_out);
}
case atype_sequence:
assert(a->tinfo != NULL);
ret = encode_sequence(buf, val, a->tinfo);
if (ret)
return ret;
tag_out->asn1class = UNIVERSAL;
tag_out->construction = CONSTRUCTED;
tag_out->tagnum = ASN1_SEQUENCE;
break;
case atype_ptr: {
const struct ptr_info *ptr = a->tinfo;
assert(ptr->basetype != NULL);
return encode_atype(buf, LOADPTR(val, ptr), ptr->basetype, tag_out);
}
case atype_offset: {
const struct offset_info *off = a->tinfo;
assert(off->basetype != NULL);
return encode_atype(buf, (const char *)val + off->dataoff,
off->basetype, tag_out);
}
case atype_optional: {
const struct optional_info *opt = a->tinfo;
assert(opt->is_present != NULL);
if (opt->is_present(val))
return encode_atype(buf, val, opt->basetype, tag_out);
else
return ASN1_OMITTED;
}
case atype_counted: {
const struct counted_info *counted = a->tinfo;
const void *dataptr = (const char *)val + counted->dataoff;
size_t count;
assert(counted->basetype != NULL);
ret = load_count(val, counted, &count);
if (ret)
return ret;
return encode_cntype(buf, dataptr, count, counted->basetype, tag_out);
}
case atype_nullterm_sequence_of:
case atype_nonempty_nullterm_sequence_of:
assert(a->tinfo != NULL);
ret = encode_nullterm_sequence_of(buf, val, a->tinfo,
a->type ==
atype_nullterm_sequence_of);
if (ret)
return ret;
tag_out->asn1class = UNIVERSAL;
tag_out->construction = CONSTRUCTED;
tag_out->tagnum = ASN1_SEQUENCE;
break;
case atype_tagged_thing: {
const struct tagged_info *tag = a->tinfo;
size_t oldcount = buf->count;
ret = encode_atype(buf, val, tag->basetype, tag_out);
if (ret)
return ret;
if (!tag->implicit) {
ret = make_tag(buf, tag_out, buf->count - oldcount);
if (ret)
return ret;
tag_out->construction = tag->construction;
}
tag_out->asn1class = tag->tagtype;
tag_out->tagnum = tag->tagval;
break;
}
case atype_bool:
k5_asn1_encode_bool(buf, load_int(val, a->size));
tag_out->asn1class = UNIVERSAL;
tag_out->construction = PRIMITIVE;
tag_out->tagnum = ASN1_BOOLEAN;
break;
case atype_int:
k5_asn1_encode_int(buf, load_int(val, a->size));
tag_out->asn1class = UNIVERSAL;
tag_out->construction = PRIMITIVE;
tag_out->tagnum = ASN1_INTEGER;
break;
case atype_uint:
k5_asn1_encode_uint(buf, load_uint(val, a->size));
tag_out->asn1class = UNIVERSAL;
tag_out->construction = PRIMITIVE;
tag_out->tagnum = ASN1_INTEGER;
break;
case atype_int_immediate: {
const struct immediate_info *imm = a->tinfo;
k5_asn1_encode_int(buf, imm->val);
tag_out->asn1class = UNIVERSAL;
tag_out->construction = PRIMITIVE;
tag_out->tagnum = ASN1_INTEGER;
break;
}
default:
assert(a->type > atype_min);
assert(a->type < atype_max);
abort();
}
return 0;
}
static krb5_error_code
encode_atype_and_tag(asn1buf *buf, const void *val, const struct atype_info *a)
{
taginfo t;
krb5_error_code ret;
size_t oldcount = buf->count;
ret = encode_atype(buf, val, a, &t);
if (ret)
return ret;
ret = make_tag(buf, &t, buf->count - oldcount);
if (ret)
return ret;
return 0;
}
/*
* Encode an object and count according to a cntype_info structure. val is a
* pointer to the object being encoded, which in most cases is itself a
* pointer (but is a union in the cntype_choice case).
*/
static krb5_error_code
encode_cntype(asn1buf *buf, const void *val, size_t count,
const struct cntype_info *c, taginfo *tag_out)
{
krb5_error_code ret;
switch (c->type) {
case cntype_string: {
const struct string_info *string = c->tinfo;
assert(string->enc != NULL);
ret = string->enc(buf, val, count);
if (ret)
return ret;
tag_out->asn1class = UNIVERSAL;
tag_out->construction = PRIMITIVE;
tag_out->tagnum = string->tagval;
break;
}
case cntype_der:
return split_der(buf, val, count, tag_out);
case cntype_seqof: {
const struct atype_info *a = c->tinfo;
const struct ptr_info *ptr = a->tinfo;
assert(a->type == atype_ptr);
val = LOADPTR(val, ptr);
ret = encode_sequence_of(buf, count, val, ptr->basetype);
if (ret)
return ret;
tag_out->asn1class = UNIVERSAL;
tag_out->construction = CONSTRUCTED;
tag_out->tagnum = ASN1_SEQUENCE;
break;
}
case cntype_choice: {
const struct choice_info *choice = c->tinfo;
if (count >= choice->n_options)
return ASN1_MISSING_FIELD;
return encode_atype(buf, val, choice->options[count], tag_out);
}
default:
assert(c->type > cntype_min);
assert(c->type < cntype_max);
abort();
}
return 0;
}
static krb5_error_code
encode_sequence(asn1buf *buf, const void *val, const struct seq_info *seq)
{
krb5_error_code ret;
size_t i;
for (i = seq->n_fields; i > 0; i--) {
ret = encode_atype_and_tag(buf, val, seq->fields[i - 1]);
if (ret == ASN1_OMITTED)
continue;
else if (ret != 0)
return ret;
}
return 0;
}
static krb5_error_code
encode_sequence_of(asn1buf *buf, size_t seqlen, const void *val,
const struct atype_info *eltinfo)
{
krb5_error_code ret;
size_t i;
const void *eltptr;
assert(eltinfo->size != 0);
for (i = seqlen; i > 0; i--) {
eltptr = (const char *)val + (i - 1) * eltinfo->size;
ret = encode_atype_and_tag(buf, eltptr, eltinfo);
if (ret)
return ret;
}
return 0;
}
/**** Functions for freeing C objects based on type info ****/
static void free_atype_ptr(const struct atype_info *a, void *val);
static void free_sequence(const struct seq_info *seq, void *val);
static void free_sequence_of(const struct atype_info *eltinfo, void *val,
size_t count);
static void free_cntype(const struct cntype_info *a, void *val, size_t count);
/*
* Free a C object according to a type description. Do not free pointers at
* the first level; they may be referenced by other fields of a sequence, and
* will be freed by free_atype_ptr in a second pass.
*/
static void
free_atype(const struct atype_info *a, void *val)
{
switch (a->type) {
case atype_fn: {
const struct fn_info *fn = a->tinfo;
if (fn->free_func != NULL)
fn->free_func(val);
break;
}
case atype_sequence:
free_sequence(a->tinfo, val);
break;
case atype_ptr: {
const struct ptr_info *ptrinfo = a->tinfo;
void *ptr = LOADPTR(val, ptrinfo);
if (ptr != NULL) {
free_atype(ptrinfo->basetype, ptr);
free_atype_ptr(ptrinfo->basetype, ptr);
}
break;
}
case atype_offset: {
const struct offset_info *off = a->tinfo;
assert(off->basetype != NULL);
free_atype(off->basetype, (char *)val + off->dataoff);
break;
}
case atype_optional: {
const struct optional_info *opt = a->tinfo;
free_atype(opt->basetype, val);
break;
}
case atype_counted: {
const struct counted_info *counted = a->tinfo;
void *dataptr = (char *)val + counted->dataoff;
size_t count;
if (load_count(val, counted, &count) == 0)
free_cntype(counted->basetype, dataptr, count);
break;
}
case atype_nullterm_sequence_of:
case atype_nonempty_nullterm_sequence_of: {
size_t count = get_nullterm_sequence_len(val, a->tinfo);
free_sequence_of(a->tinfo, val, count);
break;
}
case atype_tagged_thing: {
const struct tagged_info *tag = a->tinfo;
free_atype(tag->basetype, val);
break;
}
case atype_bool:
case atype_int:
case atype_uint:
case atype_int_immediate:
break;
default:
abort();
}
}
static void
free_atype_ptr(const struct atype_info *a, void *val)
{
switch (a->type) {
case atype_fn:
case atype_sequence:
case atype_counted:
case atype_nullterm_sequence_of:
case atype_nonempty_nullterm_sequence_of:
case atype_bool:
case atype_int:
case atype_uint:
case atype_int_immediate:
break;
case atype_ptr: {
const struct ptr_info *ptrinfo = a->tinfo;
void *ptr = LOADPTR(val, ptrinfo);
free(ptr);
STOREPTR(NULL, ptrinfo, val);
break;
}
case atype_offset: {
const struct offset_info *off = a->tinfo;
assert(off->basetype != NULL);
free_atype_ptr(off->basetype, (char *)val + off->dataoff);
break;
}
case atype_optional: {
const struct optional_info *opt = a->tinfo;
free_atype_ptr(opt->basetype, val);
break;
}
case atype_tagged_thing: {
const struct tagged_info *tag = a->tinfo;
free_atype_ptr(tag->basetype, val);
break;
}
default:
abort();
}
}
static void
free_cntype(const struct cntype_info *c, void *val, size_t count)
{
switch (c->type) {
case cntype_string:
case cntype_der:
free(*(char **)val);
*(char **)val = NULL;
break;
case cntype_seqof: {
const struct atype_info *a = c->tinfo;
const struct ptr_info *ptrinfo = a->tinfo;
void *seqptr = LOADPTR(val, ptrinfo);
free_sequence_of(ptrinfo->basetype, seqptr, count);
free(seqptr);
STOREPTR(NULL, ptrinfo, val);
break;
}
case cntype_choice: {
const struct choice_info *choice = c->tinfo;
if (count < choice->n_options) {
free_atype(choice->options[count], val);
free_atype_ptr(choice->options[count], val);
}
break;
}
default:
abort();
}
}
static void
free_sequence(const struct seq_info *seq, void *val)
{
size_t i;
for (i = 0; i < seq->n_fields; i++)
free_atype(seq->fields[i], val);
for (i = 0; i < seq->n_fields; i++)
free_atype_ptr(seq->fields[i], val);
}
static void
free_sequence_of(const struct atype_info *eltinfo, void *val, size_t count)
{
void *eltptr;
assert(eltinfo->size != 0);
while (count-- > 0) {
eltptr = (char *)val + count * eltinfo->size;
free_atype(eltinfo, eltptr);
free_atype_ptr(eltinfo, eltptr);
}
}
/**** Functions for decoding objects based on type info ****/
/* Return nonzero if t is an expected tag for an ASN.1 object of type a. */
static int
check_atype_tag(const struct atype_info *a, const taginfo *t)
{
switch (a->type) {
case atype_fn: {
const struct fn_info *fn = a->tinfo;
assert(fn->check_tag != NULL);
return fn->check_tag(t);
}
case atype_sequence:
case atype_nullterm_sequence_of:
case atype_nonempty_nullterm_sequence_of:
return (t->asn1class == UNIVERSAL && t->construction == CONSTRUCTED &&
t->tagnum == ASN1_SEQUENCE);
case atype_ptr: {
const struct ptr_info *ptrinfo = a->tinfo;
return check_atype_tag(ptrinfo->basetype, t);
}
case atype_offset: {
const struct offset_info *off = a->tinfo;
return check_atype_tag(off->basetype, t);
}
case atype_optional: {
const struct optional_info *opt = a->tinfo;
return check_atype_tag(opt->basetype, t);
}
case atype_counted: {
const struct counted_info *counted = a->tinfo;
switch (counted->basetype->type) {
case cntype_string: {
const struct string_info *string = counted->basetype->tinfo;
return (t->asn1class == UNIVERSAL &&
t->construction == PRIMITIVE &&
t->tagnum == string->tagval);
}
case cntype_seqof:
return (t->asn1class == UNIVERSAL &&
t->construction == CONSTRUCTED &&
t->tagnum == ASN1_SEQUENCE);
case cntype_der:
/*
* We treat any tag as matching a stored DER encoding. In some
* cases we know what the tag should be; in others, we truly want
* to accept any tag. If it ever becomes an issue, we could add
* optional tag info to the type and check it here.
*/
return 1;
case cntype_choice:
/*
* ASN.1 choices may or may not be extensible. For now, we treat
* all choices as extensible and match any tag. We should consider
* modeling whether choices are extensible before making the
* encoder visible to plugins.
*/
return 1;
default:
abort();
}
}
case atype_tagged_thing: {
const struct tagged_info *tag = a->tinfo;
/* NOTE: Doesn't check construction bit for implicit tags. */
if (!tag->implicit && t->construction != tag->construction)
return 0;
return (t->asn1class == tag->tagtype && t->tagnum == tag->tagval);
}
case atype_bool:
return (t->asn1class == UNIVERSAL && t->construction == PRIMITIVE &&
t->tagnum == ASN1_BOOLEAN);
case atype_int:
case atype_uint:
case atype_int_immediate:
return (t->asn1class == UNIVERSAL && t->construction == PRIMITIVE &&
t->tagnum == ASN1_INTEGER);
default:
abort();
}
}
static krb5_error_code
decode_cntype(const taginfo *t, const uint8_t *asn1, size_t len,
const struct cntype_info *c, void *val, size_t *count_out);
static krb5_error_code
decode_atype_to_ptr(const taginfo *t, const uint8_t *asn1, size_t len,
const struct atype_info *basetype, void **ptr_out);
static krb5_error_code
decode_sequence(const uint8_t *asn1, size_t len, const struct seq_info *seq,
void *val);
static krb5_error_code
decode_sequence_of(const uint8_t *asn1, size_t len,
const struct atype_info *elemtype, void **seq_out,
size_t *count_out);
/* Given the enclosing tag t, decode from asn1/len the contents of the ASN.1
* type specified by a, placing the result into val (caller-allocated). */
static krb5_error_code
decode_atype(const taginfo *t, const uint8_t *asn1, size_t len,
const struct atype_info *a, void *val)
{
krb5_error_code ret;
switch (a->type) {
case atype_fn: {
const struct fn_info *fn = a->tinfo;
assert(fn->dec != NULL);
return fn->dec(t, asn1, len, val);
}
case atype_sequence:
return decode_sequence(asn1, len, a->tinfo, val);
case atype_ptr: {
const struct ptr_info *ptrinfo = a->tinfo;
void *ptr = LOADPTR(val, ptrinfo);
assert(ptrinfo->basetype != NULL);
if (ptr != NULL) {
/* Container was already allocated by a previous sequence field. */
return decode_atype(t, asn1, len, ptrinfo->basetype, ptr);
} else {
ret = decode_atype_to_ptr(t, asn1, len, ptrinfo->basetype, &ptr);
if (ret)
return ret;
STOREPTR(ptr, ptrinfo, val);
break;
}
}
case atype_offset: {
const struct offset_info *off = a->tinfo;
assert(off->basetype != NULL);
return decode_atype(t, asn1, len, off->basetype,
(char *)val + off->dataoff);
}
case atype_optional: {
const struct optional_info *opt = a->tinfo;
return decode_atype(t, asn1, len, opt->basetype, val);
}
case atype_counted: {
const struct counted_info *counted = a->tinfo;
void *dataptr = (char *)val + counted->dataoff;
size_t count;
assert(counted->basetype != NULL);
ret = decode_cntype(t, asn1, len, counted->basetype, dataptr, &count);
if (ret)
return ret;
return store_count(count, counted, val);
}
case atype_tagged_thing: {
const struct tagged_info *tag = a->tinfo;
taginfo inner_tag;
const taginfo *tp = t;
const uint8_t *rem;
size_t rlen;
if (!tag->implicit) {
ret = get_tag(asn1, len, &inner_tag, &asn1, &len, &rem, &rlen);
if (ret)
return ret;
/* Note: we don't check rlen (it should be 0). */
tp = &inner_tag;
if (!check_atype_tag(tag->basetype, tp))
return ASN1_BAD_ID;
}
return decode_atype(tp, asn1, len, tag->basetype, val);
}
case atype_bool: {
intmax_t intval;
ret = k5_asn1_decode_bool(asn1, len, &intval);
if (ret)
return ret;
return store_int(intval, a->size, val);
}
case atype_int: {
intmax_t intval;
ret = k5_asn1_decode_int(asn1, len, &intval);
if (ret)
return ret;
return store_int(intval, a->size, val);
}
case atype_uint: {
uintmax_t intval;
ret = k5_asn1_decode_uint(asn1, len, &intval);
if (ret)
return ret;
return store_uint(intval, a->size, val);
}
case atype_int_immediate: {
const struct immediate_info *imm = a->tinfo;
intmax_t intval;
ret = k5_asn1_decode_int(asn1, len, &intval);
if (ret)
return ret;
if (intval != imm->val && imm->err != 0)
return imm->err;
break;
}
default:
/* Null-terminated sequence types are handled in decode_atype_to_ptr,
* since they create variable-sized objects. */
assert(a->type != atype_nullterm_sequence_of);
assert(a->type != atype_nonempty_nullterm_sequence_of);
assert(a->type > atype_min);
assert(a->type < atype_max);
abort();
}
return 0;
}
/*
* Given the enclosing tag t, decode from asn1/len the contents of the
* ASN.1 type described by c, placing the counted result into val/count_out.
* If the resulting count should be -1 (for an unknown union distinguisher),
* set *count_out to SIZE_MAX.
*/
static krb5_error_code
decode_cntype(const taginfo *t, const uint8_t *asn1, size_t len,
const struct cntype_info *c, void *val, size_t *count_out)
{
krb5_error_code ret;
switch (c->type) {
case cntype_string: {
const struct string_info *string = c->tinfo;
assert(string->dec != NULL);
return string->dec(asn1, len, val, count_out);
}
case cntype_der:
return store_der(t, asn1, len, val, count_out);
case cntype_seqof: {
const struct atype_info *a = c->tinfo;
const struct ptr_info *ptrinfo = a->tinfo;
void *seq;
assert(a->type == atype_ptr);
ret = decode_sequence_of(asn1, len, ptrinfo->basetype, &seq,
count_out);
if (ret)
return ret;
STOREPTR(seq, ptrinfo, val);
break;
}
case cntype_choice: {
const struct choice_info *choice = c->tinfo;
size_t i;
for (i = 0; i < choice->n_options; i++) {
if (check_atype_tag(choice->options[i], t)) {
ret = decode_atype(t, asn1, len, choice->options[i], val);
if (ret)
return ret;
*count_out = i;
return 0;
}
}
/* SIZE_MAX will be stored as -1 in the distinguisher. If we start
* modeling non-extensible choices we should check that here. */
*count_out = SIZE_MAX;
break;
}
default:
assert(c->type > cntype_min);
assert(c->type < cntype_max);
abort();
}
return 0;
}
/* Add a null pointer to the end of a sequence. ptr is consumed on success
* (to be replaced by *ptr_out), left alone on failure. */
static krb5_error_code
null_terminate(const struct atype_info *eltinfo, void *ptr, size_t count,
void **ptr_out)
{
const struct ptr_info *ptrinfo = eltinfo->tinfo;
void *endptr;
assert(eltinfo->type == atype_ptr);
ptr = realloc(ptr, (count + 1) * eltinfo->size);
if (ptr == NULL)
return ENOMEM;
endptr = (char *)ptr + count * eltinfo->size;
STOREPTR(NULL, ptrinfo, endptr);
*ptr_out = ptr;
return 0;
}
static krb5_error_code
decode_atype_to_ptr(const taginfo *t, const uint8_t *asn1, size_t len,
const struct atype_info *a, void **ptr_out)
{
krb5_error_code ret;
void *ptr;
size_t count;
*ptr_out = NULL;
switch (a->type) {
case atype_nullterm_sequence_of:
case atype_nonempty_nullterm_sequence_of:
ret = decode_sequence_of(asn1, len, a->tinfo, &ptr, &count);
if (ret)
return ret;
ret = null_terminate(a->tinfo, ptr, count, &ptr);
if (ret) {
free_sequence_of(a->tinfo, ptr, count);
return ret;
}
/* Historically we do not enforce non-emptiness of sequences when
* decoding, even when it is required by the ASN.1 type. */
break;
default:
ptr = calloc(a->size, 1);
if (ptr == NULL)
return ENOMEM;
ret = decode_atype(t, asn1, len, a, ptr);
if (ret) {
free(ptr);
return ret;
}
break;
}
*ptr_out = ptr;
return 0;
}
/* Initialize a C object when the corresponding ASN.1 type was omitted within a
* sequence. If the ASN.1 type is not optional, return ASN1_MISSING_FIELD. */
static krb5_error_code
omit_atype(const struct atype_info *a, void *val)
{
switch (a->type)
{
case atype_fn:
case atype_sequence:
case atype_nullterm_sequence_of:
case atype_nonempty_nullterm_sequence_of:
case atype_counted:
case atype_bool:
case atype_int:
case atype_uint:
case atype_int_immediate:
return ASN1_MISSING_FIELD;
case atype_ptr: {
const struct ptr_info *ptrinfo = a->tinfo;
return omit_atype(ptrinfo->basetype, val);
}
case atype_offset: {
const struct offset_info *off = a->tinfo;
return omit_atype(off->basetype, (char *)val + off->dataoff);
}
case atype_tagged_thing: {
const struct tagged_info *tag = a->tinfo;
return omit_atype(tag->basetype, val);
}
case atype_optional: {
const struct optional_info *opt = a->tinfo;
if (opt->init != NULL)
opt->init(val);
return 0;
}
default:
abort();
}
}
/* Decode an ASN.1 sequence into a C object. */
static krb5_error_code
decode_sequence(const uint8_t *asn1, size_t len, const struct seq_info *seq,
void *val)
{
krb5_error_code ret;
const uint8_t *contents;
size_t i, j, clen;
taginfo t;
assert(seq->n_fields > 0);
for (i = 0; i < seq->n_fields; i++) {
if (len == 0)
break;
ret = get_tag(asn1, len, &t, &contents, &clen, &asn1, &len);
if (ret)
goto error;
/*
* Find the applicable sequence field. This logic is a little
* oversimplified; we could match an element to an optional extensible
* choice or optional stored-DER type when we ought to match a
* subsequent non-optional field. But it's unwise and (hopefully) very
* rare for ASN.1 modules to require such precision.
*/
for (; i < seq->n_fields; i++) {
if (check_atype_tag(seq->fields[i], &t))
break;
ret = omit_atype(seq->fields[i], val);
if (ret)
goto error;
}
/* We currently model all sequences as extensible. We should consider
* changing this before making the encoder visible to plugins. */
if (i == seq->n_fields)
break;
ret = decode_atype(&t, contents, clen, seq->fields[i], val);
if (ret)
goto error;
}
/* Initialize any fields in the C object which were not accounted for in
* the sequence. Error out if any of them aren't optional. */
for (; i < seq->n_fields; i++) {
ret = omit_atype(seq->fields[i], val);
if (ret)
goto error;
}
return 0;
error:
/* Free what we've decoded so far. Free pointers in a second pass in
* case multiple fields refer to the same pointer. */
for (j = 0; j < i; j++)
free_atype(seq->fields[j], val);
for (j = 0; j < i; j++)
free_atype_ptr(seq->fields[j], val);
return ret;
}
static krb5_error_code
decode_sequence_of(const uint8_t *asn1, size_t len,
const struct atype_info *elemtype, void **seq_out,
size_t *count_out)
{
krb5_error_code ret;
void *seq = NULL, *elem, *newseq;
const uint8_t *contents;
size_t clen, count = 0;
taginfo t;
*seq_out = NULL;
*count_out = 0;
while (len > 0) {
ret = get_tag(asn1, len, &t, &contents, &clen, &asn1, &len);
if (ret)
goto error;
if (!check_atype_tag(elemtype, &t)) {
ret = ASN1_BAD_ID;
goto error;
}
newseq = realloc(seq, (count + 1) * elemtype->size);
if (newseq == NULL) {
ret = ENOMEM;
goto error;
}
seq = newseq;
elem = (char *)seq + count * elemtype->size;
memset(elem, 0, elemtype->size);
ret = decode_atype(&t, contents, clen, elemtype, elem);
if (ret)
goto error;
count++;
}
*seq_out = seq;
*count_out = count;
return 0;
error:
free_sequence_of(elemtype, seq, count);
free(seq);
return ret;
}
/* These three entry points are only needed for the kdc_req_body hack and may
* go away at some point. Define them here so we can use short names above. */
krb5_error_code
k5_asn1_encode_atype(asn1buf *buf, const void *val, const struct atype_info *a,
taginfo *tag_out)
{
return encode_atype(buf, val, a, tag_out);
}
krb5_error_code
k5_asn1_decode_atype(const taginfo *t, const uint8_t *asn1, size_t len,
const struct atype_info *a, void *val)
{
return decode_atype(t, asn1, len, a, val);
}
krb5_error_code
k5_asn1_full_encode(const void *rep, const struct atype_info *a,
krb5_data **code_out)
{
krb5_error_code ret;
asn1buf buf;
krb5_data *d;
uint8_t *bytes;
*code_out = NULL;
if (rep == NULL)
return ASN1_MISSING_FIELD;
/* Make a first pass over rep to count the encoding size. */
buf.ptr = NULL;
buf.count = 0;
ret = encode_atype_and_tag(&buf, rep, a);
if (ret)
return ret;
/* Allocate space for the encoding. */
bytes = malloc(buf.count + 1);
if (bytes == NULL)
return ENOMEM;
bytes[buf.count] = 0;
/* Make a second pass over rep to encode it. buf.ptr moves backwards as we
* encode, and will always exactly return to the base. */
buf.ptr = bytes + buf.count;
buf.count = 0;
ret = encode_atype_and_tag(&buf, rep, a);
if (ret) {
free(bytes);
return ret;
}
assert(buf.ptr == bytes);
/* Create the output data object. */
*code_out = malloc(sizeof(*d));
if (*code_out == NULL) {
free(bytes);
return ENOMEM;
}
**code_out = make_data(bytes, buf.count);
return 0;
}
krb5_error_code
k5_asn1_full_decode(const krb5_data *code, const struct atype_info *a,
void **retrep)
{
krb5_error_code ret;
const uint8_t *contents, *remainder;
size_t clen, rlen;
taginfo t;
*retrep = NULL;
ret = get_tag((uint8_t *)code->data, code->length, &t, &contents,
&clen, &remainder, &rlen);
if (ret)
return ret;
/* rlen should be 0, but we don't check it (and due to padding in
* non-length-preserving enctypes, it will sometimes be nonzero). */
if (!check_atype_tag(a, &t))
return ASN1_BAD_ID;
return decode_atype_to_ptr(&t, contents, clen, a, retrep);
}
| ./CrossVul/dataset_final_sorted/CWE-674/c/bad_4436_0 |
crossvul-cpp_data_bad_350_0 | /*
* card-iasecc.c: Support for IAS/ECC smart cards
*
* Copyright (C) 2010 Viktor Tarasov <vtarasov@gmail.com>
* OpenTrust <www.opentrust.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#ifdef ENABLE_OPENSSL /* empty file without openssl */
#include <string.h>
#include <stdlib.h>
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/sha.h>
#include <openssl/rsa.h>
#include <openssl/pkcs12.h>
#include <openssl/x509v3.h>
#include "internal.h"
#include "asn1.h"
#include "cardctl.h"
#include "opensc.h"
/* #include "sm.h" */
#include "pkcs15.h"
/* #include "hash-strings.h" */
#include "gp.h"
#include "iasecc.h"
#define IASECC_CARD_DEFAULT_FLAGS ( 0 \
| SC_ALGORITHM_ONBOARD_KEY_GEN \
| SC_ALGORITHM_RSA_PAD_ISO9796 \
| SC_ALGORITHM_RSA_PAD_PKCS1 \
| SC_ALGORITHM_RSA_HASH_NONE \
| SC_ALGORITHM_RSA_HASH_SHA1 \
| SC_ALGORITHM_RSA_HASH_SHA256)
/* generic iso 7816 operations table */
static const struct sc_card_operations *iso_ops = NULL;
/* our operations table with overrides */
static struct sc_card_operations iasecc_ops;
static struct sc_card_driver iasecc_drv = {
"IAS-ECC",
"iasecc",
&iasecc_ops,
NULL, 0, NULL
};
static struct sc_atr_table iasecc_known_atrs[] = {
{ "3B:7F:96:00:00:00:31:B8:64:40:70:14:10:73:94:01:80:82:90:00",
"FF:FF:FF:FF:FF:FF:FF:FE:FF:FF:00:00:FF:FF:FF:FF:FF:FF:FF:FF",
"IAS/ECC Gemalto", SC_CARD_TYPE_IASECC_GEMALTO, 0, NULL },
{ "3B:DD:18:00:81:31:FE:45:80:F9:A0:00:00:00:77:01:08:00:07:90:00:FE", NULL,
"IAS/ECC v1.0.1 Oberthur", SC_CARD_TYPE_IASECC_OBERTHUR, 0, NULL },
{ "3B:7D:13:00:00:4D:44:57:2D:49:41:53:2D:43:41:52:44:32", NULL,
"IAS/ECC v1.0.1 Sagem MDW-IAS-CARD2", SC_CARD_TYPE_IASECC_SAGEM, 0, NULL },
{ "3B:7F:18:00:00:00:31:B8:64:50:23:EC:C1:73:94:01:80:82:90:00", NULL,
"IAS/ECC v1.0.1 Sagem ypsID S3", SC_CARD_TYPE_IASECC_SAGEM, 0, NULL },
{ "3B:DF:96:00:80:31:FE:45:00:31:B8:64:04:1F:EC:C1:73:94:01:80:82:90:00:EC", NULL,
"IAS/ECC Morpho MinInt - Agent Card", SC_CARD_TYPE_IASECC_MI, 0, NULL },
{ "3B:DF:18:FF:81:91:FE:1F:C3:00:31:B8:64:0C:01:EC:C1:73:94:01:80:82:90:00:B3", NULL,
"IAS/ECC v1.0.1 Amos", SC_CARD_TYPE_IASECC_AMOS, 0, NULL },
{ "3B:DC:18:FF:81:91:FE:1F:C3:80:73:C8:21:13:66:02:04:03:55:00:02:34", NULL,
"IAS/ECC v1.0.1 Amos", SC_CARD_TYPE_IASECC_AMOS, 0, NULL },
{ "3B:DC:18:FF:81:91:FE:1F:C3:80:73:C8:21:13:66:01:0B:03:52:00:05:38", NULL,
"IAS/ECC v1.0.1 Amos", SC_CARD_TYPE_IASECC_AMOS, 0, NULL },
{ NULL, NULL, NULL, 0, 0, NULL }
};
static struct sc_aid OberthurIASECC_AID = {
{0xA0,0x00,0x00,0x00,0x77,0x01,0x08,0x00,0x07,0x00,0x00,0xFE,0x00,0x00,0x01,0x00}, 16
};
static struct sc_aid MIIASECC_AID = {
{ 0x4D, 0x49, 0x4F, 0x4D, 0x43, 0x54}, 6
};
struct iasecc_pin_status {
unsigned char sha1[SHA_DIGEST_LENGTH];
unsigned char reference;
struct iasecc_pin_status *next;
struct iasecc_pin_status *prev;
};
struct iasecc_pin_status *checked_pins = NULL;
static int iasecc_select_file(struct sc_card *card, const struct sc_path *path, struct sc_file **file_out);
static int iasecc_process_fci(struct sc_card *card, struct sc_file *file, const unsigned char *buf, size_t buflen);
static int iasecc_get_serialnr(struct sc_card *card, struct sc_serial_number *serial);
static int iasecc_sdo_get_data(struct sc_card *card, struct iasecc_sdo *sdo);
static int iasecc_pin_get_policy (struct sc_card *card, struct sc_pin_cmd_data *data);
static int iasecc_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left);
static int iasecc_get_free_reference(struct sc_card *card, struct iasecc_ctl_get_free_reference *ctl_data);
static int iasecc_sdo_put_data(struct sc_card *card, struct iasecc_sdo_update *update);
#ifdef ENABLE_SM
static int _iasecc_sm_read_binary(struct sc_card *card, unsigned int offs, unsigned char *buf, size_t count);
static int _iasecc_sm_update_binary(struct sc_card *card, unsigned int offs, const unsigned char *buff, size_t count);
#endif
static int
iasecc_chv_cache_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd)
{
struct sc_context *ctx = card->ctx;
struct iasecc_pin_status *pin_status = NULL, *current = NULL;
LOG_FUNC_CALLED(ctx);
for(current = checked_pins; current; current = current->next)
if (current->reference == pin_cmd->pin_reference)
break;
if (current) {
sc_log(ctx, "iasecc_chv_cache_verified() current PIN-%i", current->reference);
pin_status = current;
}
else {
pin_status = calloc(1, sizeof(struct iasecc_pin_status));
if (!pin_status)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot callocate PIN status info");
sc_log(ctx, "iasecc_chv_cache_verified() allocated %p", pin_status);
}
pin_status->reference = pin_cmd->pin_reference;
if (pin_cmd->pin1.data)
SHA1(pin_cmd->pin1.data, pin_cmd->pin1.len, pin_status->sha1);
else
memset(pin_status->sha1, 0, SHA_DIGEST_LENGTH);
sc_log_hex(ctx, "iasecc_chv_cache_verified() sha1(PIN)", pin_status->sha1, SHA_DIGEST_LENGTH);
if (!current) {
if (!checked_pins) {
checked_pins = pin_status;
}
else {
checked_pins->prev = pin_status;
pin_status->next = checked_pins;
checked_pins = pin_status;
}
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_chv_cache_clean(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd)
{
struct sc_context *ctx = card->ctx;
struct iasecc_pin_status *current = NULL;
LOG_FUNC_CALLED(ctx);
for(current = checked_pins; current; current = current->next)
if (current->reference == pin_cmd->pin_reference)
break;
if (!current)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
if (current->next && current->prev) {
current->prev->next = current->next;
current->next->prev = current->prev;
}
else if (!current->prev) {
checked_pins = current->next;
}
else if (!current->next && current->prev) {
current->prev->next = NULL;
}
free(current);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static struct iasecc_pin_status *
iasecc_chv_cache_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd)
{
struct sc_context *ctx = card->ctx;
struct iasecc_pin_status *current = NULL;
unsigned char data_sha1[SHA_DIGEST_LENGTH];
LOG_FUNC_CALLED(ctx);
if (pin_cmd->pin1.data)
SHA1(pin_cmd->pin1.data, pin_cmd->pin1.len, data_sha1);
else
memset(data_sha1, 0, SHA_DIGEST_LENGTH);
sc_log_hex(ctx, "data_sha1: %s", data_sha1, SHA_DIGEST_LENGTH);
for(current = checked_pins; current; current = current->next)
if (current->reference == pin_cmd->pin_reference)
break;
if (current && !memcmp(data_sha1, current->sha1, SHA_DIGEST_LENGTH)) {
sc_log(ctx, "PIN-%i status 'verified'", pin_cmd->pin_reference);
return current;
}
sc_log(ctx, "PIN-%i status 'not verified'", pin_cmd->pin_reference);
return NULL;
}
static int
iasecc_select_mf(struct sc_card *card, struct sc_file **file_out)
{
struct sc_context *ctx = card->ctx;
struct sc_file *mf_file = NULL;
struct sc_path path;
int rv;
LOG_FUNC_CALLED(ctx);
if (file_out)
*file_out = NULL;
memset(&path, 0, sizeof(struct sc_path));
if (!card->ef_atr || !card->ef_atr->aid.len) {
struct sc_apdu apdu;
unsigned char apdu_resp[SC_MAX_APDU_BUFFER_SIZE];
/* ISO 'select' command fails when not FCP data returned */
sc_format_path("3F00", &path);
path.type = SC_PATH_TYPE_FILE_ID;
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xA4, 0x00, 0x00);
apdu.lc = path.len;
apdu.data = path.value;
apdu.datalen = path.len;
apdu.resplen = sizeof(apdu_resp);
apdu.resp = apdu_resp;
if (card->type == SC_CARD_TYPE_IASECC_MI2)
apdu.p2 = 0x04;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, rv, "Cannot select MF");
}
else {
memset(&path, 0, sizeof(path));
path.type = SC_PATH_TYPE_DF_NAME;
memcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len);
path.len = card->ef_atr->aid.len;
rv = iasecc_select_file(card, &path, file_out);
LOG_TEST_RET(ctx, rv, "Unable to ROOT selection");
}
/* Ignore the FCP of the MF, because:
* - some cards do not return it;
* - there is not need of it -- create/delete of the files in MF is not envisaged.
*/
mf_file = sc_file_new();
if (mf_file == NULL)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate MF file");
mf_file->type = SC_FILE_TYPE_DF;
mf_file->path = path;
if (card->cache.valid)
sc_file_free(card->cache.current_df);
card->cache.current_df = NULL;
if (card->cache.valid)
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
sc_file_dup(&card->cache.current_df, mf_file);
card->cache.valid = 1;
if (file_out && *file_out == NULL)
*file_out = mf_file;
else
sc_file_free(mf_file);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_select_aid(struct sc_card *card, struct sc_aid *aid, unsigned char *out, size_t *out_len)
{
struct sc_apdu apdu;
unsigned char apdu_resp[SC_MAX_APDU_BUFFER_SIZE];
int rv;
/* Select application (deselect previously selected application) */
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x04, 0x00);
apdu.lc = aid->len;
apdu.data = aid->value;
apdu.datalen = aid->len;
apdu.resplen = sizeof(apdu_resp);
apdu.resp = apdu_resp;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(card->ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(card->ctx, rv, "Cannot select AID");
if (*out_len < apdu.resplen)
LOG_TEST_RET(card->ctx, SC_ERROR_BUFFER_TOO_SMALL, "Cannot select AID");
memcpy(out, apdu.resp, apdu.resplen);
return SC_SUCCESS;
}
static int
iasecc_match_card(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
int i;
i = _sc_match_atr(card, iasecc_known_atrs, &card->type);
if (i < 0) {
sc_log(ctx, "card not matched");
return 0;
}
sc_log(ctx, "'%s' card matched", iasecc_known_atrs[i].name);
return 1;
}
static int iasecc_parse_ef_atr(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
struct iasecc_private_data *pdata = (struct iasecc_private_data *) card->drv_data;
struct iasecc_version *version = &pdata->version;
struct iasecc_io_buffer_sizes *sizes = &pdata->max_sizes;
int rv;
LOG_FUNC_CALLED(ctx);
rv = sc_parse_ef_atr(card);
LOG_TEST_RET(ctx, rv, "MF selection error");
if (card->ef_atr->pre_issuing_len < 4)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid pre-issuing data");
version->ic_manufacturer = card->ef_atr->pre_issuing[0];
version->ic_type = card->ef_atr->pre_issuing[1];
version->os_version = card->ef_atr->pre_issuing[2];
version->iasecc_version = card->ef_atr->pre_issuing[3];
sc_log(ctx, "EF.ATR: IC manufacturer/type %X/%X, OS/IasEcc versions %X/%X",
version->ic_manufacturer, version->ic_type, version->os_version, version->iasecc_version);
if (card->ef_atr->issuer_data_len < 16)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid issuer data");
sizes->send = card->ef_atr->issuer_data[2] * 0x100 + card->ef_atr->issuer_data[3];
sizes->send_sc = card->ef_atr->issuer_data[6] * 0x100 + card->ef_atr->issuer_data[7];
sizes->recv = card->ef_atr->issuer_data[10] * 0x100 + card->ef_atr->issuer_data[11];
sizes->recv_sc = card->ef_atr->issuer_data[14] * 0x100 + card->ef_atr->issuer_data[15];
card->max_send_size = sizes->send;
card->max_recv_size = sizes->recv;
/* Most of the card producers interpret 'send' values as "maximum APDU data size".
* Oberthur strictly follows specification and interpret these values as "maximum APDU command size".
* Here we need 'data size'.
*/
if (card->max_send_size > 0xFF)
card->max_send_size -= 5;
sc_log(ctx,
"EF.ATR: max send/recv sizes %"SC_FORMAT_LEN_SIZE_T"X/%"SC_FORMAT_LEN_SIZE_T"X",
card->max_send_size, card->max_recv_size);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_init_gemalto(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
struct sc_path path;
unsigned int flags;
int rv = 0;
LOG_FUNC_CALLED(ctx);
flags = IASECC_CARD_DEFAULT_FLAGS;
_sc_card_add_rsa_alg(card, 1024, flags, 0x10001);
_sc_card_add_rsa_alg(card, 2048, flags, 0x10001);
card->caps = SC_CARD_CAP_RNG;
card->caps |= SC_CARD_CAP_APDU_EXT;
card->caps |= SC_CARD_CAP_USE_FCI_AC;
sc_format_path("3F00", &path);
rv = sc_select_file(card, &path, NULL);
/* Result ignored*/
rv = iasecc_parse_ef_atr(card);
sc_log(ctx, "rv %i", rv);
if (rv == SC_ERROR_FILE_NOT_FOUND) {
sc_log(ctx, "Select MF");
rv = iasecc_select_mf(card, NULL);
sc_log(ctx, "rv %i", rv);
LOG_TEST_RET(ctx, rv, "MF selection error");
rv = iasecc_parse_ef_atr(card);
sc_log(ctx, "rv %i", rv);
}
sc_log(ctx, "rv %i", rv);
LOG_TEST_RET(ctx, rv, "Cannot read/parse EF.ATR");
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_oberthur_match(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
unsigned char *hist = card->reader->atr_info.hist_bytes;
LOG_FUNC_CALLED(ctx);
if (*hist != 0x80 || ((*(hist+1)&0xF0) != 0xF0))
LOG_FUNC_RETURN(ctx, SC_ERROR_OBJECT_NOT_FOUND);
sc_log_hex(ctx, "AID in historical_bytes", hist + 2, *(hist+1) & 0x0F);
if (memcmp(hist + 2, OberthurIASECC_AID.value, *(hist+1) & 0x0F))
LOG_FUNC_RETURN(ctx, SC_ERROR_RECORD_NOT_FOUND);
if (!card->ef_atr)
card->ef_atr = calloc(1, sizeof(struct sc_ef_atr));
if (!card->ef_atr)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(card->ef_atr->aid.value, OberthurIASECC_AID.value, OberthurIASECC_AID.len);
card->ef_atr->aid.len = OberthurIASECC_AID.len;
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_init_oberthur(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
unsigned int flags;
int rv = 0;
LOG_FUNC_CALLED(ctx);
flags = IASECC_CARD_DEFAULT_FLAGS;
_sc_card_add_rsa_alg(card, 1024, flags, 0x10001);
_sc_card_add_rsa_alg(card, 2048, flags, 0x10001);
card->caps = SC_CARD_CAP_RNG;
card->caps |= SC_CARD_CAP_APDU_EXT;
card->caps |= SC_CARD_CAP_USE_FCI_AC;
iasecc_parse_ef_atr(card);
/* if we fail to select CM, */
if (gp_select_card_manager(card)) {
gp_select_isd_rid(card);
}
rv = iasecc_oberthur_match(card);
LOG_TEST_RET(ctx, rv, "unknown Oberthur's IAS/ECC card");
rv = iasecc_select_mf(card, NULL);
LOG_TEST_RET(ctx, rv, "MF selection error");
rv = iasecc_parse_ef_atr(card);
LOG_TEST_RET(ctx, rv, "EF.ATR read or parse error");
sc_log(ctx, "EF.ATR(aid:'%s')", sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len));
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_mi_match(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
unsigned char resp[0x100];
size_t resp_len;
int rv = 0;
LOG_FUNC_CALLED(ctx);
resp_len = sizeof(resp);
rv = iasecc_select_aid(card, &MIIASECC_AID, resp, &resp_len);
LOG_TEST_RET(ctx, rv, "IASECC: failed to select MI IAS/ECC applet");
if (!card->ef_atr)
card->ef_atr = calloc(1, sizeof(struct sc_ef_atr));
if (!card->ef_atr)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(card->ef_atr->aid.value, MIIASECC_AID.value, MIIASECC_AID.len);
card->ef_atr->aid.len = MIIASECC_AID.len;
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_init_amos_or_sagem(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
unsigned int flags;
int rv = 0;
LOG_FUNC_CALLED(ctx);
flags = IASECC_CARD_DEFAULT_FLAGS;
_sc_card_add_rsa_alg(card, 1024, flags, 0x10001);
_sc_card_add_rsa_alg(card, 2048, flags, 0x10001);
card->caps = SC_CARD_CAP_RNG;
card->caps |= SC_CARD_CAP_APDU_EXT;
card->caps |= SC_CARD_CAP_USE_FCI_AC;
if (card->type == SC_CARD_TYPE_IASECC_MI) {
rv = iasecc_mi_match(card);
if (rv)
card->type = SC_CARD_TYPE_IASECC_MI2;
else
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
rv = iasecc_parse_ef_atr(card);
if (rv == SC_ERROR_FILE_NOT_FOUND) {
rv = iasecc_select_mf(card, NULL);
LOG_TEST_RET(ctx, rv, "MF selection error");
rv = iasecc_parse_ef_atr(card);
}
LOG_TEST_RET(ctx, rv, "IASECC: ATR parse failed");
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_init(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
struct iasecc_private_data *private_data = NULL;
int rv = SC_ERROR_NO_CARD_SUPPORT;
LOG_FUNC_CALLED(ctx);
private_data = (struct iasecc_private_data *) calloc(1, sizeof(struct iasecc_private_data));
if (private_data == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
card->cla = 0x00;
card->drv_data = private_data;
if (card->type == SC_CARD_TYPE_IASECC_GEMALTO)
rv = iasecc_init_gemalto(card);
else if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR)
rv = iasecc_init_oberthur(card);
else if (card->type == SC_CARD_TYPE_IASECC_SAGEM)
rv = iasecc_init_amos_or_sagem(card);
else if (card->type == SC_CARD_TYPE_IASECC_AMOS)
rv = iasecc_init_amos_or_sagem(card);
else if (card->type == SC_CARD_TYPE_IASECC_MI)
rv = iasecc_init_amos_or_sagem(card);
else
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_CARD);
if (!rv) {
if (card->ef_atr && card->ef_atr->aid.len) {
struct sc_path path;
memset(&path, 0, sizeof(struct sc_path));
path.type = SC_PATH_TYPE_DF_NAME;
memcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len);
path.len = card->ef_atr->aid.len;
rv = iasecc_select_file(card, &path, NULL);
sc_log(ctx, "Select ECC ROOT with the AID from EF.ATR: rv %i", rv);
LOG_TEST_RET(ctx, rv, "Select EF.ATR AID failed");
}
rv = iasecc_get_serialnr(card, NULL);
}
#ifdef ENABLE_SM
card->sm_ctx.ops.read_binary = _iasecc_sm_read_binary;
card->sm_ctx.ops.update_binary = _iasecc_sm_update_binary;
#endif
if (!rv) {
sc_log(ctx, "EF.ATR(aid:'%s')", sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len));
rv = SC_ERROR_INVALID_CARD;
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_read_binary(struct sc_card *card, unsigned int offs,
unsigned char *buf, size_t count, unsigned long flags)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"iasecc_read_binary(card:%p) offs %i; count %"SC_FORMAT_LEN_SIZE_T"u",
card, offs, count);
if (offs > 0x7fff) {
sc_log(ctx, "invalid EF offset: 0x%X > 0x7FFF", offs);
return SC_ERROR_OFFSET_TOO_LARGE;
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, (offs >> 8) & 0x7F, offs & 0xFF);
apdu.le = count < 0x100 ? count : 0x100;
apdu.resplen = count;
apdu.resp = buf;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "iasecc_read_binary() failed");
sc_log(ctx,
"iasecc_read_binary() apdu.resplen %"SC_FORMAT_LEN_SIZE_T"u",
apdu.resplen);
if (apdu.resplen == IASECC_READ_BINARY_LENGTH_MAX && apdu.resplen < count) {
rv = iasecc_read_binary(card, offs + apdu.resplen, buf + apdu.resplen, count - apdu.resplen, flags);
if (rv != SC_ERROR_WRONG_LENGTH) {
LOG_TEST_RET(ctx, rv, "iasecc_read_binary() read tail failed");
apdu.resplen += rv;
}
}
LOG_FUNC_RETURN(ctx, apdu.resplen);
}
static int
iasecc_erase_binary(struct sc_card *card, unsigned int offs, size_t count, unsigned long flags)
{
struct sc_context *ctx = card->ctx;
unsigned char *tmp = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"iasecc_erase_binary(card:%p) count %"SC_FORMAT_LEN_SIZE_T"u",
card, count);
if (!count)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "'ERASE BINARY' failed: invalid size to erase");
tmp = malloc(count);
if (!tmp)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot allocate temporary buffer");
memset(tmp, 0xFF, count);
rv = sc_update_binary(card, offs, tmp, count, flags);
free(tmp);
LOG_TEST_RET(ctx, rv, "iasecc_erase_binary() update binary error");
LOG_FUNC_RETURN(ctx, rv);
}
#if ENABLE_SM
static int
_iasecc_sm_read_binary(struct sc_card *card, unsigned int offs,
unsigned char *buff, size_t count)
{
struct sc_context *ctx = card->ctx;
const struct sc_acl_entry *entry = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"iasecc_sm_read_binary() card:%p offs:%i count:%"SC_FORMAT_LEN_SIZE_T"u ",
card, offs, count);
if (offs > 0x7fff)
LOG_TEST_RET(ctx, SC_ERROR_OFFSET_TOO_LARGE, "Invalid arguments");
if (count == 0)
return 0;
sc_print_cache(card);
if (card->cache.valid && card->cache.current_ef) {
entry = sc_file_get_acl_entry(card->cache.current_ef, SC_AC_OP_READ);
if (!entry)
LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "iasecc_sm_read() 'READ' ACL not present");
sc_log(ctx, "READ method/reference %X/%X", entry->method, entry->key_ref);
if ((entry->method == SC_AC_SCB) && (entry->key_ref & IASECC_SCB_METHOD_SM)) {
unsigned char se_num = (entry->method == SC_AC_SCB) ? (entry->key_ref & IASECC_SCB_METHOD_MASK_REF) : 0;
rv = iasecc_sm_read_binary(card, se_num, offs, buff, count);
LOG_FUNC_RETURN(ctx, rv);
}
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
_iasecc_sm_update_binary(struct sc_card *card, unsigned int offs,
const unsigned char *buff, size_t count)
{
struct sc_context *ctx = card->ctx;
const struct sc_acl_entry *entry = NULL;
int rv;
if (count == 0)
return SC_SUCCESS;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"iasecc_sm_read_binary() card:%p offs:%i count:%"SC_FORMAT_LEN_SIZE_T"u ",
card, offs, count);
sc_print_cache(card);
if (card->cache.valid && card->cache.current_ef) {
entry = sc_file_get_acl_entry(card->cache.current_ef, SC_AC_OP_UPDATE);
if (!entry)
LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "iasecc_sm_update() 'UPDATE' ACL not present");
sc_log(ctx, "UPDATE method/reference %X/%X", entry->method, entry->key_ref);
if (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) {
unsigned char se_num = entry->method == SC_AC_SCB ? entry->key_ref & IASECC_SCB_METHOD_MASK_REF : 0;
rv = iasecc_sm_update_binary(card, se_num, offs, buff, count);
LOG_FUNC_RETURN(ctx, rv);
}
}
LOG_FUNC_RETURN(ctx, 0);
}
#endif
static int
iasecc_emulate_fcp(struct sc_context *ctx, struct sc_apdu *apdu)
{
unsigned char dummy_df_fcp[] = {
0x62,0xFF,
0x82,0x01,0x38,
0x8A,0x01,0x05,
0xA1,0x04,0x8C,0x02,0x02,0x00,
0x84,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF
};
LOG_FUNC_CALLED(ctx);
if (apdu->p1 != 0x04)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "FCP emulation supported only for the DF-NAME selection type");
if (apdu->datalen > 16)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid DF-NAME length");
if (apdu->resplen < apdu->datalen + 16)
LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "not enough space for FCP data");
memcpy(dummy_df_fcp + 16, apdu->data, apdu->datalen);
dummy_df_fcp[15] = apdu->datalen;
dummy_df_fcp[1] = apdu->datalen + 14;
memcpy(apdu->resp, dummy_df_fcp, apdu->datalen + 16);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
/* TODO: redesign using of cache
* TODO: do not keep intermediate results in 'file_out' argument */
static int
iasecc_select_file(struct sc_card *card, const struct sc_path *path,
struct sc_file **file_out)
{
struct sc_context *ctx = card->ctx;
struct sc_path lpath;
int cache_valid = card->cache.valid, df_from_cache = 0;
int rv, ii;
LOG_FUNC_CALLED(ctx);
memcpy(&lpath, path, sizeof(struct sc_path));
if (file_out)
*file_out = NULL;
sc_log(ctx,
"iasecc_select_file(card:%p) path.len %"SC_FORMAT_LEN_SIZE_T"u; path.type %i; aid_len %"SC_FORMAT_LEN_SIZE_T"u",
card, path->len, path->type, path->aid.len);
sc_log(ctx, "iasecc_select_file() path:%s", sc_print_path(path));
sc_print_cache(card);
if (lpath.len >= 2 && lpath.value[0] == 0x3F && lpath.value[1] == 0x00) {
sc_log(ctx, "EF.ATR(aid:'%s')", card->ef_atr ? sc_dump_hex(card->ef_atr->aid.value, card->ef_atr->aid.len) : "");
rv = iasecc_select_mf(card, file_out);
LOG_TEST_RET(ctx, rv, "MF selection error");
if (lpath.len >= 2 && lpath.value[0] == 0x3F && lpath.value[1] == 0x00) {
memmove(&lpath.value[0], &lpath.value[2], lpath.len - 2);
lpath.len -= 2;
}
}
if (lpath.aid.len) {
struct sc_file *file = NULL;
struct sc_path ppath;
sc_log(ctx,
"iasecc_select_file() select parent AID:%p/%"SC_FORMAT_LEN_SIZE_T"u",
lpath.aid.value, lpath.aid.len);
sc_log(ctx, "iasecc_select_file() select parent AID:%s", sc_dump_hex(lpath.aid.value, lpath.aid.len));
memset(&ppath, 0, sizeof(ppath));
memcpy(ppath.value, lpath.aid.value, lpath.aid.len);
ppath.len = lpath.aid.len;
ppath.type = SC_PATH_TYPE_DF_NAME;
if (card->cache.valid && card->cache.current_df
&& card->cache.current_df->path.len == lpath.aid.len
&& !memcmp(card->cache.current_df->path.value, lpath.aid.value, lpath.aid.len))
df_from_cache = 1;
rv = iasecc_select_file(card, &ppath, &file);
LOG_TEST_RET(ctx, rv, "select AID path failed");
if (file_out)
*file_out = file;
else
sc_file_free(file);
if (lpath.type == SC_PATH_TYPE_DF_NAME)
lpath.type = SC_PATH_TYPE_FROM_CURRENT;
}
if (lpath.type == SC_PATH_TYPE_PATH)
lpath.type = SC_PATH_TYPE_FROM_CURRENT;
if (!lpath.len)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
sc_print_cache(card);
if (card->cache.valid && card->cache.current_df && lpath.type == SC_PATH_TYPE_DF_NAME
&& card->cache.current_df->path.len == lpath.len
&& !memcmp(card->cache.current_df->path.value, lpath.value, lpath.len)) {
sc_log(ctx, "returns current DF path %s", sc_print_path(&card->cache.current_df->path));
if (file_out) {
sc_file_free(*file_out);
sc_file_dup(file_out, card->cache.current_df);
}
sc_print_cache(card);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
do {
struct sc_apdu apdu;
struct sc_file *file = NULL;
unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE];
int pathlen = lpath.len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xA4, 0x00, 0x00);
if (card->type != SC_CARD_TYPE_IASECC_GEMALTO
&& card->type != SC_CARD_TYPE_IASECC_OBERTHUR
&& card->type != SC_CARD_TYPE_IASECC_SAGEM
&& card->type != SC_CARD_TYPE_IASECC_AMOS
&& card->type != SC_CARD_TYPE_IASECC_MI
&& card->type != SC_CARD_TYPE_IASECC_MI2)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Unsupported card");
if (lpath.type == SC_PATH_TYPE_FILE_ID) {
apdu.p1 = 0x02;
if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR) {
apdu.p1 = 0x01;
apdu.p2 = 0x04;
}
if (card->type == SC_CARD_TYPE_IASECC_AMOS)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_MI)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_MI2)
apdu.p2 = 0x04;
}
else if (lpath.type == SC_PATH_TYPE_FROM_CURRENT) {
apdu.p1 = 0x09;
if (card->type == SC_CARD_TYPE_IASECC_OBERTHUR)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_AMOS)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_MI)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_MI2)
apdu.p2 = 0x04;
}
else if (lpath.type == SC_PATH_TYPE_PARENT) {
apdu.p1 = 0x03;
pathlen = 0;
apdu.cse = SC_APDU_CASE_2_SHORT;
}
else if (lpath.type == SC_PATH_TYPE_DF_NAME) {
apdu.p1 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_AMOS)
apdu.p2 = 0x04;
if (card->type == SC_CARD_TYPE_IASECC_MI2)
apdu.p2 = 0x04;
}
else {
sc_log(ctx, "Invalid PATH type: 0x%X", lpath.type);
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "iasecc_select_file() invalid PATH type");
}
for (ii=0; ii<2; ii++) {
apdu.lc = pathlen;
apdu.data = lpath.value;
apdu.datalen = pathlen;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 256;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
if (rv == SC_ERROR_INCORRECT_PARAMETERS &&
lpath.type == SC_PATH_TYPE_DF_NAME && apdu.p2 == 0x00) {
apdu.p2 = 0x0C;
continue;
}
if (ii) {
/* 'SELECT AID' do not returned FCP. Try to emulate. */
apdu.resplen = sizeof(rbuf);
rv = iasecc_emulate_fcp(ctx, &apdu);
LOG_TEST_RET(ctx, rv, "Failed to emulate DF FCP");
}
break;
}
/*
* Using of the cached DF and EF can cause problems in the multi-thread environment.
* FIXME: introduce config. option that invalidates this cache outside the locked card session,
* (or invent something else)
*/
if (rv == SC_ERROR_FILE_NOT_FOUND && cache_valid && df_from_cache) {
sc_invalidate_cache(card);
sc_log(ctx, "iasecc_select_file() file not found, retry without cached DF");
if (file_out) {
sc_file_free(*file_out);
*file_out = NULL;
}
rv = iasecc_select_file(card, path, file_out);
LOG_FUNC_RETURN(ctx, rv);
}
LOG_TEST_RET(ctx, rv, "iasecc_select_file() check SW failed");
sc_log(ctx,
"iasecc_select_file() apdu.resp %"SC_FORMAT_LEN_SIZE_T"u",
apdu.resplen);
if (apdu.resplen) {
sc_log(ctx, "apdu.resp %02X:%02X:%02X...", apdu.resp[0], apdu.resp[1], apdu.resp[2]);
switch (apdu.resp[0]) {
case 0x62:
case 0x6F:
file = sc_file_new();
if (file == NULL)
LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY);
file->path = lpath;
rv = iasecc_process_fci(card, file, apdu.resp, apdu.resplen);
if (rv)
LOG_FUNC_RETURN(ctx, rv);
break;
default:
LOG_FUNC_RETURN(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED);
}
sc_log(ctx, "FileType %i", file->type);
if (file->type == SC_FILE_TYPE_DF) {
if (card->cache.valid)
sc_file_free(card->cache.current_df);
card->cache.current_df = NULL;
if (card->cache.valid)
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
sc_file_dup(&card->cache.current_df, file);
card->cache.valid = 1;
}
else {
if (card->cache.valid)
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
sc_file_dup(&card->cache.current_ef, file);
}
if (file_out) {
sc_file_free(*file_out);
*file_out = file;
}
else {
sc_file_free(file);
}
}
else if (lpath.type == SC_PATH_TYPE_DF_NAME) {
sc_file_free(card->cache.current_df);
card->cache.current_df = NULL;
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
card->cache.valid = 1;
}
} while(0);
sc_print_cache(card);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_process_fci(struct sc_card *card, struct sc_file *file,
const unsigned char *buf, size_t buflen)
{
struct sc_context *ctx = card->ctx;
size_t taglen;
int rv, ii, offs;
const unsigned char *acls = NULL, *tag = NULL;
unsigned char mask;
unsigned char ops_DF[7] = {
SC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_CREATE, 0xFF
};
unsigned char ops_EF[7] = {
SC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_UPDATE, SC_AC_OP_READ
};
LOG_FUNC_CALLED(ctx);
tag = sc_asn1_find_tag(ctx, buf, buflen, 0x6F, &taglen);
sc_log(ctx, "processing FCI: 0x6F tag %p", tag);
if (tag != NULL) {
sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen);
buf = tag;
buflen = taglen;
}
tag = sc_asn1_find_tag(ctx, buf, buflen, 0x62, &taglen);
sc_log(ctx, "processing FCI: 0x62 tag %p", tag);
if (tag != NULL) {
sc_log(ctx, " FCP length %"SC_FORMAT_LEN_SIZE_T"u", taglen);
buf = tag;
buflen = taglen;
}
rv = iso_ops->process_fci(card, file, buf, buflen);
LOG_TEST_RET(ctx, rv, "ISO parse FCI failed");
/*
Gemalto: 6F 19 80 02 02 ED 82 01 01 83 02 B0 01 88 00 8C 07 7B 17 17 17 17 17 00 8A 01 05 90 00
Sagem: 6F 17 62 15 80 02 00 7D 82 01 01 8C 02 01 00 83 02 2F 00 88 01 F0 8A 01 05 90 00
Oberthur: 62 1B 80 02 05 DC 82 01 01 83 02 B0 01 88 00 A1 09 8C 07 7B 17 FF 17 17 17 00 8A 01 05 90 00
*/
sc_log(ctx, "iasecc_process_fci() type %i; let's parse file ACLs", file->type);
tag = sc_asn1_find_tag(ctx, buf, buflen, IASECC_DOCP_TAG_ACLS, &taglen);
if (tag)
acls = sc_asn1_find_tag(ctx, tag, taglen, IASECC_DOCP_TAG_ACLS_CONTACT, &taglen);
else
acls = sc_asn1_find_tag(ctx, buf, buflen, IASECC_DOCP_TAG_ACLS_CONTACT, &taglen);
if (!acls) {
sc_log(ctx,
"ACLs not found in data(%"SC_FORMAT_LEN_SIZE_T"u) %s",
buflen, sc_dump_hex(buf, buflen));
LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "ACLs tag missing");
}
sc_log(ctx, "ACLs(%"SC_FORMAT_LEN_SIZE_T"u) '%s'", taglen,
sc_dump_hex(acls, taglen));
mask = 0x40, offs = 1;
for (ii = 0; ii < 7; ii++, mask /= 2) {
unsigned char op = file->type == SC_FILE_TYPE_DF ? ops_DF[ii] : ops_EF[ii];
if (!(mask & acls[0]))
continue;
sc_log(ctx, "ACLs mask 0x%X, offs %i, op 0x%X, acls[offs] 0x%X", mask, offs, op, acls[offs]);
if (op == 0xFF) {
;
}
else if (acls[offs] == 0) {
sc_file_add_acl_entry(file, op, SC_AC_NONE, 0);
}
else if (acls[offs] == 0xFF) {
sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0);
}
else if ((acls[offs] & IASECC_SCB_METHOD_MASK) == IASECC_SCB_METHOD_USER_AUTH) {
sc_file_add_acl_entry(file, op, SC_AC_SEN, acls[offs] & IASECC_SCB_METHOD_MASK_REF);
}
else if (acls[offs] & IASECC_SCB_METHOD_MASK) {
sc_file_add_acl_entry(file, op, SC_AC_SCB, acls[offs]);
}
else {
sc_log(ctx, "Warning: non supported SCB method: %X", acls[offs]);
sc_file_add_acl_entry(file, op, SC_AC_NEVER, 0);
}
offs++;
}
LOG_FUNC_RETURN(ctx, 0);
}
static int
iasecc_fcp_encode(struct sc_card *card, struct sc_file *file, unsigned char *out, size_t out_len)
{
struct sc_context *ctx = card->ctx;
unsigned char buf[0x80], type;
unsigned char ops[7] = {
SC_AC_OP_DELETE, 0xFF, SC_AC_OP_ACTIVATE, SC_AC_OP_DEACTIVATE, 0xFF, SC_AC_OP_UPDATE, SC_AC_OP_READ
};
unsigned char smbs[8];
size_t ii, offs = 0, amb, mask, nn_smb;
LOG_FUNC_CALLED(ctx);
if (file->type == SC_FILE_TYPE_DF)
type = IASECC_FCP_TYPE_DF;
else
type = IASECC_FCP_TYPE_EF;
buf[offs++] = IASECC_FCP_TAG_SIZE;
buf[offs++] = 2;
buf[offs++] = (file->size >> 8) & 0xFF;
buf[offs++] = file->size & 0xFF;
buf[offs++] = IASECC_FCP_TAG_TYPE;
buf[offs++] = 1;
buf[offs++] = type;
buf[offs++] = IASECC_FCP_TAG_FID;
buf[offs++] = 2;
buf[offs++] = (file->id >> 8) & 0xFF;
buf[offs++] = file->id & 0xFF;
buf[offs++] = IASECC_FCP_TAG_SFID;
buf[offs++] = 0;
amb = 0, mask = 0x40, nn_smb = 0;
for (ii = 0; ii < sizeof(ops); ii++, mask >>= 1) {
const struct sc_acl_entry *entry;
if (ops[ii]==0xFF)
continue;
entry = sc_file_get_acl_entry(file, ops[ii]);
if (!entry)
continue;
sc_log(ctx, "method %X; reference %X", entry->method, entry->key_ref);
if (entry->method == SC_AC_NEVER)
continue;
else if (entry->method == SC_AC_NONE)
smbs[nn_smb++] = 0x00;
else if (entry->method == SC_AC_CHV)
smbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_USER_AUTH;
else if (entry->method == SC_AC_SEN)
smbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_USER_AUTH;
else if (entry->method == SC_AC_SCB)
smbs[nn_smb++] = entry->key_ref;
else if (entry->method == SC_AC_PRO)
smbs[nn_smb++] = entry->key_ref | IASECC_SCB_METHOD_SM;
else
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Non supported AC method");
amb |= mask;
sc_log(ctx,
"%"SC_FORMAT_LEN_SIZE_T"u: AMB %"SC_FORMAT_LEN_SIZE_T"X; nn_smb %"SC_FORMAT_LEN_SIZE_T"u",
ii, amb, nn_smb);
}
/* TODO: Encode contactless ACLs and life cycle status for all IAS/ECC cards */
if (card->type == SC_CARD_TYPE_IASECC_SAGEM ||
card->type == SC_CARD_TYPE_IASECC_AMOS ) {
unsigned char status = 0;
buf[offs++] = IASECC_FCP_TAG_ACLS;
buf[offs++] = 2*(2 + 1 + nn_smb);
buf[offs++] = IASECC_FCP_TAG_ACLS_CONTACT;
buf[offs++] = nn_smb + 1;
buf[offs++] = amb;
memcpy(buf + offs, smbs, nn_smb);
offs += nn_smb;
/* Same ACLs for contactless */
buf[offs++] = IASECC_FCP_TAG_ACLS_CONTACTLESS;
buf[offs++] = nn_smb + 1;
buf[offs++] = amb;
memcpy(buf + offs, smbs, nn_smb);
offs += nn_smb;
if (file->status == SC_FILE_STATUS_ACTIVATED)
status = 0x05;
else if (file->status == SC_FILE_STATUS_CREATION)
status = 0x01;
if (status) {
buf[offs++] = 0x8A;
buf[offs++] = 0x01;
buf[offs++] = status;
}
}
else {
buf[offs++] = IASECC_FCP_TAG_ACLS;
buf[offs++] = 2 + 1 + nn_smb;
buf[offs++] = IASECC_FCP_TAG_ACLS_CONTACT;
buf[offs++] = nn_smb + 1;
buf[offs++] = amb;
memcpy(buf + offs, smbs, nn_smb);
offs += nn_smb;
}
if (out) {
if (out_len < offs)
LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Buffer too small to encode FCP");
memcpy(out, buf, offs);
}
LOG_FUNC_RETURN(ctx, offs);
}
static int
iasecc_create_file(struct sc_card *card, struct sc_file *file)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
const struct sc_acl_entry *entry = NULL;
unsigned char sbuf[0x100];
size_t sbuf_len;
int rv;
LOG_FUNC_CALLED(ctx);
sc_print_cache(card);
if (file->type != SC_FILE_TYPE_WORKING_EF)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Creation of the file with of this type is not supported");
sbuf_len = iasecc_fcp_encode(card, file, sbuf + 2, sizeof(sbuf)-2);
LOG_TEST_RET(ctx, sbuf_len, "FCP encode error");
sbuf[0] = IASECC_FCP_TAG;
sbuf[1] = sbuf_len;
if (card->cache.valid && card->cache.current_df) {
entry = sc_file_get_acl_entry(card->cache.current_df, SC_AC_OP_CREATE);
if (!entry)
LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "iasecc_create_file() 'CREATE' ACL not present");
sc_log(ctx, "iasecc_create_file() 'CREATE' method/reference %X/%X", entry->method, entry->key_ref);
sc_log(ctx, "iasecc_create_file() create data: '%s'", sc_dump_hex(sbuf, sbuf_len + 2));
if (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) {
rv = iasecc_sm_create_file(card, entry->key_ref & IASECC_SCB_METHOD_MASK_REF, sbuf, sbuf_len + 2);
LOG_TEST_RET(ctx, rv, "iasecc_create_file() SM create file error");
rv = iasecc_select_file(card, &file->path, NULL);
LOG_FUNC_RETURN(ctx, rv);
}
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xE0, 0, 0);
apdu.data = sbuf;
apdu.datalen = sbuf_len + 2;
apdu.lc = sbuf_len + 2;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "iasecc_create_file() create file error");
rv = iasecc_select_file(card, &file->path, NULL);
LOG_TEST_RET(ctx, rv, "Cannot select newly created file");
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_logout(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
struct sc_path path;
int rv;
LOG_FUNC_CALLED(ctx);
if (!card->ef_atr || !card->ef_atr->aid.len)
return SC_SUCCESS;
memset(&path, 0, sizeof(struct sc_path));
path.type = SC_PATH_TYPE_DF_NAME;
memcpy(path.value, card->ef_atr->aid.value, card->ef_atr->aid.len);
path.len = card->ef_atr->aid.len;
rv = iasecc_select_file(card, &path, NULL);
sc_log(ctx, "Select ECC ROOT with the AID from EF.ATR: rv %i", rv);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_finish(struct sc_card *card)
{
struct sc_context *ctx = card->ctx;
struct iasecc_private_data *private_data = (struct iasecc_private_data *)card->drv_data;
struct iasecc_se_info *se_info = private_data->se_info, *next;
LOG_FUNC_CALLED(ctx);
while (se_info) {
sc_file_free(se_info->df);
next = se_info->next;
free(se_info);
se_info = next;
}
free(card->drv_data);
card->drv_data = NULL;
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_delete_file(struct sc_card *card, const struct sc_path *path)
{
struct sc_context *ctx = card->ctx;
const struct sc_acl_entry *entry = NULL;
struct sc_apdu apdu;
struct sc_file *file = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
sc_print_cache(card);
rv = iasecc_select_file(card, path, &file);
if (rv == SC_ERROR_FILE_NOT_FOUND)
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
LOG_TEST_RET(ctx, rv, "Cannot select file to delete");
entry = sc_file_get_acl_entry(file, SC_AC_OP_DELETE);
if (!entry)
LOG_TEST_RET(ctx, SC_ERROR_OBJECT_NOT_FOUND, "Cannot delete file: no 'DELETE' acl");
sc_log(ctx, "DELETE method/reference %X/%X", entry->method, entry->key_ref);
if (entry->method == SC_AC_SCB && (entry->key_ref & IASECC_SCB_METHOD_SM)) {
unsigned char se_num = (entry->method == SC_AC_SCB) ? (entry->key_ref & IASECC_SCB_METHOD_MASK_REF) : 0;
rv = iasecc_sm_delete_file(card, se_num, file->id);
}
else {
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0xE4, 0x00, 0x00);
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "Delete file failed");
if (card->cache.valid)
sc_file_free(card->cache.current_ef);
card->cache.current_ef = NULL;
}
sc_file_free(file);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_check_sw(struct sc_card *card, unsigned int sw1, unsigned int sw2)
{
if (sw1 == 0x62 && sw2 == 0x82)
return SC_SUCCESS;
return iso_ops->check_sw(card, sw1, sw2);
}
static unsigned
iasecc_get_algorithm(struct sc_context *ctx, const struct sc_security_env *env,
unsigned operation, unsigned mechanism)
{
const struct sc_supported_algo_info *info = NULL;
int ii;
if (!env)
return 0;
for (ii=0;ii<SC_MAX_SUPPORTED_ALGORITHMS && env->supported_algos[ii].reference; ii++)
if ((env->supported_algos[ii].operations & operation)
&& (env->supported_algos[ii].mechanism == mechanism))
break;
if (ii < SC_MAX_SUPPORTED_ALGORITHMS && env->supported_algos[ii].reference) {
info = &env->supported_algos[ii];
sc_log(ctx, "found IAS/ECC algorithm %X:%X:%X:%X",
info->reference, info->mechanism, info->operations, info->algo_ref);
}
else {
sc_log(ctx, "cannot find IAS/ECC algorithm (operation:%X,mechanism:%X)", operation, mechanism);
}
return info ? info->algo_ref : 0;
}
static int
iasecc_se_cache_info(struct sc_card *card, struct iasecc_se_info *se)
{
struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;
struct sc_context *ctx = card->ctx;
struct iasecc_se_info *se_info = NULL, *si = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
se_info = calloc(1, sizeof(struct iasecc_se_info));
if (!se_info)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "SE info allocation error");
memcpy(se_info, se, sizeof(struct iasecc_se_info));
if (card->cache.valid && card->cache.current_df) {
sc_file_dup(&se_info->df, card->cache.current_df);
if (se_info->df == NULL) {
free(se_info);
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot duplicate current DF file");
}
}
rv = iasecc_docp_copy(ctx, &se->docp, &se_info->docp);
if (rv < 0) {
free(se_info->df);
free(se_info);
LOG_TEST_RET(ctx, rv, "Cannot make copy of DOCP");
}
if (!prv->se_info) {
prv->se_info = se_info;
}
else {
for (si = prv->se_info; si->next; si = si->next)
;
si->next = se_info;
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_se_get_info_from_cache(struct sc_card *card, struct iasecc_se_info *se)
{
struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;
struct sc_context *ctx = card->ctx;
struct iasecc_se_info *si = NULL;
int rv;
LOG_FUNC_CALLED(ctx);
for(si = prv->se_info; si; si = si->next) {
if (si->reference != se->reference)
continue;
if (!(card->cache.valid && card->cache.current_df) && si->df)
continue;
if (card->cache.valid && card->cache.current_df && !si->df)
continue;
if (card->cache.valid && card->cache.current_df && si->df)
if (memcmp(&card->cache.current_df->path, &si->df->path, sizeof(struct sc_path)))
continue;
break;
}
if (!si)
return SC_ERROR_OBJECT_NOT_FOUND;
memcpy(se, si, sizeof(struct iasecc_se_info));
if (si->df) {
sc_file_dup(&se->df, si->df);
if (se->df == NULL)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot duplicate current DF file");
}
rv = iasecc_docp_copy(ctx, &si->docp, &se->docp);
LOG_TEST_RET(ctx, rv, "Cannot make copy of DOCP");
LOG_FUNC_RETURN(ctx, rv);
}
int
iasecc_se_get_info(struct sc_card *card, struct iasecc_se_info *se)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char rbuf[0x100];
unsigned char sbuf_iasecc[10] = {
0x4D, 0x08, IASECC_SDO_TEMPLATE_TAG, 0x06,
IASECC_SDO_TAG_HEADER, IASECC_SDO_CLASS_SE | IASECC_OBJECT_REF_LOCAL,
se->reference & 0x3F,
0x02, IASECC_SDO_CLASS_SE, 0x80
};
int rv;
LOG_FUNC_CALLED(ctx);
if (se->reference > IASECC_SE_REF_MAX)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
rv = iasecc_se_get_info_from_cache(card, se);
if (rv == SC_ERROR_OBJECT_NOT_FOUND) {
sc_log(ctx, "No SE#%X info in cache, try to use 'GET DATA'", se->reference);
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xCB, 0x3F, 0xFF);
apdu.data = sbuf_iasecc;
apdu.datalen = sizeof(sbuf_iasecc);
apdu.lc = apdu.datalen;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = sizeof(rbuf);
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "get SE data error");
rv = iasecc_se_parse(card, apdu.resp, apdu.resplen, se);
LOG_TEST_RET(ctx, rv, "cannot parse SE data");
rv = iasecc_se_cache_info(card, se);
LOG_TEST_RET(ctx, rv, "failed to put SE data into cache");
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_set_security_env(struct sc_card *card,
const struct sc_security_env *env, int se_num)
{
struct sc_context *ctx = card->ctx;
struct iasecc_sdo sdo;
struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;
unsigned algo_ref;
struct sc_apdu apdu;
unsigned sign_meth, sign_ref, auth_meth, auth_ref, aflags;
unsigned char cse_crt_at[] = {
0x84, 0x01, 0xFF,
0x80, 0x01, IASECC_ALGORITHM_RSA_PKCS
};
unsigned char cse_crt_dst[] = {
0x84, 0x01, 0xFF,
0x80, 0x01, (IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA1)
};
unsigned char cse_crt_ht[] = {
0x80, 0x01, IASECC_ALGORITHM_SHA1
};
unsigned char cse_crt_ct[] = {
0x84, 0x01, 0xFF,
0x80, 0x01, (IASECC_ALGORITHM_RSA_PKCS_DECRYPT | IASECC_ALGORITHM_SHA1)
};
int rv, operation = env->operation;
/* TODO: take algorithm references from 5032, not from header file. */
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "iasecc_set_security_env(card:%p) operation 0x%X; senv.algorithm 0x%X, senv.algorithm_ref 0x%X",
card, env->operation, env->algorithm, env->algorithm_ref);
memset(&sdo, 0, sizeof(sdo));
sdo.sdo_class = IASECC_SDO_CLASS_RSA_PRIVATE;
sdo.sdo_ref = env->key_ref[0] & ~IASECC_OBJECT_REF_LOCAL;
rv = iasecc_sdo_get_data(card, &sdo);
LOG_TEST_RET(ctx, rv, "Cannot get RSA PRIVATE SDO data");
/* To made by iasecc_sdo_convert_to_file() */
prv->key_size = *(sdo.docp.size.value + 0) * 0x100 + *(sdo.docp.size.value + 1);
sc_log(ctx, "prv->key_size 0x%"SC_FORMAT_LEN_SIZE_T"X", prv->key_size);
rv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_PSO_COMPUTE_SIGNATURE, &sign_meth, &sign_ref);
LOG_TEST_RET(ctx, rv, "Cannot convert SC_AC_OP_SIGN acl");
rv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_INTERNAL_AUTHENTICATE, &auth_meth, &auth_ref);
LOG_TEST_RET(ctx, rv, "Cannot convert SC_AC_OP_INT_AUTH acl");
aflags = env->algorithm_flags;
if (!(aflags & SC_ALGORITHM_RSA_PAD_PKCS1))
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Only supported signature with PKCS1 padding");
if (operation == SC_SEC_OPERATION_SIGN) {
if (!(aflags & (SC_ALGORITHM_RSA_HASH_SHA1 | SC_ALGORITHM_RSA_HASH_SHA256))) {
sc_log(ctx, "CKM_RSA_PKCS asked -- use 'AUTHENTICATE' sign operation instead of 'SIGN'");
operation = SC_SEC_OPERATION_AUTHENTICATE;
}
else if (sign_meth == SC_AC_NEVER) {
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "PSO_DST not allowed for this key");
}
}
if (operation == SC_SEC_OPERATION_SIGN) {
prv->op_method = sign_meth;
prv->op_ref = sign_ref;
}
else if (operation == SC_SEC_OPERATION_AUTHENTICATE) {
if (auth_meth == SC_AC_NEVER)
LOG_TEST_RET(ctx, SC_ERROR_NOT_ALLOWED, "INTERNAL_AUTHENTICATE is not allowed for this key");
prv->op_method = auth_meth;
prv->op_ref = auth_ref;
}
sc_log(ctx, "senv.algorithm 0x%X, senv.algorithm_ref 0x%X", env->algorithm, env->algorithm_ref);
sc_log(ctx,
"se_num %i, operation 0x%X, algorithm 0x%X, algorithm_ref 0x%X, flags 0x%X; key size %"SC_FORMAT_LEN_SIZE_T"u",
se_num, operation, env->algorithm, env->algorithm_ref,
env->algorithm_flags, prv->key_size);
switch (operation) {
case SC_SEC_OPERATION_SIGN:
if (!(env->algorithm_flags & SC_ALGORITHM_RSA_PAD_PKCS1))
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Need RSA_PKCS1 specified");
if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA256) {
algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_HASH, CKM_SHA256);
if (!algo_ref)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Card application do not supports HASH:SHA256");
cse_crt_ht[2] = algo_ref; /* IASECC_ALGORITHM_SHA2 */
algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_SHA256_RSA_PKCS);
if (!algo_ref)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Card application do not supports SIGNATURE:SHA1_RSA_PKCS");
cse_crt_dst[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL;
cse_crt_dst[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA2 */
}
else if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) {
algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_HASH, CKM_SHA_1);
if (!algo_ref)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Card application do not supports HASH:SHA1");
cse_crt_ht[2] = algo_ref; /* IASECC_ALGORITHM_SHA1 */
algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_SHA1_RSA_PKCS);
if (!algo_ref)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Card application do not supports SIGNATURE:SHA1_RSA_PKCS");
cse_crt_dst[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL;
cse_crt_dst[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS | IASECC_ALGORITHM_SHA1 */
}
else {
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Need RSA_HASH_SHA[1,256] specified");
}
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_HT);
apdu.data = cse_crt_ht;
apdu.datalen = sizeof(cse_crt_ht);
apdu.lc = sizeof(cse_crt_ht);
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "MSE restore error");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_DST);
apdu.data = cse_crt_dst;
apdu.datalen = sizeof(cse_crt_dst);
apdu.lc = sizeof(cse_crt_dst);
break;
case SC_SEC_OPERATION_AUTHENTICATE:
algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_COMPUTE_SIGNATURE, CKM_RSA_PKCS);
if (!algo_ref)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Application do not supports SIGNATURE:RSA_PKCS");
cse_crt_at[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL;
cse_crt_at[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_AT);
apdu.data = cse_crt_at;
apdu.datalen = sizeof(cse_crt_at);
apdu.lc = sizeof(cse_crt_at);
break;
case SC_SEC_OPERATION_DECIPHER:
rv = iasecc_sdo_convert_acl(card, &sdo, SC_AC_OP_PSO_DECRYPT, &prv->op_method, &prv->op_ref);
LOG_TEST_RET(ctx, rv, "Cannot convert SC_AC_OP_PSO_DECRYPT acl");
algo_ref = iasecc_get_algorithm(ctx, env, SC_PKCS15_ALGO_OP_DECIPHER, CKM_RSA_PKCS);
if (!algo_ref)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Application do not supports DECIPHER:RSA_PKCS");
cse_crt_ct[2] = env->key_ref[0] | IASECC_OBJECT_REF_LOCAL;
cse_crt_ct[5] = algo_ref; /* IASECC_ALGORITHM_RSA_PKCS_DECRYPT | IASECC_ALGORITHM_SHA1 */
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x22, 0x41, IASECC_CRT_TAG_CT);
apdu.data = cse_crt_ct;
apdu.datalen = sizeof(cse_crt_ct);
apdu.lc = sizeof(cse_crt_ct);
break;
default:
LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
}
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "MSE restore error");
prv->security_env = *env;
prv->security_env.operation = operation;
LOG_FUNC_RETURN(ctx, 0);
}
static int
iasecc_chv_verify_pinpad(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd, int *tries_left)
{
struct sc_context *ctx = card->ctx;
unsigned char buffer[0x100];
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "CHV PINPAD PIN reference %i", pin_cmd->pin_reference);
rv = iasecc_pin_is_verified(card, pin_cmd, tries_left);
if (!rv)
LOG_FUNC_RETURN(ctx, rv);
if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) {
sc_log(ctx, "Reader not ready for PIN PAD");
LOG_FUNC_RETURN(ctx, SC_ERROR_READER);
}
/* When PIN stored length available
* P10 verify data contains full template of 'VERIFY PIN' APDU.
* Without PIN stored length
* pin-pad has to set the Lc and fill PIN data itself.
* Not all pin-pads support this case
*/
pin_cmd->pin1.len = pin_cmd->pin1.stored_length;
pin_cmd->pin1.length_offset = 5;
memset(buffer, 0xFF, sizeof(buffer));
pin_cmd->pin1.data = buffer;
pin_cmd->cmd = SC_PIN_CMD_VERIFY;
pin_cmd->flags |= SC_PIN_CMD_USE_PINPAD;
/*
if (card->reader && card->reader->ops && card->reader->ops->load_message) {
rv = card->reader->ops->load_message(card->reader, card->slot, 0, "Here we are!");
sc_log(ctx, "Load message returned %i", rv);
}
*/
rv = iso_ops->pin_cmd(card, pin_cmd, tries_left);
sc_log(ctx, "rv %i", rv);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_chv_verify(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd,
int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct sc_acl_entry acl = pin_cmd->pin1.acls[IASECC_ACLS_CHV_VERIFY];
struct sc_apdu apdu;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "Verify CHV PIN(ref:%i,len:%i,acl:%X:%X)", pin_cmd->pin_reference, pin_cmd->pin1.len,
acl.method, acl.key_ref);
if (acl.method & IASECC_SCB_METHOD_SM) {
rv = iasecc_sm_pin_verify(card, acl.key_ref, pin_cmd, tries_left);
LOG_FUNC_RETURN(ctx, rv);
}
if (pin_cmd->pin1.data && !pin_cmd->pin1.len) {
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x20, 0, pin_cmd->pin_reference);
}
else if (pin_cmd->pin1.data && pin_cmd->pin1.len) {
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x20, 0, pin_cmd->pin_reference);
apdu.data = pin_cmd->pin1.data;
apdu.datalen = pin_cmd->pin1.len;
apdu.lc = pin_cmd->pin1.len;
}
else if ((card->reader->capabilities & SC_READER_CAP_PIN_PAD) && !pin_cmd->pin1.data && !pin_cmd->pin1.len) {
rv = iasecc_chv_verify_pinpad(card, pin_cmd, tries_left);
sc_log(ctx, "Result of verifying CHV with PIN pad %i", rv);
LOG_FUNC_RETURN(ctx, rv);
}
else {
LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
}
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
if (tries_left && apdu.sw1 == 0x63 && (apdu.sw2 & 0xF0) == 0xC0)
*tries_left = apdu.sw2 & 0x0F;
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_se_at_to_chv_reference(struct sc_card *card, unsigned reference,
unsigned *chv_reference)
{
struct sc_context *ctx = card->ctx;
struct iasecc_se_info se;
struct sc_crt crt;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "SE reference %i", reference);
if (reference > IASECC_SE_REF_MAX)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
memset(&se, 0, sizeof(se));
se.reference = reference;
rv = iasecc_se_get_info(card, &se);
LOG_TEST_RET(ctx, rv, "SDO get data error");
memset(&crt, 0, sizeof(crt));
crt.tag = IASECC_CRT_TAG_AT;
crt.usage = IASECC_UQB_AT_USER_PASSWORD;
rv = iasecc_se_get_crt(card, &se, &crt);
LOG_TEST_RET(ctx, rv, "no authentication template for USER PASSWORD");
if (chv_reference)
*chv_reference = crt.refs[0];
sc_file_free(se.df);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_pin_is_verified(struct sc_card *card, struct sc_pin_cmd_data *pin_cmd_data,
int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct sc_pin_cmd_data pin_cmd;
struct sc_acl_entry acl = pin_cmd_data->pin1.acls[IASECC_ACLS_CHV_VERIFY];
int rv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
LOG_FUNC_CALLED(ctx);
if (pin_cmd_data->pin_type != SC_AC_CHV)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "PIN type is not supported for the verification");
sc_log(ctx, "Verify ACL(method:%X;ref:%X)", acl.method, acl.key_ref);
if (acl.method != IASECC_SCB_ALWAYS)
LOG_FUNC_RETURN(ctx, SC_ERROR_SECURITY_STATUS_NOT_SATISFIED);
pin_cmd = *pin_cmd_data;
pin_cmd.pin1.data = (unsigned char *)"";
pin_cmd.pin1.len = 0;
rv = iasecc_chv_verify(card, &pin_cmd, tries_left);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_pin_verify(struct sc_card *card, unsigned type, unsigned reference,
const unsigned char *data, size_t data_len, int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct sc_pin_cmd_data pin_cmd;
unsigned chv_ref = reference;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"Verify PIN(type:%X,ref:%i,data(len:%"SC_FORMAT_LEN_SIZE_T"u,%p)",
type, reference, data_len, data);
if (type == SC_AC_AUT) {
rv = iasecc_sm_external_authentication(card, reference, tries_left);
LOG_FUNC_RETURN(ctx, rv);
}
else if (type == SC_AC_SCB) {
if (reference & IASECC_SCB_METHOD_USER_AUTH) {
type = SC_AC_SEN;
reference = reference & IASECC_SCB_METHOD_MASK_REF;
}
else {
sc_log(ctx, "Do not try to verify non CHV PINs");
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
}
if (type == SC_AC_SEN) {
rv = iasecc_se_at_to_chv_reference(card, reference, &chv_ref);
LOG_TEST_RET(ctx, rv, "SE AT to CHV reference error");
}
memset(&pin_cmd, 0, sizeof(pin_cmd));
pin_cmd.pin_type = SC_AC_CHV;
pin_cmd.pin_reference = chv_ref;
pin_cmd.cmd = SC_PIN_CMD_VERIFY;
rv = iasecc_pin_get_policy(card, &pin_cmd);
LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error");
pin_cmd.pin1.data = data;
pin_cmd.pin1.len = data_len;
rv = iasecc_pin_is_verified(card, &pin_cmd, tries_left);
if (data && !data_len)
LOG_FUNC_RETURN(ctx, rv);
if (!rv) {
if (iasecc_chv_cache_is_verified(card, &pin_cmd))
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
else if (rv != SC_ERROR_PIN_CODE_INCORRECT && rv != SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {
LOG_FUNC_RETURN(ctx, rv);
}
iasecc_chv_cache_clean(card, &pin_cmd);
rv = iasecc_chv_verify(card, &pin_cmd, tries_left);
LOG_TEST_RET(ctx, rv, "PIN CHV verification error");
rv = iasecc_chv_cache_verified(card, &pin_cmd);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_chv_change_pinpad(struct sc_card *card, unsigned reference, int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct sc_pin_cmd_data pin_cmd;
unsigned char pin1_data[0x100], pin2_data[0x100];
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "CHV PINPAD PIN reference %i", reference);
memset(pin1_data, 0xFF, sizeof(pin1_data));
memset(pin2_data, 0xFF, sizeof(pin2_data));
if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) {
sc_log(ctx, "Reader not ready for PIN PAD");
LOG_FUNC_RETURN(ctx, SC_ERROR_READER);
}
memset(&pin_cmd, 0, sizeof(pin_cmd));
pin_cmd.pin_type = SC_AC_CHV;
pin_cmd.pin_reference = reference;
pin_cmd.cmd = SC_PIN_CMD_CHANGE;
pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD;
rv = iasecc_pin_get_policy(card, &pin_cmd);
LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error");
/* Some pin-pads do not support mode with Lc=0.
* Give them a chance to work with some cards.
*/
if ((pin_cmd.pin1.min_length == pin_cmd.pin1.stored_length) && (pin_cmd.pin1.max_length == pin_cmd.pin1.min_length))
pin_cmd.pin1.len = pin_cmd.pin1.stored_length;
else
pin_cmd.pin1.len = 0;
pin_cmd.pin1.length_offset = 5;
pin_cmd.pin1.data = pin1_data;
memcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin1));
pin_cmd.pin2.data = pin2_data;
sc_log(ctx,
"PIN1 max/min/stored: %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u",
pin_cmd.pin1.max_length, pin_cmd.pin1.min_length,
pin_cmd.pin1.stored_length);
sc_log(ctx,
"PIN2 max/min/stored: %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u",
pin_cmd.pin2.max_length, pin_cmd.pin2.min_length,
pin_cmd.pin2.stored_length);
rv = iso_ops->pin_cmd(card, &pin_cmd, tries_left);
LOG_FUNC_RETURN(ctx, rv);
}
#if 0
static int
iasecc_chv_set_pinpad(struct sc_card *card, unsigned char reference)
{
struct sc_context *ctx = card->ctx;
struct sc_pin_cmd_data pin_cmd;
unsigned char pin_data[0x100];
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "Set CHV PINPAD PIN reference %i", reference);
memset(pin_data, 0xFF, sizeof(pin_data));
if (!card->reader || !card->reader->ops || !card->reader->ops->perform_verify) {
sc_log(ctx, "Reader not ready for PIN PAD");
LOG_FUNC_RETURN(ctx, SC_ERROR_READER);
}
memset(&pin_cmd, 0, sizeof(pin_cmd));
pin_cmd.pin_type = SC_AC_CHV;
pin_cmd.pin_reference = reference;
pin_cmd.cmd = SC_PIN_CMD_UNBLOCK;
pin_cmd.flags |= SC_PIN_CMD_USE_PINPAD;
rv = iasecc_pin_get_policy(card, &pin_cmd);
LOG_TEST_RET(ctx, rv, "Get 'PIN policy' error");
if ((pin_cmd.pin1.min_length == pin_cmd.pin1.stored_length) && (pin_cmd.pin1.max_length == pin_cmd.pin1.min_length))
pin_cmd.pin1.len = pin_cmd.pin1.stored_length;
else
pin_cmd.pin1.len = 0;
pin_cmd.pin1.length_offset = 5;
pin_cmd.pin1.data = pin_data;
memcpy(&pin_cmd.pin2, &pin_cmd.pin1, sizeof(pin_cmd.pin1));
memset(&pin_cmd.pin1, 0, sizeof(pin_cmd.pin1));
pin_cmd.flags |= SC_PIN_CMD_IMPLICIT_CHANGE;
sc_log(ctx, "PIN1(max:%i,min:%i)", pin_cmd.pin1.max_length, pin_cmd.pin1.min_length);
sc_log(ctx, "PIN2(max:%i,min:%i)", pin_cmd.pin2.max_length, pin_cmd.pin2.min_length);
rv = iso_ops->pin_cmd(card, &pin_cmd, NULL);
LOG_FUNC_RETURN(ctx, rv);
}
#endif
static int
iasecc_pin_get_policy (struct sc_card *card, struct sc_pin_cmd_data *data)
{
struct sc_context *ctx = card->ctx;
struct sc_file *save_current_df = NULL, *save_current_ef = NULL;
struct iasecc_sdo sdo;
struct sc_path path;
unsigned ii;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "iasecc_pin_get_policy(card:%p)", card);
if (data->pin_type != SC_AC_CHV) {
sc_log(ctx, "To unblock PIN it's CHV reference should be presented");
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
}
if (card->cache.valid && card->cache.current_df) {
sc_file_dup(&save_current_df, card->cache.current_df);
if (save_current_df == NULL) {
rv = SC_ERROR_OUT_OF_MEMORY;
sc_log(ctx, "Cannot duplicate current DF file");
goto err;
}
}
if (card->cache.valid && card->cache.current_ef) {
sc_file_dup(&save_current_ef, card->cache.current_ef);
if (save_current_ef == NULL) {
rv = SC_ERROR_OUT_OF_MEMORY;
sc_log(ctx, "Cannot duplicate current EF file");
goto err;
}
}
if (!(data->pin_reference & IASECC_OBJECT_REF_LOCAL) && card->cache.valid && card->cache.current_df) {
sc_format_path("3F00", &path);
path.type = SC_PATH_TYPE_FILE_ID;
rv = iasecc_select_file(card, &path, NULL);
LOG_TEST_GOTO_ERR(ctx, rv, "Unable to select MF");
}
memset(&sdo, 0, sizeof(sdo));
sdo.sdo_class = IASECC_SDO_CLASS_CHV;
sdo.sdo_ref = data->pin_reference & ~IASECC_OBJECT_REF_LOCAL;
sc_log(ctx, "iasecc_pin_get_policy() reference %i", sdo.sdo_ref);
rv = iasecc_sdo_get_data(card, &sdo);
LOG_TEST_GOTO_ERR(ctx, rv, "Cannot get SDO PIN data");
if (sdo.docp.acls_contact.size == 0) {
rv = SC_ERROR_INVALID_DATA;
sc_log(ctx, "Extremely strange ... there is no ACLs");
goto err;
}
sc_log(ctx,
"iasecc_pin_get_policy() sdo.docp.size.size %"SC_FORMAT_LEN_SIZE_T"u",
sdo.docp.size.size);
for (ii=0; ii<sizeof(sdo.docp.scbs); ii++) {
struct iasecc_se_info se;
unsigned char scb = sdo.docp.scbs[ii];
struct sc_acl_entry *acl = &data->pin1.acls[ii];
int crt_num = 0;
memset(&se, 0, sizeof(se));
memset(&acl->crts, 0, sizeof(acl->crts));
sc_log(ctx, "iasecc_pin_get_policy() set info acls: SCB 0x%X", scb);
/* acl->raw_value = scb; */
acl->method = scb & IASECC_SCB_METHOD_MASK;
acl->key_ref = scb & IASECC_SCB_METHOD_MASK_REF;
if (scb==0 || scb==0xFF)
continue;
if (se.reference != (int)acl->key_ref) {
memset(&se, 0, sizeof(se));
se.reference = acl->key_ref;
rv = iasecc_se_get_info(card, &se);
LOG_TEST_GOTO_ERR(ctx, rv, "SDO get data error");
}
if (scb & IASECC_SCB_METHOD_USER_AUTH) {
rv = iasecc_se_get_crt_by_usage(card, &se,
IASECC_CRT_TAG_AT, IASECC_UQB_AT_USER_PASSWORD, &acl->crts[crt_num]);
LOG_TEST_GOTO_ERR(ctx, rv, "no authentication template for 'USER PASSWORD'");
sc_log(ctx, "iasecc_pin_get_policy() scb:0x%X; sdo_ref:[%i,%i,...]",
scb, acl->crts[crt_num].refs[0], acl->crts[crt_num].refs[1]);
crt_num++;
}
if (scb & (IASECC_SCB_METHOD_SM | IASECC_SCB_METHOD_EXT_AUTH)) {
sc_log(ctx, "'SM' and 'EXTERNAL AUTHENTICATION' protection methods are not supported: SCB:0x%X", scb);
/* Set to 'NEVER' if all conditions are needed or
* there is no user authentication method allowed */
if (!crt_num || (scb & IASECC_SCB_METHOD_NEED_ALL))
acl->method = SC_AC_NEVER;
continue;
}
sc_file_free(se.df);
}
if (sdo.data.chv.size_max.value)
data->pin1.max_length = *sdo.data.chv.size_max.value;
if (sdo.data.chv.size_min.value)
data->pin1.min_length = *sdo.data.chv.size_min.value;
if (sdo.docp.tries_maximum.value)
data->pin1.max_tries = *sdo.docp.tries_maximum.value;
if (sdo.docp.tries_remaining.value)
data->pin1.tries_left = *sdo.docp.tries_remaining.value;
if (sdo.docp.size.value) {
for (ii=0; ii<sdo.docp.size.size; ii++)
data->pin1.stored_length = ((data->pin1.stored_length) << 8) + *(sdo.docp.size.value + ii);
}
data->pin1.encoding = SC_PIN_ENCODING_ASCII;
data->pin1.offset = 5;
data->pin1.logged_in = SC_PIN_STATE_UNKNOWN;
sc_log(ctx,
"PIN policy: size max/min %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u, tries max/left %i/%i",
data->pin1.max_length, data->pin1.min_length,
data->pin1.max_tries, data->pin1.tries_left);
iasecc_sdo_free_fields(card, &sdo);
if (save_current_df) {
sc_log(ctx, "iasecc_pin_get_policy() restore current DF");
rv = iasecc_select_file(card, &save_current_df->path, NULL);
LOG_TEST_GOTO_ERR(ctx, rv, "Cannot return to saved DF");
}
if (save_current_ef) {
sc_log(ctx, "iasecc_pin_get_policy() restore current EF");
rv = iasecc_select_file(card, &save_current_ef->path, NULL);
LOG_TEST_GOTO_ERR(ctx, rv, "Cannot return to saved EF");
}
err:
sc_file_free(save_current_df);
sc_file_free(save_current_ef);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_keyset_change(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct iasecc_sdo_update update;
struct iasecc_sdo sdo;
unsigned scb;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "Change keyset(ref:%i,lengths:%i)", data->pin_reference, data->pin2.len);
if (!data->pin2.data || data->pin2.len < 32)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Needs at least 32 bytes for a new keyset value");
memset(&sdo, 0, sizeof(sdo));
sdo.sdo_class = IASECC_SDO_CLASS_KEYSET;
sdo.sdo_ref = data->pin_reference;
rv = iasecc_sdo_get_data(card, &sdo);
LOG_TEST_RET(ctx, rv, "Cannot get keyset data");
if (sdo.docp.acls_contact.size == 0)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Bewildered ... there are no ACLs");
scb = sdo.docp.scbs[IASECC_ACLS_KEYSET_PUT_DATA];
iasecc_sdo_free_fields(card, &sdo);
sc_log(ctx, "SCB:0x%X", scb);
if (!(scb & IASECC_SCB_METHOD_SM))
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Other then protected by SM, the keyset change is not supported");
memset(&update, 0, sizeof(update));
update.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA;
update.sdo_class = sdo.sdo_class;
update.sdo_ref = sdo.sdo_ref;
update.fields[0].parent_tag = IASECC_SDO_KEYSET_TAG;
update.fields[0].tag = IASECC_SDO_KEYSET_TAG_MAC;
/* FIXME is it safe to modify the const value here? */
update.fields[0].value = (unsigned char *) data->pin2.data;
update.fields[0].size = 16;
update.fields[1].parent_tag = IASECC_SDO_KEYSET_TAG;
update.fields[1].tag = IASECC_SDO_KEYSET_TAG_ENC;
/* FIXME is it safe to modify the const value here? */
update.fields[1].value = (unsigned char *) data->pin2.data + 16;
update.fields[1].size = 16;
rv = iasecc_sm_sdo_update(card, (scb & IASECC_SCB_METHOD_MASK_REF), &update);
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_pin_change(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned reference = data->pin_reference;
unsigned char pin_data[0x100];
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "Change PIN(ref:%i,type:0x%X,lengths:%i/%i)", reference, data->pin_type, data->pin1.len, data->pin2.len);
if ((card->reader->capabilities & SC_READER_CAP_PIN_PAD)) {
if (!data->pin1.data && !data->pin1.len && !data->pin2.data && !data->pin2.len) {
rv = iasecc_chv_change_pinpad(card, reference, tries_left);
sc_log(ctx, "iasecc_pin_cmd(SC_PIN_CMD_CHANGE) chv_change_pinpad returned %i", rv);
LOG_FUNC_RETURN(ctx, rv);
}
}
if (!data->pin1.data && data->pin1.len)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid PIN1 arguments");
if (!data->pin2.data && data->pin2.len)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid PIN2 arguments");
rv = iasecc_pin_verify(card, data->pin_type, reference, data->pin1.data, data->pin1.len, tries_left);
sc_log(ctx, "iasecc_pin_cmd(SC_PIN_CMD_CHANGE) pin_verify returned %i", rv);
LOG_TEST_RET(ctx, rv, "PIN verification error");
if ((unsigned)(data->pin1.len + data->pin2.len) > sizeof(pin_data))
LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Buffer too small for the 'Change PIN' data");
if (data->pin1.data)
memcpy(pin_data, data->pin1.data, data->pin1.len);
if (data->pin2.data)
memcpy(pin_data + data->pin1.len, data->pin2.data, data->pin2.len);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x24, 0, reference);
apdu.data = pin_data;
apdu.datalen = data->pin1.len + data->pin2.len;
apdu.lc = apdu.datalen;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "PIN cmd failed");
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_pin_reset(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
struct sc_context *ctx = card->ctx;
struct sc_file *save_current = NULL;
struct iasecc_sdo sdo;
struct sc_apdu apdu;
unsigned reference, scb;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "Reset PIN(ref:%i,lengths:%i/%i)", data->pin_reference, data->pin1.len, data->pin2.len);
if (data->pin_type != SC_AC_CHV)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Unblock procedure can be used only with the PINs of type CHV");
reference = data->pin_reference;
if (!(data->pin_reference & IASECC_OBJECT_REF_LOCAL) && card->cache.valid && card->cache.current_df) {
struct sc_path path;
sc_file_dup(&save_current, card->cache.current_df);
if (save_current == NULL)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot duplicate current DF file");
sc_format_path("3F00", &path);
path.type = SC_PATH_TYPE_FILE_ID;
rv = iasecc_select_file(card, &path, NULL);
LOG_TEST_RET(ctx, rv, "Unable to select MF");
}
memset(&sdo, 0, sizeof(sdo));
sdo.sdo_class = IASECC_SDO_CLASS_CHV;
sdo.sdo_ref = reference & ~IASECC_OBJECT_REF_LOCAL;
rv = iasecc_sdo_get_data(card, &sdo);
LOG_TEST_RET(ctx, rv, "Cannot get PIN data");
if (sdo.docp.acls_contact.size == 0)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Extremely strange ... there are no ACLs");
scb = sdo.docp.scbs[IASECC_ACLS_CHV_RESET];
do {
unsigned need_all = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0;
unsigned char se_num = scb & IASECC_SCB_METHOD_MASK_REF;
if (scb & IASECC_SCB_METHOD_USER_AUTH) {
sc_log(ctx, "Verify PIN in SE %X", se_num);
rv = iasecc_pin_verify(card, SC_AC_SEN, se_num, data->pin1.data, data->pin1.len, tries_left);
LOG_TEST_RET(ctx, rv, "iasecc_pin_reset() verify PUK error");
if (!need_all)
break;
}
if (scb & IASECC_SCB_METHOD_SM) {
rv = iasecc_sm_pin_reset(card, se_num, data);
LOG_FUNC_RETURN(ctx, rv);
}
if (scb & IASECC_SCB_METHOD_EXT_AUTH) {
rv = iasecc_sm_external_authentication(card, reference, tries_left);
LOG_TEST_RET(ctx, rv, "iasecc_pin_reset() external authentication error");
}
} while(0);
iasecc_sdo_free_fields(card, &sdo);
if (data->pin2.len) {
sc_log(ctx, "Reset PIN %X and set new value", reference);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2C, 0x02, reference);
apdu.data = data->pin2.data;
apdu.datalen = data->pin2.len;
apdu.lc = apdu.datalen;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "PIN cmd failed");
}
else if (data->pin2.data) {
sc_log(ctx, "Reset PIN %X and set new value", reference);
sc_format_apdu(card, &apdu, SC_APDU_CASE_1, 0x2C, 3, reference);
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "PIN cmd failed");
}
else {
sc_log(ctx, "Reset PIN %X and set new value with PIN-PAD", reference);
#if 0
rv = iasecc_chv_set_pinpad(card, reference);
LOG_TEST_RET(ctx, rv, "Reset PIN failed");
#else
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Reset retry counter with PIN PAD not supported ");
#endif
}
if (save_current) {
rv = iasecc_select_file(card, &save_current->path, NULL);
LOG_TEST_RET(ctx, rv, "Cannot return to saved PATH");
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_pin_cmd(struct sc_card *card, struct sc_pin_cmd_data *data, int *tries_left)
{
struct sc_context *ctx = card->ctx;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(ctx, "iasecc_pin_cmd() cmd 0x%X, PIN type 0x%X, PIN reference %i, PIN-1 %p:%i, PIN-2 %p:%i",
data->cmd, data->pin_type, data->pin_reference,
data->pin1.data, data->pin1.len, data->pin2.data, data->pin2.len);
switch (data->cmd) {
case SC_PIN_CMD_VERIFY:
rv = iasecc_pin_verify(card, data->pin_type, data->pin_reference, data->pin1.data, data->pin1.len, tries_left);
break;
case SC_PIN_CMD_CHANGE:
if (data->pin_type == SC_AC_AUT)
rv = iasecc_keyset_change(card, data, tries_left);
else
rv = iasecc_pin_change(card, data, tries_left);
break;
case SC_PIN_CMD_UNBLOCK:
rv = iasecc_pin_reset(card, data, tries_left);
break;
case SC_PIN_CMD_GET_INFO:
rv = iasecc_pin_get_policy(card, data);
break;
default:
sc_log(ctx, "Other pin commands not supported yet: 0x%X", data->cmd);
rv = SC_ERROR_NOT_SUPPORTED;
}
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_get_serialnr(struct sc_card *card, struct sc_serial_number *serial)
{
struct sc_context *ctx = card->ctx;
struct sc_iin *iin = &card->serialnr.iin;
struct sc_apdu apdu;
unsigned char rbuf[0xC0];
size_t ii, offs;
int rv;
LOG_FUNC_CALLED(ctx);
if (card->serialnr.len)
goto end;
memset(&card->serialnr, 0, sizeof(card->serialnr));
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0xB0, 0x80 | IASECC_SFI_EF_SN, 0);
apdu.le = sizeof(rbuf);
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "Get 'serial number' data failed");
if (rbuf[0] != ISO7812_PAN_SN_TAG)
LOG_TEST_RET(ctx, SC_ERROR_UNKNOWN_DATA_RECEIVED, "serial number parse error");
iin->mii = (rbuf[2] >> 4) & 0x0F;
iin->country = 0;
for (ii=5; ii<8; ii++) {
iin->country *= 10;
iin->country += (rbuf[ii/2] >> ((ii & 0x01) ? 0 : 4)) & 0x0F;
}
iin->issuer_id = 0;
for (ii=8; ii<10; ii++) {
iin->issuer_id *= 10;
iin->issuer_id += (rbuf[ii/2] >> (ii & 0x01 ? 0 : 4)) & 0x0F;
}
offs = rbuf[1] > 8 ? rbuf[1] - 8 : 0;
if (card->type == SC_CARD_TYPE_IASECC_SAGEM) {
/* 5A 0A 92 50 00 20 10 10 25 00 01 3F */
/* 00 02 01 01 02 50 00 13 */
for (ii=0; (ii < rbuf[1] - offs) && (ii + offs + 2 < sizeof(rbuf)); ii++)
*(card->serialnr.value + ii) = ((rbuf[ii + offs + 1] & 0x0F) << 4)
+ ((rbuf[ii + offs + 2] & 0xF0) >> 4) ;
card->serialnr.len = ii;
}
else {
for (ii=0; ii < rbuf[1] - offs; ii++)
*(card->serialnr.value + ii) = rbuf[ii + offs + 2];
card->serialnr.len = ii;
}
do {
char txt[0x200];
for (ii=0;ii<card->serialnr.len;ii++)
sprintf(txt + ii*2, "%02X", *(card->serialnr.value + ii));
sc_log(ctx, "serial number '%s'; mii %i; country %i; issuer_id %li", txt, iin->mii, iin->country, iin->issuer_id);
} while(0);
end:
if (serial)
memcpy(serial, &card->serialnr, sizeof(*serial));
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_sdo_create(struct sc_card *card, struct iasecc_sdo *sdo)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char *data = NULL, sdo_class = sdo->sdo_class;
struct iasecc_sdo_update update;
struct iasecc_extended_tlv *field = NULL;
int rv = SC_ERROR_NOT_SUPPORTED, data_len;
LOG_FUNC_CALLED(ctx);
if (sdo->magic != SC_CARDCTL_IASECC_SDO_MAGIC)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO data");
sc_log(ctx, "iasecc_sdo_create(card:%p) %02X%02X%02X", card,
IASECC_SDO_TAG_HEADER, sdo->sdo_class | 0x80, sdo->sdo_ref);
data_len = iasecc_sdo_encode_create(ctx, sdo, &data);
LOG_TEST_RET(ctx, data_len, "iasecc_sdo_create() cannot encode SDO create data");
sc_log(ctx, "iasecc_sdo_create() create data(%i):%s", data_len, sc_dump_hex(data, data_len));
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF);
apdu.data = data;
apdu.datalen = data_len;
apdu.lc = data_len;
apdu.flags |= SC_APDU_FLAGS_CHAINING;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "iasecc_sdo_create() SDO put data error");
memset(&update, 0, sizeof(update));
update.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA;
update.sdo_class = sdo->sdo_class;
update.sdo_ref = sdo->sdo_ref;
if (sdo_class == IASECC_SDO_CLASS_RSA_PRIVATE) {
update.fields[0] = sdo->data.prv_key.compulsory;
update.fields[0].parent_tag = IASECC_SDO_PRVKEY_TAG;
field = &sdo->data.prv_key.compulsory;
}
else if (sdo_class == IASECC_SDO_CLASS_RSA_PUBLIC) {
update.fields[0] = sdo->data.pub_key.compulsory;
update.fields[0].parent_tag = IASECC_SDO_PUBKEY_TAG;
field = &sdo->data.pub_key.compulsory;
}
else if (sdo_class == IASECC_SDO_CLASS_KEYSET) {
update.fields[0] = sdo->data.keyset.compulsory;
update.fields[0].parent_tag = IASECC_SDO_KEYSET_TAG;
field = &sdo->data.keyset.compulsory;
}
if (update.fields[0].value && !update.fields[0].on_card) {
rv = iasecc_sdo_put_data(card, &update);
LOG_TEST_RET(ctx, rv, "failed to update 'Compulsory usage' data");
if (field)
field->on_card = 1;
}
free(data);
LOG_FUNC_RETURN(ctx, rv);
}
/* Oberthur's specific */
static int
iasecc_sdo_delete(struct sc_card *card, struct iasecc_sdo *sdo)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char data[6] = {
0x70, 0x04, 0xBF, 0xFF, 0xFF, 0x00
};
int rv;
LOG_FUNC_CALLED(ctx);
if (sdo->magic != SC_CARDCTL_IASECC_SDO_MAGIC)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO data");
data[2] = IASECC_SDO_TAG_HEADER;
data[3] = sdo->sdo_class | 0x80;
data[4] = sdo->sdo_ref;
sc_log(ctx, "delete SDO %02X%02X%02X", data[2], data[3], data[4]);
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF);
apdu.data = data;
apdu.datalen = sizeof(data);
apdu.lc = sizeof(data);
apdu.flags |= SC_APDU_FLAGS_CHAINING;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "delete SDO error");
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_sdo_put_data(struct sc_card *card, struct iasecc_sdo_update *update)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
int ii, rv;
LOG_FUNC_CALLED(ctx);
if (update->magic != SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Invalid SDO update data");
for(ii=0; update->fields[ii].tag && ii < IASECC_SDO_TAGS_UPDATE_MAX; ii++) {
unsigned char *encoded = NULL;
int encoded_len;
encoded_len = iasecc_sdo_encode_update_field(ctx, update->sdo_class, update->sdo_ref,
&update->fields[ii], &encoded);
sc_log(ctx, "iasecc_sdo_put_data() encode[%i]; tag %X; encoded_len %i", ii, update->fields[ii].tag, encoded_len);
LOG_TEST_RET(ctx, encoded_len, "Cannot encode update data");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0xDB, 0x3F, 0xFF);
apdu.data = encoded;
apdu.datalen = encoded_len;
apdu.lc = encoded_len;
apdu.flags |= SC_APDU_FLAGS_CHAINING;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "SDO put data error");
free(encoded);
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_sdo_key_rsa_put_data(struct sc_card *card, struct iasecc_sdo_rsa_update *update)
{
struct sc_context *ctx = card->ctx;
unsigned char scb;
int rv;
LOG_FUNC_CALLED(ctx);
if (update->sdo_prv_key) {
sc_log(ctx, "encode private rsa in %p", &update->update_prv);
rv = iasecc_sdo_encode_rsa_update(card->ctx, update->sdo_prv_key, update->p15_rsa, &update->update_prv);
LOG_TEST_RET(ctx, rv, "failed to encode update of RSA private key");
}
if (update->sdo_pub_key) {
sc_log(ctx, "encode public rsa in %p", &update->update_pub);
if (card->type == SC_CARD_TYPE_IASECC_SAGEM) {
if (update->sdo_pub_key->data.pub_key.cha.value) {
free(update->sdo_pub_key->data.pub_key.cha.value);
memset(&update->sdo_pub_key->data.pub_key.cha, 0, sizeof(update->sdo_pub_key->data.pub_key.cha));
}
}
rv = iasecc_sdo_encode_rsa_update(card->ctx, update->sdo_pub_key, update->p15_rsa, &update->update_pub);
LOG_TEST_RET(ctx, rv, "failed to encode update of RSA public key");
}
if (update->sdo_prv_key) {
sc_log(ctx, "reference of the private key to store: %X", update->sdo_prv_key->sdo_ref);
if (update->sdo_prv_key->docp.acls_contact.size == 0)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "extremely strange ... there are no ACLs");
scb = update->sdo_prv_key->docp.scbs[IASECC_ACLS_RSAKEY_PUT_DATA];
sc_log(ctx, "'UPDATE PRIVATE RSA' scb 0x%X", scb);
do {
unsigned all_conditions = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0;
if ((scb & IASECC_SCB_METHOD_USER_AUTH) && !all_conditions)
break;
if (scb & IASECC_SCB_METHOD_EXT_AUTH)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Not yet");
if (scb & IASECC_SCB_METHOD_SM) {
#ifdef ENABLE_SM
rv = iasecc_sm_rsa_update(card, scb & IASECC_SCB_METHOD_MASK_REF, update);
LOG_FUNC_RETURN(ctx, rv);
#else
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "built without support of Secure-Messaging");
#endif
}
} while(0);
rv = iasecc_sdo_put_data(card, &update->update_prv);
LOG_TEST_RET(ctx, rv, "failed to update of RSA private key");
}
if (update->sdo_pub_key) {
sc_log(ctx, "reference of the public key to store: %X", update->sdo_pub_key->sdo_ref);
rv = iasecc_sdo_put_data(card, &update->update_pub);
LOG_TEST_RET(ctx, rv, "failed to update of RSA public key");
}
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_sdo_tag_from_class(unsigned sdo_class)
{
switch (sdo_class & ~IASECC_OBJECT_REF_LOCAL) {
case IASECC_SDO_CLASS_CHV:
return IASECC_SDO_CHV_TAG;
case IASECC_SDO_CLASS_RSA_PRIVATE:
return IASECC_SDO_PRVKEY_TAG;
case IASECC_SDO_CLASS_RSA_PUBLIC:
return IASECC_SDO_PUBKEY_TAG;
case IASECC_SDO_CLASS_SE:
return IASECC_SDO_CLASS_SE;
case IASECC_SDO_CLASS_KEYSET:
return IASECC_SDO_KEYSET_TAG;
}
return -1;
}
static int
iasecc_sdo_get_tagged_data(struct sc_card *card, int sdo_tag, struct iasecc_sdo *sdo)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char sbuf[0x100];
size_t offs = sizeof(sbuf) - 1;
unsigned char rbuf[0x400];
int rv;
LOG_FUNC_CALLED(ctx);
sbuf[offs--] = 0x80;
sbuf[offs--] = sdo_tag & 0xFF;
if ((sdo_tag >> 8) & 0xFF)
sbuf[offs--] = (sdo_tag >> 8) & 0xFF;
sbuf[offs] = sizeof(sbuf) - offs - 1;
offs--;
sbuf[offs--] = sdo->sdo_ref & 0x9F;
sbuf[offs--] = sdo->sdo_class | IASECC_OBJECT_REF_LOCAL;
sbuf[offs--] = IASECC_SDO_TAG_HEADER;
sbuf[offs] = sizeof(sbuf) - offs - 1;
offs--;
sbuf[offs--] = IASECC_SDO_TEMPLATE_TAG;
sbuf[offs] = sizeof(sbuf) - offs - 1;
offs--;
sbuf[offs] = 0x4D;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0xCB, 0x3F, 0xFF);
apdu.data = sbuf + offs;
apdu.datalen = sizeof(sbuf) - offs;
apdu.lc = sizeof(sbuf) - offs;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0x100;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "SDO get data error");
rv = iasecc_sdo_parse(card, apdu.resp, apdu.resplen, sdo);
LOG_TEST_RET(ctx, rv, "cannot parse SDO data");
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_sdo_get_data(struct sc_card *card, struct iasecc_sdo *sdo)
{
struct sc_context *ctx = card->ctx;
int rv, sdo_tag;
LOG_FUNC_CALLED(ctx);
sdo_tag = iasecc_sdo_tag_from_class(sdo->sdo_class);
rv = iasecc_sdo_get_tagged_data(card, sdo_tag, sdo);
/* When there is no public data 'GET DATA' returns error */
if (rv != SC_ERROR_INCORRECT_PARAMETERS)
LOG_TEST_RET(ctx, rv, "cannot parse ECC SDO data");
rv = iasecc_sdo_get_tagged_data(card, IASECC_DOCP_TAG, sdo);
LOG_TEST_RET(ctx, rv, "cannot parse ECC DOCP data");
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_sdo_generate(struct sc_card *card, struct iasecc_sdo *sdo)
{
struct sc_context *ctx = card->ctx;
struct iasecc_sdo_update update_pubkey;
struct sc_apdu apdu;
unsigned char scb, sbuf[5], rbuf[0x400], exponent[3] = {0x01, 0x00, 0x01};
int offs = 0, rv = SC_ERROR_NOT_SUPPORTED;
LOG_FUNC_CALLED(ctx);
if (sdo->sdo_class != IASECC_SDO_CLASS_RSA_PRIVATE)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "For a moment, only RSA_PRIVATE class can be accepted for the SDO generation");
if (sdo->docp.acls_contact.size == 0)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_DATA, "Bewildered ... there are no ACLs");
scb = sdo->docp.scbs[IASECC_ACLS_RSAKEY_GENERATE];
sc_log(ctx, "'generate RSA key' SCB 0x%X", scb);
do {
unsigned all_conditions = scb & IASECC_SCB_METHOD_NEED_ALL ? 1 : 0;
if (scb & IASECC_SCB_METHOD_USER_AUTH)
if (!all_conditions)
break;
if (scb & IASECC_SCB_METHOD_EXT_AUTH)
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Not yet");
if (scb & IASECC_SCB_METHOD_SM) {
rv = iasecc_sm_rsa_generate(card, scb & IASECC_SCB_METHOD_MASK_REF, sdo);
LOG_FUNC_RETURN(ctx, rv);
}
} while(0);
memset(&update_pubkey, 0, sizeof(update_pubkey));
update_pubkey.magic = SC_CARDCTL_IASECC_SDO_MAGIC_PUT_DATA;
update_pubkey.sdo_class = IASECC_SDO_CLASS_RSA_PUBLIC;
update_pubkey.sdo_ref = sdo->sdo_ref;
update_pubkey.fields[0].parent_tag = IASECC_SDO_PUBKEY_TAG;
update_pubkey.fields[0].tag = IASECC_SDO_PUBKEY_TAG_E;
update_pubkey.fields[0].value = exponent;
update_pubkey.fields[0].size = sizeof(exponent);
rv = iasecc_sdo_put_data(card, &update_pubkey);
LOG_TEST_RET(ctx, rv, "iasecc_sdo_generate() update SDO public key failed");
offs = 0;
sbuf[offs++] = IASECC_SDO_TEMPLATE_TAG;
sbuf[offs++] = 0x03;
sbuf[offs++] = IASECC_SDO_TAG_HEADER;
sbuf[offs++] = IASECC_SDO_CLASS_RSA_PRIVATE | IASECC_OBJECT_REF_LOCAL;
sbuf[offs++] = sdo->sdo_ref & ~IASECC_OBJECT_REF_LOCAL;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x47, 0x00, 0x00);
apdu.data = sbuf;
apdu.datalen = offs;
apdu.lc = offs;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0x100;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "SDO get data error");
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_get_chv_reference_from_se(struct sc_card *card, int *se_reference)
{
struct sc_context *ctx = card->ctx;
struct iasecc_se_info se;
struct sc_crt crt;
int rv;
LOG_FUNC_CALLED(ctx);
if (!se_reference)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid arguments");
memset(&se, 0, sizeof(se));
se.reference = *se_reference;
rv = iasecc_se_get_info(card, &se);
LOG_TEST_RET(ctx, rv, "get SE info error");
memset(&crt, 0, sizeof(crt));
crt.tag = IASECC_CRT_TAG_AT;
crt.usage = IASECC_UQB_AT_USER_PASSWORD;
rv = iasecc_se_get_crt(card, &se, &crt);
LOG_TEST_RET(ctx, rv, "Cannot get 'USER PASSWORD' authentication template");
sc_file_free(se.df);
LOG_FUNC_RETURN(ctx, crt.refs[0]);
}
static int
iasecc_card_ctl(struct sc_card *card, unsigned long cmd, void *ptr)
{
struct sc_context *ctx = card->ctx;
struct iasecc_sdo *sdo = (struct iasecc_sdo *) ptr;
switch (cmd) {
case SC_CARDCTL_GET_SERIALNR:
return iasecc_get_serialnr(card, (struct sc_serial_number *)ptr);
case SC_CARDCTL_IASECC_SDO_CREATE:
sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_CREATE: sdo_class %X", sdo->sdo_class);
return iasecc_sdo_create(card, (struct iasecc_sdo *) ptr);
case SC_CARDCTL_IASECC_SDO_DELETE:
sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_DELETE: sdo_class %X", sdo->sdo_class);
return iasecc_sdo_delete(card, (struct iasecc_sdo *) ptr);
case SC_CARDCTL_IASECC_SDO_PUT_DATA:
sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_PUT_DATA: sdo_class %X", sdo->sdo_class);
return iasecc_sdo_put_data(card, (struct iasecc_sdo_update *) ptr);
case SC_CARDCTL_IASECC_SDO_KEY_RSA_PUT_DATA:
sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_KEY_RSA_PUT_DATA");
return iasecc_sdo_key_rsa_put_data(card, (struct iasecc_sdo_rsa_update *) ptr);
case SC_CARDCTL_IASECC_SDO_GET_DATA:
sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_GET_DATA: sdo_class %X", sdo->sdo_class);
return iasecc_sdo_get_data(card, (struct iasecc_sdo *) ptr);
case SC_CARDCTL_IASECC_SDO_GENERATE:
sc_log(ctx, "CMD SC_CARDCTL_IASECC_SDO_GET_DATA: sdo_class %X", sdo->sdo_class);
return iasecc_sdo_generate(card, (struct iasecc_sdo *) ptr);
case SC_CARDCTL_GET_SE_INFO:
sc_log(ctx, "CMD SC_CARDCTL_GET_SE_INFO: sdo_class %X", sdo->sdo_class);
return iasecc_se_get_info(card, (struct iasecc_se_info *) ptr);
case SC_CARDCTL_GET_CHV_REFERENCE_IN_SE:
sc_log(ctx, "CMD SC_CARDCTL_GET_CHV_REFERENCE_IN_SE");
return iasecc_get_chv_reference_from_se(card, (int *)ptr);
case SC_CARDCTL_IASECC_GET_FREE_KEY_REFERENCE:
sc_log(ctx, "CMD SC_CARDCTL_IASECC_GET_FREE_KEY_REFERENCE");
return iasecc_get_free_reference(card, (struct iasecc_ctl_get_free_reference *)ptr);
}
return SC_ERROR_NOT_SUPPORTED;
}
static int
iasecc_decipher(struct sc_card *card,
const unsigned char *in, size_t in_len,
unsigned char *out, size_t out_len)
{
struct sc_context *ctx = card->ctx;
struct sc_apdu apdu;
unsigned char sbuf[0x200];
unsigned char resp[SC_MAX_APDU_BUFFER_SIZE];
size_t offs;
int rv;
LOG_FUNC_CALLED(ctx);
sc_log(card->ctx,
"crgram_len %"SC_FORMAT_LEN_SIZE_T"u; outlen %"SC_FORMAT_LEN_SIZE_T"u",
in_len, out_len);
if (!out || !out_len || in_len > SC_MAX_APDU_BUFFER_SIZE)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
offs = 0;
sbuf[offs++] = 0x81;
memcpy(sbuf + offs, in, in_len);
offs += in_len;
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x2A, 0x80, 0x86);
apdu.flags |= SC_APDU_FLAGS_CHAINING;
apdu.data = sbuf;
apdu.datalen = offs;
apdu.lc = offs;
apdu.resp = resp;
apdu.resplen = sizeof(resp);
apdu.le = 256;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "Card returned error");
if (out_len > apdu.resplen)
out_len = apdu.resplen;
memcpy(out, apdu.resp, out_len);
rv = out_len;
LOG_FUNC_RETURN(ctx, rv);
}
static int
iasecc_qsign_data_sha1(struct sc_context *ctx, const unsigned char *in, size_t in_len,
struct iasecc_qsign_data *out)
{
SHA_CTX sha;
SHA_LONG pre_hash_Nl, *hh[5] = {
&sha.h0, &sha.h1, &sha.h2, &sha.h3, &sha.h4
};
int jj, ii;
int hh_size = sizeof(SHA_LONG), hh_num = SHA_DIGEST_LENGTH / sizeof(SHA_LONG);
LOG_FUNC_CALLED(ctx);
if (!in || !in_len || !out)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
sc_log(ctx,
"sc_pkcs15_get_qsign_data() input data length %"SC_FORMAT_LEN_SIZE_T"u",
in_len);
memset(out, 0, sizeof(struct iasecc_qsign_data));
SHA1_Init(&sha);
SHA1_Update(&sha, in, in_len);
for (jj=0; jj<hh_num; jj++)
for(ii=0; ii<hh_size; ii++)
out->pre_hash[jj*hh_size + ii] = ((*hh[jj] >> 8*(hh_size-1-ii)) & 0xFF);
out->pre_hash_size = SHA_DIGEST_LENGTH;
sc_log(ctx, "Pre SHA1:%s", sc_dump_hex(out->pre_hash, out->pre_hash_size));
pre_hash_Nl = sha.Nl - (sha.Nl % (sizeof(sha.data) * 8));
for (ii=0; ii<hh_size; ii++) {
out->counter[ii] = (sha.Nh >> 8*(hh_size-1-ii)) &0xFF;
out->counter[hh_size+ii] = (pre_hash_Nl >> 8*(hh_size-1-ii)) &0xFF;
}
for (ii=0, out->counter_long=0; ii<(int)sizeof(out->counter); ii++)
out->counter_long = out->counter_long*0x100 + out->counter[ii];
sc_log(ctx, "Pre counter(%li):%s", out->counter_long, sc_dump_hex(out->counter, sizeof(out->counter)));
if (sha.num) {
memcpy(out->last_block, in + in_len - sha.num, sha.num);
out->last_block_size = sha.num;
sc_log(ctx, "Last block(%"SC_FORMAT_LEN_SIZE_T"u):%s",
out->last_block_size,
sc_dump_hex(out->last_block, out->last_block_size));
}
SHA1_Final(out->hash, &sha);
out->hash_size = SHA_DIGEST_LENGTH;
sc_log(ctx, "Expected digest %s\n", sc_dump_hex(out->hash, out->hash_size));
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
#if OPENSSL_VERSION_NUMBER >= 0x00908000L
static int
iasecc_qsign_data_sha256(struct sc_context *ctx, const unsigned char *in, size_t in_len,
struct iasecc_qsign_data *out)
{
SHA256_CTX sha256;
SHA_LONG pre_hash_Nl;
int jj, ii;
int hh_size = sizeof(SHA_LONG), hh_num = SHA256_DIGEST_LENGTH / sizeof(SHA_LONG);
LOG_FUNC_CALLED(ctx);
if (!in || !in_len || !out)
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
sc_log(ctx,
"sc_pkcs15_get_qsign_data() input data length %"SC_FORMAT_LEN_SIZE_T"u",
in_len);
memset(out, 0, sizeof(struct iasecc_qsign_data));
SHA256_Init(&sha256);
SHA256_Update(&sha256, in, in_len);
for (jj=0; jj<hh_num; jj++)
for(ii=0; ii<hh_size; ii++)
out->pre_hash[jj*hh_size + ii] = ((sha256.h[jj] >> 8*(hh_size-1-ii)) & 0xFF);
out->pre_hash_size = SHA256_DIGEST_LENGTH;
sc_log(ctx, "Pre hash:%s", sc_dump_hex(out->pre_hash, out->pre_hash_size));
pre_hash_Nl = sha256.Nl - (sha256.Nl % (sizeof(sha256.data) * 8));
for (ii=0; ii<hh_size; ii++) {
out->counter[ii] = (sha256.Nh >> 8*(hh_size-1-ii)) &0xFF;
out->counter[hh_size+ii] = (pre_hash_Nl >> 8*(hh_size-1-ii)) &0xFF;
}
for (ii=0, out->counter_long=0; ii<(int)sizeof(out->counter); ii++)
out->counter_long = out->counter_long*0x100 + out->counter[ii];
sc_log(ctx, "Pre counter(%li):%s", out->counter_long, sc_dump_hex(out->counter, sizeof(out->counter)));
if (sha256.num) {
memcpy(out->last_block, in + in_len - sha256.num, sha256.num);
out->last_block_size = sha256.num;
sc_log(ctx, "Last block(%"SC_FORMAT_LEN_SIZE_T"u):%s",
out->last_block_size,
sc_dump_hex(out->last_block, out->last_block_size));
}
SHA256_Final(out->hash, &sha256);
out->hash_size = SHA256_DIGEST_LENGTH;
sc_log(ctx, "Expected digest %s\n", sc_dump_hex(out->hash, out->hash_size));
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
#endif
static int
iasecc_compute_signature_dst(struct sc_card *card,
const unsigned char *in, size_t in_len, unsigned char *out, size_t out_len)
{
struct sc_context *ctx = card->ctx;
struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;
struct sc_security_env *env = &prv->security_env;
struct iasecc_qsign_data qsign_data;
struct sc_apdu apdu;
size_t offs = 0, hash_len = 0;
unsigned char sbuf[SC_MAX_APDU_BUFFER_SIZE];
unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE];
int rv = SC_SUCCESS;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"iasecc_compute_signature_dst() input length %"SC_FORMAT_LEN_SIZE_T"u",
in_len);
if (env->operation != SC_SEC_OPERATION_SIGN)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "It's not SC_SEC_OPERATION_SIGN");
else if (!(prv->key_size & 0x1E0) || (prv->key_size & ~0x1E0))
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Invalid key size for SC_SEC_OPERATION_SIGN");
memset(&qsign_data, 0, sizeof(qsign_data));
if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA1) {
rv = iasecc_qsign_data_sha1(card->ctx, in, in_len, &qsign_data);
}
else if (env->algorithm_flags & SC_ALGORITHM_RSA_HASH_SHA256) {
#if OPENSSL_VERSION_NUMBER >= 0x00908000L
rv = iasecc_qsign_data_sha256(card->ctx, in, in_len, &qsign_data);
#else
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "SHA256 is not supported by OpenSSL previous to v0.9.8");
#endif
}
else
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Need RSA_HASH_SHA1 or RSA_HASH_SHA256 algorithm");
LOG_TEST_RET(ctx, rv, "Cannot get QSign data");
sc_log(ctx,
"iasecc_compute_signature_dst() hash_len %"SC_FORMAT_LEN_SIZE_T"u; key_size %"SC_FORMAT_LEN_SIZE_T"u",
hash_len, prv->key_size);
memset(sbuf, 0, sizeof(sbuf));
sbuf[offs++] = 0x90;
if (qsign_data.counter_long) {
sbuf[offs++] = qsign_data.hash_size + 8;
memcpy(sbuf + offs, qsign_data.pre_hash, qsign_data.pre_hash_size);
offs += qsign_data.pre_hash_size;
memcpy(sbuf + offs, qsign_data.counter, sizeof(qsign_data.counter));
offs += sizeof(qsign_data.counter);
}
else {
sbuf[offs++] = 0;
}
sbuf[offs++] = 0x80;
sbuf[offs++] = qsign_data.last_block_size;
memcpy(sbuf + offs, qsign_data.last_block, qsign_data.last_block_size);
offs += qsign_data.last_block_size;
sc_log(ctx,
"iasecc_compute_signature_dst() offs %"SC_FORMAT_LEN_SIZE_T"u; OP(meth:%X,ref:%X)",
offs, prv->op_method, prv->op_ref);
if (prv->op_method == SC_AC_SCB && (prv->op_ref & IASECC_SCB_METHOD_SM))
LOG_TEST_RET(ctx, SC_ERROR_NOT_SUPPORTED, "Not yet");
sc_format_apdu(card, &apdu, SC_APDU_CASE_3_SHORT, 0x2A, 0x90, 0xA0);
apdu.data = sbuf;
apdu.datalen = offs;
apdu.lc = offs;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "Compute signature failed");
sc_log(ctx, "iasecc_compute_signature_dst() partial hash OK");
sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, 0x2A, 0x9E, 0x9A);
apdu.resp = rbuf;
apdu.resplen = prv->key_size;
apdu.le = prv->key_size;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "Compute signature failed");
sc_log(ctx,
"iasecc_compute_signature_dst() DST resplen %"SC_FORMAT_LEN_SIZE_T"u",
apdu.resplen);
if (apdu.resplen > out_len)
LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Result buffer too small for the DST signature");
memcpy(out, apdu.resp, apdu.resplen);
LOG_FUNC_RETURN(ctx, apdu.resplen);
}
static int
iasecc_compute_signature_at(struct sc_card *card,
const unsigned char *in, size_t in_len, unsigned char *out, size_t out_len)
{
struct sc_context *ctx = card->ctx;
struct iasecc_private_data *prv = (struct iasecc_private_data *) card->drv_data;
struct sc_security_env *env = &prv->security_env;
struct sc_apdu apdu;
size_t offs = 0, sz = 0;
unsigned char rbuf[SC_MAX_APDU_BUFFER_SIZE];
int rv;
LOG_FUNC_CALLED(ctx);
if (env->operation != SC_SEC_OPERATION_AUTHENTICATE)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "It's not SC_SEC_OPERATION_AUTHENTICATE");
sc_format_apdu(card, &apdu, SC_APDU_CASE_4_SHORT, 0x88, 0x00, 0x00);
apdu.datalen = in_len;
apdu.data = in;
apdu.lc = in_len;
apdu.resp = rbuf;
apdu.resplen = sizeof(rbuf);
apdu.le = 0x100;
rv = sc_transmit_apdu(card, &apdu);
LOG_TEST_RET(ctx, rv, "APDU transmit failed");
rv = sc_check_sw(card, apdu.sw1, apdu.sw2);
LOG_TEST_RET(ctx, rv, "Compute signature failed");
do {
if (offs + apdu.resplen > out_len)
LOG_TEST_RET(ctx, SC_ERROR_BUFFER_TOO_SMALL, "Buffer too small to return signature");
memcpy(out + offs, rbuf, apdu.resplen);
offs += apdu.resplen;
if (apdu.sw1 == 0x90 && apdu.sw2 == 0x00)
break;
if (apdu.sw1 == 0x61) {
sz = apdu.sw2 == 0x00 ? 0x100 : apdu.sw2;
rv = iso_ops->get_response(card, &sz, rbuf);
LOG_TEST_RET(ctx, rv, "Get response error");
apdu.resplen = rv;
}
else {
LOG_TEST_RET(ctx, SC_ERROR_INTERNAL, "Impossible error: SW1 is not 0x90 neither 0x61");
}
} while(rv > 0);
LOG_FUNC_RETURN(ctx, offs);
}
static int
iasecc_compute_signature(struct sc_card *card,
const unsigned char *in, size_t in_len, unsigned char *out, size_t out_len)
{
struct sc_context *ctx;
struct iasecc_private_data *prv;
struct sc_security_env *env;
if (!card || !in || !out)
return SC_ERROR_INVALID_ARGUMENTS;
ctx = card->ctx;
prv = (struct iasecc_private_data *) card->drv_data;
env = &prv->security_env;
LOG_FUNC_CALLED(ctx);
sc_log(ctx,
"inlen %"SC_FORMAT_LEN_SIZE_T"u, outlen %"SC_FORMAT_LEN_SIZE_T"u",
in_len, out_len);
if (env->operation == SC_SEC_OPERATION_SIGN)
return iasecc_compute_signature_dst(card, in, in_len, out, out_len);
else if (env->operation == SC_SEC_OPERATION_AUTHENTICATE)
return iasecc_compute_signature_at(card, in, in_len, out, out_len);
LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
}
static int
iasecc_read_public_key(struct sc_card *card, unsigned type,
struct sc_path *key_path, unsigned ref, unsigned size,
unsigned char **out, size_t *out_len)
{
struct sc_context *ctx = card->ctx;
struct iasecc_sdo sdo;
struct sc_pkcs15_bignum bn[2];
struct sc_pkcs15_pubkey_rsa rsa_key;
int rv;
LOG_FUNC_CALLED(ctx);
if (type != SC_ALGORITHM_RSA)
LOG_FUNC_RETURN(ctx, SC_ERROR_NOT_SUPPORTED);
sc_log(ctx, "read public kay(ref:%i;size:%i)", ref, size);
memset(&sdo, 0, sizeof(sdo));
sdo.sdo_class = IASECC_SDO_CLASS_RSA_PUBLIC;
sdo.sdo_ref = ref & ~IASECC_OBJECT_REF_LOCAL;
rv = iasecc_sdo_get_data(card, &sdo);
LOG_TEST_RET(ctx, rv, "failed to read public key: cannot get RSA SDO data");
if (out)
*out = NULL;
if (out_len)
*out_len = 0;
bn[0].data = (unsigned char *) malloc(sdo.data.pub_key.n.size);
if (!bn[0].data)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "failed to read public key: cannot allocate modulus");
bn[0].len = sdo.data.pub_key.n.size;
memcpy(bn[0].data, sdo.data.pub_key.n.value, sdo.data.pub_key.n.size);
bn[1].data = (unsigned char *) malloc(sdo.data.pub_key.e.size);
if (!bn[1].data)
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "failed to read public key: cannot allocate exponent");
bn[1].len = sdo.data.pub_key.e.size;
memcpy(bn[1].data, sdo.data.pub_key.e.value, sdo.data.pub_key.e.size);
rsa_key.modulus = bn[0];
rsa_key.exponent = bn[1];
rv = sc_pkcs15_encode_pubkey_rsa(ctx, &rsa_key, out, out_len);
LOG_TEST_RET(ctx, rv, "failed to read public key: cannot encode RSA public key");
if (out && out_len)
sc_log(ctx, "encoded public key: %s", sc_dump_hex(*out, *out_len));
if (bn[0].data)
free(bn[0].data);
if (bn[1].data)
free(bn[1].data);
iasecc_sdo_free_fields(card, &sdo);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static int
iasecc_get_free_reference(struct sc_card *card, struct iasecc_ctl_get_free_reference *ctl_data)
{
struct sc_context *ctx = card->ctx;
struct iasecc_sdo *sdo = NULL;
int idx, rv;
LOG_FUNC_CALLED(ctx);
if ((ctl_data->key_size % 0x40) || ctl_data->index < 1 || (ctl_data->index > IASECC_OBJECT_REF_MAX))
LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ARGUMENTS);
sc_log(ctx, "get reference for key(index:%i,usage:%X,access:%X)", ctl_data->index, ctl_data->usage, ctl_data->access);
/* TODO: when looking for the slot for the signature keys, check also PSO_SIGNATURE ACL */
for (idx = ctl_data->index; idx <= IASECC_OBJECT_REF_MAX; idx++) {
unsigned char sdo_tag[3] = {
IASECC_SDO_TAG_HEADER, IASECC_OBJECT_REF_LOCAL | IASECC_SDO_CLASS_RSA_PRIVATE, idx
};
size_t sz;
if (sdo)
iasecc_sdo_free(card, sdo);
rv = iasecc_sdo_allocate_and_parse(card, sdo_tag, 3, &sdo);
LOG_TEST_RET(ctx, rv, "cannot parse SDO data");
rv = iasecc_sdo_get_data(card, sdo);
if (rv == SC_ERROR_DATA_OBJECT_NOT_FOUND) {
iasecc_sdo_free(card, sdo);
sc_log(ctx, "found empty key slot %i", idx);
break;
}
else
LOG_TEST_RET(ctx, rv, "get new key reference failed");
sz = *(sdo->docp.size.value + 0) * 0x100 + *(sdo->docp.size.value + 1);
sc_log(ctx,
"SDO(idx:%i) size %"SC_FORMAT_LEN_SIZE_T"u; key_size %"SC_FORMAT_LEN_SIZE_T"u",
idx, sz, ctl_data->key_size);
if (sz != ctl_data->key_size / 8) {
sc_log(ctx,
"key index %i ignored: different key sizes %"SC_FORMAT_LEN_SIZE_T"u/%"SC_FORMAT_LEN_SIZE_T"u",
idx, sz, ctl_data->key_size / 8);
continue;
}
if (sdo->docp.non_repudiation.value) {
sc_log(ctx, "non repudiation flag %X", sdo->docp.non_repudiation.value[0]);
if ((ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && !(*sdo->docp.non_repudiation.value)) {
sc_log(ctx, "key index %i ignored: need non repudiation", idx);
continue;
}
if (!(ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && *sdo->docp.non_repudiation.value) {
sc_log(ctx, "key index %i ignored: don't need non-repudiation", idx);
continue;
}
}
if (ctl_data->access & SC_PKCS15_PRKEY_ACCESS_LOCAL) {
if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_GENERATE] == IASECC_SCB_NEVER) {
sc_log(ctx, "key index %i ignored: GENERATE KEY not allowed", idx);
continue;
}
}
else {
if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PUT_DATA] == IASECC_SCB_NEVER) {
sc_log(ctx, "key index %i ignored: PUT DATA not allowed", idx);
continue;
}
}
if ((ctl_data->usage & SC_PKCS15_PRKEY_USAGE_NONREPUDIATION) && (ctl_data->usage & SC_PKCS15_PRKEY_USAGE_SIGN)) {
if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PSO_SIGN] == IASECC_SCB_NEVER) {
sc_log(ctx, "key index %i ignored: PSO SIGN not allowed", idx);
continue;
}
}
else if (ctl_data->usage & SC_PKCS15_PRKEY_USAGE_SIGN) {
if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_INTERNAL_AUTH] == IASECC_SCB_NEVER) {
sc_log(ctx, "key index %i ignored: INTERNAL AUTHENTICATE not allowed", idx);
continue;
}
}
if (ctl_data->usage & (SC_PKCS15_PRKEY_USAGE_DECRYPT | SC_PKCS15_PRKEY_USAGE_UNWRAP)) {
if (sdo->docp.scbs[IASECC_ACLS_RSAKEY_PSO_DECIPHER] == IASECC_SCB_NEVER) {
sc_log(ctx, "key index %i ignored: PSO DECIPHER not allowed", idx);
continue;
}
}
break;
}
ctl_data->index = idx;
if (idx > IASECC_OBJECT_REF_MAX)
LOG_FUNC_RETURN(ctx, SC_ERROR_DATA_OBJECT_NOT_FOUND);
LOG_FUNC_RETURN(ctx, SC_SUCCESS);
}
static struct sc_card_driver *
sc_get_driver(void)
{
struct sc_card_driver *iso_drv = sc_get_iso7816_driver();
if (!iso_ops)
iso_ops = iso_drv->ops;
iasecc_ops = *iso_ops;
iasecc_ops.match_card = iasecc_match_card;
iasecc_ops.init = iasecc_init;
iasecc_ops.finish = iasecc_finish;
iasecc_ops.read_binary = iasecc_read_binary;
/* write_binary: ISO7816 implementation works */
/* update_binary: ISO7816 implementation works */
iasecc_ops.erase_binary = iasecc_erase_binary;
/* resize_binary */
/* read_record: Untested */
/* write_record: Untested */
/* append_record: Untested */
/* update_record: Untested */
iasecc_ops.select_file = iasecc_select_file;
/* get_response: Untested */
/* get_challenge: ISO7816 implementation works */
iasecc_ops.logout = iasecc_logout;
/* restore_security_env */
iasecc_ops.set_security_env = iasecc_set_security_env;
iasecc_ops.decipher = iasecc_decipher;
iasecc_ops.compute_signature = iasecc_compute_signature;
iasecc_ops.create_file = iasecc_create_file;
iasecc_ops.delete_file = iasecc_delete_file;
/* list_files */
iasecc_ops.check_sw = iasecc_check_sw;
iasecc_ops.card_ctl = iasecc_card_ctl;
iasecc_ops.process_fci = iasecc_process_fci;
/* construct_fci: Not needed */
iasecc_ops.pin_cmd = iasecc_pin_cmd;
/* get_data: Not implemented */
/* put_data: Not implemented */
/* delete_record: Not implemented */
iasecc_ops.read_public_key = iasecc_read_public_key;
return &iasecc_drv;
}
struct sc_card_driver *
sc_get_iasecc_driver(void)
{
return sc_get_driver();
}
#else
/* we need to define the functions below to export them */
#include "errors.h"
int
iasecc_se_get_info()
{
return SC_ERROR_NOT_SUPPORTED;
}
#endif /* ENABLE_OPENSSL */
| ./CrossVul/dataset_final_sorted/CWE-674/c/bad_350_0 |
crossvul-cpp_data_good_5309_0 | // This may look like C code, but it is really -*- C++ -*-
//
// Copyright Bob Friesenhahn, 1999, 2000, 2003
//
// Test STL appendImages function
//
#include <Magick++.h>
#include <string>
#include <iostream>
#include <list>
#include <vector>
using namespace std;
using namespace Magick;
int main( int /*argc*/, char ** argv)
{
// Initialize ImageMagick install location for Windows
InitializeMagick(*argv);
int failures=0;
try {
string srcdir("");
if(getenv("SRCDIR") != 0)
srcdir = getenv("SRCDIR");
//
// Test appendImages
//
list<Image> imageList;
readImages( &imageList, srcdir + "test_image_anim.miff" );
Image appended;
// Horizontal
appendImages( &appended, imageList.begin(), imageList.end() );
// appended.display();
if (( appended.signature() != "3a90bb0bb8f69f6788ab99e9e25598a0d6c5cdbbb797f77ad68011e0a8b1689d" ) &&
( appended.signature() != "c15fcd1e739b73638dc4e36837bdb53f7087359544664caf7b1763928129f3c7" ) &&
( appended.signature() != "229ff72f812e5f536245dc3b4502a0bc2ab2363f67c545863a85ab91ebfbfb83" ) &&
( appended.signature() != "b98c42c55fc4e661cb3684154256809c03c0c6b53da2738b6ce8066e1b6ddef0" ))
{
++failures;
cout << "Line: " << __LINE__
<< " Horizontal append failed, signature = "
<< appended.signature() << endl;
appended.write("appendImages_horizontal_out.miff");
// appended.display();
}
// Vertical
appendImages( &appended, imageList.begin(), imageList.end(), true );
if (( appended.signature() != "d73d25ccd6011936d08b6d0d89183b7a61790544c2195269aff4db2f782ffc08" ) &&
( appended.signature() != "f3590c183018757da798613a23505ab9600b35935988eee12f096cb6219f2bc3" ) &&
( appended.signature() != "11b97ba6ac1664aa1c2faed4c86195472ae9cce2ed75402d975bb4ffcf1de751" ) &&
( appended.signature() != "cae4815eeb3cb689e73b94d897a9957d3414d1d4f513e8b5e52579b05d164bfe" ))
{
++failures;
cout << "Line: " << __LINE__
<< " Vertical append failed, signature = "
<< appended.signature() << endl;
appended.write("appendImages_vertical_out.miff");
// appended.display();
}
}
catch( Exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
catch( exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
if ( failures )
{
cout << failures << " failures" << endl;
return 1;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-369/cpp/good_5309_0 |
crossvul-cpp_data_bad_5309_0 | // This may look like C code, but it is really -*- C++ -*-
//
// Copyright Bob Friesenhahn, 1999, 2000, 2003
//
// Test STL appendImages function
//
#include <Magick++.h>
#include <string>
#include <iostream>
#include <list>
#include <vector>
using namespace std;
using namespace Magick;
int main( int /*argc*/, char ** argv)
{
// Initialize ImageMagick install location for Windows
InitializeMagick(*argv);
int failures=0;
try {
string srcdir("");
if(getenv("SRCDIR") != 0)
srcdir = getenv("SRCDIR");
//
// Test appendImages
//
list<Image> imageList;
readImages( &imageList, srcdir + "test_image_anim.miff" );
Image appended;
// Horizontal
appendImages( &appended, imageList.begin(), imageList.end() );
// appended.display();
if (( appended.signature() != "3a90bb0bb8f69f6788ab99e9e25598a0d6c5cdbbb797f77ad68011e0a8b1689d" ) &&
( appended.signature() != "c15fcd1e739b73638dc4e36837bdb53f7087359544664caf7b1763928129f3c7" ) &&
( appended.signature() != "229ff72f812e5f536245dc3b4502a0bc2ab2363f67c545863a85ab91ebfbfb83" ) &&
( appended.signature() != "b98c42c55fc4e661cb3684154256809c03c0c6b53da2738b6ce8066e1b6ddef0" ))
{
++failures;
cout << "Line: " << __LINE__
<< " Horizontal append failed, signature = "
<< appended.signature() << endl;
appended.write("appendImages_horizontal_out.miff");
// appended.display();
}
// Vertical
appendImages( &appended, imageList.begin(), imageList.end(), true );
if (( appended.signature() != "d73d25ccd6011936d08b6d0d89183b7a61790544c2195269aff4db2f782ffc08" ) &&
( appended.signature() != "0909f7ffa7c6ea410fb2ebfdbcb19d61b19c4bd271851ce3bd51662519dc2b58" ) &&
( appended.signature() != "11b97ba6ac1664aa1c2faed4c86195472ae9cce2ed75402d975bb4ffcf1de751" ) &&
( appended.signature() != "cae4815eeb3cb689e73b94d897a9957d3414d1d4f513e8b5e52579b05d164bfe" ))
{
++failures;
cout << "Line: " << __LINE__
<< " Vertical append failed, signature = "
<< appended.signature() << endl;
appended.write("appendImages_vertical_out.miff");
// appended.display();
}
}
catch( Exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
catch( exception &error_ )
{
cout << "Caught exception: " << error_.what() << endl;
return 1;
}
if ( failures )
{
cout << failures << " failures" << endl;
return 1;
}
return 0;
}
| ./CrossVul/dataset_final_sorted/CWE-369/cpp/bad_5309_0 |
crossvul-cpp_data_good_2528_0 | // JPEGsnoop - JPEG Image Decoder & Analysis Utility
// Copyright (C) 2017 - Calvin Hass
// http://www.impulseadventure.com/photo/jpeg-snoop.html
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#include "stdafx.h"
#include "JfifDecode.h"
#include "snoop.h"
#include "JPEGsnoop.h" // for m_pAppConfig get
#include "WindowBuf.h"
#include "Md5.h"
#include "afxinet.h"
#include "windows.h"
#include "UrlString.h"
#include "DbSigs.h"
#include "General.h"
// Maximum number of component values to extract into array for display
#define MAX_anValues 64
// Clear out internal members
void CjfifDecode::Reset()
{
// File handling
m_nPos = 0;
m_nPosSos = 0;
m_nPosEoi = 0;
m_nPosEmbedStart = 0;
m_nPosEmbedEnd = 0;
m_nPosFileEnd = 0;
// SOS / SOF handling
m_nSofNumLines_Y = 0;
m_nSofSampsPerLine_X = 0;
m_nSofNumComps_Nf = 0;
// Quantization tables
ClearDQT();
// Photoshop
m_nImgQualPhotoshopSfw = 0;
m_nImgQualPhotoshopSa = 0;
m_nApp14ColTransform = -1;
// Restart marker
m_nImgRstEn = false;
m_nImgRstInterval = 0;
// Basic metadata
m_strImgExifMake = _T("???");
m_nImgExifMakeSubtype = 0;
m_strImgExifModel = _T("???");
m_bImgExifMakernotes = false;
m_strImgExtras = _T("");
m_strComment = _T("");
m_strSoftware = _T("");
m_bImgProgressive = false;
m_bImgSofUnsupported = false;
_tcscpy_s(m_acApp0Identifier,_T(""));
// Derived metadata
m_strHash = _T("NONE");
m_strHashRot = _T("NONE");
m_eImgLandscape = ENUM_LANDSCAPE_UNSET;
m_strImgQualExif = _T("");
m_bAvi = false;
m_bAviMjpeg = false;
m_bPsd = false;
// Misc
m_bImgOK = false; // Set during SOF to indicate further proc OK
m_bBufFakeDHT = false; // Start in normal Buf mode
m_eImgEdited = EDITED_UNSET;
m_eDbReqSuggest = DB_ADD_SUGGEST_UNSET;
m_bSigExactInDB = false;
// Embedded thumbnail
m_nImgExifThumbComp = 0;
m_nImgExifThumbOffset = 0;
m_nImgExifThumbLen = 0;
m_strHashThumb = _T("NONE"); // Will go into DB to say NONE!
m_strHashThumbRot = _T("NONE"); // Will go into DB to say NONE!
m_nImgThumbNumLines = 0;
m_nImgThumbSampsPerLine = 0;
// Now clear out any previously generated bitmaps
// or image decoding parameters
if (m_pImgDec) {
if (m_pImgSrcDirty) {
m_pImgDec->Reset();
}
}
// Reset the decoding state checks
// These are to help ensure we don't start decoding SOS
// if we haven't seen other valid markers yet! Otherwise
// we could run into very bad loops (e.g. .PSD files)
// just because we saw FFD8FF first then JFIF_SOS
m_bStateAbort = false;
m_bStateSoi = false;
m_bStateDht = false;
m_bStateDhtOk = false;
m_bStateDhtFake = false;
m_bStateDqt = false;
m_bStateDqtOk = false;
m_bStateSof = false;
m_bStateSofOk = false;
m_bStateSos = false;
m_bStateSosOk = false;
m_bStateEoi = false;
}
// Initialize the JFIF decoder. Several class pointers are provided
// as parameters, so that we can directly access the output log, the
// file buffer and the image scan decoder.
// Loads up the signature database.
//
// INPUT:
// - pLog Ptr to log file class
// - pWBuf Ptr to Window Buf class
// - pImgDec Ptr to Image Decoder class
//
// PRE:
// - Requires that CDocLog, CwindowBuf and CimgDecode classes
// are already initialized
//
CjfifDecode::CjfifDecode(CDocLog* pLog,CwindowBuf* pWBuf,CimgDecode* pImgDec)
{
// Ideally this would be passed by constructor, but simply access
// directly for now.
CJPEGsnoopApp* pApp;
pApp = (CJPEGsnoopApp*)AfxGetApp();
m_pAppConfig = pApp->m_pAppConfig;
ASSERT(m_pAppConfig);
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CjfifDecode::CjfifDecode() Begin"));
ASSERT(pLog);
ASSERT(pWBuf);
ASSERT(pImgDec);
// Need to zero out the private members
m_bOutputDB = FALSE; // mySQL output for web
// Enable verbose reporting
m_bVerbose = FALSE;
m_pImgSrcDirty = TRUE;
// Generate lookup tables for Huffman codes
GenLookupHuffMask();
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CjfifDecode::CjfifDecode() Checkpoint 1"));
// Window status bar is not ready yet, wait for call to SetStatusBar()
m_pStatBar = NULL;
// Save copies of other class pointers
m_pLog = pLog;
m_pWBuf = pWBuf;
m_pImgDec = pImgDec;
// Reset decoding state
Reset();
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CjfifDecode::CjfifDecode() Checkpoint 2"));
// Load the local database (if it exists)
theApp.m_pDbSigs->DatabaseExtraLoad();
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CjfifDecode::CjfifDecode() Checkpoint 3"));
// Allocate the Photoshop decoder
m_pPsDec = new CDecodePs(pWBuf,pLog);
if (!m_pPsDec) {
ASSERT(false);
return;
}
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CjfifDecode::CjfifDecode() Checkpoint 4"));
#ifdef SUPPORT_DICOM
// Allocate the DICOM decoder
m_pDecDicom = new CDecodeDicom(pWBuf,pLog);
if (!m_pDecDicom) {
ASSERT(false);
return;
}
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CjfifDecode::CjfifDecode() Checkpoint 5"));
#endif
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CjfifDecode::CjfifDecode() End"));
}
// Destructor
CjfifDecode::~CjfifDecode()
{
// Free the Photoshop decoder
if (m_pPsDec) {
delete m_pPsDec;
m_pPsDec = NULL;
}
#ifdef SUPPORT_DICOM
// Free the DICOM decoder
if (m_pDecDicom) {
delete m_pDecDicom;
m_pDecDicom = NULL;
}
#endif
}
// Asynchronously update a local pointer to the status bar once
// it becomes available. Note that the status bar is not ready by
// the time of the CjfifDecode class constructor call.
//
// INPUT:
// - pStatBar Ptr to status bar
//
// POST:
// - m_pStatBar
//
void CjfifDecode::SetStatusBar(CStatusBar* pStatBar)
{
m_pStatBar = pStatBar;
}
// Indicate that the source of the image scan data
// has been dirtied. Either the source has changed
// or some of the View2 options have changed.
//
// POST:
// - m_pImgSrcDirty
//
void CjfifDecode::ImgSrcChanged()
{
m_pImgSrcDirty = true;
}
// Set the AVI mode flag for this file
//
// POST:
// - m_bAvi
// - m_bAviMjpeg
//
void CjfifDecode::SetAviMode(bool bIsAvi,bool bIsMjpeg)
{
m_bAvi = bIsAvi;
m_bAviMjpeg = bIsMjpeg;
}
// Fetch the AVI mode flag for this file
//
// PRE:
// - m_bAvi
// - m_bAviMjpeg
//
// OUTPUT:
// - bIsAvi
// - bIsMjpeg
//
void CjfifDecode::GetAviMode(bool &bIsAvi,bool &bIsMjpeg)
{
bIsAvi = m_bAvi;
bIsMjpeg = m_bAviMjpeg;
}
// Fetch the starting file position of the embedded thumbnail
//
// PRE:
// - m_nPosEmbedStart
//
// RETURN:
// - File position
//
unsigned long CjfifDecode::GetPosEmbedStart()
{
return m_nPosEmbedStart;
}
// Fetch the ending file position of the embedded thumbnail
//
// PRE:
// - m_nPosEmbedEnd
//
// RETURN:
// - File position
//
unsigned long CjfifDecode::GetPosEmbedEnd()
{
return m_nPosEmbedEnd;
}
// Determine if the last analysis revealed a JFIF with known markers
//
// RETURN:
// - TRUE if file (at position during analysis) appeared to decode OK
//
bool CjfifDecode::GetDecodeStatus()
{
return m_bImgOK;
}
// Fetch a summary of the JFIF decoder results
// These details are used in preparation of signature submission to the DB
//
// PRE:
// - m_strHash
// - m_strHashRot
// - m_strImgExifMake
// - m_strImgExifModel
// - m_strImgQualExif
// - m_strSoftware
// - m_eDbReqSuggest
//
// OUTPUT:
// - strHash
// - strHashRot
// - strImgExifMake
// - strImgExifModel
// - strImgQualExif
// - strSoftware
// - nDbReqSuggest
//
void CjfifDecode::GetDecodeSummary(CString &strHash,CString &strHashRot,CString &strImgExifMake,CString &strImgExifModel,
CString &strImgQualExif,CString &strSoftware,teDbAdd &eDbReqSuggest)
{
strHash = m_strHash;
strHashRot = m_strHashRot;
strImgExifMake = m_strImgExifMake;
strImgExifModel = m_strImgExifModel;
strImgQualExif = m_strImgQualExif;
strSoftware = m_strSoftware;
eDbReqSuggest = m_eDbReqSuggest;
}
// Fetch an element from the "standard" luminance quantization table
//
// PRE:
// - glb_anStdQuantLum[]
//
// RETURN:
// - DQT matrix element
//
unsigned CjfifDecode::GetDqtQuantStd(unsigned nInd)
{
if (nInd < MAX_DQT_COEFF) {
return glb_anStdQuantLum[nInd];
} else {
#ifdef DEBUG_LOG
CString strTmp;
CString strDebug;
strTmp.Format(_T("GetDqtQuantStd() with nInd out of range. nInd=[%u]"),nInd);
strDebug.Format(_T("## File=[%-100s] Block=[%-10s] Error=[%s]\n"),(LPCTSTR)m_pAppConfig->strCurFname,
_T("JfifDecode"),(LPCTSTR)strTmp);
OutputDebugString(strDebug);
#else
ASSERT(false);
#endif
return 0;
}
}
// Fetch the DQT ordering index (with optional zigzag sequence)
//
// INPUT:
// - nInd Coefficient index
// - bZigZag Use zig-zag ordering
//
// RETURN:
// - Sequence index
//
unsigned CjfifDecode::GetDqtZigZagIndex(unsigned nInd,bool bZigZag)
{
if (nInd < MAX_DQT_COEFF) {
if (bZigZag) {
return nInd;
} else {
return glb_anZigZag[nInd];
}
} else {
#ifdef DEBUG_LOG
CString strTmp;
CString strDebug;
strTmp.Format(_T("GetDqtZigZagIndex() with nInd out of range. nInd=[%u]"),nInd);
strDebug.Format(_T("## File=[%-100s] Block=[%-10s] Error=[%s]\n"),(LPCTSTR)m_pAppConfig->strCurFname,
_T("JfifDecode"),(LPCTSTR)strTmp);
OutputDebugString(strDebug);
#else
ASSERT(false);
#endif
return 0;
}
}
// Reset the DQT tables
//
// POST:
// - m_anImgDqtTbl[][]
// - m_anImgThumbDqt[][]
// - m_adImgDqtQual[]
// - m_abImgDqtSet[]
// - m_abImgDqtThumbSet[]
//
void CjfifDecode::ClearDQT()
{
for (unsigned nTblInd=0;nTblInd<MAX_DQT_DEST_ID;nTblInd++)
{
for (unsigned nCoeffInd=0;nCoeffInd<MAX_DQT_COEFF;nCoeffInd++)
{
m_anImgDqtTbl[nTblInd][nCoeffInd] = 0;
m_anImgThumbDqt[nTblInd][nCoeffInd] = 0;
}
m_adImgDqtQual[nTblInd] = 0;
m_abImgDqtSet[nTblInd] = false;
m_abImgDqtThumbSet[nTblInd] = false;
}
}
// Set the DQT matrix element
//
// INPUT:
// - dqt0[] Matrix array for table 0
// - dqt1[] Matrix array for table 1
//
// POST:
// - m_anImgDqtTbl[][]
// - m_eImgLandscape
// - m_abImgDqtSet[]
// - m_strImgQuantCss
//
void CjfifDecode::SetDQTQuick(unsigned anDqt0[64],unsigned anDqt1[64])
{
m_eImgLandscape = ENUM_LANDSCAPE_YES;
for (unsigned ind=0;ind<MAX_DQT_COEFF;ind++)
{
m_anImgDqtTbl[0][ind] = anDqt0[ind];
m_anImgDqtTbl[1][ind] = anDqt1[ind];
}
m_abImgDqtSet[0] = true;
m_abImgDqtSet[1] = true;
m_strImgQuantCss = _T("NA");
}
// Construct a lookup table for the Huffman code masks
// The result is a simple bit sequence of zeros followed by
// an increasing number of 1 bits.
// 00000000...00000001
// 00000000...00000011
// 00000000...00000111
// ...
// 01111111...11111111
// 11111111...11111111
//
// POST:
// - m_anMaskLookup[]
//
void CjfifDecode::GenLookupHuffMask()
{
unsigned int mask;
for (unsigned len=0;len<32;len++)
{
mask = (1 << (len))-1;
mask <<= 32-len;
m_anMaskLookup[len] = mask;
}
}
// Provide a short-hand alias for the m_pWBuf buffer
// Also support redirection to a local table in case we are
// faking out the DHT (eg. for MotionJPEG files).
//
// PRE:
// - m_bBufFakeDHT Flag to include Fake DHT table
// - m_abMJPGDHTSeg[] DHT table used if m_bBufFakeDHT=true
//
// INPUT:
// - nOffset File offset to read from
// - bClean Forcibly disables any redirection to Fake DHT table
//
// POST:
// - m_pLog
//
// RETURN:
// - Byte from file (or local table)
//
BYTE CjfifDecode::Buf(unsigned long nOffset,bool bClean=false)
{
// Buffer can be redirected to internal array for AVI DHT
// tables, so check for it here.
if (m_bBufFakeDHT) {
return m_abMJPGDHTSeg[nOffset];
} else {
return m_pWBuf->Buf(nOffset,bClean);
}
}
// Write out a line to the log buffer if we are in verbose mode
//
// PRE:
// - m_bVerbose Verbose mode
//
// INPUT:
// - strLine String to output
//
// OUTPUT:
// - none
//
// POST:
// - m_pLog
//
// RETURN:
// - none
//
void CjfifDecode::DbgAddLine(LPCTSTR strLine)
{
if (m_bVerbose)
{
m_pLog->AddLine(strLine);
}
}
// Convert a UINT32 and decompose into 4 bytes, but support
// either endian byte-swap mode
//
// PRE:
// - m_nImgExifEndian Byte swap mode (0=little, 1=big)
//
// INPUT:
// - nVal Input UINT32
//
// OUTPUT:
// - nByte0 Byte #1
// - nByte1 Byte #2
// - nByte2 Byte #3
// - nByte3 Byte #4
//
// RETURN:
// - none
//
void CjfifDecode::UnByteSwap4(unsigned nVal,unsigned &nByte0,unsigned &nByte1,unsigned &nByte2,unsigned &nByte3)
{
if (m_nImgExifEndian == 0) {
// Little Endian
nByte3 = (nVal & 0xFF000000) >> 24;
nByte2 = (nVal & 0x00FF0000) >> 16;
nByte1 = (nVal & 0x0000FF00) >> 8;
nByte0 = (nVal & 0x000000FF);
} else {
// Big Endian
nByte0 = (nVal & 0xFF000000) >> 24;
nByte1 = (nVal & 0x00FF0000) >> 16;
nByte2 = (nVal & 0x0000FF00) >> 8;
nByte3 = (nVal & 0x000000FF);
}
}
// Perform conversion from 4 bytes into UINT32 with
// endian byte-swapping support
//
// PRE:
// - m_nImgExifEndian Byte swap mode (0=little, 1=big)
//
// INPUT:
// - nByte0 Byte #1
// - nByte1 Byte #2
// - nByte2 Byte #3
// - nByte3 Byte #4
//
// RETURN:
// - UINT32
//
unsigned CjfifDecode::ByteSwap4(unsigned nByte0,unsigned nByte1, unsigned nByte2, unsigned nByte3)
{
unsigned nVal;
if (m_nImgExifEndian == 0) {
// Little endian, byte swap required
nVal = (nByte3<<24) + (nByte2<<16) + (nByte1<<8) + nByte0;
} else {
// Big endian, no swap required
nVal = (nByte0<<24) + (nByte1<<16) + (nByte2<<8) + nByte3;
}
return nVal;
}
// Perform conversion from 2 bytes into half-word with
// endian byte-swapping support
//
// PRE:
// - m_nImgExifEndian Byte swap mode (0=little, 1=big)
//
// INPUT:
// - nByte0 Byte #1
// - nByte1 Byte #2
//
// RETURN:
// - UINT16
//
unsigned CjfifDecode::ByteSwap2(unsigned nByte0,unsigned nByte1)
{
unsigned nVal;
if (m_nImgExifEndian == 0) {
// Little endian, byte swap required
nVal = (nByte1<<8) + nByte0;
} else {
// Big endian, no swap required
nVal = (nByte0<<8) + nByte1;
}
return nVal;
}
// Decode Canon Makernotes
// Only the most common makernotes are supported; there are a large
// number of makernotes that have not been documented anywhere.
CStr2 CjfifDecode::LookupMakerCanonTag(unsigned nMainTag,unsigned nSubTag,unsigned nVal)
{
CString strTmp;
CStr2 sRetVal;
sRetVal.strTag = _T("???");
sRetVal.bUnknown = false; // Set to true in default clauses
sRetVal.strVal.Format(_T("%u"),nVal); // Provide default value
unsigned nValHi,nValLo;
nValHi = (nVal & 0xff00) >> 8;
nValLo = (nVal & 0x00ff);
switch(nMainTag)
{
case 0x0001:
switch(nSubTag)
{
case 0x0001: sRetVal.strTag = _T("Canon.Cs1.Macro");break; // Short Macro mode
case 0x0002: sRetVal.strTag = _T("Canon.Cs1.Selftimer");break; // Short Self timer
case 0x0003: sRetVal.strTag = _T("Canon.Cs1.Quality");
if (nVal == 2) { sRetVal.strVal = _T("norm"); }
else if (nVal == 3) { sRetVal.strVal = _T("fine"); }
else if (nVal == 5) { sRetVal.strVal = _T("superfine"); }
else {
sRetVal.strVal = _T("?");
}
// Save the quality string for later
m_strImgQualExif = sRetVal.strVal;
break; // Short Quality
case 0x0004: sRetVal.strTag = _T("Canon.Cs1.FlashMode");break; // Short Flash mode setting
case 0x0005: sRetVal.strTag = _T("Canon.Cs1.DriveMode");break; // Short Drive mode setting
case 0x0007: sRetVal.strTag = _T("Canon.Cs1.FocusMode"); // Short Focus mode setting
switch(nVal) {
case 0 : sRetVal.strVal = _T("One-shot");break;
case 1 : sRetVal.strVal = _T("AI Servo");break;
case 2 : sRetVal.strVal = _T("AI Focus");break;
case 3 : sRetVal.strVal = _T("Manual Focus");break;
case 4 : sRetVal.strVal = _T("Single");break;
case 5 : sRetVal.strVal = _T("Continuous");break;
case 6 : sRetVal.strVal = _T("Manual Focus");break;
default : sRetVal.strVal = _T("?");break;
}
break;
case 0x000a: sRetVal.strTag = _T("Canon.Cs1.ImageSize"); // Short Image size
if (nVal == 0) { sRetVal.strVal = _T("Large"); }
else if (nVal == 1) { sRetVal.strVal = _T("Medium"); }
else if (nVal == 2) { sRetVal.strVal = _T("Small"); }
else {
sRetVal.strVal = _T("?");
}
break;
case 0x000b: sRetVal.strTag = _T("Canon.Cs1.EasyMode");break; // Short Easy shooting mode
case 0x000c: sRetVal.strTag = _T("Canon.Cs1.DigitalZoom");break; // Short Digital zoom
case 0x000d: sRetVal.strTag = _T("Canon.Cs1.Contrast");break; // Short Contrast setting
case 0x000e: sRetVal.strTag = _T("Canon.Cs1.Saturation");break; // Short Saturation setting
case 0x000f: sRetVal.strTag = _T("Canon.Cs1.Sharpness");break; // Short Sharpness setting
case 0x0010: sRetVal.strTag = _T("Canon.Cs1.ISOSpeed");break; // Short ISO speed setting
case 0x0011: sRetVal.strTag = _T("Canon.Cs1.MeteringMode");break; // Short Metering mode setting
case 0x0012: sRetVal.strTag = _T("Canon.Cs1.FocusType");break; // Short Focus type setting
case 0x0013: sRetVal.strTag = _T("Canon.Cs1.AFPoint");break; // Short AF point selected
case 0x0014: sRetVal.strTag = _T("Canon.Cs1.ExposureProgram");break; // Short Exposure mode setting
case 0x0016: sRetVal.strTag = _T("Canon.Cs1.LensType");break; //
case 0x0017: sRetVal.strTag = _T("Canon.Cs1.Lens");break; // Short 'long' and 'short' focal length of lens (in 'focal m_nImgUnits') and 'focal m_nImgUnits' per mm
case 0x001a: sRetVal.strTag = _T("Canon.Cs1.MaxAperture");break; //
case 0x001b: sRetVal.strTag = _T("Canon.Cs1.MinAperture");break; //
case 0x001c: sRetVal.strTag = _T("Canon.Cs1.FlashActivity");break; // Short Flash activity
case 0x001d: sRetVal.strTag = _T("Canon.Cs1.FlashDetails");break; // Short Flash details
case 0x0020: sRetVal.strTag = _T("Canon.Cs1.FocusMode");break; // Short Focus mode setting
default:
sRetVal.strTag.Format(_T("Canon.Cs1.x%04X"),nSubTag);
sRetVal.bUnknown = true;
break;
} // switch nSubTag
break;
case 0x0004:
switch(nSubTag)
{
case 0x0002: sRetVal.strTag = _T("Canon.Cs2.ISOSpeed");break; // Short ISO speed used
case 0x0004: sRetVal.strTag = _T("Canon.Cs2.TargetAperture");break; // Short Target Aperture
case 0x0005: sRetVal.strTag = _T("Canon.Cs2.TargetShutterSpeed");break; // Short Target shutter speed
case 0x0007: sRetVal.strTag = _T("Canon.Cs2.WhiteBalance");break; // Short White balance setting
case 0x0009: sRetVal.strTag = _T("Canon.Cs2.Sequence");break; // Short Sequence number (if in a continuous burst)
case 0x000e: sRetVal.strTag = _T("Canon.Cs2.AFPointUsed");break; // Short AF point used
case 0x000f: sRetVal.strTag = _T("Canon.Cs2.FlashBias");break; // Short Flash bias
case 0x0013: sRetVal.strTag = _T("Canon.Cs2.SubjectDistance");break; // Short Subject distance (m_nImgUnits are not clear)
case 0x0015: sRetVal.strTag = _T("Canon.Cs2.ApertureValue");break; // Short Aperture
case 0x0016: sRetVal.strTag = _T("Canon.Cs2.ShutterSpeedValue");break; // Short Shutter speed
default:
sRetVal.strTag.Format(_T("Canon.Cs2.x%04X"),nSubTag);
sRetVal.bUnknown = true;
break;
} // switch nSubTag
break;
case 0x000F:
// CustomFunctions are different! Tag given by high byte, value by low
// Index order (usually the nSubTag) is not used.
sRetVal.strVal.Format(_T("%u"),nValLo); // Provide default value
switch(nValHi)
{
case 0x0001: sRetVal.strTag = _T("Canon.Cf.NoiseReduction");break; // Short Long exposure noise reduction
case 0x0002: sRetVal.strTag = _T("Canon.Cf.ShutterAeLock");break; // Short Shutter/AE lock buttons
case 0x0003: sRetVal.strTag = _T("Canon.Cf.MirrorLockup");break; // Short Mirror lockup
case 0x0004: sRetVal.strTag = _T("Canon.Cf.ExposureLevelIncrements");break; // Short Tv/Av and exposure level
case 0x0005: sRetVal.strTag = _T("Canon.Cf.AFAssist");break; // Short AF assist light
case 0x0006: sRetVal.strTag = _T("Canon.Cf.FlashSyncSpeedAv");break; // Short Shutter speed in Av mode
case 0x0007: sRetVal.strTag = _T("Canon.Cf.AEBSequence");break; // Short AEB sequence/auto cancellation
case 0x0008: sRetVal.strTag = _T("Canon.Cf.ShutterCurtainSync");break; // Short Shutter curtain sync
case 0x0009: sRetVal.strTag = _T("Canon.Cf.LensAFStopButton");break; // Short Lens AF stop button Fn. Switch
case 0x000a: sRetVal.strTag = _T("Canon.Cf.FillFlashAutoReduction");break; // Short Auto reduction of fill flash
case 0x000b: sRetVal.strTag = _T("Canon.Cf.MenuButtonReturn");break; // Short Menu button return position
case 0x000c: sRetVal.strTag = _T("Canon.Cf.SetButtonFunction");break; // Short SET button func. when shooting
case 0x000d: sRetVal.strTag = _T("Canon.Cf.SensorCleaning");break; // Short Sensor cleaning
case 0x000e: sRetVal.strTag = _T("Canon.Cf.SuperimposedDisplay");break; // Short Superimposed display
case 0x000f: sRetVal.strTag = _T("Canon.Cf.ShutterReleaseNoCFCard");break; // Short Shutter Release W/O CF Card
default:
sRetVal.strTag.Format(_T("Canon.Cf.x%04X"),nValHi);
sRetVal.bUnknown = true;
break;
} // switch nSubTag
break;
/*
// Other ones assumed to use high-byte/low-byte method:
case 0x00C0:
sRetVal.strVal.Format(_T("%u"),nValLo); // Provide default value
switch(nValHi)
{
//case 0x0001: sRetVal.strTag = _T("Canon.x00C0.???");break; //
default:
sRetVal.strTag.Format(_T("Canon.x00C0.x%04X"),nValHi);
break;
}
break;
case 0x00C1:
sRetVal.strVal.Format(_T("%u"),nValLo); // Provide default value
switch(nValHi)
{
//case 0x0001: sRetVal.strTag = _T("Canon.x00C1.???");break; //
default:
sRetVal.strTag.Format(_T("Canon.x00C1.x%04X"),nValHi);
break;
}
break;
*/
case 0x0012:
switch(nSubTag)
{
case 0x0002: sRetVal.strTag = _T("Canon.Pi.ImageWidth");break; //
case 0x0003: sRetVal.strTag = _T("Canon.Pi.ImageHeight");break; //
case 0x0004: sRetVal.strTag = _T("Canon.Pi.ImageWidthAsShot");break; //
case 0x0005: sRetVal.strTag = _T("Canon.Pi.ImageHeightAsShot");break; //
case 0x0016: sRetVal.strTag = _T("Canon.Pi.AFPointsUsed");break; //
case 0x001a: sRetVal.strTag = _T("Canon.Pi.AFPointsUsed20D");break; //
default:
sRetVal.strTag.Format(_T("Canon.Pi.x%04X"),nSubTag);
sRetVal.bUnknown = true;
break;
} // switch nSubTag
break;
default:
sRetVal.strTag.Format(_T("Canon.x%04X.x%04X"),nMainTag,nSubTag);
sRetVal.bUnknown = true;
break;
} // switch mainTag
return sRetVal;
}
// Perform decode of EXIF IFD tags including MakerNote tags
//
// PRE:
// - m_strImgExifMake Used for MakerNote decode
//
// INPUT:
// - strSect IFD section
// - nTag Tag code value
//
// OUTPUT:
// - bUnknown Was the tag unknown?
//
// RETURN:
// - Formatted string
//
CString CjfifDecode::LookupExifTag(CString strSect,unsigned nTag,bool &bUnknown)
{
CString strTmp;
bUnknown = false;
if (strSect == _T("IFD0"))
{
switch(nTag)
{
case 0x010E: return _T("ImageDescription");break; // ascii string Describes image
case 0x010F: return _T("Make");break; // ascii string Shows manufacturer of digicam
case 0x0110: return _T("Model");break; // ascii string Shows model number of digicam
case 0x0112: return _T("Orientation");break; // unsigned short 1 The orientation of the camera relative to the scene, when the image was captured. The start point of stored data is, '1' means upper left, '3' lower right, '6' upper right, '8' lower left, '9' undefined.
case 0x011A: return _T("XResolution");break; // unsigned rational 1 Display/Print resolution of image. Large number of digicam uses 1/72inch, but it has no mean because personal computer doesn't use this value to display/print out.
case 0x011B: return _T("YResolution");break; // unsigned rational 1
case 0x0128: return _T("ResolutionUnit");break; // unsigned short 1 Unit of XResolution(0x011a)/YResolution(0x011b). '1' means no-unit, '2' means inch, '3' means centimeter.
case 0x0131: return _T("Software");break; // ascii string Shows firmware(internal software of digicam) version number.
case 0x0132: return _T("DateTime");break; // ascii string 20 Date/Time of image was last modified. Data format is "YYYY:MM:DD HH:MM:SS"+0x00, total 20bytes. In usual, it has the same value of DateTimeOriginal(0x9003)
case 0x013B: return _T("Artist");break; // Seems to be here and not only in SubIFD (maybe instead of SubIFD)
case 0x013E: return _T("WhitePoint");break; // unsigned rational 2 Defines chromaticity of white point of the image. If the image uses CIE Standard Illumination D65(known as international standard of 'daylight'), the values are '3127/10000,3290/10000'.
case 0x013F: return _T("PrimChromaticities");break; // unsigned rational 6 Defines chromaticity of the primaries of the image. If the image uses CCIR Recommendation 709 primearies, values are '640/1000,330/1000,300/1000,600/1000,150/1000,0/1000'.
case 0x0211: return _T("YCbCrCoefficients");break; // unsigned rational 3 When image format is YCbCr, this value shows a constant to translate it to RGB format. In usual, values are '0.299/0.587/0.114'.
case 0x0213: return _T("YCbCrPositioning");break; // unsigned short 1 When image format is YCbCr and uses 'Subsampling'(cropping of chroma data, all the digicam do that), defines the chroma sample point of subsampling pixel array. '1' means the center of pixel array, '2' means the datum point.
case 0x0214: return _T("ReferenceBlackWhite");break; // unsigned rational 6 Shows reference value of black point/white point. In case of YCbCr format, first 2 show black/white of Y, next 2 are Cb, last 2 are Cr. In case of RGB format, first 2 show black/white of R, next 2 are G, last 2 are B.
case 0x8298: return _T("Copyright");break; // ascii string Shows copyright information
case 0x8769: return _T("ExifOffset");break; //unsigned long 1 Offset to Exif Sub IFD
case 0x8825: return _T("GPSOffset");break; //unsigned long 1 Offset to Exif GPS IFD
//NEW:
case 0x9C9B: return _T("XPTitle");break;
case 0x9C9C: return _T("XPComment");break;
case 0x9C9D: return _T("XPAuthor");break;
case 0x9C9e: return _T("XPKeywords");break;
case 0x9C9f: return _T("XPSubject");break;
//NEW: The following were found in IFD0 even though they should just be SubIFD?
case 0xA401: return _T("CustomRendered");break;
case 0xA402: return _T("ExposureMode");break;
case 0xA403: return _T("WhiteBalance");break;
case 0xA406: return _T("SceneCaptureType");break;
default:
strTmp.Format(_T("IFD0.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} else if (strSect == _T("SubIFD")) {
switch(nTag)
{
case 0x00fe: return _T("NewSubfileType");break; // unsigned long 1
case 0x00ff: return _T("SubfileType");break; // unsigned short 1
case 0x012d: return _T("TransferFunction");break; // unsigned short 3
case 0x013b: return _T("Artist");break; // ascii string
case 0x013d: return _T("Predictor");break; // unsigned short 1
case 0x0142: return _T("TileWidth");break; // unsigned short 1
case 0x0143: return _T("TileLength");break; // unsigned short 1
case 0x0144: return _T("TileOffsets");break; // unsigned long
case 0x0145: return _T("TileByteCounts");break; // unsigned short
case 0x014a: return _T("SubIFDs");break; // unsigned long
case 0x015b: return _T("JPEGTables");break; // undefined
case 0x828d: return _T("CFARepeatPatternDim");break; // unsigned short 2
case 0x828e: return _T("CFAPattern");break; // unsigned byte
case 0x828f: return _T("BatteryLevel");break; // unsigned rational 1
case 0x829A: return _T("ExposureTime");break;
case 0x829D: return _T("FNumber");break;
case 0x83bb: return _T("IPTC/NAA");break; // unsigned long
case 0x8773: return _T("InterColorProfile");break; // undefined
case 0x8822: return _T("ExposureProgram");break;
case 0x8824: return _T("SpectralSensitivity");break; // ascii string
case 0x8825: return _T("GPSInfo");break; // unsigned long 1
case 0x8827: return _T("ISOSpeedRatings");break;
case 0x8828: return _T("OECF");break; // undefined
case 0x8829: return _T("Interlace");break; // unsigned short 1
case 0x882a: return _T("TimeZoneOffset");break; // signed short 1
case 0x882b: return _T("SelfTimerMode");break; // unsigned short 1
case 0x9000: return _T("ExifVersion");break;
case 0x9003: return _T("DateTimeOriginal");break;
case 0x9004: return _T("DateTimeDigitized");break;
case 0x9101: return _T("ComponentsConfiguration");break;
case 0x9102: return _T("CompressedBitsPerPixel");break;
case 0x9201: return _T("ShutterSpeedValue");break;
case 0x9202: return _T("ApertureValue");break;
case 0x9203: return _T("BrightnessValue");break;
case 0x9204: return _T("ExposureBiasValue");break;
case 0x9205: return _T("MaxApertureValue");break;
case 0x9206: return _T("SubjectDistance");break;
case 0x9207: return _T("MeteringMode");break;
case 0x9208: return _T("LightSource");break;
case 0x9209: return _T("Flash");break;
case 0x920A: return _T("FocalLength");break;
case 0x920b: return _T("FlashEnergy");break; // unsigned rational 1
case 0x920c: return _T("SpatialFrequencyResponse");break; // undefined
case 0x920d: return _T("Noise");break; // undefined
case 0x9211: return _T("ImageNumber");break; // unsigned long 1
case 0x9212: return _T("SecurityClassification");break; // ascii string 1
case 0x9213: return _T("ImageHistory");break; // ascii string
case 0x9214: return _T("SubjectLocation");break; // unsigned short 4
case 0x9215: return _T("ExposureIndex");break; // unsigned rational 1
case 0x9216: return _T("TIFF/EPStandardID");break; // unsigned byte 4
case 0x927C: return _T("MakerNote");break;
case 0x9286: return _T("UserComment");break;
case 0x9290: return _T("SubSecTime");break; // ascii string
case 0x9291: return _T("SubSecTimeOriginal");break; // ascii string
case 0x9292: return _T("SubSecTimeDigitized");break; // ascii string
case 0xA000: return _T("FlashPixVersion");break;
case 0xA001: return _T("ColorSpace");break;
case 0xA002: return _T("ExifImageWidth");break;
case 0xA003: return _T("ExifImageHeight");break;
case 0xA004: return _T("RelatedSoundFile");break;
case 0xA005: return _T("ExifInteroperabilityOffset");break;
case 0xa20b: return _T("FlashEnergy unsigned");break; // rational 1
case 0xa20c: return _T("SpatialFrequencyResponse");break; // unsigned short 1
case 0xA20E: return _T("FocalPlaneXResolution");break;
case 0xA20F: return _T("FocalPlaneYResolution");break;
case 0xA210: return _T("FocalPlaneResolutionUnit");break;
case 0xa214: return _T("SubjectLocation");break; // unsigned short 1
case 0xa215: return _T("ExposureIndex");break; // unsigned rational 1
case 0xA217: return _T("SensingMethod");break;
case 0xA300: return _T("FileSource");break;
case 0xA301: return _T("SceneType");break;
case 0xa302: return _T("CFAPattern");break; // undefined 1
case 0xa401: return _T("CustomRendered");break; // Short Custom image processing
case 0xa402: return _T("ExposureMode");break; // Short Exposure mode
case 0xa403: return _T("WhiteBalance");break; // Short White balance
case 0xa404: return _T("DigitalZoomRatio");break; // Rational Digital zoom ratio
case 0xa405: return _T("FocalLengthIn35mmFilm");break; // Short Focal length in 35 mm film
case 0xa406: return _T("SceneCaptureType");break; // Short Scene capture type
case 0xa407: return _T("GainControl");break; // Rational Gain control
case 0xa408: return _T("Contrast");break; // Short Contrast
case 0xa409: return _T("Saturation");break; // Short Saturation
case 0xa40a: return _T("Sharpness");break; // Short Sharpness
case 0xa40b: return _T("DeviceSettingDescription");break; // Undefined Device settings description
case 0xa40c: return _T("SubjectDistanceRange");break; // Short Subject distance range
case 0xa420: return _T("ImageUniqueID");break; // Ascii Unique image ID
default:
strTmp.Format(_T("SubIFD.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} else if (strSect == _T("IFD1")) {
switch(nTag)
{
case 0x0100: return _T("ImageWidth");break; // unsigned short/long 1 Shows size of thumbnail image.
case 0x0101: return _T("ImageLength");break; // unsigned short/long 1
case 0x0102: return _T("BitsPerSample");break; // unsigned short 3 When image format is no compression, this value shows the number of bits per component for each pixel. Usually this value is '8,8,8'
case 0x0103: return _T("Compression");break; // unsigned short 1 Shows compression method. '1' means no compression, '6' means JPEG compression.
case 0x0106: return _T("PhotometricInterpretation");break; // unsigned short 1 Shows the color space of the image data components. '1' means monochrome, '2' means RGB, '6' means YCbCr.
case 0x0111: return _T("StripOffsets");break; // unsigned short/long When image format is no compression, this value shows offset to image data. In some case image data is striped and this value is plural.
case 0x0115: return _T("SamplesPerPixel");break; // unsigned short 1 When image format is no compression, this value shows the number of components stored for each pixel. At color image, this value is '3'.
case 0x0116: return _T("RowsPerStrip");break; // unsigned short/long 1 When image format is no compression and image has stored as strip, this value shows how many rows stored to each strip. If image has not striped, this value is the same as ImageLength(0x0101).
case 0x0117: return _T("StripByteConunts");break; // unsigned short/long When image format is no compression and stored as strip, this value shows how many bytes used for each strip and this value is plural. If image has not stripped, this value is single and means whole data size of image.
case 0x011a: return _T("XResolution");break; // unsigned rational 1 Display/Print resolution of image. Large number of digicam uses 1/72inch, but it has no mean because personal computer doesn't use this value to display/print out.
case 0x011b: return _T("YResolution");break; // unsigned rational 1
case 0x011c: return _T("PlanarConfiguration");break; // unsigned short 1 When image format is no compression YCbCr, this value shows byte aligns of YCbCr data. If value is '1', Y/Cb/Cr value is chunky format, contiguous for each subsampling pixel. If value is '2', Y/Cb/Cr value is separated and stored to Y plane/Cb plane/Cr plane format.
case 0x0128: return _T("ResolutionUnit");break; // unsigned short 1 Unit of XResolution(0x011a)/YResolution(0x011b). '1' means inch, '2' means centimeter.
case 0x0201: return _T("JpegIFOffset");break; // unsigned long 1 When image format is JPEG, this value show offset to JPEG data stored.
case 0x0202: return _T("JpegIFByteCount");break; // unsigned long 1 When image format is JPEG, this value shows data size of JPEG image.
case 0x0211: return _T("YCbCrCoefficients");break; // unsigned rational 3 When image format is YCbCr, this value shows constants to translate it to RGB format. In usual, '0.299/0.587/0.114' are used.
case 0x0212: return _T("YCbCrSubSampling");break; // unsigned short 2 When image format is YCbCr and uses subsampling(cropping of chroma data, all the digicam do that), this value shows how many chroma data subsampled. First value shows horizontal, next value shows vertical subsample rate.
case 0x0213: return _T("YCbCrPositioning");break; // unsigned short 1 When image format is YCbCr and uses 'Subsampling'(cropping of chroma data, all the digicam do that), this value defines the chroma sample point of subsampled pixel array. '1' means the center of pixel array, '2' means the datum point(0,0).
case 0x0214: return _T("ReferenceBlackWhite");break; // unsigned rational 6 Shows reference value of black point/white point. In case of YCbCr format, first 2 show black/white of Y, next 2 are Cb, last 2 are Cr. In case of RGB format, first 2 show black/white of R, next 2 are G, last 2 are B.
default:
strTmp.Format(_T("IFD1.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} else if (strSect == _T("InteropIFD")) {
switch(nTag) {
case 0x0001: return _T("InteroperabilityIndex");break;
case 0x0002: return _T("InteroperabilityVersion");break;
case 0x1000: return _T("RelatedImageFileFormat");break;
case 0x1001: return _T("RelatedImageWidth");break;
case 0x1002: return _T("RelatedImageLength");break;
default:
strTmp.Format(_T("Interop.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} else if (strSect == _T("GPSIFD")) {
switch(nTag) {
case 0x0000: return _T("GPSVersionID");break;
case 0x0001: return _T("GPSLatitudeRef");break;
case 0x0002: return _T("GPSLatitude");break;
case 0x0003: return _T("GPSLongitudeRef");break;
case 0x0004: return _T("GPSLongitude");break;
case 0x0005: return _T("GPSAltitudeRef");break;
case 0x0006: return _T("GPSAltitude");break;
case 0x0007: return _T("GPSTimeStamp");break;
case 0x0008: return _T("GPSSatellites");break;
case 0x0009: return _T("GPSStatus");break;
case 0x000A: return _T("GPSMeasureMode");break;
case 0x000B: return _T("GPSDOP");break;
case 0x000C: return _T("GPSSpeedRef");break;
case 0x000D: return _T("GPSSpeed");break;
case 0x000E: return _T("GPSTrackRef");break;
case 0x000F: return _T("GPSTrack");break;
case 0x0010: return _T("GPSImgDirectionRef");break;
case 0x0011: return _T("GPSImgDirection");break;
case 0x0012: return _T("GPSMapDatum");break;
case 0x0013: return _T("GPSDestLatitudeRef");break;
case 0x0014: return _T("GPSDestLatitude");break;
case 0x0015: return _T("GPSDestLongitudeRef");break;
case 0x0016: return _T("GPSDestLongitude");break;
case 0x0017: return _T("GPSDestBearingRef");break;
case 0x0018: return _T("GPSDestBearing");break;
case 0x0019: return _T("GPSDestDistanceRef");break;
case 0x001A: return _T("GPSDestDistance");break;
case 0x001B: return _T("GPSProcessingMethod");break;
case 0x001C: return _T("GPSAreaInformation");break;
case 0x001D: return _T("GPSDateStamp");break;
case 0x001E: return _T("GPSDifferential");break;
default:
strTmp.Format(_T("GPS.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} else if (strSect == _T("MakerIFD")) {
// Makernotes need special handling
// We only support a few different manufacturers for makernotes.
// A few Canon tags are supported in this routine, the rest are
// handled by the LookupMakerCanonTag() call.
if (m_strImgExifMake == _T("Canon")) {
switch(nTag)
{
case 0x0001: return _T("Canon.CameraSettings1");break;
case 0x0004: return _T("Canon.CameraSettings2");break;
case 0x0006: return _T("Canon.ImageType");break;
case 0x0007: return _T("Canon.FirmwareVersion");break;
case 0x0008: return _T("Canon.ImageNumber");break;
case 0x0009: return _T("Canon.OwnerName");break;
case 0x000C: return _T("Canon.SerialNumber");break;
case 0x000F: return _T("Canon.CustomFunctions");break;
case 0x0012: return _T("Canon.PictureInfo");break;
case 0x00A9: return _T("Canon.WhiteBalanceTable");break;
default:
strTmp.Format(_T("Canon.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} // Canon
else if (m_strImgExifMake == _T("SIGMA"))
{
switch(nTag)
{
case 0x0002: return _T("Sigma.SerialNumber");break; // Ascii Camera serial number
case 0x0003: return _T("Sigma.DriveMode");break; // Ascii Drive Mode
case 0x0004: return _T("Sigma.ResolutionMode");break; // Ascii Resolution Mode
case 0x0005: return _T("Sigma.AutofocusMode");break; // Ascii Autofocus mode
case 0x0006: return _T("Sigma.FocusSetting");break; // Ascii Focus setting
case 0x0007: return _T("Sigma.WhiteBalance");break; // Ascii White balance
case 0x0008: return _T("Sigma.ExposureMode");break; // Ascii Exposure mode
case 0x0009: return _T("Sigma.MeteringMode");break; // Ascii Metering mode
case 0x000a: return _T("Sigma.LensRange");break; // Ascii Lens focal length range
case 0x000b: return _T("Sigma.ColorSpace");break; // Ascii Color space
case 0x000c: return _T("Sigma.Exposure");break; // Ascii Exposure
case 0x000d: return _T("Sigma.Contrast");break; // Ascii Contrast
case 0x000e: return _T("Sigma.Shadow");break; // Ascii Shadow
case 0x000f: return _T("Sigma.Highlight");break; // Ascii Highlight
case 0x0010: return _T("Sigma.Saturation");break; // Ascii Saturation
case 0x0011: return _T("Sigma.Sharpness");break; // Ascii Sharpness
case 0x0012: return _T("Sigma.FillLight");break; // Ascii X3 Fill light
case 0x0014: return _T("Sigma.ColorAdjustment");break; // Ascii Color adjustment
case 0x0015: return _T("Sigma.AdjustmentMode");break; // Ascii Adjustment mode
case 0x0016: return _T("Sigma.Quality");break; // Ascii Quality
case 0x0017: return _T("Sigma.Firmware");break; // Ascii Firmware
case 0x0018: return _T("Sigma.Software");break; // Ascii Software
case 0x0019: return _T("Sigma.AutoBracket");break; // Ascii Auto bracket
default:
strTmp.Format(_T("Sigma.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} // SIGMA
else if (m_strImgExifMake == _T("SONY"))
{
switch(nTag)
{
case 0xb021: return _T("Sony.ColorTemperature");break;
case 0xb023: return _T("Sony.SceneMode");break;
case 0xb024: return _T("Sony.ZoneMatching");break;
case 0xb025: return _T("Sony.DynamicRangeOptimizer");break;
case 0xb026: return _T("Sony.ImageStabilization");break;
case 0xb027: return _T("Sony.LensID");break;
case 0xb029: return _T("Sony.ColorMode");break;
case 0xb040: return _T("Sony.Macro");break;
case 0xb041: return _T("Sony.ExposureMode");break;
case 0xb047: return _T("Sony.Quality");break;
case 0xb04e: return _T("Sony.LongExposureNoiseReduction");break;
default:
// No real info is known
strTmp.Format(_T("Sony.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} // SONY
else if (m_strImgExifMake == _T("FUJIFILM"))
{
switch(nTag)
{
case 0x0000: return _T("Fujifilm.Version");break; // Undefined Fujifilm Makernote version
case 0x1000: return _T("Fujifilm.Quality");break; // Ascii Image quality setting
case 0x1001: return _T("Fujifilm.Sharpness");break; // Short Sharpness setting
case 0x1002: return _T("Fujifilm.WhiteBalance");break; // Short White balance setting
case 0x1003: return _T("Fujifilm.Color");break; // Short Chroma saturation setting
case 0x1004: return _T("Fujifilm.Tone");break; // Short Contrast setting
case 0x1010: return _T("Fujifilm.FlashMode");break; // Short Flash firing mode setting
case 0x1011: return _T("Fujifilm.FlashStrength");break; // SRational Flash firing strength compensation setting
case 0x1020: return _T("Fujifilm.Macro");break; // Short Macro mode setting
case 0x1021: return _T("Fujifilm.FocusMode");break; // Short Focusing mode setting
case 0x1030: return _T("Fujifilm.SlowSync");break; // Short Slow synchro mode setting
case 0x1031: return _T("Fujifilm.PictureMode");break; // Short Picture mode setting
case 0x1100: return _T("Fujifilm.Continuous");break; // Short Continuous shooting or auto bracketing setting
case 0x1210: return _T("Fujifilm.FinePixColor");break; // Short Fuji FinePix Color setting
case 0x1300: return _T("Fujifilm.BlurWarning");break; // Short Blur warning status
case 0x1301: return _T("Fujifilm.FocusWarning");break; // Short Auto Focus warning status
case 0x1302: return _T("Fujifilm.AeWarning");break; // Short Auto Exposure warning status
default:
strTmp.Format(_T("Fujifilm.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} // FUJIFILM
else if (m_strImgExifMake == _T("NIKON"))
{
if (m_nImgExifMakeSubtype == 1) {
// Type 1
switch(nTag)
{
case 0x0001: return _T("Nikon1.Version");break; // Undefined Nikon Makernote version
case 0x0002: return _T("Nikon1.ISOSpeed");break; // Short ISO speed setting
case 0x0003: return _T("Nikon1.ColorMode");break; // Ascii Color mode
case 0x0004: return _T("Nikon1.Quality");break; // Ascii Image quality setting
case 0x0005: return _T("Nikon1.WhiteBalance");break; // Ascii White balance
case 0x0006: return _T("Nikon1.Sharpening");break; // Ascii Image sharpening setting
case 0x0007: return _T("Nikon1.Focus");break; // Ascii Focus mode
case 0x0008: return _T("Nikon1.Flash");break; // Ascii Flash mode
case 0x000f: return _T("Nikon1.ISOSelection");break; // Ascii ISO selection
case 0x0010: return _T("Nikon1.DataDump");break; // Undefined Data dump
case 0x0080: return _T("Nikon1.ImageAdjustment");break; // Ascii Image adjustment setting
case 0x0082: return _T("Nikon1.Adapter");break; // Ascii Adapter used
case 0x0085: return _T("Nikon1.FocusDistance");break; // Rational Manual focus distance
case 0x0086: return _T("Nikon1.DigitalZoom");break; // Rational Digital zoom setting
case 0x0088: return _T("Nikon1.AFFocusPos");break; // Undefined AF focus position
default:
strTmp.Format(_T("Nikon1.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
}
else if (m_nImgExifMakeSubtype == 2)
{
// Type 2
switch(nTag)
{
case 0x0003: return _T("Nikon2.Quality");break; // Short Image quality setting
case 0x0004: return _T("Nikon2.ColorMode");break; // Short Color mode
case 0x0005: return _T("Nikon2.ImageAdjustment");break; // Short Image adjustment setting
case 0x0006: return _T("Nikon2.ISOSpeed");break; // Short ISO speed setting
case 0x0007: return _T("Nikon2.WhiteBalance");break; // Short White balance
case 0x0008: return _T("Nikon2.Focus");break; // Rational Focus mode
case 0x000a: return _T("Nikon2.DigitalZoom");break; // Rational Digital zoom setting
case 0x000b: return _T("Nikon2.Adapter");break; // Short Adapter used
default:
strTmp.Format(_T("Nikon2.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
}
else if (m_nImgExifMakeSubtype == 3)
{
// Type 3
switch(nTag)
{
case 0x0001: return _T("Nikon3.Version");break; // Undefined Nikon Makernote version
case 0x0002: return _T("Nikon3.ISOSpeed");break; // Short ISO speed used
case 0x0003: return _T("Nikon3.ColorMode");break; // Ascii Color mode
case 0x0004: return _T("Nikon3.Quality");break; // Ascii Image quality setting
case 0x0005: return _T("Nikon3.WhiteBalance");break; // Ascii White balance
case 0x0006: return _T("Nikon3.Sharpening");break; // Ascii Image sharpening setting
case 0x0007: return _T("Nikon3.Focus");break; // Ascii Focus mode
case 0x0008: return _T("Nikon3.FlashSetting");break; // Ascii Flash setting
case 0x0009: return _T("Nikon3.FlashMode");break; // Ascii Flash mode
case 0x000b: return _T("Nikon3.WhiteBalanceBias");break; // SShort White balance bias
case 0x000e: return _T("Nikon3.ExposureDiff");break; // Undefined Exposure difference
case 0x000f: return _T("Nikon3.ISOSelection");break; // Ascii ISO selection
case 0x0010: return _T("Nikon3.DataDump");break; // Undefined Data dump
case 0x0011: return _T("Nikon3.ThumbOffset");break; // Long Thumbnail IFD offset
case 0x0012: return _T("Nikon3.FlashComp");break; // Undefined Flash compensation setting
case 0x0013: return _T("Nikon3.ISOSetting");break; // Short ISO speed setting
case 0x0016: return _T("Nikon3.ImageBoundary");break; // Short Image boundry
case 0x0018: return _T("Nikon3.FlashBracketComp");break; // Undefined Flash bracket compensation applied
case 0x0019: return _T("Nikon3.ExposureBracketComp");break; // SRational AE bracket compensation applied
case 0x0080: return _T("Nikon3.ImageAdjustment");break; // Ascii Image adjustment setting
case 0x0081: return _T("Nikon3.ToneComp");break; // Ascii Tone compensation setting (contrast)
case 0x0082: return _T("Nikon3.AuxiliaryLens");break; // Ascii Auxiliary lens (adapter)
case 0x0083: return _T("Nikon3.LensType");break; // Byte Lens type
case 0x0084: return _T("Nikon3.Lens");break; // Rational Lens
case 0x0085: return _T("Nikon3.FocusDistance");break; // Rational Manual focus distance
case 0x0086: return _T("Nikon3.DigitalZoom");break; // Rational Digital zoom setting
case 0x0087: return _T("Nikon3.FlashType");break; // Byte Type of flash used
case 0x0088: return _T("Nikon3.AFFocusPos");break; // Undefined AF focus position
case 0x0089: return _T("Nikon3.Bracketing");break; // Short Bracketing
case 0x008b: return _T("Nikon3.LensFStops");break; // Undefined Number of lens stops
case 0x008c: return _T("Nikon3.ToneCurve");break; // Undefined Tone curve
case 0x008d: return _T("Nikon3.ColorMode");break; // Ascii Color mode
case 0x008f: return _T("Nikon3.SceneMode");break; // Ascii Scene mode
case 0x0090: return _T("Nikon3.LightingType");break; // Ascii Lighting type
case 0x0092: return _T("Nikon3.HueAdjustment");break; // SShort Hue adjustment
case 0x0094: return _T("Nikon3.Saturation");break; // SShort Saturation adjustment
case 0x0095: return _T("Nikon3.NoiseReduction");break; // Ascii Noise reduction
case 0x0096: return _T("Nikon3.CompressionCurve");break; // Undefined Compression curve
case 0x0097: return _T("Nikon3.ColorBalance2");break; // Undefined Color balance 2
case 0x0098: return _T("Nikon3.LensData");break; // Undefined Lens data
case 0x0099: return _T("Nikon3.NEFThumbnailSize");break; // Short NEF thumbnail size
case 0x009a: return _T("Nikon3.SensorPixelSize");break; // Rational Sensor pixel size
case 0x00a0: return _T("Nikon3.SerialNumber");break; // Ascii Camera serial number
case 0x00a7: return _T("Nikon3.ShutterCount");break; // Long Number of shots taken by camera
case 0x00a9: return _T("Nikon3.ImageOptimization");break; // Ascii Image optimization
case 0x00aa: return _T("Nikon3.Saturation");break; // Ascii Saturation
case 0x00ab: return _T("Nikon3.VariProgram");break; // Ascii Vari program
default:
strTmp.Format(_T("Nikon3.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
}
} // NIKON
} // if strSect
bUnknown = true;
return _T("???");
}
// Interpret the MakerNote header to determine any applicable MakerNote subtype.
//
// PRE:
// - m_strImgExifMake
// - buffer
//
// INPUT:
// - none
//
// RETURN:
// - Decode success
//
// POST:
// - m_nImgExifMakeSubtype
//
bool CjfifDecode::DecodeMakerSubType()
{
CString strTmp;
m_nImgExifMakeSubtype = 0;
if (m_strImgExifMake == _T("NIKON"))
{
strTmp = _T("");
for (unsigned nInd=0;nInd<5;nInd++) {
strTmp += (char)Buf(m_nPos+nInd);
}
if (strTmp == _T("Nikon")) {
if (Buf(m_nPos+6) == 1) {
// Type 1
m_pLog->AddLine(_T(" Nikon Makernote Type 1 detected"));
m_nImgExifMakeSubtype = 1;
m_nPos += 8;
} else if (Buf(m_nPos+6) == 2) {
// Type 3
m_pLog->AddLine(_T(" Nikon Makernote Type 3 detected"));
m_nImgExifMakeSubtype = 3;
m_nPos += 18;
} else {
CString strTmp = _T("ERROR: Unknown Nikon Makernote Type");
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return FALSE;
}
} else {
// Type 2
m_pLog->AddLine(_T(" Nikon Makernote Type 2 detected"));
//m_nImgExifMakeSubtype = 2;
// tests on D1 seem to indicate that it uses Type 1 headers
m_nImgExifMakeSubtype = 1;
m_nPos += 0;
}
}
else if (m_strImgExifMake == _T("SIGMA"))
{
strTmp = _T("");
for (unsigned ind=0;ind<8;ind++) {
if (Buf(m_nPos+ind) != 0)
strTmp += (char)Buf(m_nPos+ind);
}
if ( (strTmp == _T("SIGMA")) ||
(strTmp == _T("FOVEON")) )
{
// Valid marker
// Now skip over the 8-chars and 2 unknown chars
m_nPos += 10;
} else {
CString strTmp = _T("ERROR: Unknown SIGMA Makernote identifier");
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return FALSE;
}
} // SIGMA
else if (m_strImgExifMake == _T("FUJIFILM"))
{
strTmp = _T("");
for (unsigned ind=0;ind<8;ind++) {
if (Buf(m_nPos+ind) != 0)
strTmp += (char)Buf(m_nPos+ind);
}
if (strTmp == _T("FUJIFILM"))
{
// Valid marker
// Now skip over the 8-chars and 4 Pointer chars
// FIXME: Do I need to dereference this pointer?
m_nPos += 12;
} else {
CString strTmp = _T("ERROR: Unknown FUJIFILM Makernote identifier");
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return FALSE;
}
} // FUJIFILM
else if (m_strImgExifMake == _T("SONY"))
{
strTmp = _T("");
for (unsigned ind=0;ind<12;ind++) {
if (Buf(m_nPos+ind) != 0)
strTmp += (char)Buf(m_nPos+ind);
}
if (strTmp == _T("SONY DSC "))
{
// Valid marker
// Now skip over the 9-chars and 3 null chars
m_nPos += 12;
} else {
CString strTmp = _T("ERROR: Unknown SONY Makernote identifier");
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return FALSE;
}
} // SONY
return TRUE;
}
// Read two UINT32 from the buffer (8B) and interpret
// as a rational entry. Convert to floating point.
// Byte swap as required
//
// INPUT:
// - pos Buffer position
// - val Floating point value
//
// RETURN:
// - Was the conversion successful?
//
bool CjfifDecode::DecodeValRational(unsigned nPos,float &nVal)
{
int nValNumer;
int nValDenom;
nVal = 0;
nValNumer = ByteSwap4(Buf(nPos+0),Buf(nPos+1),Buf(nPos+2),Buf(nPos+3));
nValDenom = ByteSwap4(Buf(nPos+4),Buf(nPos+5),Buf(nPos+6),Buf(nPos+7));
if (nValDenom == 0) {
// Divide by zero!
return false;
} else {
nVal = (float)nValNumer/(float)nValDenom;
return true;
}
}
// Read two UINT32 from the buffer (8B) to create a formatted
// fraction string. Byte swap as required
//
// INPUT:
// - pos Buffer position
//
// RETURN:
// - Formatted string
//
CString CjfifDecode::DecodeValFraction(unsigned nPos)
{
CString strTmp;
int nValNumer = ReadSwap4(nPos+0);
int nValDenom = ReadSwap4(nPos+4);
strTmp.Format(_T("%d/%d"),nValNumer,nValDenom);
return strTmp;
}
// Convert multiple coordinates into a formatted GPS string
//
// INPUT:
// - nCount Number of coordinates (1,2,3)
// - fCoord1 Coordinate #1
// - fCoord2 Coordinate #2
// - fCoord3 Coordinate #3
//
// OUTPUT:
// - strCoord The formatted GPS string
//
// RETURN:
// - Was the conversion successful?
//
bool CjfifDecode::PrintValGPS(unsigned nCount, float fCoord1, float fCoord2, float fCoord3,CString &strCoord)
{
float fTemp;
unsigned nCoordDeg;
unsigned nCoordMin;
float fCoordSec;
// TODO: Extend to support 1 & 2 coordinate GPS entries
if (nCount == 3) {
nCoordDeg = unsigned(fCoord1);
nCoordMin = unsigned(fCoord2);
if (fCoord3 == 0) {
fTemp = fCoord2 - (float)nCoordMin;
fCoordSec = fTemp * (float)60.0;
} else {
fCoordSec = fCoord3;
}
strCoord.Format(_T("%u deg %u' %.3f\""),nCoordDeg,nCoordMin,fCoordSec);
return true;
} else {
strCoord.Format(_T("ERROR: Can't handle %u-comonent GPS coords"),nCount);
return false;
}
}
// Read in 3 rational values from the buffer and output as a formatted GPS string
//
// INPUT:
// - pos Buffer position
//
// OUTPUT:
// - strCoord The formatted GPS string
//
// RETURN:
// - Was the conversion successful?
//
bool CjfifDecode::DecodeValGPS(unsigned nPos,CString &strCoord)
{
float fCoord1,fCoord2,fCoord3;
bool bRet;
bRet = true;
if (bRet) { bRet = DecodeValRational(nPos,fCoord1); nPos += 8; }
if (bRet) { bRet = DecodeValRational(nPos,fCoord2); nPos += 8; }
if (bRet) { bRet = DecodeValRational(nPos,fCoord3); nPos += 8; }
if (!bRet) {
strCoord.Format(_T("???"));
return false;
} else {
return PrintValGPS(3,fCoord1,fCoord2,fCoord3,strCoord);
}
}
// Read a UINT16 from the buffer, byte swap as required
//
// INPUT:
// - nPos Buffer position
//
// RETURN:
// - UINT16 from buffer
//
unsigned CjfifDecode::ReadSwap2(unsigned nPos)
{
return ByteSwap2(Buf(nPos+0),Buf(nPos+1));
}
// Read a UINT32 from the buffer, byte swap as required
//
// INPUT:
// - nPos Buffer position
//
// RETURN:
// - UINT32 from buffer
//
unsigned CjfifDecode::ReadSwap4(unsigned nPos)
{
return ByteSwap4(Buf(nPos),Buf(nPos+1),Buf(nPos+2),Buf(nPos+3));
}
// Read a UINT32 from the buffer, force as big endian
//
// INPUT:
// - nPos Buffer position
//
// RETURN:
// - UINT32 from buffer
//
unsigned CjfifDecode::ReadBe4(unsigned nPos)
{
// Big endian, no swap required
return (Buf(nPos)<<24) + (Buf(nPos+1)<<16) + (Buf(nPos+2)<<8) + Buf(nPos+3);
}
// Print hex from array of unsigned char
//
// INPUT:
// - anBytes Array of unsigned chars
// - nCount Indicates the number of array entries originally specified
// but the printing routine limits it to the maximum array depth
// allocated (MAX_anValues) and add an ellipsis "..."
// RETURN:
// - A formatted string
//
CString CjfifDecode::PrintAsHexUC(unsigned char* anBytes,unsigned nCount)
{
CString strVal;
CString strFull;
strFull = _T("0x[");
unsigned nMaxDisplay = MAX_anValues;
bool bExceedMaxDisplay;
bExceedMaxDisplay = (nCount > nMaxDisplay);
for (unsigned nInd=0;nInd<nCount;nInd++)
{
if (nInd < nMaxDisplay) {
if ((nInd % 4) == 0) {
if (nInd == 0) {
// Don't do anything for first value!
} else {
// Every 16 add big spacer / break
strFull += _T(" ");
}
} else {
//strFull += _T(" ");
}
strVal.Format(_T("%02X"),anBytes[nInd]);
strFull += strVal;
}
if ((nInd == nMaxDisplay) && (bExceedMaxDisplay)) {
strFull += _T("...");
}
}
strFull += _T("]");
return strFull;
}
// Print hex from array of unsigned bytes
//
// INPUT:
// - anBytes Array is passed as UINT32* even though it only
// represents a byte per entry
// - nCount Indicates the number of array entries originally specified
// but the printing routine limits it to the maximum array depth
// allocated (MAX_anValues) and add an ellipsis "..."
//
// RETURN:
// - A formatted string
//
CString CjfifDecode::PrintAsHex8(unsigned* anBytes,unsigned nCount)
{
CString strVal;
CString strFull;
unsigned nMaxDisplay = MAX_anValues;
bool bExceedMaxDisplay;
strFull = _T("0x[");
bExceedMaxDisplay = (nCount > nMaxDisplay);
for (unsigned nInd=0;nInd<nCount;nInd++)
{
if (nInd < nMaxDisplay) {
if ((nInd % 4) == 0) {
if (nInd == 0) {
// Don't do anything for first value!
} else {
// Every 16 add big spacer / break
strFull += _T(" ");
}
}
strVal.Format(_T("%02X"),anBytes[nInd]);
strFull += strVal;
}
if ((nInd == nMaxDisplay) && (bExceedMaxDisplay)) {
strFull += _T("...");
}
}
strFull += _T("]");
return strFull;
}
// Print hex from array of unsigned words
//
// INPUT:
// - anWords Array of UINT32 is passed
// - nCount Indicates the number of array entries originally specified
// but the printing routine limits it to the maximum array depth
// allocated (MAX_anValues) and add an ellipsis "..."
//
// RETURN:
// - A formatted string
//
CString CjfifDecode::PrintAsHex32(unsigned* anWords,unsigned nCount)
{
CString strVal;
CString strFull;
strFull = _T("0x[");
unsigned nMaxDisplay = MAX_anValues/4; // Reduce number of words to display since each is 32b not 8b
bool bExceedMaxDisplay;
bExceedMaxDisplay = (nCount > nMaxDisplay);
for (unsigned nInd=0;nInd<nCount;nInd++)
{
if (nInd < nMaxDisplay) {
if (nInd == 0) {
// Don't do anything for first value!
} else {
// Every word add a spacer
strFull += _T(" ");
}
strVal.Format(_T("%08X"),anWords[nInd]); // 32-bit words
strFull += strVal;
}
if ((nInd == nMaxDisplay) && (bExceedMaxDisplay)) {
strFull += _T("...");
}
}
strFull += _T("]");
return strFull;
}
// Process all of the entries within an EXIF IFD directory
// This is used for the main EXIF IFDs as well as MakerNotes
//
// INPUT:
// - ifdStr The IFD section that we are processing
// - pos_exif_start
// - start_ifd_ptr
//
// PRE:
// - m_strImgExifMake
// - m_bImgExifMakeSupported
// - m_nImgExifMakeSubtype
// - m_nImgExifMakerPtr
//
// RETURN:
// - 0 Decoding OK
// - 2 Decoding failure
//
// POST:
// - m_nPos
// - m_strImgExifMake
// - m_strImgExifModel
// - m_strImgQualExif
// - m_strImgExtras
// - m_strImgExifMake
// - m_nImgExifSubIfdPtr
// - m_nImgExifGpsIfdPtr
// - m_nImgExifInteropIfdPtr
// - m_bImgExifMakeSupported
// - m_bImgExifMakernotes
// - m_nImgExifMakerPtr
// - m_nImgExifThumbComp
// - m_nImgExifThumbOffset
// - m_nImgExifThumbLen
// - m_strSoftware
//
// NOTE:
// - IFD1 typically contains the thumbnail
//
unsigned CjfifDecode::DecodeExifIfd(CString strIfd,unsigned nPosExifStart,unsigned nStartIfdPtr)
{
// Temp variables
bool bRet;
CString strTmp;
CStr2 strRetVal;
CString strValTmp;
float fValReal;
CString strMaker;
// Display output variables
CString strFull;
CString strValOut;
BOOL bExtraDecode;
// Primary IFD variables
char acIfdValOffsetStr[5];
unsigned nIfdDirLen;
unsigned nIfdTagVal;
unsigned nIfdFormat;
unsigned nIfdNumComps;
bool nIfdTagUnknown;
unsigned nCompsToDisplay; // Maximum number of values to capture for display
unsigned anValues[MAX_anValues]; // Array of decoded values (Uint32)
signed anValuesS[MAX_anValues]; // Array of decoded values (Int32)
float afValues[MAX_anValues]; // Array of decoded values (float)
unsigned nIfdOffset; // First DWORD decode, usually offset
// Clear values array
for (unsigned ind=0;ind<MAX_anValues;ind++) {
anValues[ind] = 0;
anValuesS[ind] = 0;
afValues[ind] = 0;
}
// ==========================================================================
// Process IFD directory header
// ==========================================================================
// Move the file pointer to the start of the IFD
m_nPos = nPosExifStart+nStartIfdPtr;
strTmp.Format(_T(" EXIF %s @ Absolute 0x%08X"),(LPCTSTR)strIfd,m_nPos);
m_pLog->AddLine(strTmp);
////////////
// NOTE: Nikon type 3 starts out with the ASCII string "Nikon\0"
// before the rest of the items.
// TODO: need to process type1,type2,type3
// see: http://www.gvsoft.homedns.org/exif/makernote-nikon.html
strTmp.Format(_T("strIfd=[%s] m_strImgExifMake=[%s]"),(LPCTSTR)strIfd,(LPCTSTR)m_strImgExifMake);
DbgAddLine(strTmp);
// If this is the MakerNotes section, then we may want to skip
// altogether. Check to see if we are configured to process this
// section or if it is a supported manufacturer.
if (strIfd == _T("MakerIFD"))
{
// Mark the image as containing Makernotes
m_bImgExifMakernotes = true;
if (!m_pAppConfig->bDecodeMaker) {
strTmp.Format(_T(" Makernote decode option not enabled."));
m_pLog->AddLine(strTmp);
// If user didn't enable makernote decode, don't exit, just
// hide output. We still want to get at some info (such as Quality setting).
// At end, we'll need to re-enable it again.
m_pLog->Disable();
}
// If this Make is not supported, we'll need to exit
if (!m_bImgExifMakeSupported) {
strTmp.Format(_T(" Makernotes not yet supported for [%s]"),(LPCTSTR)m_strImgExifMake);
m_pLog->AddLine(strTmp);
m_pLog->Enable();
return 2;
}
// Determine the sub-type of the Maker field (if applicable)
// and advance the m_nPos pointer past the custom header.
// This call uses the class members: Buf(),m_nPos
if (!DecodeMakerSubType())
{
// If the subtype decode failed, skip the processing
m_pLog->Enable();
return 2;
}
}
// ==========================================================================
// Process IFD directory entries
// ==========================================================================
CString strIfdTag;
// =========== EXIF IFD Header (Start) ===========
// - Defined in Exif 2.2 Standard (JEITA CP-3451) section 4.6.2
// - Contents (2 bytes total)
// - Number of fields (2 bytes)
nIfdDirLen = ReadSwap2(m_nPos);
m_nPos+=2;
strTmp.Format(_T(" Dir Length = 0x%04X"),nIfdDirLen);
m_pLog->AddLine(strTmp);
// =========== EXIF IFD Header (End) ===========
// Start of IFD processing
// Step through each IFD entry and determine the type and
// decode accordingly.
for (unsigned nIfdEntryInd=0;nIfdEntryInd<nIfdDirLen;nIfdEntryInd++)
{
// By default, show single-line value summary
// bExtraDecode is used to indicate that additional special
// parsing output is available for this entry
bExtraDecode = FALSE;
strTmp.Format(_T(" Entry #%02u:"),nIfdEntryInd);
DbgAddLine(strTmp);
// =========== EXIF IFD Interoperability entry (Start) ===========
// - Defined in Exif 2.2 Standard (JEITA CP-3451) section 4.6.2
// - Contents (12 bytes total)
// - Tag (2 bytes)
// - Type (2 bytes)
// - Count (4 bytes)
// - Value Offset (4 bytes)
// Read Tag #
nIfdTagVal = ReadSwap2(m_nPos);
m_nPos+=2;
nIfdTagUnknown = false;
strIfdTag = LookupExifTag(strIfd,nIfdTagVal,nIfdTagUnknown);
strTmp.Format(_T(" Tag # = 0x%04X = [%s]"),nIfdTagVal,(LPCTSTR)strIfdTag);
DbgAddLine(strTmp);
// Read Format (or Type)
nIfdFormat = ReadSwap2(m_nPos);
m_nPos+=2;
strTmp.Format(_T(" Format # = 0x%04X"),nIfdFormat);
DbgAddLine(strTmp);
// Read number of Components
nIfdNumComps = ReadSwap4(m_nPos);
m_nPos+=4;
strTmp.Format(_T(" # Comps = 0x%08X"),nIfdNumComps);
DbgAddLine(strTmp);
// Check to see how many components have been listed.
// This helps trap errors in corrupted IFD segments, otherwise
// we will hang trying to decode millions of entries!
// See issue & testcase #1148
if (nIfdNumComps > 4000) {
// Warn user that we have clippped the component list.
// Note that this condition is only relevant when we are
// processing the general array fields. Fields such as MakerNote
// will also enter this condition so we shouldn't warn in those cases.
//
// TODO: Defer this warning message until after we are sure that we
// didn't handle the large dataset elsewhere.
// For now, only report this warning if we are not processing MakerNote
if (strIfdTag.Compare(_T("MakerNote"))!=0) {
strTmp.Format(_T(" Excessive # components (%u). Limiting to first 4000."),nIfdNumComps);
m_pLog->AddLineWarn(strTmp);
}
nIfdNumComps = 4000;
}
// Read Component Value / Offset
// We first treat it as a string and then re-interpret it as an integer
// ... first as a string (just in case length <=4)
for (unsigned i=0;i<4;i++) {
acIfdValOffsetStr[i] = (char)Buf(m_nPos+i);
}
acIfdValOffsetStr[4] = '\0';
// ... now as an unsigned value
// This assignment is general-purpose, typically used when
// we know that the IFD Value/Offset is just an offset
nIfdOffset = ReadSwap4(m_nPos);
strTmp.Format(_T(" # Val/Offset = 0x%08X"),nIfdOffset);
DbgAddLine(strTmp);
// =========== EXIF IFD Interoperability entry (End) ===========
// ==========================================================================
// Extract the IFD component entries
// ==========================================================================
// The EXIF IFD entries can appear in a wide range of
// formats / data types. The formats that have been
// publicly documented include:
// EXIF_FORMAT_BYTE = 1,
// EXIF_FORMAT_ASCII = 2,
// EXIF_FORMAT_SHORT = 3,
// EXIF_FORMAT_LONG = 4,
// EXIF_FORMAT_RATIONAL = 5,
// EXIF_FORMAT_SBYTE = 6,
// EXIF_FORMAT_UNDEFINED = 7,
// EXIF_FORMAT_SSHORT = 8,
// EXIF_FORMAT_SLONG = 9,
// EXIF_FORMAT_SRATIONAL = 10,
// EXIF_FORMAT_FLOAT = 11,
// EXIF_FORMAT_DOUBLE = 12
// The IFD variable formatter logic operates in two stages:
// In the first stage, the format type is decoded, which results
// in a generic decode for the IFD entry. Then, we start a second
// stage which re-interprets the values for a number of known
// special types.
switch(nIfdFormat)
{
// ----------------------------------------
// --- IFD Entry Type: Unsigned Byte
// ----------------------------------------
case 1:
strFull = _T(" Unsigned Byte=[");
strValOut = _T("");
// Limit display output
nCompsToDisplay = min(MAX_anValues,nIfdNumComps);
// If only a single value, use decimal, else use hex
if (nIfdNumComps == 1) {
anValues[0] = Buf(m_nPos+0);
strTmp.Format(_T("%u"),anValues[0]);
strValOut += strTmp;
} else {
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++)
{
if (nIfdNumComps <= 4) {
// Components fit inside 4B inline region
anValues[nInd] = Buf(m_nPos+nInd);
} else {
// Since the components don't fit inside 4B inline region
// we need to dereference
anValues[nInd] = Buf(nPosExifStart+nIfdOffset+nInd);
}
}
strValOut = PrintAsHex8(anValues,nIfdNumComps);
}
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
break;
// ----------------------------------------
// --- IFD Entry Type: ASCII string
// ----------------------------------------
case 2:
strFull = _T(" String=");
strValOut = _T("");
char cVal;
BYTE nVal;
// Limit display output
// TODO: Decide what an appropriate string limit would be
nCompsToDisplay = min(250,nIfdNumComps);
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++)
{
if (nIfdNumComps<=4) {
nVal = acIfdValOffsetStr[nInd];
}
else
{
// TODO: See if this can be migrated to the "custom decode"
// section later in the code. Decoding makernotes here is
// less desirable but unfortunately some Nikon makernotes use
// a non-standard offset value.
if ( (strIfd == _T("MakerIFD")) && (m_strImgExifMake == _T("NIKON")) && (m_nImgExifMakeSubtype == 3) )
{
// It seems that pointers in the Nikon Makernotes are
// done relative to the start of Maker IFD
// But why 10? Is this 10 = 18-8?
nVal = Buf(nPosExifStart+m_nImgExifMakerPtr+nIfdOffset+10+nInd);
} else if ( (strIfd == _T("MakerIFD")) && (m_strImgExifMake == _T("NIKON")) )
{
// It seems that pointers in the Nikon Makernotes are
// done relative to the start of Maker IFD
nVal = Buf(nPosExifStart+nIfdOffset+0+nInd);
} else {
// Canon Makernotes seem to be relative to the start
// of the EXIF IFD
nVal = Buf(nPosExifStart+nIfdOffset+nInd);
}
}
// Just in case the string has been null-terminated early
// or we have garbage, replace with '.'
// TODO: Clean this up
if (nVal != 0) {
cVal = (char)nVal;
if (!isprint(nVal)) {
cVal = '.';
}
strValOut += cVal;
}
}
strFull += strValOut;
DbgAddLine(strFull);
// TODO: Ideally, we would use a different string for display
// purposes that is wrapped in quotes. Currently "strValOut" is used
// in other sections of code (eg. in assignment to EXIF Make/Model/Software, etc.)
// so we don't want to affect that.
break;
// ----------------------------------------
// --- IFD Entry Type: Unsigned Short (2 bytes)
// ----------------------------------------
case 3:
// Limit display output
nCompsToDisplay = min(MAX_anValues,nIfdNumComps);
// Unsigned Short (2 bytes)
if (nIfdNumComps == 1) {
strFull = _T(" Unsigned Short=[");
// TODO: Confirm endianness is correct here
// Refer to Exif2-2 spec, page 14.
// Currently selecting 2 byte conversion from [1:0] out of [3:0]
anValues[0] = ReadSwap2(m_nPos);
strValOut.Format(_T("%u"),anValues[0]);
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
} else if (nIfdNumComps == 2) {
strFull = _T(" Unsigned Short=[");
// 2 unsigned shorts in 1 word
anValues[0] = ReadSwap2(m_nPos+0);
anValues[1] = ReadSwap2(m_nPos+2);
strValOut.Format(_T("%u, %u"),anValues[0],anValues[1]);
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
} else if (nIfdNumComps > MAX_IFD_COMPS) {
strValTmp.Format(_T(" Unsigned Short=[Too many entries (%u) to display]"),nIfdNumComps);
DbgAddLine(strValTmp);
strValOut.Format(_T("[Too many entries (%u) to display]"),nIfdNumComps);
} else {
// Try to handle multiple entries... note that this
// is used by the Maker notes IFD decode
strValOut = _T("");
strFull = _T(" Unsigned Short=[");
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++) {
if (nInd!=0) { strValOut += _T(", "); }
anValues[nInd] = ReadSwap2(nPosExifStart+nIfdOffset+(2*nInd));
strValTmp.Format(_T("%u"),anValues[nInd]);
strValOut += strValTmp;
}
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
}
break;
// ----------------------------------------
// --- IFD Entry Type: Unsigned Long (4 bytes)
// ----------------------------------------
case 4:
strFull = _T(" Unsigned Long=[");
strValOut = _T("");
// Limit display output
nCompsToDisplay = min(MAX_anValues,nIfdNumComps);
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++)
{
if (nIfdNumComps == 1) {
// Components fit inside 4B inline region
anValues[nInd] = ReadSwap4(m_nPos+(nInd*4));
} else {
// Since the components don't fit inside 4B inline region
// we need to dereference
anValues[nInd] = ReadSwap4(nPosExifStart+nIfdOffset+(nInd*4));
}
}
strValOut = PrintAsHex32(anValues,nIfdNumComps);
// If we only have a single component, then display both the hex and decimal
if (nCompsToDisplay==1) {
strTmp.Format(_T("%s / %u"),(LPCTSTR)strValOut,anValues[0]);
strValOut = strTmp;
}
break;
// ----------------------------------------
// --- IFD Entry Type: Unsigned Rational (8 bytes)
// ----------------------------------------
case 5:
// Unsigned Rational
strFull = _T(" Unsigned Rational=[");
strValOut = _T("");
// Limit display output
nCompsToDisplay = min(MAX_anValues,nIfdNumComps);
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++)
{
if (nInd!=0) { strValOut += _T(", "); }
strValTmp = DecodeValFraction(nPosExifStart+nIfdOffset+(nInd*8));
bRet = DecodeValRational(nPosExifStart+nIfdOffset+(nInd*8),fValReal);
afValues[nInd] = fValReal;
strValOut += strValTmp;
}
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
break;
// ----------------------------------------
// --- IFD Entry Type: Undefined (?)
// ----------------------------------------
case 7:
// Undefined -- assume 1 word long
// This is supposed to be a series of 8-bit bytes
// It is usually used for 32-bit pointers (in case of offsets), but could
// also represent ExifVersion, etc.
strFull = _T(" Undefined=[");
strValOut = _T("");
// Limit display output
nCompsToDisplay = min(MAX_anValues,nIfdNumComps);
if (nIfdNumComps <= 4) {
// This format is not defined, so output as hex for now
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++) {
anValues[nInd] = Buf(m_nPos+nInd);
}
strValOut = PrintAsHex8(anValues,nIfdNumComps);
strFull += strValOut;
} else {
// Dereference pointer
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++) {
anValues[nInd] = Buf(nPosExifStart+nIfdOffset+nInd);
}
strValOut = PrintAsHex8(anValues,nIfdNumComps);
strFull += strValOut;
}
strFull += _T("]");
DbgAddLine(strFull);
break;
// ----------------------------------------
// --- IFD Entry Type: Signed Short (2 bytes)
// ----------------------------------------
case 8:
// Limit display output
nCompsToDisplay = min(MAX_anValues,nIfdNumComps);
// Signed Short (2 bytes)
if (nIfdNumComps == 1) {
strFull = _T(" Signed Short=[");
// TODO: Confirm endianness is correct here
// Refer to Exif2-2 spec, page 14.
// Currently selecting 2 byte conversion from [1:0] out of [3:0]
// TODO: Ensure that ReadSwap2 handles signed notation properly
anValuesS[0] = ReadSwap2(m_nPos);
strValOut.Format(_T("%d"),anValuesS[0]);
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
} else if (nIfdNumComps == 2) {
strFull = _T(" Signed Short=[");
// 2 signed shorts in 1 word
// TODO: Ensure that ReadSwap2 handles signed notation properly
anValuesS[0] = ReadSwap2(m_nPos+0);
anValuesS[1] = ReadSwap2(m_nPos+2);
strValOut.Format(_T("%d, %d"),anValuesS[0],anValuesS[0]);
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
} else if (nIfdNumComps > MAX_IFD_COMPS) {
// Only print it out if it has less than MAX_IFD_COMPS entries
strValTmp.Format(_T(" Signed Short=[Too many entries (%u) to display]"),nIfdNumComps);
DbgAddLine(strValTmp);
strValOut.Format(_T("[Too many entries (%u) to display]"),nIfdNumComps);
} else {
// Try to handle multiple entries... note that this
// is used by the Maker notes IFD decode
// Note that we don't call LookupMakerCanonTag() here
// as that is only needed for the "unsigned short", not
// "signed short".
strValOut = _T("");
strFull = _T(" Signed Short=[");
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++) {
if (nInd!=0) { strValOut += _T(", "); }
anValuesS[nInd] = ReadSwap2(nPosExifStart+nIfdOffset+(2*nInd));
strValTmp.Format(_T("%d"),anValuesS[nInd]);
strValOut += strValTmp;
}
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
}
break;
// ----------------------------------------
// --- IFD Entry Type: Signed Rational (8 bytes)
// ----------------------------------------
case 10:
// Signed Rational
strFull = _T(" Signed Rational=[");
strValOut = _T("");
// Limit display output
nCompsToDisplay = min(MAX_anValues,nIfdNumComps);
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++)
{
if (nInd!=0) { strValOut += _T(", "); }
strValTmp = DecodeValFraction(nPosExifStart+nIfdOffset+(nInd*8));
bRet = DecodeValRational(nPosExifStart+nIfdOffset+(nInd*8),fValReal);
afValues[nInd] = fValReal;
strValOut += strValTmp;
}
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
break;
default:
strTmp.Format(_T("ERROR: Unsupported format [%d]"),nIfdFormat);
anValues[0] = ReadSwap4(m_nPos);
strValOut.Format(_T("0x%08X???"),anValues[0]);
m_pLog->Enable();
return 2;
break;
} // switch nIfdTagVal
// ==========================================================================
// Custom Value String decodes
// ==========================================================================
// At this point we might re-format the values, thereby
// overriding the default strValOut. We have access to the
// anValues[] (array of unsigned int)
// anValuesS[] (array of signed int)
// afValues[] (array of float)
// Re-format special output items
// This will override "strValOut" that may have previously been defined
if ((strIfdTag == _T("GPSLatitude")) ||
(strIfdTag == _T("GPSLongitude"))) {
bRet = PrintValGPS(nIfdNumComps,afValues[0],afValues[1],afValues[2],strValOut);
} else if (strIfdTag == _T("GPSVersionID")) {
strValOut.Format(_T("%u.%u.%u.%u"),anValues[0],anValues[1],anValues[2],anValues[3]);
} else if (strIfdTag == _T("GPSAltitudeRef")) {
switch (anValues[0]) {
case 0 : strValOut = _T("Above Sea Level"); break;
case 1 : strValOut = _T("Below Sea Level"); break;
}
} else if (strIfdTag == _T("GPSStatus")) {
switch (acIfdValOffsetStr[0]) {
case 'A' : strValOut = _T("Measurement in progress"); break;
case 'V' : strValOut = _T("Measurement Interoperability"); break;
}
} else if (strIfdTag == _T("GPSMeasureMode")) {
switch (acIfdValOffsetStr[0]) {
case '2' : strValOut = _T("2-dimensional"); break;
case '3' : strValOut = _T("3-dimensional"); break;
}
} else if ((strIfdTag == _T("GPSSpeedRef")) ||
(strIfdTag == _T("GPSDestDistanceRef"))) {
switch (acIfdValOffsetStr[0]) {
case 'K' : strValOut = _T("km/h"); break;
case 'M' : strValOut = _T("mph"); break;
case 'N' : strValOut = _T("knots"); break;
}
} else if ((strIfdTag == _T("GPSTrackRef")) ||
(strIfdTag == _T("GPSImgDirectionRef")) ||
(strIfdTag == _T("GPSDestBearingRef"))) {
switch (acIfdValOffsetStr[0]) {
case 'T' : strValOut = _T("True direction"); break;
case 'M' : strValOut = _T("Magnetic direction"); break;
}
} else if (strIfdTag == _T("GPSDifferential")) {
switch (anValues[0]) {
case 0 : strValOut = _T("Measurement without differential correction"); break;
case 1 : strValOut = _T("Differential correction applied"); break;
}
} else if (strIfdTag == _T("GPSAltitude")) {
strValOut.Format(_T("%.3f m"),afValues[0]);
} else if (strIfdTag == _T("GPSSpeed")) {
strValOut.Format(_T("%.3f"),afValues[0]);
} else if (strIfdTag == _T("GPSTimeStamp")) {
strValOut.Format(_T("%.0f:%.0f:%.2f"),afValues[0],afValues[1],afValues[2]);
} else if (strIfdTag == _T("GPSTrack")) {
strValOut.Format(_T("%.2f"),afValues[0]);
} else if (strIfdTag == _T("GPSDOP")) {
strValOut.Format(_T("%.4f"),afValues[0]);
}
if (strIfdTag == _T("Compression")) {
switch (anValues[0]) {
case 1 : strValOut = _T("None"); break;
case 6 : strValOut = _T("JPEG"); break;
}
} else if (strIfdTag == _T("ExposureTime")) {
// Assume only one
strValTmp = strValOut;
strValOut.Format(_T("%s s"),(LPCTSTR)strValTmp);
} else if (strIfdTag == _T("FNumber")) {
// Assume only one
strValOut.Format(_T("F%.1f"),afValues[0]);
} else if (strIfdTag == _T("FocalLength")) {
// Assume only one
strValOut.Format(_T("%.0f mm"),afValues[0]);
} else if (strIfdTag == _T("ExposureBiasValue")) {
// Assume only one
// TODO: Need to test negative numbers
strValOut.Format(_T("%0.2f eV"),afValues[0]);
} else if (strIfdTag == _T("ExifVersion")) {
// Assume only one
strValOut.Format(_T("%c%c.%c%c"),anValues[0],anValues[1],anValues[2],anValues[3]);
} else if (strIfdTag == _T("FlashPixVersion")) {
// Assume only one
strValOut.Format(_T("%c%c.%c%c"),anValues[0],anValues[1],anValues[2],anValues[3]);
} else if (strIfdTag == _T("PhotometricInterpretation")) {
switch (anValues[0]) {
case 1 : strValOut = _T("Monochrome"); break;
case 2 : strValOut = _T("RGB"); break;
case 6 : strValOut = _T("YCbCr"); break;
}
} else if (strIfdTag == _T("Orientation")) {
switch (anValues[0]) {
case 1 : strValOut = _T("1 = Row 0: top, Col 0: left"); break;
case 2 : strValOut = _T("2 = Row 0: top, Col 0: right"); break;
case 3 : strValOut = _T("3 = Row 0: bottom, Col 0: right"); break;
case 4 : strValOut = _T("4 = Row 0: bottom, Col 0: left"); break;
case 5 : strValOut = _T("5 = Row 0: left, Col 0: top"); break;
case 6 : strValOut = _T("6 = Row 0: right, Col 0: top"); break;
case 7 : strValOut = _T("7 = Row 0: right, Col 0: bottom"); break;
case 8 : strValOut = _T("8 = Row 0: left, Col 0: bottom"); break;
}
} else if (strIfdTag == _T("PlanarConfiguration")) {
switch (anValues[0]) {
case 1 : strValOut = _T("Chunky format"); break;
case 2 : strValOut = _T("Planar format"); break;
}
} else if (strIfdTag == _T("YCbCrSubSampling")) {
switch (anValues[0]*65536 + anValues[1]) {
case 0x00020001 : strValOut = _T("4:2:2"); break;
case 0x00020002 : strValOut = _T("4:2:0"); break;
}
} else if (strIfdTag == _T("YCbCrPositioning")) {
switch (anValues[0]) {
case 1 : strValOut = _T("Centered"); break;
case 2 : strValOut = _T("Co-sited"); break;
}
} else if (strIfdTag == _T("ResolutionUnit")) {
switch (anValues[0]) {
case 1 : strValOut = _T("None"); break;
case 2 : strValOut = _T("Inch"); break;
case 3 : strValOut = _T("Centimeter"); break;
}
} else if (strIfdTag == _T("FocalPlaneResolutionUnit")) {
switch (anValues[0]) {
case 1 : strValOut = _T("None"); break;
case 2 : strValOut = _T("Inch"); break;
case 3 : strValOut = _T("Centimeter"); break;
}
} else if (strIfdTag == _T("ColorSpace")) {
switch (anValues[0]) {
case 1 : strValOut = _T("sRGB"); break;
case 0xFFFF : strValOut = _T("Uncalibrated"); break;
}
} else if (strIfdTag == _T("ComponentsConfiguration")) {
// Undefined type, assume 4 bytes
strValOut = _T("[");
for (unsigned vind=0;vind<4;vind++) {
if (vind != 0) { strValOut += _T(" "); }
switch (anValues[vind]) {
case 0 : strValOut += _T("."); break;
case 1 : strValOut += _T("Y"); break;
case 2 : strValOut += _T("Cb"); break;
case 3 : strValOut += _T("Cr"); break;
case 4 : strValOut += _T("R"); break;
case 5 : strValOut += _T("G"); break;
case 6 : strValOut += _T("B"); break;
default : strValOut += _T("?"); break;
}
}
strValOut += _T("]");
} else if ( (strIfdTag == _T("XPTitle")) ||
(strIfdTag == _T("XPComment")) ||
(strIfdTag == _T("XPAuthor")) ||
(strIfdTag == _T("XPKeywords")) ||
(strIfdTag == _T("XPSubject")) ) {
strValOut = _T("\"");
CString strVal;
strVal = m_pWBuf->BufReadUniStr2(nPosExifStart+nIfdOffset,nIfdNumComps);
strValOut += strVal;
strValOut += _T("\"");
} else if (strIfdTag == _T("UserComment")) {
// Character code
unsigned anCharCode[8];
for (unsigned vInd=0;vInd<8;vInd++) {
anCharCode[vInd] = Buf(nPosExifStart+nIfdOffset+0+vInd);
}
// Actual string
strValOut = _T("\"");
bool bDone = false;
char cTmp;
for (unsigned vInd=0;(vInd<nIfdNumComps-8)&&(!bDone);vInd++) {
cTmp = (char)Buf(nPosExifStart+nIfdOffset+8+vInd);
if (cTmp == 0) { bDone = true; } else { strValOut += cTmp; }
}
strValOut += _T("\"");
} else if (strIfdTag == _T("MeteringMode")) {
switch (anValues[0]) {
case 0 : strValOut = _T("Unknown"); break;
case 1 : strValOut = _T("Average"); break;
case 2 : strValOut = _T("CenterWeightedAverage"); break;
case 3 : strValOut = _T("Spot"); break;
case 4 : strValOut = _T("MultiSpot"); break;
case 5 : strValOut = _T("Pattern"); break;
case 6 : strValOut = _T("Partial"); break;
case 255 : strValOut = _T("Other"); break;
}
} else if (strIfdTag == _T("ExposureProgram")) {
switch (anValues[0]) {
case 0 : strValOut = _T("Not defined"); break;
case 1 : strValOut = _T("Manual"); break;
case 2 : strValOut = _T("Normal program"); break;
case 3 : strValOut = _T("Aperture priority"); break;
case 4 : strValOut = _T("Shutter priority"); break;
case 5 : strValOut = _T("Creative program (depth of field)"); break;
case 6 : strValOut = _T("Action program (fast shutter speed)"); break;
case 7 : strValOut = _T("Portrait mode"); break;
case 8 : strValOut = _T("Landscape mode"); break;
}
} else if (strIfdTag == _T("Flash")) {
switch (anValues[0] & 1) {
case 0 : strValOut = _T("Flash did not fire"); break;
case 1 : strValOut = _T("Flash fired"); break;
}
// TODO: Add other bitfields?
} else if (strIfdTag == _T("SensingMethod")) {
switch (anValues[0]) {
case 1 : strValOut = _T("Not defined"); break;
case 2 : strValOut = _T("One-chip color area sensor"); break;
case 3 : strValOut = _T("Two-chip color area sensor"); break;
case 4 : strValOut = _T("Three-chip color area sensor"); break;
case 5 : strValOut = _T("Color sequential area sensor"); break;
case 7 : strValOut = _T("Trilinear sensor"); break;
case 8 : strValOut = _T("Color sequential linear sensor"); break;
}
} else if (strIfdTag == _T("FileSource")) {
switch (anValues[0]) {
case 3 : strValOut = _T("DSC"); break;
}
} else if (strIfdTag == _T("CustomRendered")) {
switch (anValues[0]) {
case 0 : strValOut = _T("Normal process"); break;
case 1 : strValOut = _T("Custom process"); break;
}
} else if (strIfdTag == _T("ExposureMode")) {
switch (anValues[0]) {
case 0 : strValOut = _T("Auto exposure"); break;
case 1 : strValOut = _T("Manual exposure"); break;
case 2 : strValOut = _T("Auto bracket"); break;
}
} else if (strIfdTag == _T("WhiteBalance")) {
switch (anValues[0]) {
case 0 : strValOut = _T("Auto white balance"); break;
case 1 : strValOut = _T("Manual white balance"); break;
}
} else if (strIfdTag == _T("SceneCaptureType")) {
switch (anValues[0]) {
case 0 : strValOut = _T("Standard"); break;
case 1 : strValOut = _T("Landscape"); break;
case 2 : strValOut = _T("Portrait"); break;
case 3 : strValOut = _T("Night scene"); break;
}
} else if (strIfdTag == _T("SceneType")) {
switch (anValues[0]) {
case 1 : strValOut = _T("A directly photographed image"); break;
}
} else if (strIfdTag == _T("LightSource")) {
switch (anValues[0]) {
case 0 : strValOut = _T("unknown"); break;
case 1 : strValOut = _T("Daylight"); break;
case 2 : strValOut = _T("Fluorescent"); break;
case 3 : strValOut = _T("Tungsten (incandescent light)"); break;
case 4 : strValOut = _T("Flash"); break;
case 9 : strValOut = _T("Fine weather"); break;
case 10 : strValOut = _T("Cloudy weather"); break;
case 11 : strValOut = _T("Shade"); break;
case 12 : strValOut = _T("Daylight fluorescent (D 5700 � 7100K)"); break;
case 13 : strValOut = _T("Day white fluorescent (N 4600 � 5400K)"); break;
case 14 : strValOut = _T("Cool white fluorescent (W 3900 � 4500K)"); break;
case 15 : strValOut = _T("White fluorescent (WW 3200 � 3700K)"); break;
case 17 : strValOut = _T("Standard light A"); break;
case 18 : strValOut = _T("Standard light B"); break;
case 19 : strValOut = _T("Standard light C"); break;
case 20 : strValOut = _T("D55"); break;
case 21 : strValOut = _T("D65"); break;
case 22 : strValOut = _T("D75"); break;
case 23 : strValOut = _T("D50"); break;
case 24 : strValOut = _T("ISO studio tungsten"); break;
case 255 : strValOut = _T("other light source"); break;
}
} else if (strIfdTag == _T("SubjectArea")) {
switch (nIfdNumComps) {
case 2 :
// coords
strValOut.Format(_T("Coords: Center=[%u,%u]"),
anValues[0],anValues[1]);
break;
case 3 :
// circle
strValOut.Format(_T("Coords (Circle): Center=[%u,%u] Diameter=%u"),
anValues[0],anValues[1],anValues[2]);
break;
case 4 :
// rectangle
strValOut.Format(_T("Coords (Rect): Center=[%u,%u] Width=%u Height=%u"),
anValues[0],anValues[1],anValues[2],anValues[3]);
break;
default:
// Leave default decode, unexpected value
break;
}
}
if (strIfdTag == _T("CFAPattern")) {
unsigned nHorzRepeat,nVertRepeat;
unsigned anCfaVal[16][16];
unsigned nInd=0;
unsigned nVal;
CString strLine,strCol;
nHorzRepeat = anValues[nInd+0]*256+anValues[nInd+1];
nVertRepeat = anValues[nInd+2]*256+anValues[nInd+3];
nInd+=4;
if ((nHorzRepeat < 16) && (nVertRepeat < 16)) {
bExtraDecode = TRUE;
strTmp.Format(_T(" [%-36s] ="),(LPCTSTR)strIfdTag);
m_pLog->AddLine(strTmp);
for (unsigned nY=0;nY<nVertRepeat;nY++) {
strLine.Format(_T(" %-36s = [ " ),_T(""));
for (unsigned nX=0;nX<nHorzRepeat;nX++) {
if (nInd<MAX_anValues) {
nVal = anValues[nInd++];
anCfaVal[nY][nX] = nVal;
switch(nVal) {
case 0: strCol = _T("Red");break;
case 1: strCol = _T("Grn");break;
case 2: strCol = _T("Blu");break;
case 3: strCol = _T("Cya");break;
case 4: strCol = _T("Mgn");break;
case 5: strCol = _T("Yel");break;
case 6: strCol = _T("Wht");break;
default: strCol.Format(_T("x%02X"),nVal);break;
}
strLine.AppendFormat(_T("%s "),(LPCTSTR)strCol);
}
}
strLine.Append(_T("]"));
m_pLog->AddLine(strLine);
}
}
}
if ((strIfd == _T("InteropIFD")) && (strIfdTag == _T("InteroperabilityVersion"))) {
// Assume only one
strValOut.Format(_T("%c%c.%c%c"),anValues[0],anValues[1],anValues[2],anValues[3]);
}
// ==========================================================================
// ----------------------------------------
// Handle certain MakerNotes
// For Canon, we have a special parser routine to handle these
// ----------------------------------------
if (strIfd == _T("MakerIFD")) {
if ((m_strImgExifMake == _T("Canon")) && (nIfdFormat == 3) && (nIfdNumComps > 4)) {
// Print summary line now, before sub details
// Disable later summary line
bExtraDecode = TRUE;
if ((!m_pAppConfig->bExifHideUnknown) || (!nIfdTagUnknown)) {
strTmp.Format(_T(" [%-36s]"),(LPCTSTR)strIfdTag);
m_pLog->AddLine(strTmp);
// Assume it is a maker field with subentries!
for (unsigned ind=0;ind<nIfdNumComps;ind++) {
// Limit the number of entries (in case there was a decode error
// or simply too many to report)
if (ind<MAX_anValues) {
strValOut.Format(_T("#%u=%u "),ind,anValues[ind]);
strRetVal = LookupMakerCanonTag(nIfdTagVal,ind,anValues[ind]);
strMaker = strRetVal.strTag;
strValTmp.Format(_T(" [%-34s] = %s"),(LPCTSTR)strMaker,(LPCTSTR)(strRetVal.strVal));
if ((!m_pAppConfig->bExifHideUnknown) || (!strRetVal.bUnknown)) {
m_pLog->AddLine(strValTmp);
}
} else if (ind == MAX_anValues) {
m_pLog->AddLine(_T(" [... etc ...]"));
} else {
// Don't print!
}
}
}
strValOut = _T("...");
}
// For Nikon & Sigma, we simply support the quality field
if ( (strIfdTag=="Nikon1.Quality") ||
(strIfdTag=="Nikon2.Quality") ||
(strIfdTag=="Nikon3.Quality") ||
(strIfdTag=="Sigma.Quality") )
{
m_strImgQualExif = strValOut;
// Collect extra details (for later DB submission)
strTmp = _T("");
strTmp.Format(_T("[%s]:[%s],"),(LPCTSTR)strIfdTag,(LPCTSTR)strValOut);
m_strImgExtras += strTmp;
}
// Collect extra details (for later DB submission)
if (strIfdTag==_T("Canon.ImageType")) {
strTmp = _T("");
strTmp.Format(_T("[%s]:[%s],"),(LPCTSTR)strIfdTag,(LPCTSTR)strValOut);
m_strImgExtras += strTmp;
}
}
// ----------------------------------------
// Now extract some of the important offsets / pointers
if ((strIfd == _T("IFD0")) && (strIfdTag == _T("ExifOffset"))) {
// EXIF SubIFD - Pointer
m_nImgExifSubIfdPtr = nIfdOffset;
strValOut.Format(_T("@ 0x%04X"),nIfdOffset);
}
if ((strIfd == _T("IFD0")) && (strIfdTag == _T("GPSOffset"))) {
// GPS SubIFD - Pointer
m_nImgExifGpsIfdPtr = nIfdOffset;
strValOut.Format(_T("@ 0x%04X"),nIfdOffset);
}
// TODO: Add Interoperability IFD (0xA005)?
if ((strIfd == _T("SubIFD")) && (strIfdTag == _T("ExifInteroperabilityOffset"))) {
m_nImgExifInteropIfdPtr = nIfdOffset;
strValOut.Format(_T("@ 0x%04X"),nIfdOffset);
}
// Extract software field
if ((strIfd == _T("IFD0")) && (strIfdTag == _T("Software"))) {
m_strSoftware = strValOut;
}
// -------------------------
// IFD0 - ExifMake
// -------------------------
if ((strIfd == _T("IFD0")) && (strIfdTag == _T("Make"))) {
m_strImgExifMake = strValOut;
m_strImgExifMake.Trim(); // Trim whitespace (e.g. Pentax)
}
// -------------------------
// IFD0 - ExifModel
// -------------------------
if ((strIfd == _T("IFD0")) && (strIfdTag == _T("Model"))) {
m_strImgExifModel= strValOut;
m_strImgExifModel.Trim();
}
if ((strIfd == _T("SubIFD")) && (strIfdTag == _T("MakerNote"))) {
// Maker IFD - Pointer
m_nImgExifMakerPtr = nIfdOffset;
strValOut.Format(_T("@ 0x%04X"),nIfdOffset);
}
// -------------------------
// IFD1 - Embedded Thumbnail
// -------------------------
if ((strIfd == _T("IFD1")) && (strIfdTag == _T("Compression"))) {
// Embedded thumbnail, compression format
m_nImgExifThumbComp = ReadSwap4(m_nPos);
}
if ((strIfd == _T("IFD1")) && (strIfdTag == _T("JpegIFOffset"))) {
// Embedded thumbnail, offset
m_nImgExifThumbOffset = nIfdOffset + nPosExifStart;
strValOut.Format(_T("@ +0x%04X = @ 0x%04X"),nIfdOffset,m_nImgExifThumbOffset);
}
if ((strIfd == _T("IFD1")) && (strIfdTag == _T("JpegIFByteCount"))) {
// Embedded thumbnail, length
m_nImgExifThumbLen = ReadSwap4(m_nPos);
}
// ==========================================================================
// Determine MakerNote support
// ==========================================================================
if (m_strImgExifMake != _T("")) {
// 1) Identify the supported MakerNotes
// 2) Remap variations of the Maker field (e.g. Nikon)
// as some manufacturers have been inconsistent in their
// use of the Make field
m_bImgExifMakeSupported = FALSE;
if (m_strImgExifMake == _T("Canon")) {
m_bImgExifMakeSupported = TRUE;
}
else if (m_strImgExifMake == _T("PENTAX Corporation")) {
m_strImgExifMake = _T("PENTAX");
}
else if (m_strImgExifMake == _T("NIKON CORPORATION")) {
m_strImgExifMake = _T("NIKON");
m_bImgExifMakeSupported = TRUE;
}
else if (m_strImgExifMake == _T("NIKON")) {
m_strImgExifMake = _T("NIKON");
m_bImgExifMakeSupported = TRUE;
}
else if (m_strImgExifMake == _T("SIGMA")) {
m_bImgExifMakeSupported = TRUE;
}
else if (m_strImgExifMake == _T("SONY")) {
m_bImgExifMakeSupported = TRUE;
}
else if (m_strImgExifMake == _T("FUJIFILM")) {
// TODO:
// FUJIFILM Maker notes apparently use
// big endian format even though main section uses little.
// Need to switch if in maker section for FUJI
// For now, disable support
m_bImgExifMakeSupported = FALSE;
}
}
// Now advance the m_nPos ptr as we have finished with valoffset
m_nPos+=4;
// ==========================================================================
// SUMMARY REPORT
// ==========================================================================
// If we haven't already output a detailed decode of this field
// then we can output the generic representation here
if (!bExtraDecode)
{
// Provide option to skip unknown fields
if ((!m_pAppConfig->bExifHideUnknown) || (!nIfdTagUnknown)) {
// If the tag is an ASCII string, we want to wrap with quote marks
if (nIfdFormat == 2) {
strTmp.Format(_T(" [%-36s] = \"%s\""),(LPCTSTR)strIfdTag,(LPCTSTR)strValOut);
} else {
strTmp.Format(_T(" [%-36s] = %s"),(LPCTSTR)strIfdTag,(LPCTSTR)strValOut);
}
m_pLog->AddLine(strTmp);
}
}
DbgAddLine(_T(""));
} // for nIfdEntryInd
// =========== EXIF IFD (End) ===========
// - Defined in Exif 2.2 Standard (JEITA CP-3451) section 4.6.2
// - Is completed by 4-byte offset to next IFD, which is
// read in next iteration.
m_pLog->Enable();
return 0;
}
// Handle APP13 marker
// This includes:
// - Photoshop "Save As" and "Save for Web" quality settings
// - IPTC entries
// PRE:
// - m_nPos
// POST:
// - m_nImgQualPhotoshopSa
unsigned CjfifDecode::DecodeApp13Ps()
{
// Photoshop APP13 marker definition doesn't appear to have a
// well-defined length, so I will read until I encounter a
// non-"8BIM" entry, then we reset the position counter
// and move on to the next marker.
// FIXME: This does not appear to be very robust
CString strTmp;
CString strBimName;
bool bDone = false;
unsigned nVal = 0x8000;
unsigned nSaveFormat = 0;
CString strVal;
CString strByte;
CString strBimSig;
// Reset PsDec decoder state
m_pPsDec->Reset();
while (!bDone)
{
// FIXME: Need to check for actual marker section extent, not
// just the lack of an 8BIM signature as the terminator!
// Check the signature but don't advance the file pointer
strBimSig = m_pWBuf->BufReadStrn(m_nPos,4);
// Check for signature "8BIM"
if (strBimSig == _T("8BIM")) {
m_pPsDec->PhotoshopParseImageResourceBlock(m_nPos,3);
} else {
// Not 8BIM?
bDone = true;
}
}
// Now that we've finished with the PsDec decoder we can fetch
// some of the parser state
// TODO: Migrate into accessor
m_nImgQualPhotoshopSa = m_pPsDec->m_nQualitySaveAs;
m_nImgQualPhotoshopSfw = m_pPsDec->m_nQualitySaveForWeb;
m_bPsd = m_pPsDec->m_bPsd;
return 0;
}
// Start decoding a single ICC header segment @ nPos
unsigned CjfifDecode::DecodeIccHeader(unsigned nPos)
{
CString strTmp,strTmp1;
// Profile header
unsigned nProfSz;
unsigned nPrefCmmType;
unsigned nProfVer;
unsigned nProfDevClass;
unsigned nDataColorSpace;
unsigned nPcs;
unsigned anDateTimeCreated[3];
unsigned nProfFileSig;
unsigned nPrimPlatSig;
unsigned nProfFlags;
unsigned nDevManuf;
unsigned nDevModel;
unsigned anDevAttrib[2];
unsigned nRenderIntent;
unsigned anIllumPcsXyz[3];
unsigned nProfCreatorSig;
unsigned anProfId[4];
unsigned anRsvd[7];
// Read in all of the ICC header bytes
nProfSz = ReadBe4(nPos);nPos+=4;
nPrefCmmType = ReadBe4(nPos);nPos+=4;
nProfVer = ReadBe4(nPos);nPos+=4;
nProfDevClass = ReadBe4(nPos);nPos+=4;
nDataColorSpace = ReadBe4(nPos);nPos+=4;
nPcs = ReadBe4(nPos);nPos+=4;
anDateTimeCreated[2] = ReadBe4(nPos);nPos+=4;
anDateTimeCreated[1] = ReadBe4(nPos);nPos+=4;
anDateTimeCreated[0] = ReadBe4(nPos);nPos+=4;
nProfFileSig = ReadBe4(nPos);nPos+=4;
nPrimPlatSig = ReadBe4(nPos);nPos+=4;
nProfFlags = ReadBe4(nPos);nPos+=4;
nDevManuf = ReadBe4(nPos);nPos+=4;
nDevModel = ReadBe4(nPos);nPos+=4;
anDevAttrib[1] = ReadBe4(nPos);nPos+=4;
anDevAttrib[0] = ReadBe4(nPos);nPos+=4;
nRenderIntent = ReadBe4(nPos);nPos+=4;
anIllumPcsXyz[2] = ReadBe4(nPos);nPos+=4;
anIllumPcsXyz[1] = ReadBe4(nPos);nPos+=4;
anIllumPcsXyz[0] = ReadBe4(nPos);nPos+=4;
nProfCreatorSig = ReadBe4(nPos);nPos+=4;
anProfId[3] = ReadBe4(nPos);nPos+=4;
anProfId[2] = ReadBe4(nPos);nPos+=4;
anProfId[1] = ReadBe4(nPos);nPos+=4;
anProfId[0] = ReadBe4(nPos);nPos+=4;
anRsvd[6] = ReadBe4(nPos);nPos+=4;
anRsvd[5] = ReadBe4(nPos);nPos+=4;
anRsvd[4] = ReadBe4(nPos);nPos+=4;
anRsvd[3] = ReadBe4(nPos);nPos+=4;
anRsvd[2] = ReadBe4(nPos);nPos+=4;
anRsvd[1] = ReadBe4(nPos);nPos+=4;
anRsvd[0] = ReadBe4(nPos);nPos+=4;
// Now output the formatted version of the above data structures
strTmp.Format(_T(" %-33s : %u bytes"),_T("Profile Size"),nProfSz);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : %s"),_T("Preferred CMM Type"),(LPCTSTR)Uint2Chars(nPrefCmmType));
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : %u.%u.%u.%u (0x%08X)"),_T("Profile Version"),
((nProfVer & 0xF0000000)>>28),
((nProfVer & 0x0F000000)>>24),
((nProfVer & 0x00F00000)>>20),
((nProfVer & 0x000F0000)>>16),
nProfVer);
m_pLog->AddLine(strTmp);
switch (nProfDevClass) {
case 'scnr':
strTmp1.Format(_T("Input Device profile"));break;
case 'mntr':
strTmp1.Format(_T("Display Device profile"));break;
case 'prtr':
strTmp1.Format(_T("Output Device profile"));break;
case 'link':
strTmp1.Format(_T("DeviceLink Device profile"));break;
case 'spac':
strTmp1.Format(_T("ColorSpace Conversion profile"));break;
case 'abst':
strTmp1.Format(_T("Abstract profile"));break;
case 'nmcl':
strTmp1.Format(_T("Named colour profile"));break;
default:
strTmp1.Format(_T("? (0x%08X)"),nProfDevClass);
break;
}
strTmp.Format(_T(" %-33s : %s (%s)"),_T("Profile Device/Class"),(LPCTSTR)strTmp1,(LPCTSTR)Uint2Chars(nProfDevClass));
m_pLog->AddLine(strTmp);
switch (nDataColorSpace) {
case 'XYZ ':
strTmp1.Format(_T("XYZData"));break;
case 'Lab ':
strTmp1.Format(_T("labData"));break;
case 'Luv ':
strTmp1.Format(_T("lubData"));break;
case 'YCbr':
strTmp1.Format(_T("YCbCrData"));break;
case 'Yxy ':
strTmp1.Format(_T("YxyData"));break;
case 'RGB ':
strTmp1.Format(_T("rgbData"));break;
case 'GRAY':
strTmp1.Format(_T("grayData"));break;
case 'HSV ':
strTmp1.Format(_T("hsvData"));break;
case 'HLS ':
strTmp1.Format(_T("hlsData"));break;
case 'CMYK':
strTmp1.Format(_T("cmykData"));break;
case 'CMY ':
strTmp1.Format(_T("cmyData"));break;
case '2CLR':
strTmp1.Format(_T("2colourData"));break;
case '3CLR':
strTmp1.Format(_T("3colourData"));break;
case '4CLR':
strTmp1.Format(_T("4colourData"));break;
case '5CLR':
strTmp1.Format(_T("5colourData"));break;
case '6CLR':
strTmp1.Format(_T("6colourData"));break;
case '7CLR':
strTmp1.Format(_T("7colourData"));break;
case '8CLR':
strTmp1.Format(_T("8colourData"));break;
case '9CLR':
strTmp1.Format(_T("9colourData"));break;
case 'ACLR':
strTmp1.Format(_T("10colourData"));break;
case 'BCLR':
strTmp1.Format(_T("11colourData"));break;
case 'CCLR':
strTmp1.Format(_T("12colourData"));break;
case 'DCLR':
strTmp1.Format(_T("13colourData"));break;
case 'ECLR':
strTmp1.Format(_T("14colourData"));break;
case 'FCLR':
strTmp1.Format(_T("15colourData"));break;
default:
strTmp1.Format(_T("? (0x%08X)"),nDataColorSpace);
break;
}
strTmp.Format(_T(" %-33s : %s (%s)"),_T("Data Colour Space"),(LPCTSTR)strTmp1,(LPCTSTR)Uint2Chars(nDataColorSpace));
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : %s"),_T("Profile connection space (PCS)"),(LPCTSTR)Uint2Chars(nPcs));
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : %s"),_T("Profile creation date"),(LPCTSTR)DecodeIccDateTime(anDateTimeCreated));
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : %s"),_T("Profile file signature"),(LPCTSTR)Uint2Chars(nProfFileSig));
m_pLog->AddLine(strTmp);
switch (nPrimPlatSig) {
case 'APPL':
strTmp1.Format(_T("Apple Computer, Inc."));break;
case 'MSFT':
strTmp1.Format(_T("Microsoft Corporation"));break;
case 'SGI ':
strTmp1.Format(_T("Silicon Graphics, Inc."));break;
case 'SUNW':
strTmp1.Format(_T("Sun Microsystems, Inc."));break;
default:
strTmp1.Format(_T("? (0x%08X)"),nPrimPlatSig);
break;
}
strTmp.Format(_T(" %-33s : %s (%s)"),_T("Primary platform"),(LPCTSTR)strTmp1,(LPCTSTR)Uint2Chars(nPrimPlatSig));
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : 0x%08X"),_T("Profile flags"),nProfFlags);
m_pLog->AddLine(strTmp);
strTmp1 = (TestBit(nProfFlags,0))?"Embedded profile":"Profile not embedded";
strTmp.Format(_T(" %-35s > %s"),_T("Profile flags"),(LPCTSTR)strTmp1);
m_pLog->AddLine(strTmp);
strTmp1 = (TestBit(nProfFlags,1))?"Profile can be used independently of embedded":"Profile can't be used independently of embedded";
strTmp.Format(_T(" %-35s > %s"),_T("Profile flags"),(LPCTSTR)strTmp1);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : %s"),_T("Device Manufacturer"),(LPCTSTR)Uint2Chars(nDevManuf));
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : %s"),_T("Device Model"),(LPCTSTR)Uint2Chars(nDevModel));
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : 0x%08X_%08X"),_T("Device attributes"),anDevAttrib[1],anDevAttrib[0]);
m_pLog->AddLine(strTmp);
strTmp1 = (TestBit(anDevAttrib[0],0))?"Transparency":"Reflective";
strTmp.Format(_T(" %-35s > %s"),_T("Device attributes"),(LPCTSTR)strTmp1);
m_pLog->AddLine(strTmp);
strTmp1 = (TestBit(anDevAttrib[0],1))?"Matte":"Glossy";
strTmp.Format(_T(" %-35s > %s"),_T("Device attributes"),(LPCTSTR)strTmp1);
m_pLog->AddLine(strTmp);
strTmp1 = (TestBit(anDevAttrib[0],2))?"Media polarity = positive":"Media polarity = negative";
strTmp.Format(_T(" %-35s > %s"),_T("Device attributes"),(LPCTSTR)strTmp1);
m_pLog->AddLine(strTmp);
strTmp1 = (TestBit(anDevAttrib[0],3))?"Colour media":"Black & white media";
strTmp.Format(_T(" %-35s > %s"),_T("Device attributes"),(LPCTSTR)strTmp1);
m_pLog->AddLine(strTmp);
switch(nRenderIntent) {
case 0x00000000: strTmp1.Format(_T("Perceptual"));break;
case 0x00000001: strTmp1.Format(_T("Media-Relative Colorimetric"));break;
case 0x00000002: strTmp1.Format(_T("Saturation"));break;
case 0x00000003: strTmp1.Format(_T("ICC-Absolute Colorimetric"));break;
default:
strTmp1.Format(_T("0x%08X"),nRenderIntent);
break;
}
strTmp.Format(_T(" %-33s : %s"),_T("Rendering intent"),(LPCTSTR)strTmp1);
m_pLog->AddLine(strTmp);
// PCS illuminant
strTmp.Format(_T(" %-33s : %s"),_T("Profile creator"),(LPCTSTR)Uint2Chars(nProfCreatorSig));
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : 0x%08X_%08X_%08X_%08X"),_T("Profile ID"),
anProfId[3],anProfId[2],anProfId[1],anProfId[0]);
m_pLog->AddLine(strTmp);
return 0;
}
// Provide special output formatter for ICC Date/Time
// NOTE: It appears that the nParts had to be decoded in the
// reverse order from what I had expected, so one should
// confirm that the byte order / endianness is appropriate.
CString CjfifDecode::DecodeIccDateTime(unsigned anVal[3])
{
CString strDate;
unsigned short anParts[6];
anParts[0] = (anVal[2] & 0xFFFF0000) >> 16; // Year
anParts[1] = (anVal[2] & 0x0000FFFF); // Mon
anParts[2] = (anVal[1] & 0xFFFF0000) >> 16; // Day
anParts[3] = (anVal[1] & 0x0000FFFF); // Hour
anParts[4] = (anVal[0] & 0xFFFF0000) >> 16; // Min
anParts[5] = (anVal[0] & 0x0000FFFF); // Sec
strDate.Format(_T("%04u-%02u-%02u %02u:%02u:%02u"),
anParts[0],anParts[1],anParts[2],anParts[3],anParts[4],anParts[5]);
return strDate;
}
// Parser for APP2 ICC profile marker
unsigned CjfifDecode::DecodeApp2IccProfile(unsigned nLen)
{
CString strTmp;
unsigned nMarkerSeqNum; // Byte
unsigned nNumMarkers; // Byte
unsigned nPayloadLen; // Len of this ICC marker payload
unsigned nMarkerPosStart;
nMarkerSeqNum = Buf(m_nPos++);
nNumMarkers = Buf(m_nPos++);
nPayloadLen = nLen - 2 - 12 - 2; // TODO: check?
strTmp.Format(_T(" Marker Number = %u of %u"),nMarkerSeqNum,nNumMarkers);
m_pLog->AddLine(strTmp);
if (nMarkerSeqNum == 1) {
nMarkerPosStart = m_nPos;
DecodeIccHeader(nMarkerPosStart);
} else {
m_pLog->AddLineWarn(_T(" Only support decode of 1st ICC Marker"));
}
return 0;
}
// Parser for APP2 FlashPix marker
unsigned CjfifDecode::DecodeApp2Flashpix()
{
CString strTmp;
unsigned nFpxVer;
unsigned nFpxSegType;
unsigned nFpxInteropCnt;
unsigned nFpxEntitySz;
unsigned nFpxDefault;
bool bFpxStorage;
CString strFpxStorageClsStr;
unsigned nFpxStIndexCont;
unsigned nFpxStOffset;
unsigned nFpxStWByteOrder;
unsigned nFpxStWFormat;
CString strFpxStClsidStr;
unsigned nFpxStDwOsVer;
unsigned nFpxStRsvd;
CString streamStr;
nFpxVer = Buf(m_nPos++);
nFpxSegType = Buf(m_nPos++);
// FlashPix segments: Contents List or Stream Data
if (nFpxSegType == 1) {
// Contents List
strTmp.Format(_T(" Segment: CONTENTS LIST"));
m_pLog->AddLine(strTmp);
nFpxInteropCnt = (Buf(m_nPos++)<<8) + Buf(m_nPos++);
strTmp.Format(_T(" Interoperability Count = %u"),nFpxInteropCnt);
m_pLog->AddLine(strTmp);
for (unsigned ind=0;ind<nFpxInteropCnt;ind++) {
strTmp.Format(_T(" Entity Index #%u"),ind);
m_pLog->AddLine(strTmp);
nFpxEntitySz = (Buf(m_nPos++)<<24) + (Buf(m_nPos++)<<16) + (Buf(m_nPos++)<<8) + Buf(m_nPos++);
// If the "entity size" field is 0xFFFFFFFF, then it should be treated as
// a "storage". It looks like we should probably be using this to determine
// that we have a "storage"
bFpxStorage = false;
if (nFpxEntitySz == 0xFFFFFFFF) {
bFpxStorage = true;
}
if (!bFpxStorage) {
strTmp.Format(_T(" Entity Size = %u"),nFpxEntitySz);
m_pLog->AddLine(strTmp);
} else {
strTmp.Format(_T(" Entity is Storage"));
m_pLog->AddLine(strTmp);
}
nFpxDefault = Buf(m_nPos++);
// BUG: #1112
//streamStr = m_pWBuf->BufReadUniStr(m_nPos);
streamStr = m_pWBuf->BufReadUniStr2(m_nPos,MAX_BUF_READ_STR);
m_nPos += 2*((unsigned)_tcslen(streamStr)+1); // 2x because unicode
strTmp.Format(_T(" Stream Name = [%s]"),(LPCTSTR)streamStr);
m_pLog->AddLine(strTmp);
// In the case of "storage", we decode the next 16 bytes as the class
if (bFpxStorage) {
// FIXME:
// NOTE: Very strange reordering required here. Doesn't seem consistent
// This means that other fields are probably wrong as well (endian)
strFpxStorageClsStr.Format(_T("%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X"),
Buf(m_nPos+3),Buf(m_nPos+2),Buf(m_nPos+1),Buf(m_nPos+0),
Buf(m_nPos+5),Buf(m_nPos+4),
Buf(m_nPos+7),Buf(m_nPos+6),
Buf(m_nPos+8),Buf(m_nPos+9),
Buf(m_nPos+10),Buf(m_nPos+11),Buf(m_nPos+12),Buf(m_nPos+13),Buf(m_nPos+14),Buf(m_nPos+15) );
m_nPos+= 16;
strTmp.Format(_T(" Storage Class = [%s]"),(LPCTSTR)strFpxStorageClsStr);
m_pLog->AddLine(strTmp);
}
}
return 0;
} else if (nFpxSegType == 2) {
// Stream Data
strTmp.Format(_T(" Segment: STREAM DATA"));
m_pLog->AddLine(strTmp);
nFpxStIndexCont = (Buf(m_nPos++)<<8) + Buf(m_nPos++);
strTmp.Format(_T(" Index in Contents List = %u"),nFpxStIndexCont);
m_pLog->AddLine(strTmp);
nFpxStOffset = (Buf(m_nPos++)<<24) + (Buf(m_nPos++)<<16) + (Buf(m_nPos++)<<8) + Buf(m_nPos++);
strTmp.Format(_T(" Offset in stream = %u (0x%08X)"),nFpxStOffset,nFpxStOffset);
m_pLog->AddLine(strTmp);
// Now decode the Property Set Header
// NOTE: Should only decode this if we are doing first part of stream
// TODO: How do we know this? First reference to index #?
nFpxStWByteOrder = (Buf(m_nPos++)<<8) + Buf(m_nPos++);
nFpxStWFormat = (Buf(m_nPos++)<<8) + Buf(m_nPos++);
nFpxStDwOsVer = (Buf(m_nPos++)<<24) + (Buf(m_nPos++)<<16) + (Buf(m_nPos++)<<8) + Buf(m_nPos++);
// FIXME:
// NOTE: Very strange reordering required here. Doesn't seem consistent!
// This means that other fields are probably wrong as well (endian)
strFpxStClsidStr.Format(_T("%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X"),
Buf(m_nPos+3),Buf(m_nPos+2),Buf(m_nPos+1),Buf(m_nPos+0),
Buf(m_nPos+5),Buf(m_nPos+4),
Buf(m_nPos+7),Buf(m_nPos+6),
Buf(m_nPos+8),Buf(m_nPos+9),
Buf(m_nPos+10),Buf(m_nPos+11),Buf(m_nPos+12),Buf(m_nPos+13),Buf(m_nPos+14),Buf(m_nPos+15) );
m_nPos+= 16;
nFpxStRsvd = (Buf(m_nPos++)<<8) + Buf(m_nPos++);
strTmp.Format(_T(" ByteOrder = 0x%04X"),nFpxStWByteOrder);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" Format = 0x%04X"),nFpxStWFormat);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" OSVer = 0x%08X"),nFpxStDwOsVer);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" clsid = %s"),(LPCTSTR)strFpxStClsidStr);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" reserved = 0x%08X"),nFpxStRsvd);
m_pLog->AddLine(strTmp);
// ....
return 2;
} else {
strTmp.Format(_T(" Reserved Segment. Stopping."));
m_pLog->AddLineErr(strTmp);
return 1;
}
}
// Decode the DHT marker segment (Huffman Tables)
// In some cases (such as for MotionJPEG), we fake out
// the DHT tables (when bInject=true) with a standard table
// as each JPEG frame in the MJPG does not include the DHT.
// In all other cases (bInject=false), we simply read the
// DHT table from the file buffer via Buf()
//
// ITU-T standard indicates that we can expect up to a
// maximum of 16-bit huffman code bitstrings.
void CjfifDecode::DecodeDHT(bool bInject)
{
unsigned nLength;
unsigned nTmpVal;
CString strTmp,strFull;
unsigned nPosEnd;
unsigned nPosSaved;
bool bRet;
if (bInject) {
// Redirect Buf() to DHT table in MJPGDHTSeg[]
// ... so change mode that Buf() call uses
m_bBufFakeDHT = true;
// Preserve the "m_nPos" pointer, at end we undo it
// And we also start at 2 which is just after FFC4 in array
nPosSaved = m_nPos;
m_nPos = 2;
}
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
nPosEnd = m_nPos+nLength;
m_nPos+=2;
strTmp.Format(_T(" Huffman table length = %u"),nLength);
m_pLog->AddLine(strTmp);
unsigned nDhtClass_Tc; // Range 0..1
unsigned nDhtHuffTblId_Th; // Range 0..3
// In various places, added m_bStateAbort check to allow us
// to escape in case we get in excessive number of DHT entries
// See BUG FIX #1003
while ((!m_bStateAbort)&&(nPosEnd > m_nPos))
{
m_pLog->AddLine(_T(" ----"));
nTmpVal = Buf(m_nPos++);
nDhtClass_Tc = (nTmpVal & 0xF0) >> 4; // Tc, range 0..1
nDhtHuffTblId_Th = nTmpVal & 0x0F; // Th, range 0..3
strTmp.Format(_T(" Destination ID = %u"),nDhtHuffTblId_Th);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" Class = %u (%s)"),nDhtClass_Tc,(nDhtClass_Tc?_T("AC Table"):_T("DC / Lossless Table")));
m_pLog->AddLine(strTmp);
// Add in some error checking to prevent
if (nDhtClass_Tc >= MAX_DHT_CLASS) {
strTmp.Format(_T("ERROR: Invalid DHT Class (%u). Aborting DHT Load."),nDhtClass_Tc);
m_pLog->AddLineErr(strTmp);
m_nPos = nPosEnd;
//m_bStateAbort = true; // Stop decoding
break;
}
if (nDhtHuffTblId_Th >= MAX_DHT_DEST_ID) {
strTmp.Format(_T("ERROR: Invalid DHT Dest ID (%u). Aborting DHT Load."),nDhtHuffTblId_Th);
m_pLog->AddLineErr(strTmp);
m_nPos = nPosEnd;
//m_bStateAbort = true; // Stop decoding
break;
}
// Read in the array of DHT code lengths
for (unsigned int i=1;i<=MAX_DHT_CODELEN;i++)
{
m_anDhtNumCodesLen_Li[i] = Buf(m_nPos++); // Li, range 0..255
}
#define DECODE_DHT_MAX_DHT 256
unsigned int anDhtCodeVal[DECODE_DHT_MAX_DHT+1]; // Should only need max 162 codes
unsigned int nDhtInd;
unsigned int nDhtCodesTotal;
// Clear out the code list
for (nDhtInd = 0;nDhtInd <DECODE_DHT_MAX_DHT;nDhtInd++)
{
anDhtCodeVal[nDhtInd] = 0xFFFF; // Dummy value
}
// Now read in all of the DHT codes according to the lengths
// read in earlier
nDhtCodesTotal = 0;
nDhtInd = 0;
for (unsigned int nIndLen=1;((!m_bStateAbort)&&(nIndLen<=MAX_DHT_CODELEN));nIndLen++)
{
// Keep a total count of the number of DHT codes read
nDhtCodesTotal += m_anDhtNumCodesLen_Li[nIndLen];
strFull.Format(_T(" Codes of length %02u bits (%03u total): "),nIndLen,m_anDhtNumCodesLen_Li[nIndLen]);
for (unsigned int nIndCode=0;((!m_bStateAbort)&&(nIndCode<m_anDhtNumCodesLen_Li[nIndLen]));nIndCode++)
{
// Start a new line for every 16 codes
if ( (nIndCode != 0) && ((nIndCode % 16) == 0) ) {
strFull = _T(" ");
}
nTmpVal = Buf(m_nPos++);
strTmp.Format(_T("%02X "),nTmpVal);
strFull += strTmp;
// Only write 16 codes per line
if ((nIndCode % 16) == 15) {
m_pLog->AddLine(strFull);
strFull = _T("");
}
// Save the huffman code
// Just in case we have more DHT codes than we expect, trap
// the range check here, otherwise we'll have buffer overrun!
if (nDhtInd < DECODE_DHT_MAX_DHT) {
anDhtCodeVal[nDhtInd++] = nTmpVal; // Vij, range 0..255
} else {
nDhtInd++;
strTmp.Format(_T("Excessive DHT entries (%u)... skipping"),nDhtInd);
m_pLog->AddLineErr(strTmp);
if (!m_bStateAbort) { DecodeErrCheck(true); }
}
}
m_pLog->AddLine(strFull);
}
strTmp.Format(_T(" Total number of codes: %03u"),nDhtCodesTotal);
m_pLog->AddLine(strTmp);
unsigned int nDhtLookupInd = 0;
// Now print out the actual binary strings!
unsigned long nBitVal = 0;
unsigned int nCodeVal = 0;
nDhtInd = 0;
if (m_pAppConfig->bOutputDHTexpand) {
m_pLog->AddLine(_T(""));
m_pLog->AddLine(_T(" Expanded Form of Codes:"));
}
for (unsigned int nBitLen=1;((!m_bStateAbort)&&(nBitLen<=16));nBitLen++)
{
if (m_anDhtNumCodesLen_Li[nBitLen] > 0)
{
if (m_pAppConfig->bOutputDHTexpand) {
strTmp.Format(_T(" Codes of length %02u bits:"),nBitLen);
m_pLog->AddLine(strTmp);
}
// Codes exist for this bit-length
// Walk through and generate the bitvalues
for (unsigned int bit_ind=1;((!m_bStateAbort)&&(bit_ind<=m_anDhtNumCodesLen_Li[nBitLen]));bit_ind++)
{
unsigned int nDecVal = nCodeVal;
unsigned int nBinBit;
TCHAR acBinStr[17] = _T("");
unsigned int nBinStrLen = 0;
// If the user has enabled output of DHT expanded tables,
// report the bit-string sequences.
if (m_pAppConfig->bOutputDHTexpand) {
for (unsigned int nBinInd=nBitLen;nBinInd>=1;nBinInd--)
{
nBinBit = (nDecVal >> (nBinInd-1)) & 1;
acBinStr[nBinStrLen++] = (nBinBit)?'1':'0';
}
acBinStr[nBinStrLen] = '\0';
strFull.Format(_T(" %s = %02X"),acBinStr,anDhtCodeVal[nDhtInd]);
// The following are only valid for AC components
// Bug [3442132]
if (nDhtClass_Tc == DHT_CLASS_AC) {
if (anDhtCodeVal[nDhtInd] == 0x00) { strFull += _T(" (EOB)"); }
if (anDhtCodeVal[nDhtInd] == 0xF0) { strFull += _T(" (ZRL)"); }
}
strTmp.Format(_T("%-40s (Total Len = %2u)"),(LPCTSTR)strFull,nBitLen + (anDhtCodeVal[nDhtInd] & 0xF));
m_pLog->AddLine(strTmp);
}
// Store the lookup value
// Shift left to MSB of 32-bit
unsigned nTmpMask = m_anMaskLookup[nBitLen];
unsigned nTmpBits = nDecVal << (32-nBitLen);
unsigned nTmpCode = anDhtCodeVal[nDhtInd];
bRet = m_pImgDec->SetDhtEntry(nDhtHuffTblId_Th,nDhtClass_Tc,nDhtLookupInd,nBitLen,
nTmpBits,nTmpMask,nTmpCode);
DecodeErrCheck(bRet);
nDhtLookupInd++;
// Move to the next code
nCodeVal++;
nDhtInd++;
}
}
// For each loop iteration (on bit length), we shift the code value
nCodeVal <<= 1;
}
// Now store the dht_lookup_size
unsigned nTmpSize = nDhtLookupInd;
bRet = m_pImgDec->SetDhtSize(nDhtHuffTblId_Th,nDhtClass_Tc,nTmpSize);
if (!m_bStateAbort) { DecodeErrCheck(bRet); }
m_pLog->AddLine(_T(""));
}
if (bInject) {
// Restore position (as if we didn't move)
m_nPos = nPosSaved;
m_bBufFakeDHT = false;
}
}
// Check return value of previous call. If failed, then ask
// user if they wish to continue decoding. If no, then flag to
// the decoder that we're done (avoids continuous failures)
void CjfifDecode::DecodeErrCheck(bool bRet)
{
if (!bRet) {
if (m_pAppConfig->bInteractive) {
if (AfxMessageBox(_T("Do you want to continue decoding?"),MB_YESNO|MB_ICONQUESTION)== IDNO) {
m_bStateAbort = true;
}
}
}
}
// This routine is called after the expected fields of the marker segment
// have been processed. The file position should line up with the offset
// dictated by the marker length. If a mismatch is detected, report an
// error.
//
// RETURN:
// - True if decode error is fatal (configurable)
//
bool CjfifDecode::ExpectMarkerEnd(unsigned long nMarkerStart,unsigned nMarkerLen)
{
CString strTmp;
unsigned long nMarkerEnd = nMarkerStart + nMarkerLen;
unsigned long nMarkerExtra = nMarkerEnd - m_nPos;
if (m_nPos < nMarkerEnd) {
// The length indicates that there is more data than we processed
strTmp.Format(_T(" WARNING: Marker length longer than expected"));
m_pLog->AddLineWarn(strTmp);
if (!m_pAppConfig->bRelaxedParsing) {
// Abort
m_pLog->AddLineErr(_T(" Stopping decode"));
m_pLog->AddLineErr(_T(" Use [Img Search Fwd/Rev] to locate other valid embedded JPEGs"));
return false;
} else {
// Warn and skip
strTmp.Format(_T(" Skipping remainder [%u bytes]"),nMarkerExtra);
m_pLog->AddLineWarn(strTmp);
m_nPos += nMarkerExtra;
}
} else if (m_nPos > nMarkerEnd) {
// The length indicates that there is less data than we processed
strTmp.Format(_T(" WARNING: Marker length shorter than expected"));
m_pLog->AddLineWarn(strTmp);
if (!m_pAppConfig->bRelaxedParsing) {
// Abort
m_pLog->AddLineErr(_T(" Stopping decode"));
m_pLog->AddLineErr(_T(" Use [Img Search Fwd/Rev] to locate other valid embedded JPEGs"));
return false;
} else {
// Warn but no skip
// Note that we can't skip as the length would imply a rollback
// Most resilient solution is probably to assume length was
// wrong and continue from where the marker should have ended.
// For resiliency, attempt two methods to find point to resume:
// 1) Current position
// 2) Actual length defined in marker
if (Buf(m_nPos) == 0xFF) {
// Using actual data expected seems more promising
m_pLog->AddLineWarn(_T(" Resuming decode"));
} else if (Buf(nMarkerEnd) == 0xFF) {
// Using actual length seems more promising
m_nPos = nMarkerEnd;
m_pLog->AddLineWarn(_T(" Rolling back pointer to end indicated by length"));
m_pLog->AddLineWarn(_T(" Resuming decode"));
} else {
// No luck. Expect marker failure now
m_pLog->AddLineWarn(_T(" Resuming decode"));
}
}
}
// If we get here, then we haven't seen a fatal issue
return true;
}
// Validate an unsigned value to ensure it is in allowable range
// - If the value is outside the range, an error is shown and
// the parsing stops if relaxed parsing is not enabled
// - An optional override value is provided for the resume case
//
// INPUT:
// - nVal Input value (unsigned 32-bit)
// - nMin Minimum allowed value
// - nMax Maximum allowed value
// - strName Name of the field
// - bOverride Should we override the value upon out-of-range?
// - nOverrideVal Value to override if bOverride and out-of-range
//
// PRE:
// - m_pAppConfig
//
// OUTPUT:
// - nVal Output value (including any override)
//
bool CjfifDecode::ValidateValue(unsigned &nVal,unsigned nMin,unsigned nMax,CString strName,bool bOverride,unsigned nOverrideVal)
{
CString strErr;
if ((nVal >= nMin) && (nVal <= nMax)) {
// Value is within range
return true;
} else {
if (nVal < nMin) {
strErr.Format(_T(" ERROR: %s value too small (Actual = %u, Expected >= %u)"),
(LPCTSTR)strName,nVal,nMin);
m_pLog->AddLineErr(strErr);
} else if (nVal > nMax) {
strErr.Format(_T(" ERROR: %s value too large (Actual = %u, Expected <= %u)"),
(LPCTSTR)strName,nVal,nMax);
m_pLog->AddLineErr(strErr);
}
if (!m_pAppConfig->bRelaxedParsing) {
// Defined as fatal error
// TODO: Replace with glb_strMsgStopDecode?
m_pLog->AddLineErr(_T(" Stopping decode"));
m_pLog->AddLineErr(_T(" Use [Relaxed Parsing] to continue"));
return false;
} else {
// Non-fatal
if (bOverride) {
// Update value with override
nVal = nOverrideVal;
strErr.Format(_T(" WARNING: Forcing value to [%u]"),nOverrideVal);
m_pLog->AddLineWarn(strErr);
m_pLog->AddLineWarn(_T(" Resuming decode"));
} else {
// No override
strErr.Format(_T(" Resuming decode"));
m_pLog->AddLineWarn(strErr);
}
return true;
}
}
}
// This is the primary JFIF marker parser. It reads the
// marker value at the current file position and launches the
// specific parser routine. This routine exits when
#define DECMARK_OK 0
#define DECMARK_ERR 1
#define DECMARK_EOI 2
unsigned CjfifDecode::DecodeMarker()
{
TCHAR acIdentifier[MAX_IDENTIFIER];
CString strTmp;
CString strFull; // Used for concatenation
unsigned nLength; // General purpose
unsigned nTmpVal;
unsigned nCode;
unsigned long nPosEnd;
unsigned long nPosSaved; // General-purpose saved position in file
unsigned long nPosExifStart;
unsigned nRet; // General purpose return value
bool bRet;
unsigned long nPosMarkerStart; // Offset for current marker
unsigned nColTransform = 0; // Color Transform from APP14 marker
// For DQT
CString strDqtPrecision = _T("");
CString strDqtZigZagOrder = _T("");
if (Buf(m_nPos) != 0xFF) {
if (m_nPos == 0) {
// Don't give error message if we've already alerted them of AVI / PSD
if ((!m_bAvi) && (!m_bPsd)) {
strTmp.Format(_T("NOTE: File did not start with JPEG marker. Consider using [Tools->Img Search Fwd] to locate embedded JPEG."));
m_pLog->AddLineErr(strTmp);
}
} else {
strTmp.Format(_T("ERROR: Expected marker 0xFF, got 0x%02X @ offset 0x%08X. Consider using [Tools->Img Search Fwd/Rev]."),Buf(m_nPos),m_nPos);
m_pLog->AddLineErr(strTmp);
}
m_nPos++;
return DECMARK_ERR;
}
m_nPos++;
// Read the current marker code
nCode = Buf(m_nPos++);
// Handle Marker Padding
//
// According to Section B.1.1.2:
// "Any marker may optionally be preceded by any number of fill bytes, which are bytes assigned code X�FF�."
//
unsigned nSkipMarkerPad = 0;
while (nCode == 0xFF) {
// Count the pad
nSkipMarkerPad++;
// Read another byte
nCode = Buf(m_nPos++);
}
// Report out any padding
if (nSkipMarkerPad>0) {
strTmp.Format(_T("*** Skipped %u marker pad bytes ***"),nSkipMarkerPad);
m_pLog->AddLineHdr(strTmp);
}
// Save the current marker offset
nPosMarkerStart = m_nPos;
AddHeader(nCode);
switch (nCode)
{
case JFIF_SOI: // SOI
m_bStateSoi = true;
break;
case JFIF_APP12:
// Photoshop DUCKY (Save For Web)
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
//nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian);
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
nPosSaved = m_nPos;
m_nPos += 2; // Move past length now that we've used it
_tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1));
acIdentifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case
strTmp.Format(_T(" Identifier = [%s]"),acIdentifier);
m_pLog->AddLine(strTmp);
m_nPos += (unsigned)_tcslen(acIdentifier)+1;
if (_tcscmp(acIdentifier,_T("Ducky")) != 0)
{
m_pLog->AddLine(_T(" Not Photoshop DUCKY. Skipping remainder."));
}
else // Photoshop
{
// Please see reference on http://cpan.uwinnipeg.ca/htdocs/Image-ExifTool/Image/ExifTool/APP12.pm.html
// A direct indexed approach should be safe
m_nImgQualPhotoshopSfw = Buf(m_nPos+6);
strTmp.Format(_T(" Photoshop Save For Web Quality = [%d]"),m_nImgQualPhotoshopSfw);
m_pLog->AddLine(strTmp);
}
// Restore original position in file to a point
// after the section
m_nPos = nPosSaved+nLength;
break;
case JFIF_APP14:
// JPEG Adobe tag
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
nPosSaved = m_nPos;
// Some files had very short segment (eg. nLength=2)
if (nLength < 2+12) {
m_pLog->AddLine(_T(" Segment too short for Identifier. Skipping remainder."));
m_nPos = nPosSaved+nLength;
break;
}
m_nPos += 2; // Move past length now that we've used it
// TODO: Confirm Adobe flag
m_nPos += 5;
nTmpVal = Buf(m_nPos+0)*256 + Buf(m_nPos+1);
strTmp.Format(_T(" DCTEncodeVersion = %u"),nTmpVal);
m_pLog->AddLine(strTmp);
nTmpVal = Buf(m_nPos+2)*256 + Buf(m_nPos+3);
strTmp.Format(_T(" APP14Flags0 = %u"),nTmpVal);
m_pLog->AddLine(strTmp);
nTmpVal = Buf(m_nPos+4)*256 + Buf(m_nPos+5);
strTmp.Format(_T(" APP14Flags1 = %u"),nTmpVal);
m_pLog->AddLine(strTmp);
nColTransform = Buf(m_nPos+6);
switch (nColTransform) {
case APP14_COLXFM_UNK_RGB:
strTmp.Format(_T(" ColorTransform = %u [Unknown (RGB or CMYK)]"),nColTransform);
break;
case APP14_COLXFM_YCC:
strTmp.Format(_T(" ColorTransform = %u [YCbCr]"),nColTransform);
break;
case APP14_COLXFM_YCCK:
strTmp.Format(_T(" ColorTransform = %u [YCCK]"),nColTransform);
break;
default:
strTmp.Format(_T(" ColorTransform = %u [???]"),nColTransform);
break;
}
m_pLog->AddLine(strTmp);
m_nApp14ColTransform = (nColTransform & 0xFF);
// Restore original position in file to a point
// after the section
m_nPos = nPosSaved+nLength;
break;
case JFIF_APP13:
// Photoshop (Save As)
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
//nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian);
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
nPosSaved = m_nPos;
// Some files had very short segment (eg. nLength=2)
if (nLength < 2+20) {
m_pLog->AddLine(_T(" Segment too short for Identifier. Skipping remainder."));
m_nPos = nPosSaved+nLength;
break;
}
m_nPos += 2; // Move past length now that we've used it
_tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1));
acIdentifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case
strTmp.Format(_T(" Identifier = [%s]"),acIdentifier);
m_pLog->AddLine(strTmp);
m_nPos += (unsigned)_tcslen(acIdentifier)+1;
if (_tcscmp(acIdentifier,_T("Photoshop 3.0")) != 0)
{
m_pLog->AddLine(_T(" Not Photoshop. Skipping remainder."));
}
else // Photoshop
{
DecodeApp13Ps();
}
// Restore original position in file to a point
// after the section
m_nPos = nPosSaved+nLength;
break;
case JFIF_APP1:
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
//nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian);
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
nPosSaved = m_nPos;
m_nPos += 2; // Move past length now that we've used it
_tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1));
acIdentifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case
strTmp.Format(_T(" Identifier = [%s]"),acIdentifier);
m_pLog->AddLine(strTmp);
m_nPos += (unsigned)_tcslen(acIdentifier);
if (!_tcsnccmp(acIdentifier,_T("http://ns.adobe.com/xap/1.0/\x00"),29) != 0) {
// XMP
m_pLog->AddLine(_T(" XMP = "));
m_nPos++;
unsigned nPosMarkerEnd = nPosSaved+nLength-1;
unsigned sXmpLen = nPosMarkerEnd-m_nPos;
char cXmpChar;
bool bNonSpace;
CString strLine;
// Reset state
strLine = _T(" |");
bNonSpace = false;
for (unsigned nInd=0;nInd<sXmpLen;nInd++) {
// Get the next char
cXmpChar = (char)m_pWBuf->Buf(m_nPos+nInd);
// Detect a non-space in line
if ((cXmpChar != 0x20) && (cXmpChar != 0x0A)) {
bNonSpace = true;
}
// Detect Linefeed, print out line
if (cXmpChar == 0x0A) {
// Only print line if some non-space elements!
if (bNonSpace) {
m_pLog->AddLine(strLine);
}
// Reset state
strLine = _T(" |");
bNonSpace = false;
} else {
// Add the char
strLine.AppendChar(cXmpChar);
}
}
}
else if (!_tcscmp(acIdentifier,_T("Exif")) != 0)
{
// Only decode it further if it is EXIF format
m_nPos += 2; // Skip two 00 bytes
nPosExifStart = m_nPos; // Save m_nPos @ start of EXIF used for all IFD offsets
// =========== EXIF TIFF Header (Start) ===========
// - Defined in Exif 2.2 Standard (JEITA CP-3451) section 4.5.2
// - Contents (8 bytes total)
// - Byte order (2 bytes)
// - 0x002A (2 bytes)
// - Offset of 0th IFD (4 bytes)
unsigned char acIdentifierTiff[9];
strFull = _T("");
strTmp = _T("");
strFull = _T(" Identifier TIFF = ");
for (unsigned int i=0;i<8;i++) {
acIdentifierTiff[i] = (unsigned char)Buf(m_nPos++);
}
strTmp = PrintAsHexUC(acIdentifierTiff,8);
strFull += strTmp;
m_pLog->AddLine(strFull);
switch (acIdentifierTiff[0]*256+acIdentifierTiff[1])
{
case 0x4949: // "II"
// Intel alignment
m_nImgExifEndian = 0;
m_pLog->AddLine(_T(" Endian = Intel (little)"));
break;
case 0x4D4D: // "MM"
// Motorola alignment
m_nImgExifEndian = 1;
m_pLog->AddLine(_T(" Endian = Motorola (big)"));
break;
}
// We expect the TAG mark of 0x002A (depending on endian mode)
unsigned test_002a;
test_002a = ByteSwap2(acIdentifierTiff[2],acIdentifierTiff[3]);
strTmp.Format(_T(" TAG Mark x002A = 0x%04X"),test_002a);
m_pLog->AddLine(strTmp);
unsigned nIfdCount; // Current IFD #
unsigned nOffsetIfd1;
// Mark pointer to EXIF Sub IFD as 0 so that we can
// detect if the tag never showed up.
m_nImgExifSubIfdPtr = 0;
m_nImgExifMakerPtr = 0;
m_nImgExifGpsIfdPtr = 0;
m_nImgExifInteropIfdPtr = 0;
bool exif_done = FALSE;
nOffsetIfd1 = ByteSwap4(acIdentifierTiff[4],acIdentifierTiff[5],
acIdentifierTiff[6],acIdentifierTiff[7]);
// =========== EXIF TIFF Header (End) ===========
// =========== EXIF IFD 0 ===========
// Do we start the 0th IFD for the "Primary Image Data"?
// Even though the nOffsetIfd1 pointer should indicate to
// us where the IFD should start (0x0008 if immediately after
// EXIF TIFF Header), I have observed JPEG files that
// do not contain the IFD. Therefore, we must check for this
// condition by comparing against the APP marker length.
// Example file: http://img9.imageshack.us/img9/194/90114543.jpg
if ((nPosSaved + nLength) <= (nPosExifStart+nOffsetIfd1)) {
// We've run out of space for any IFD, so cancel now
exif_done = true;
m_pLog->AddLine(_T(" NOTE: No IFD entries"));
}
nIfdCount = 0;
while (!exif_done) {
m_pLog->AddLine(_T(""));
strTmp.Format(_T("IFD%u"),nIfdCount);
// Process the IFD
nRet = DecodeExifIfd(strTmp,nPosExifStart,nOffsetIfd1);
// Now that we have gone through all entries in the IFD directory,
// we read the offset to the next IFD
nOffsetIfd1 = ByteSwap4(Buf(m_nPos+0),Buf(m_nPos+1),Buf(m_nPos+2),Buf(m_nPos+3));
m_nPos += 4;
strTmp.Format(_T(" Offset to Next IFD = 0x%08X"),nOffsetIfd1);
m_pLog->AddLine(strTmp);
if (nRet != 0) {
// Error condition (DecodeExifIfd returned error)
nOffsetIfd1 = 0x00000000;
}
if (nOffsetIfd1 == 0x00000000) {
// Either error condition or truly end of IFDs
exif_done = TRUE;
} else {
nIfdCount++;
}
} // while ! exif_done
// If EXIF SubIFD was defined, then handle it now
if (m_nImgExifSubIfdPtr != 0)
{
m_pLog->AddLine(_T(""));
DecodeExifIfd(_T("SubIFD"),nPosExifStart,m_nImgExifSubIfdPtr);
}
if (m_nImgExifMakerPtr != 0)
{
m_pLog->AddLine(_T(""));
DecodeExifIfd(_T("MakerIFD"),nPosExifStart,m_nImgExifMakerPtr);
}
if (m_nImgExifGpsIfdPtr != 0)
{
m_pLog->AddLine(_T(""));
DecodeExifIfd(_T("GPSIFD"),nPosExifStart,m_nImgExifGpsIfdPtr);
}
if (m_nImgExifInteropIfdPtr != 0)
{
m_pLog->AddLine(_T(""));
DecodeExifIfd(_T("InteropIFD"),nPosExifStart,m_nImgExifInteropIfdPtr);
}
} else {
strTmp.Format(_T("Identifier [%s] not supported. Skipping remainder."),(LPCTSTR)acIdentifier);
m_pLog->AddLine(strTmp);
}
//////////
// Dump out Makernote area
// TODO: Disabled for now
#if 0
unsigned ptr_base;
if (m_bVerbose)
{
if (m_nImgExifMakerPtr != 0)
{
// FIXME: Seems that nPosExifStart is not initialized in VERBOSE mode
ptr_base = nPosExifStart+m_nImgExifMakerPtr;
m_pLog->AddLine(_T("Exif Maker IFD DUMP"));
strFull.Format(_T(" MarkerOffset @ 0x%08X"),ptr_base);
m_pLog->AddLine(strFull);
}
}
#endif
// End of dump out makernote area
// Restore file position
m_nPos = nPosSaved;
// Restore original position in file to a point
// after the section
m_nPos = nPosSaved+nLength;
break;
case JFIF_APP2:
// Typically used for Flashpix and possibly ICC profiles
// Photoshop (Save As)
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
//nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian);
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
nPosSaved = m_nPos;
m_nPos += 2; // Move past length now that we've used it
_tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1));
acIdentifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case
strTmp.Format(_T(" Identifier = [%s]"),acIdentifier);
m_pLog->AddLine(strTmp);
m_nPos += (unsigned)_tcslen(acIdentifier)+1;
if (_tcscmp(acIdentifier,_T("FPXR")) == 0) {
// Photoshop
m_pLog->AddLine(_T(" FlashPix:"));
DecodeApp2Flashpix();
} else if (_tcscmp(acIdentifier,_T("ICC_PROFILE")) == 0) {
// ICC Profile
m_pLog->AddLine(_T(" ICC Profile:"));
DecodeApp2IccProfile(nLength);
} else {
m_pLog->AddLine(_T(" Not supported. Skipping remainder."));
}
// Restore original position in file to a point
// after the section
m_nPos = nPosSaved+nLength;
break;
case JFIF_APP3:
case JFIF_APP4:
case JFIF_APP5:
case JFIF_APP6:
case JFIF_APP7:
case JFIF_APP8:
case JFIF_APP9:
case JFIF_APP10:
case JFIF_APP11:
//case JFIF_APP12: // Handled separately
//case JFIF_APP13: // Handled separately
//case JFIF_APP14: // Handled separately
case JFIF_APP15:
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
//nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian);
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
if (m_bVerbose)
{
strFull = _T("");
for (unsigned int i=0;i<nLength;i++)
{
// Start a new line for every 16 codes
if ((i % 16) == 0) {
strFull.Format(_T(" MarkerOffset [%04X]: "),i);
} else if ((i % 8) == 0) {
strFull += _T(" ");
}
nTmpVal = Buf(m_nPos+i);
strTmp.Format(_T("%02X "),nTmpVal);
strFull += strTmp;
if ((i%16) == 15) {
m_pLog->AddLine(strFull);
strFull = _T("");
}
}
m_pLog->AddLine(strFull);
strFull = _T("");
for (unsigned int i=0;i<nLength;i++)
{
// Start a new line for every 16 codes
if ((i % 32) == 0) {
strFull.Format(_T(" MarkerOffset [%04X]: "),i);
} else if ((i % 8) == 0) {
strFull += _T(" ");
}
nTmpVal = Buf(m_nPos+i);
if (_istprint(nTmpVal)) {
strTmp.Format(_T("%c"),nTmpVal);
strFull += strTmp;
} else {
strFull += _T(".");
}
if ((i%32)==31) {
m_pLog->AddLine(strFull);
}
}
m_pLog->AddLine(strFull);
} // nVerbose
m_nPos += nLength;
break;
case JFIF_APP0: // APP0
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
//nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian);
m_nPos+=2;
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
_tcscpy_s(m_acApp0Identifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1));
m_acApp0Identifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case
strTmp.Format(_T(" Identifier = [%s]"),m_acApp0Identifier);
m_pLog->AddLine(strTmp);
if (!_tcscmp(m_acApp0Identifier,_T("JFIF")))
{
// Only process remainder if it is JFIF. This marker
// is also used for application-specific functions.
m_nPos += (unsigned)(_tcslen(m_acApp0Identifier)+1);
m_nImgVersionMajor = Buf(m_nPos++);
m_nImgVersionMinor = Buf(m_nPos++);
strTmp.Format(_T(" version = [%u.%u]"),m_nImgVersionMajor,m_nImgVersionMinor);
m_pLog->AddLine(strTmp);
m_nImgUnits = Buf(m_nPos++);
m_nImgDensityX = Buf(m_nPos)*256 + Buf(m_nPos+1);
//m_nImgDensityX = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian);
m_nPos+=2;
m_nImgDensityY = Buf(m_nPos)*256 + Buf(m_nPos+1);
//m_nImgDensityY = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian);
m_nPos+=2;
strTmp.Format(_T(" density = %u x %u "),m_nImgDensityX,m_nImgDensityY);
strFull = strTmp;
switch (m_nImgUnits)
{
case 0:
strFull += _T("(aspect ratio)");
m_pLog->AddLine(strFull);
break;
case 1:
strFull += _T("DPI (dots per inch)");
m_pLog->AddLine(strFull);
break;
case 2:
strFull += _T("DPcm (dots per cm)");
m_pLog->AddLine(strFull);
break;
default:
strTmp.Format(_T("ERROR: Unknown ImgUnits parameter [%u]"),m_nImgUnits);
strFull += strTmp;
m_pLog->AddLineWarn(strFull);
//return DECMARK_ERR;
break;
}
m_nImgThumbSizeX = Buf(m_nPos++);
m_nImgThumbSizeY = Buf(m_nPos++);
strTmp.Format(_T(" thumbnail = %u x %u"),m_nImgThumbSizeX,m_nImgThumbSizeY);
m_pLog->AddLine(strTmp);
// Unpack the thumbnail:
unsigned thumbnail_r,thumbnail_g,thumbnail_b;
if (m_nImgThumbSizeX && m_nImgThumbSizeY) {
for (unsigned y=0;y<m_nImgThumbSizeY;y++) {
strFull.Format(_T(" Thumb[%03u] = "),y);
for (unsigned x=0;x<m_nImgThumbSizeX;x++) {
thumbnail_r = Buf(m_nPos++);
thumbnail_g = Buf(m_nPos++);
thumbnail_b = Buf(m_nPos++);
strTmp.Format(_T("(0x%02X,0x%02X,0x%02X) "),thumbnail_r,thumbnail_g,thumbnail_b);
strFull += strTmp;
m_pLog->AddLine(strFull);
}
}
}
// TODO:
// - In JPEG-B mode (GeoRaster), we will need to fake out
// the DHT & DQT tables here. Unfortunately, we'll have to
// rely on the user to put us into this mode as there is nothing
// in the file that specifies this mode.
/*
// TODO: Need to ensure that Faked DHT is correct table
AddHeader(JFIF_DHT_FAKE);
DecodeDHT(true);
// Need to mark DHT tables as OK
m_bStateDht = true;
m_bStateDhtFake = true;
m_bStateDhtOk = true;
// ... same for DQT
*/
} else if (!_tcsnccmp(m_acApp0Identifier,_T("AVI1"),4))
{
// AVI MJPEG type
// Need to fill in predefined DHT table from spec:
// OpenDML file format for AVI, section "Proposed Data Chunk Format"
// Described in MMREG.H
m_pLog->AddLine(_T(" Detected MotionJPEG"));
m_pLog->AddLine(_T(" Importing standard Huffman table..."));
m_pLog->AddLine(_T(""));
AddHeader(JFIF_DHT_FAKE);
DecodeDHT(true);
// Need to mark DHT tables as OK
m_bStateDht = true;
m_bStateDhtFake = true;
m_bStateDhtOk = true;
m_nPos += nLength-2; // Skip over, and undo length short read
} else {
// Not JFIF or AVI1
m_pLog->AddLine(_T(" Not known APP0 type. Skipping remainder."));
m_nPos += nLength-2;
}
if (!ExpectMarkerEnd(nPosMarkerStart,nLength))
return DECMARK_ERR;
break;
case JFIF_DQT: // Define quantization tables
m_bStateDqt = true;
unsigned nDqtPrecision_Pq;
unsigned nDqtQuantDestId_Tq;
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Lq
nPosEnd = m_nPos+nLength;
m_nPos+=2;
//XXX strTmp.Format(_T(" Table length <Lq> = %u"),nLength);
strTmp.Format(_T(" Table length = %u"),nLength);
m_pLog->AddLine(strTmp);
while (nPosEnd > m_nPos)
{
strTmp.Format(_T(" ----"));
m_pLog->AddLine(strTmp);
nTmpVal = Buf(m_nPos++); // Pq | Tq
nDqtPrecision_Pq = (nTmpVal & 0xF0) >> 4; // Pq, range 0-1
nDqtQuantDestId_Tq = nTmpVal & 0x0F; // Tq, range 0-3
// Decode per ITU-T.81 standard
#if 1
if (nDqtPrecision_Pq == 0) {
strDqtPrecision = _T("8 bits");
} else if (nDqtPrecision_Pq == 1) {
strDqtPrecision = _T("16 bits");
} else {
strTmp.Format(_T(" Unsupported precision value [%u]"),nDqtPrecision_Pq);
m_pLog->AddLineWarn(strTmp);
strDqtPrecision = _T("???");
// FIXME: Consider terminating marker parsing early
}
if (!ValidateValue(nDqtPrecision_Pq,0,1,_T("DQT Precision <Pq>"),true,0)) return DECMARK_ERR;
if (!ValidateValue(nDqtQuantDestId_Tq,0,3,_T("DQT Destination ID <Tq>"),true,0)) return DECMARK_ERR;
strTmp.Format(_T(" Precision=%s"),(LPCTSTR)strDqtPrecision);
m_pLog->AddLine(strTmp);
#else
// Decode with additional DQT extension (ITU-T-JPEG-Plus-Proposal_R3.doc)
if ((nDqtPrecision_Pq & 0xE) == 0) {
// Per ITU-T.81 Standard
if (nDqtPrecision_Pq == 0) {
strDqtPrecision = _T("8 bits");
} else if (nDqtPrecision_Pq == 1) {
strDqtPrecision = _T("16 bits");
}
strTmp.Format(_T(" Precision=%s"),strDqtPrecision);
m_pLog->AddLine(strTmp);
} else {
// Non-standard
// JPEG-Plus-Proposal-R3:
// - Alternative sub-block-wise sequence
strTmp.Format(_T(" Non-Standard DQT Extension detected"));
m_pLog->AddLineWarn(strTmp);
// FIXME: Should prevent attempt to decode until this is implemented
if (nDqtPrecision_Pq == 0) {
strDqtPrecision = _T("8 bits");
} else if (nDqtPrecision_Pq == 1) {
strDqtPrecision = _T("16 bits");
}
strTmp.Format(_T(" Precision=%s"),strDqtPrecision);
m_pLog->AddLine(strTmp);
if ((nDqtPrecision_Pq & 0x2) == 0) {
strDqtZigZagOrder = _T("Diagonal zig-zag coeff scan seqeunce");
} else if ((nDqtPrecision_Pq & 0x2) == 1) {
strDqtZigZagOrder = _T("Alternate coeff scan seqeunce");
}
strTmp.Format(_T(" Coeff Scan Sequence=%s"),strDqtZigZagOrder);
m_pLog->AddLine(strTmp);
if ((nDqtPrecision_Pq & 0x4) == 1) {
strTmp.Format(_T(" Custom coeff scan sequence"));
m_pLog->AddLine(strTmp);
// Now expect sequence of 64 coefficient entries
CString strSequence = _T("");
for (unsigned nInd=0;nInd<64;nInd++) {
nTmpVal = Buf(m_nPos++);
strTmp.Format(_T("%u"),nTmpVal);
strSequence += strTmp;
if (nInd!=63) {
strSequence += _T(", ");
}
}
strTmp.Format(_T(" Custom sequence = [ %s ]"),strSequence);
m_pLog->AddLine(strTmp);
}
}
#endif
strTmp.Format(_T(" Destination ID=%u"),nDqtQuantDestId_Tq);
if (nDqtQuantDestId_Tq == 0) {
strTmp += _T(" (Luminance)");
}
else if (nDqtQuantDestId_Tq == 1) {
strTmp += _T(" (Chrominance)");
}
else if (nDqtQuantDestId_Tq == 2) {
strTmp += _T(" (Chrominance)");
}
else {
strTmp += _T(" (???)");
}
m_pLog->AddLine(strTmp);
// FIXME: The following is somewhat superseded by ValidateValue() above
// with the exception of skipping remainder
if (nDqtQuantDestId_Tq >= MAX_DQT_DEST_ID) {
strTmp.Format(_T("ERROR: Destination ID <Tq> = %u, >= %u"),nDqtQuantDestId_Tq,MAX_DQT_DEST_ID);
m_pLog->AddLineErr(strTmp);
if (!m_pAppConfig->bRelaxedParsing) {
m_pLog->AddLineErr(_T(" Stopping decode"));
return DECMARK_ERR;
} else {
// Now skip remainder of DQT
// FIXME
strTmp.Format(_T(" Skipping remainder of marker [%u bytes]"),nPosMarkerStart + nLength - m_nPos);
m_pLog->AddLineWarn(strTmp);
m_pLog->AddLine(_T(""));
m_nPos = nPosMarkerStart + nLength;
return DECMARK_OK;
}
}
bool bQuantAllOnes = true;
double dComparePercent;
double dSumPercent=0;
double dSumPercentSqr=0;
for (unsigned nCoeffInd=0;nCoeffInd<MAX_DQT_COEFF;nCoeffInd++)
{
nTmpVal = Buf(m_nPos++);
if (nDqtPrecision_Pq == 1) {
// 16-bit DQT entries!
nTmpVal <<= 8;
nTmpVal += Buf(m_nPos++);
}
m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]] = nTmpVal;
/* scaling factor in percent */
// Now calculate the comparison with the Annex sample
// FIXME: Should probably use check for landscape orientation and
// rotate comparison matrix accordingly
if (nDqtQuantDestId_Tq == 0) {
if (m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]] != 0) {
m_afStdQuantLumCompare[glb_anZigZag[nCoeffInd]] =
(float)(glb_anStdQuantLum[glb_anZigZag[nCoeffInd]]) /
(float)(m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]]);
dComparePercent = 100.0 *
(double)(m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]]) /
(double)(glb_anStdQuantLum[glb_anZigZag[nCoeffInd]]);
} else {
m_afStdQuantLumCompare[glb_anZigZag[nCoeffInd]] = (float)999.99;
dComparePercent = 999.99;
}
} else {
if (m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]] != 0) {
m_afStdQuantChrCompare[glb_anZigZag[nCoeffInd]] =
(float)(glb_anStdQuantChr[glb_anZigZag[nCoeffInd]]) /
(float)(m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]]);
dComparePercent = 100.0 *
(double)(m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]]) /
(double)(glb_anStdQuantChr[glb_anZigZag[nCoeffInd]]);
} else {
m_afStdQuantChrCompare[glb_anZigZag[nCoeffInd]] = (float)999.99;
}
}
dSumPercent += dComparePercent;
dSumPercentSqr += dComparePercent * dComparePercent;
// Check just in case entire table are ones (Quality 100)
if (m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]] != 1) bQuantAllOnes = 0;
} // 0..63
// Note that the DQT table that we are saving is already
// after doing zigzag reordering:
// From high freq -> low freq
// To X,Y, left-to-right, top-to-bottom
// Flag this DQT table as being set!
m_abImgDqtSet[nDqtQuantDestId_Tq] = true;
unsigned nCoeffInd;
// Now display the table
for (unsigned nDqtY=0;nDqtY<8;nDqtY++) {
strFull.Format(_T(" DQT, Row #%u: "),nDqtY);
for (unsigned nDqtX=0;nDqtX<8;nDqtX++) {
nCoeffInd = nDqtY*8+nDqtX;
strTmp.Format(_T("%3u "),m_anImgDqtTbl[nDqtQuantDestId_Tq][nCoeffInd]);
strFull += strTmp;
// Store the DQT entry into the Image Decoder
bRet = m_pImgDec->SetDqtEntry(nDqtQuantDestId_Tq,nCoeffInd,glb_anUnZigZag[nCoeffInd],
m_anImgDqtTbl[nDqtQuantDestId_Tq][nCoeffInd]);
DecodeErrCheck(bRet);
}
// Now add the compare with Annex K
// Decided to disable this as it was confusing users
/*
strFull += _T(" AnnexRatio: <");
for (unsigned nDqtX=0;nDqtX<8;nDqtX++) {
nCoeffInd = nDqtY*8+nDqtX;
if (nDqtQuantDestId_Tq == 0) {
strTmp.Format(_T("%5.1f "),m_afStdQuantLumCompare[nCoeffInd]);
} else {
strTmp.Format(_T("%5.1f "),m_afStdQuantChrCompare[nCoeffInd]);
}
strFull += strTmp;
}
strFull += _T(">");
*/
m_pLog->AddLine(strFull);
}
// Perform some statistical analysis of the quality factor
// to determine the likelihood of the current quantization
// table being a scaled version of the "standard" tables.
// If the variance is high, it is unlikely to be the case.
double dQuality;
double dVariance;
dSumPercent /= 64.0; /* mean scale factor */
dSumPercentSqr /= 64.0;
dVariance = dSumPercentSqr - (dSumPercent * dSumPercent); /* variance */
// Generate the equivalent IJQ "quality" factor
if (bQuantAllOnes) /* special case for all-ones table */
dQuality = 100.0;
else if (dSumPercent <= 100.0)
dQuality = (200.0 - dSumPercent) / 2.0;
else
dQuality = 5000.0 / dSumPercent;
// Save the quality rating for later
m_adImgDqtQual[nDqtQuantDestId_Tq] = dQuality;
strTmp.Format(_T(" Approx quality factor = %.2f (scaling=%.2f variance=%.2f)"),
dQuality,dSumPercent,dVariance);
m_pLog->AddLine(strTmp);
}
m_bStateDqtOk = true;
if (!ExpectMarkerEnd(nPosMarkerStart,nLength))
return DECMARK_ERR;
break;
case JFIF_DAC: // DAC (Arithmetic Coding)
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // La
m_nPos+=2;
//XXX strTmp.Format(_T(" Arithmetic coding header length <La> = %u"),nLength);
strTmp.Format(_T(" Arithmetic coding header length = %u"),nLength);
m_pLog->AddLine(strTmp);
unsigned nDAC_n;
unsigned nDAC_Tc,nDAC_Tb;
unsigned nDAC_Cs;
nDAC_n = (nLength>2)?(nLength-2)/2:0;
for (unsigned nInd=0;nInd<nDAC_n;nInd++) {
nTmpVal = Buf(m_nPos++); // Tc,Tb
nDAC_Tc = (nTmpVal & 0xF0) >> 4;
nDAC_Tb = (nTmpVal & 0x0F);
//XXX strTmp.Format(_T(" #%02u: Table class <Tc> = %u"),nInd+1,nDAC_Tc);
strTmp.Format(_T(" #%02u: Table class = %u"),nInd+1,nDAC_Tc);
m_pLog->AddLine(strTmp);
//XXX strTmp.Format(_T(" #%02u: Table destination identifier <Tb> = %u"),nInd+1,nDAC_Tb);
strTmp.Format(_T(" #%02u: Table destination identifier = %u"),nInd+1,nDAC_Tb);
m_pLog->AddLine(strTmp);
nDAC_Cs = Buf(m_nPos++); // Cs
//XXX strTmp.Format(_T(" #%02u: Conditioning table value <Cs> = %u"),nInd+1,nDAC_Cs);
strTmp.Format(_T(" #%02u: Conditioning table value = %u"),nInd+1,nDAC_Cs);
m_pLog->AddLine(strTmp);
if (!ValidateValue(nDAC_Tc,0,1,_T("Table class <Tc>"),true,0)) return DECMARK_ERR;
if (!ValidateValue(nDAC_Tb,0,3,_T("Table destination ID <Tb>"),true,0)) return DECMARK_ERR;
// Parameter range constraints per Table B.6:
// ------------|-------------------------|-------------------|------------
// | Sequential DCT | Progressive DCT | Lossless
// Parameter | Baseline Extended | |
// ------------|-----------|-------------|-------------------|------------
// Cs | Undef | Tc=0: 0-255 | Tc=0: 0-255 | 0-255
// | | Tc=1: 1-63 | Tc=1: 1-63 |
// ------------|-----------|-------------|-------------------|------------
// However, to keep it simple (and not depend on lossless mode),
// we will only check the maximal range
if (!ValidateValue(nDAC_Cs,0,255,_T("Conditioning table value <Cs>"),true,0)) return DECMARK_ERR;
}
if (!ExpectMarkerEnd(nPosMarkerStart,nLength))
return DECMARK_ERR;
break;
case JFIF_DNL: // DNL (Define number of lines)
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Ld
m_nPos+=2;
//XXX strTmp.Format(_T(" Header length <Ld> = %u"),nLength);
strTmp.Format(_T(" Header length = %u"),nLength);
m_pLog->AddLine(strTmp);
nTmpVal = Buf(m_nPos)*256 + Buf(m_nPos+1); // NL
m_nPos+=2;
//XXX strTmp.Format(_T(" Number of lines <NL> = %u"),nTmpVal);
strTmp.Format(_T(" Number of lines = %u"),nTmpVal);
m_pLog->AddLine(strTmp);
if (!ValidateValue(nTmpVal,1,65535,_T("Number of lines <NL>"),true,1)) return DECMARK_ERR;
if (!ExpectMarkerEnd(nPosMarkerStart,nLength))
return DECMARK_ERR;
break;
case JFIF_EXP:
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Le
m_nPos+=2;
//XXX strTmp.Format(_T(" Header length <Le> = %u"),nLength);
strTmp.Format(_T(" Header length = %u"),nLength);
m_pLog->AddLine(strTmp);
unsigned nEXP_Eh,nEXP_Ev;
nTmpVal = Buf(m_nPos)*256 + Buf(m_nPos+1); // Eh,Ev
nEXP_Eh = (nTmpVal & 0xF0) >> 4;
nEXP_Ev = (nTmpVal & 0x0F);
m_nPos+=2;
//XXX strTmp.Format(_T(" Expand horizontally <Eh> = %u"),nEXP_Eh);
strTmp.Format(_T(" Expand horizontally = %u"),nEXP_Eh);
m_pLog->AddLine(strTmp);
//XXX strTmp.Format(_T(" Expand vertically <Ev> = %u"),nEXP_Ev);
strTmp.Format(_T(" Expand vertically = %u"),nEXP_Ev);
m_pLog->AddLine(strTmp);
if (!ValidateValue(nEXP_Eh,0,1,_T("Expand horizontally <Eh>"),true,0)) return DECMARK_ERR;
if (!ValidateValue(nEXP_Ev,0,1,_T("Expand vertically <Ev>"),true,0)) return DECMARK_ERR;
if (!ExpectMarkerEnd(nPosMarkerStart,nLength))
return DECMARK_ERR;
break;
case JFIF_SOF0: // SOF0 (Baseline DCT)
case JFIF_SOF1: // SOF1 (Extended sequential)
case JFIF_SOF2: // SOF2 (Progressive)
case JFIF_SOF3:
case JFIF_SOF5:
case JFIF_SOF6:
case JFIF_SOF7:
case JFIF_SOF9:
case JFIF_SOF10:
case JFIF_SOF11:
case JFIF_SOF13:
case JFIF_SOF14:
case JFIF_SOF15:
// TODO:
// - JFIF_DHP should be able to reuse the JFIF_SOF marker parsing
// however as we don't support hierarchical image decode, we
// would want to skip the update of class members.
m_bStateSof = true;
// Determine if this is a SOF mode that we support
// At this time, we only support Baseline DCT & Extended Sequential Baseline DCT
// (non-differential) with Huffman coding. Progressive, Lossless,
// Differential and Arithmetic coded modes are not supported.
m_bImgSofUnsupported = true;
if (nCode == JFIF_SOF0) { m_bImgSofUnsupported = false; }
if (nCode == JFIF_SOF1) { m_bImgSofUnsupported = false; }
// For reference, note progressive scan files even though
// we don't currently support their decode
if (nCode == JFIF_SOF2) { m_bImgProgressive = true; }
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Lf
m_nPos+=2;
//XXX strTmp.Format(_T(" Frame header length <Lf> = %u"),nLength);
strTmp.Format(_T(" Frame header length = %u"),nLength);
m_pLog->AddLine(strTmp);
m_nSofPrecision_P = Buf(m_nPos++); // P
//XXX strTmp.Format(_T(" Precision <P> = %u"),m_nSofPrecision_P);
strTmp.Format(_T(" Precision = %u"),m_nSofPrecision_P);
m_pLog->AddLine(strTmp);
if (!ValidateValue(m_nSofPrecision_P,2,16,_T("Precision <P>"),true,8)) return DECMARK_ERR;
m_nSofNumLines_Y = Buf(m_nPos)*256 + Buf(m_nPos+1); // Y
m_nPos += 2;
//XXX strTmp.Format(_T(" Number of Lines <Y> = %u"),m_nSofNumLines_Y);
strTmp.Format(_T(" Number of Lines = %u"),m_nSofNumLines_Y);
m_pLog->AddLine(strTmp);
if (!ValidateValue(m_nSofNumLines_Y,0,65535,_T("Number of Lines <Y>"),true,0)) return DECMARK_ERR;
m_nSofSampsPerLine_X = Buf(m_nPos)*256 + Buf(m_nPos+1); // X
m_nPos += 2;
//XXX strTmp.Format(_T(" Samples per Line <X> = %u"),m_nSofSampsPerLine_X);
strTmp.Format(_T(" Samples per Line = %u"),m_nSofSampsPerLine_X);
m_pLog->AddLine(strTmp);
if (!ValidateValue(m_nSofSampsPerLine_X,1,65535,_T("Samples per Line <X>"),true,1)) return DECMARK_ERR;
strTmp.Format(_T(" Image Size = %u x %u"),m_nSofSampsPerLine_X,m_nSofNumLines_Y);
m_pLog->AddLine(strTmp);
// Determine orientation
// m_nSofSampsPerLine_X = X
// m_nSofNumLines_Y = Y
m_eImgLandscape = ENUM_LANDSCAPE_YES;
if (m_nSofNumLines_Y > m_nSofSampsPerLine_X)
m_eImgLandscape = ENUM_LANDSCAPE_NO;
strTmp.Format(_T(" Raw Image Orientation = %s"),(m_eImgLandscape==ENUM_LANDSCAPE_YES)?_T("Landscape"):_T("Portrait"));
m_pLog->AddLine(strTmp);
m_nSofNumComps_Nf = Buf(m_nPos++); // Nf, range 1..255
//XXX strTmp.Format(_T(" Number of Img components <Nf> = %u"),m_nSofNumComps_Nf);
strTmp.Format(_T(" Number of Img components = %u"),m_nSofNumComps_Nf);
m_pLog->AddLine(strTmp);
if (!ValidateValue(m_nSofNumComps_Nf,1,255,_T("Number of Img components <Nf>"),true,1)) return DECMARK_ERR;
unsigned nCompIdent;
unsigned anSofSampFact[MAX_SOF_COMP_NF];
m_nSofHorzSampFactMax_Hmax = 0;
m_nSofVertSampFactMax_Vmax = 0;
// Now clear the output image content (all components)
// TODO: Migrate some of the bitmap allocation / clearing from
// DecodeScanImg() into ResetImageContent() and call here
//m_pImgDec->ResetImageContent();
// Per JFIF v1.02:
// - Nf = 1 or 3
// - C1 = Y
// - C2 = Cb
// - C3 = Cr
for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++)
{
nCompIdent = Buf(m_nPos++); // Ci, range 0..255
m_anSofQuantCompId[nCompInd] = nCompIdent;
//if (!ValidateValue(m_anSofQuantCompId[nCompInd],0,255,_T("Component ID <Ci>"),true,0)) return DECMARK_ERR;
anSofSampFact[nCompIdent] = Buf(m_nPos++);
m_anSofQuantTblSel_Tqi[nCompIdent] = Buf(m_nPos++); // Tqi, range 0..3
//if (!ValidateValue(m_anSofQuantTblSel_Tqi[nCompIdent],0,3,_T("Table Destination ID <Tqi>"),true,0)) return DECMARK_ERR;
// NOTE: We protect against bad input here as replication ratios are
// determined later that depend on dividing by sampling factor (hence
// possibility of div by 0).
m_anSofHorzSampFact_Hi[nCompIdent] = (anSofSampFact[nCompIdent] & 0xF0) >> 4; // Hi, range 1..4
m_anSofVertSampFact_Vi[nCompIdent] = (anSofSampFact[nCompIdent] & 0x0F); // Vi, range 1..4
if (!ValidateValue(m_anSofHorzSampFact_Hi[nCompIdent],1,4,_T("Horizontal Sampling Factor <Hi>"),true,1)) return DECMARK_ERR;
if (!ValidateValue(m_anSofVertSampFact_Vi[nCompIdent],1,4,_T("Vertical Sampling Factor <Vi>"),true,1)) return DECMARK_ERR;
}
// Calculate max sampling factors
for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++)
{
nCompIdent = m_anSofQuantCompId[nCompInd];
// Calculate maximum sampling factor for the SOF. This is only
// used for later generation of m_strImgQuantCss an the SOF
// reporting below. The CimgDecode block is responsible for
// calculating the maximum sampling factor on a per-scan basis.
m_nSofHorzSampFactMax_Hmax = max(m_nSofHorzSampFactMax_Hmax,m_anSofHorzSampFact_Hi[nCompIdent]);
m_nSofVertSampFactMax_Vmax = max(m_nSofVertSampFactMax_Vmax,m_anSofVertSampFact_Vi[nCompIdent]);
}
// Report per-component sampling factors and quantization table selectors
for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++)
{
nCompIdent = m_anSofQuantCompId[nCompInd];
// Create subsampling ratio
// - Protect against division-by-zero
CString strSubsampH = _T("?");
CString strSubsampV = _T("?");
if (m_anSofHorzSampFact_Hi[nCompIdent] > 0) {
strSubsampH.Format(_T("%u"),m_nSofHorzSampFactMax_Hmax/m_anSofHorzSampFact_Hi[nCompIdent]);
}
if (m_anSofVertSampFact_Vi[nCompIdent] > 0) {
strSubsampV.Format(_T("%u"),m_nSofVertSampFactMax_Vmax/m_anSofVertSampFact_Vi[nCompIdent]);
}
strFull.Format(_T(" Component[%u]: "),nCompInd); // Note i in Ci is 1-based
//XXX strTmp.Format(_T("ID=0x%02X, Samp Fac <Hi,Vi>=0x%02X (Subsamp %u x %u), Quant Tbl Sel <Tqi>=0x%02X"),
strTmp.Format(_T("ID=0x%02X, Samp Fac=0x%02X (Subsamp %s x %s), Quant Tbl Sel=0x%02X"),
nCompIdent,anSofSampFact[nCompIdent],
(LPCTSTR)strSubsampH,(LPCTSTR)strSubsampV,
m_anSofQuantTblSel_Tqi[nCompIdent]);
strFull += strTmp;
// Mapping from component index (not ID) to colour channel per JFIF
if (m_nSofNumComps_Nf == 1) {
// Assume grayscale
strFull += _T(" (Lum: Y)");
} else if (m_nSofNumComps_Nf == 3) {
// Assume YCC
if (nCompInd == SCAN_COMP_Y) {
strFull += _T(" (Lum: Y)");
}
else if (nCompInd == SCAN_COMP_CB) {
strFull += _T(" (Chrom: Cb)");
}
else if (nCompInd == SCAN_COMP_CR) {
strFull += _T(" (Chrom: Cr)");
}
} else if (m_nSofNumComps_Nf == 4) {
// Assume YCCK
if (nCompInd == 1) {
strFull += _T(" (Y)");
}
else if (nCompInd == 2) {
strFull += _T(" (Cb)");
}
else if (nCompInd == 3) {
strFull += _T(" (Cr)");
}
else if (nCompInd == 4) {
strFull += _T(" (K)");
}
} else {
strFull += _T(" (???)"); // Unknown
}
m_pLog->AddLine(strFull);
}
// Test for bad input, clean up if bad
for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++)
{
nCompIdent = m_anSofQuantCompId[nCompInd];
if (!ValidateValue(m_anSofQuantCompId[nCompInd],0,255,_T("Component ID <Ci>"),true,0)) return DECMARK_ERR;
if (!ValidateValue(m_anSofQuantTblSel_Tqi[nCompIdent],0,3,_T("Table Destination ID <Tqi>"),true,0)) return DECMARK_ERR;
if (!ValidateValue(m_anSofHorzSampFact_Hi[nCompIdent],1,4,_T("Horizontal Sampling Factor <Hi>"),true,1)) return DECMARK_ERR;
if (!ValidateValue(m_anSofVertSampFact_Vi[nCompIdent],1,4,_T("Vertical Sampling Factor <Vi>"),true,1)) return DECMARK_ERR;
}
// Finally, assign the cleaned values to the decoder
for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++)
{
nCompIdent = m_anSofQuantCompId[nCompInd];
// Store the DQT Table selection for the Image Decoder
// Param values: Nf,Tqi
// Param ranges: 1..255,0..3
// Note that the Image Decoder doesn't need to see the Component Identifiers
bRet = m_pImgDec->SetDqtTables(nCompInd,m_anSofQuantTblSel_Tqi[nCompIdent]);
DecodeErrCheck(bRet);
// Store the Precision (to handle 12-bit decode)
m_pImgDec->SetPrecision(m_nSofPrecision_P);
}
if (!m_bStateAbort) {
// Set the component sampling factors (chroma subsampling)
// FIXME: check ranging
for (unsigned nCompInd=1;nCompInd<=m_nSofNumComps_Nf;nCompInd++) {
// nCompInd is component index (1...Nf)
// nCompIdent is Component Identifier (Ci)
// Note that the Image Decoder doesn't need to see the Component Identifiers
nCompIdent = m_anSofQuantCompId[nCompInd];
m_pImgDec->SetSofSampFactors(nCompInd,m_anSofHorzSampFact_Hi[nCompIdent],m_anSofVertSampFact_Vi[nCompIdent]);
}
// Now mark the image as been somewhat OK (ie. should
// also be suitable for EmbeddedThumb() and PrepareSignature()
m_bImgOK = true;
m_bStateSofOk = true;
}
if (!ExpectMarkerEnd(nPosMarkerStart,nLength))
return DECMARK_ERR;
break;
case JFIF_COM: // COM
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
m_nPos+=2;
strTmp.Format(_T(" Comment length = %u"),nLength);
m_pLog->AddLine(strTmp);
// Check for JPEG COM vulnerability
// http://marc.info/?l=bugtraq&m=109524346729948
// Note that the recovery is not very graceful. It will assume that the
// field is actually zero-length, which will make the next byte trigger the
// "Expected marker 0xFF" error message and probably abort. There is no
// obvious way to
if ( (nLength == 0) || (nLength == 1) ) {
strTmp.Format(_T(" JPEG Comment Field Vulnerability detected!"));
m_pLog->AddLineErr(strTmp);
strTmp.Format(_T(" Skipping data until next marker..."));
m_pLog->AddLineErr(strTmp);
nLength = 2;
bool bDoneSearch = false;
unsigned nSkipStart = m_nPos;
while (!bDoneSearch) {
if (Buf(m_nPos) != 0xFF) {
m_nPos++;
} else {
bDoneSearch = true;
}
if (m_nPos >= m_pWBuf->GetPosEof()) {
bDoneSearch = true;
}
}
strTmp.Format(_T(" Skipped %u bytes"),m_nPos - nSkipStart);
m_pLog->AddLineErr(strTmp);
// Break out of case statement
break;
}
// Assume COM field valid length (ie. >= 2)
strFull = _T(" Comment=");
m_strComment = _T("");
for (unsigned ind=0;ind<nLength-2;ind++)
{
nTmpVal = Buf(m_nPos++);
if (_istprint(nTmpVal)) {
strTmp.Format(_T("%c"),nTmpVal);
m_strComment += strTmp;
} else {
m_strComment += _T(".");
}
}
strFull += m_strComment;
m_pLog->AddLine(strFull);
break;
case JFIF_DHT: // DHT
m_bStateDht = true;
DecodeDHT(false);
m_bStateDhtOk = true;
break;
case JFIF_SOS: // SOS
unsigned long nPosScanStart; // Byte count at start of scan data segment
m_bStateSos = true;
// NOTE: Only want to capture position of first SOS
// This should make other function such as AVI frame extract
// more robust in case we get multiple SOS segments.
// We assume that this value is reset when we start a new decode
if (m_nPosSos == 0) {
m_nPosSos = m_nPos-2; // Used for Extract. Want to include actual marker
}
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
m_nPos+=2;
// Ensure that we have seen proper markers before we try this one!
if (!m_bStateSofOk) {
strTmp.Format(_T(" ERROR: SOS before valid SOF defined"));
m_pLog->AddLineErr(strTmp);
return DECMARK_ERR;
}
strTmp.Format(_T(" Scan header length = %u"),nLength);
m_pLog->AddLine(strTmp);
m_nSosNumCompScan_Ns = Buf(m_nPos++); // Ns, range 1..4
//XXX strTmp.Format(_T(" Number of image components <Ns> = %u"),m_nSosNumCompScan_Ns);
strTmp.Format(_T(" Number of img components = %u"),m_nSosNumCompScan_Ns);
m_pLog->AddLine(strTmp);
// Just in case something got corrupted, don't want to get out
// of range here. Note that this will be a hard abort, and
// will not resume decoding.
if (m_nSosNumCompScan_Ns > MAX_SOS_COMP_NS) {
strTmp.Format(_T(" ERROR: Scan decode does not support > %u components"),MAX_SOS_COMP_NS);
m_pLog->AddLineErr(strTmp);
return DECMARK_ERR;
}
unsigned nSosCompSel_Cs;
unsigned nSosHuffTblSel;
unsigned nSosHuffTblSelDc_Td;
unsigned nSosHuffTblSelAc_Ta;
// Max range of components indices is between 1..4
for (unsigned int nScanCompInd=1;((nScanCompInd<=m_nSosNumCompScan_Ns) && (!m_bStateAbort));nScanCompInd++)
{
strFull.Format(_T(" Component[%u]: "),nScanCompInd);
nSosCompSel_Cs = Buf(m_nPos++); // Cs, range 0..255
nSosHuffTblSel = Buf(m_nPos++);
nSosHuffTblSelDc_Td = (nSosHuffTblSel & 0xf0)>>4; // Td, range 0..3
nSosHuffTblSelAc_Ta = (nSosHuffTblSel & 0x0f); // Ta, range 0..3
strTmp.Format(_T("selector=0x%02X, table=%u(DC),%u(AC)"),nSosCompSel_Cs,nSosHuffTblSelDc_Td,nSosHuffTblSelAc_Ta);
strFull += strTmp;
m_pLog->AddLine(strFull);
bRet = m_pImgDec->SetDhtTables(nScanCompInd,nSosHuffTblSelDc_Td,nSosHuffTblSelAc_Ta);
DecodeErrCheck(bRet);
}
m_nSosSpectralStart_Ss = Buf(m_nPos++);
m_nSosSpectralEnd_Se = Buf(m_nPos++);
m_nSosSuccApprox_A = Buf(m_nPos++);
strTmp.Format(_T(" Spectral selection = %u .. %u"),m_nSosSpectralStart_Ss,m_nSosSpectralEnd_Se);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" Successive approximation = 0x%02X"),m_nSosSuccApprox_A);
m_pLog->AddLine(strTmp);
if (m_pAppConfig->bOutputScanDump) {
m_pLog->AddLine(_T(""));
m_pLog->AddLine(_T(" Scan Data: (after bitstuff removed)"));
}
// Save the scan data segment position
nPosScanStart = m_nPos;
// Skip over the Scan Data segment
// Pass 1) Quick, allowing for bOutputScanDump to dump first 640B.
// Pass 2) If bDecodeScanImg, we redo the process but in detail decoding.
// FIXME: Not sure why, but if I skip over Pass 1 (eg if I leave in the
// following line uncommented), then I get an error at the end of the
// pass 2 decode (indicating that EOI marker not seen, and expecting
// marker).
// if (m_pAppConfig->bOutputScanDump) {
// --- PASS 1 ---
bool bSkipDone;
unsigned nSkipCount;
unsigned nSkipData;
unsigned nSkipPos;
bool bScanDumpTrunc;
bSkipDone = false;
nSkipCount = 0;
nSkipPos = 0;
bScanDumpTrunc = FALSE;
strFull = _T("");
while (!bSkipDone)
{
nSkipCount++;
nSkipPos++;
nSkipData = Buf(m_nPos++);
if (nSkipData == 0xFF) {
// this could either be a marker or a byte stuff
nSkipData = Buf(m_nPos++);
nSkipCount++;
if (nSkipData == 0x00) {
// Byte stuff
nSkipData = 0xFF;
} else if ((nSkipData >= JFIF_RST0) && (nSkipData <= JFIF_RST7)) {
// Skip over
} else {
// Marker
bSkipDone = true;
m_nPos -= 2;
}
}
if (m_pAppConfig->bOutputScanDump && (!bSkipDone) ) {
// Only display 20 lines of scan data
if (nSkipPos > 640) {
if (!bScanDumpTrunc) {
m_pLog->AddLineWarn(_T(" WARNING: Dump truncated."));
bScanDumpTrunc = TRUE;
}
} else {
if ( ((nSkipPos-1) == 0) || (((nSkipPos-1) % 32) == 0) ) {
strFull = _T(" ");
}
strTmp.Format(_T("%02x "),nSkipData);
strFull += strTmp;
if (((nSkipPos-1) % 32) == 31) {
m_pLog->AddLine(strFull);
strFull = _T("");
}
}
}
// Did we run out of bytes?
// FIXME:
// NOTE: This line here doesn't allow us to attempt to
// decode images that are missing EOI. Maybe this is
// not the best solution here? Instead, we should be
// checking m_nPos against file length? .. and not
// return but "break".
if (!m_pWBuf->GetBufOk()) {
strTmp.Format(_T("ERROR: Ran out of buffer before EOI during phase 1 of Scan decode @ 0x%08X"),m_nPos);
m_pLog->AddLineErr(strTmp);
break;
}
}
m_pLog->AddLine(strFull);
// }
// --- PASS 2 ---
// If the option is set, start parsing!
if (m_pAppConfig->bDecodeScanImg && m_bImgSofUnsupported) {
// SOF marker was of type we don't support, so skip decoding
m_pLog->AddLineWarn(_T(" NOTE: Scan parsing doesn't support this SOF mode."));
#ifndef DEBUG_YCCK
} else if (m_pAppConfig->bDecodeScanImg && (m_nSofNumComps_Nf == 4)) {
m_pLog->AddLineWarn(_T(" NOTE: Scan parsing doesn't support CMYK files yet."));
#endif
} else if (m_pAppConfig->bDecodeScanImg && !m_bImgSofUnsupported) {
if (!m_bStateSofOk) {
m_pLog->AddLineWarn(_T(" NOTE: Scan decode disabled as SOF not decoded."));
} else if (!m_bStateDqtOk) {
m_pLog->AddLineWarn(_T(" NOTE: Scan decode disabled as DQT not decoded."));
} else if (!m_bStateDhtOk) {
m_pLog->AddLineWarn(_T(" NOTE: Scan decode disabled as DHT not decoded."));
} else {
m_pLog->AddLine(_T(""));
// Set the primary image details
m_pImgDec->SetImageDetails(m_nSofSampsPerLine_X,m_nSofNumLines_Y,
m_nSofNumComps_Nf,m_nSosNumCompScan_Ns,m_nImgRstEn,m_nImgRstInterval);
// Only recalculate the scan decoding if we need to (i.e. file
// changed, offset changed, scan option changed)
// TODO: In order to decode multiple scans, we will need to alter the
// way that m_pImgSrcDirty is set
if (m_pImgSrcDirty) {
m_pImgDec->DecodeScanImg(nPosScanStart,true,false);
m_pImgSrcDirty = false;
}
}
}
m_bStateSosOk = true;
break;
case JFIF_DRI:
unsigned nVal;
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
nVal = Buf(m_nPos+2)*256 + Buf(m_nPos+3);
// According to ITU-T spec B.2.4.4, we only expect
// restart markers if DRI value is non-zero!
m_nImgRstInterval = nVal;
if (nVal != 0) {
m_nImgRstEn = true;
} else {
m_nImgRstEn = false;
}
strTmp.Format(_T(" interval = %u"),m_nImgRstInterval);
m_pLog->AddLine(strTmp);
m_nPos += 4;
if (!ExpectMarkerEnd(nPosMarkerStart,nLength))
return DECMARK_ERR;
break;
case JFIF_EOI: // EOI
m_pLog->AddLine(_T(""));
// Save the EOI file position
// NOTE: If the file is missing the EOI, then this variable will be
// set to mark the end of file.
m_nPosEmbedEnd = m_nPos;
m_nPosEoi = m_nPos;
m_bStateEoi = true;
return DECMARK_EOI;
break;
// Markers that are not yet supported in JPEGsnoop
case JFIF_DHP:
// Markers defined for future use / extensions
case JFIF_JPG:
case JFIF_JPG0:
case JFIF_JPG1:
case JFIF_JPG2:
case JFIF_JPG3:
case JFIF_JPG4:
case JFIF_JPG5:
case JFIF_JPG6:
case JFIF_JPG7:
case JFIF_JPG8:
case JFIF_JPG9:
case JFIF_JPG10:
case JFIF_JPG11:
case JFIF_JPG12:
case JFIF_JPG13:
case JFIF_TEM:
// Unsupported marker
// - Provide generic decode based on length
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Length
strTmp.Format(_T(" Header length = %u"),nLength);
m_pLog->AddLine(strTmp);
m_pLog->AddLineWarn(_T(" Skipping unsupported marker"));
m_nPos += nLength;
break;
case JFIF_RST0:
case JFIF_RST1:
case JFIF_RST2:
case JFIF_RST3:
case JFIF_RST4:
case JFIF_RST5:
case JFIF_RST6:
case JFIF_RST7:
// We don't expect to see restart markers outside the entropy coded segment.
// NOTE: RST# are standalone markers, so no length indicator exists
// But for the sake of robustness, we can check here to see if treating
// as a standalone marker will arrive at another marker (ie. OK). If not,
// proceed to assume there is a length indicator.
strTmp.Format(_T(" WARNING: Restart marker [0xFF%02X] detected outside scan"),nCode);
m_pLog->AddLineWarn(strTmp);
if (!m_pAppConfig->bRelaxedParsing) {
// Abort
m_pLog->AddLineErr(_T(" Stopping decode"));
m_pLog->AddLine(_T(" Use [Img Search Fwd/Rev] to locate other valid embedded JPEGs"));
return DECMARK_ERR;
} else {
// Ignore
// Check to see if standalone marker treatment looks OK
if (Buf(m_nPos+2) == 0xFF) {
// Looks like standalone
m_pLog->AddLineWarn(_T(" Ignoring standalone marker. Proceeding with decode."));
m_nPos += 2;
} else {
// Looks like marker with length
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
strTmp.Format(_T(" Header length = %u"),nLength);
m_pLog->AddLine(strTmp);
m_pLog->AddLineWarn(_T(" Skipping marker"));
m_nPos += nLength;
}
}
break;
default:
strTmp.Format(_T(" WARNING: Unknown marker [0xFF%02X]"),nCode);
m_pLog->AddLineWarn(strTmp);
if (!m_pAppConfig->bRelaxedParsing) {
// Abort
m_pLog->AddLineErr(_T(" Stopping decode"));
m_pLog->AddLine(_T(" Use [Img Search Fwd/Rev] to locate other valid embedded JPEGs"));
return DECMARK_ERR;
} else {
// Skip
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
strTmp.Format(_T(" Header length = %u"),nLength);
m_pLog->AddLine(strTmp);
m_pLog->AddLineWarn(_T(" Skipping marker"));
m_nPos += nLength;
}
}
// Add white-space between each marker
m_pLog->AddLine(_T(" "));
// If we decided to abort for any reason, make sure we trap it now.
// This will stop the ProcessFile() while loop. We can set m_bStateAbort
// if user says that they want to stop.
if (m_bStateAbort) {
return DECMARK_ERR;
}
return DECMARK_OK;
}
// Print out a header for the current JFIF marker code
void CjfifDecode::AddHeader(unsigned nCode)
{
CString strTmp;
switch(nCode)
{
case JFIF_SOI: m_pLog->AddLineHdr(_T("*** Marker: SOI (xFFD8) ***")); break;
case JFIF_APP0: m_pLog->AddLineHdr(_T("*** Marker: APP0 (xFFE0) ***")); break;
case JFIF_APP1: m_pLog->AddLineHdr(_T("*** Marker: APP1 (xFFE1) ***")); break;
case JFIF_APP2: m_pLog->AddLineHdr(_T("*** Marker: APP2 (xFFE2) ***")); break;
case JFIF_APP3: m_pLog->AddLineHdr(_T("*** Marker: APP3 (xFFE3) ***")); break;
case JFIF_APP4: m_pLog->AddLineHdr(_T("*** Marker: APP4 (xFFE4) ***")); break;
case JFIF_APP5: m_pLog->AddLineHdr(_T("*** Marker: APP5 (xFFE5) ***")); break;
case JFIF_APP6: m_pLog->AddLineHdr(_T("*** Marker: APP6 (xFFE6) ***")); break;
case JFIF_APP7: m_pLog->AddLineHdr(_T("*** Marker: APP7 (xFFE7) ***")); break;
case JFIF_APP8: m_pLog->AddLineHdr(_T("*** Marker: APP8 (xFFE8) ***")); break;
case JFIF_APP9: m_pLog->AddLineHdr(_T("*** Marker: APP9 (xFFE9) ***")); break;
case JFIF_APP10: m_pLog->AddLineHdr(_T("*** Marker: APP10 (xFFEA) ***")); break;
case JFIF_APP11: m_pLog->AddLineHdr(_T("*** Marker: APP11 (xFFEB) ***")); break;
case JFIF_APP12: m_pLog->AddLineHdr(_T("*** Marker: APP12 (xFFEC) ***")); break;
case JFIF_APP13: m_pLog->AddLineHdr(_T("*** Marker: APP13 (xFFED) ***")); break;
case JFIF_APP14: m_pLog->AddLineHdr(_T("*** Marker: APP14 (xFFEE) ***")); break;
case JFIF_APP15: m_pLog->AddLineHdr(_T("*** Marker: APP15 (xFFEF) ***")); break;
case JFIF_SOF0: m_pLog->AddLineHdr(_T("*** Marker: SOF0 (Baseline DCT) (xFFC0) ***")); break;
case JFIF_SOF1: m_pLog->AddLineHdr(_T("*** Marker: SOF1 (Extended Sequential DCT, Huffman) (xFFC1) ***")); break;
case JFIF_SOF2: m_pLog->AddLineHdr(_T("*** Marker: SOF2 (Progressive DCT, Huffman) (xFFC2) ***")); break;
case JFIF_SOF3: m_pLog->AddLineHdr(_T("*** Marker: SOF3 (Lossless Process, Huffman) (xFFC3) ***")); break;
case JFIF_SOF5: m_pLog->AddLineHdr(_T("*** Marker: SOF5 (Differential Sequential DCT, Huffman) (xFFC4) ***")); break;
case JFIF_SOF6: m_pLog->AddLineHdr(_T("*** Marker: SOF6 (Differential Progressive DCT, Huffman) (xFFC5) ***")); break;
case JFIF_SOF7: m_pLog->AddLineHdr(_T("*** Marker: SOF7 (Differential Lossless Process, Huffman) (xFFC6) ***")); break;
case JFIF_SOF9: m_pLog->AddLineHdr(_T("*** Marker: SOF9 (Sequential DCT, Arithmetic) (xFFC9) ***")); break;
case JFIF_SOF10: m_pLog->AddLineHdr(_T("*** Marker: SOF10 (Progressive DCT, Arithmetic) (xFFCA) ***")); break;
case JFIF_SOF11: m_pLog->AddLineHdr(_T("*** Marker: SOF11 (Lossless Process, Arithmetic) (xFFCB) ***")); break;
case JFIF_SOF13: m_pLog->AddLineHdr(_T("*** Marker: SOF13 (Differential Sequential, Arithmetic) (xFFCD) ***")); break;
case JFIF_SOF14: m_pLog->AddLineHdr(_T("*** Marker: SOF14 (Differential Progressive DCT, Arithmetic) (xFFCE) ***")); break;
case JFIF_SOF15: m_pLog->AddLineHdr(_T("*** Marker: SOF15 (Differential Lossless Process, Arithmetic) (xFFCF) ***")); break;
case JFIF_JPG: m_pLog->AddLineHdr(_T("*** Marker: JPG (xFFC8) ***")); break;
case JFIF_DAC: m_pLog->AddLineHdr(_T("*** Marker: DAC (xFFCC) ***")); break;
case JFIF_RST0:
case JFIF_RST1:
case JFIF_RST2:
case JFIF_RST3:
case JFIF_RST4:
case JFIF_RST5:
case JFIF_RST6:
case JFIF_RST7:
m_pLog->AddLineHdr(_T("*** Marker: RST# ***"));
break;
case JFIF_DQT: // Define quantization tables
m_pLog->AddLineHdr(_T("*** Marker: DQT (xFFDB) ***"));
m_pLog->AddLineHdrDesc(_T(" Define a Quantization Table."));
break;
case JFIF_COM: // COM
m_pLog->AddLineHdr(_T("*** Marker: COM (Comment) (xFFFE) ***"));
break;
case JFIF_DHT: // DHT
m_pLog->AddLineHdr(_T("*** Marker: DHT (Define Huffman Table) (xFFC4) ***"));
break;
case JFIF_DHT_FAKE: // DHT from standard table (MotionJPEG)
m_pLog->AddLineHdr(_T("*** Marker: DHT from MotionJPEG standard (Define Huffman Table) ***"));
break;
case JFIF_SOS: // SOS
m_pLog->AddLineHdr(_T("*** Marker: SOS (Start of Scan) (xFFDA) ***"));
break;
case JFIF_DRI: // DRI
m_pLog->AddLineHdr(_T("*** Marker: DRI (Restart Interval) (xFFDD) ***"));
break;
case JFIF_EOI: // EOI
m_pLog->AddLineHdr(_T("*** Marker: EOI (End of Image) (xFFD9) ***"));
break;
case JFIF_DNL: m_pLog->AddLineHdr(_T("*** Marker: DNL (Define Number of Lines) (xFFDC) ***")); break;
case JFIF_DHP: m_pLog->AddLineHdr(_T("*** Marker: DHP (Define Hierarchical Progression) (xFFDE) ***")); break;
case JFIF_EXP: m_pLog->AddLineHdr(_T("*** Marker: EXP (Expand Reference Components) (xFFDF) ***")); break;
case JFIF_JPG0: m_pLog->AddLineHdr(_T("*** Marker: JPG0 (JPEG Extension) (xFFF0) ***")); break;
case JFIF_JPG1: m_pLog->AddLineHdr(_T("*** Marker: JPG1 (JPEG Extension) (xFFF1) ***")); break;
case JFIF_JPG2: m_pLog->AddLineHdr(_T("*** Marker: JPG2 (JPEG Extension) (xFFF2) ***")); break;
case JFIF_JPG3: m_pLog->AddLineHdr(_T("*** Marker: JPG3 (JPEG Extension) (xFFF3) ***")); break;
case JFIF_JPG4: m_pLog->AddLineHdr(_T("*** Marker: JPG4 (JPEG Extension) (xFFF4) ***")); break;
case JFIF_JPG5: m_pLog->AddLineHdr(_T("*** Marker: JPG5 (JPEG Extension) (xFFF5) ***")); break;
case JFIF_JPG6: m_pLog->AddLineHdr(_T("*** Marker: JPG6 (JPEG Extension) (xFFF6) ***")); break;
case JFIF_JPG7: m_pLog->AddLineHdr(_T("*** Marker: JPG7 (JPEG Extension) (xFFF7) ***")); break;
case JFIF_JPG8: m_pLog->AddLineHdr(_T("*** Marker: JPG8 (JPEG Extension) (xFFF8) ***")); break;
case JFIF_JPG9: m_pLog->AddLineHdr(_T("*** Marker: JPG9 (JPEG Extension) (xFFF9) ***")); break;
case JFIF_JPG10: m_pLog->AddLineHdr(_T("*** Marker: JPG10 (JPEG Extension) (xFFFA) ***")); break;
case JFIF_JPG11: m_pLog->AddLineHdr(_T("*** Marker: JPG11 (JPEG Extension) (xFFFB) ***")); break;
case JFIF_JPG12: m_pLog->AddLineHdr(_T("*** Marker: JPG12 (JPEG Extension) (xFFFC) ***")); break;
case JFIF_JPG13: m_pLog->AddLineHdr(_T("*** Marker: JPG13 (JPEG Extension) (xFFFD) ***")); break;
case JFIF_TEM: m_pLog->AddLineHdr(_T("*** Marker: TEM (Temporary) (xFF01) ***")); break;
default:
strTmp.Format(_T("*** Marker: ??? (Unknown) (xFF%02X) ***"),nCode);
m_pLog->AddLineHdr(strTmp);
break;
}
// Adjust position to account for the word used in decoding the marker!
strTmp.Format(_T(" OFFSET: 0x%08X"),m_nPos-2);
m_pLog->AddLine(strTmp);
}
// Update the status bar with a message
void CjfifDecode::SetStatusText(CString strText)
{
// Make sure that we have been connected to the status
// bar of the main window first! Note that it is jpegsnoopDoc
// that sets this variable.
if (m_pStatBar) {
m_pStatBar->SetPaneText(0,strText);
}
}
// Generate a special output form of the current image's
// compression signature and other characteristics. This is only
// used during development and batch import to build the MySQL repository.
void CjfifDecode::OutputSpecial()
{
CString strTmp;
CString strFull;
ASSERT(m_eImgLandscape!=ENUM_LANDSCAPE_UNSET);
// This mode of operation is currently only used
// to import the local signature database into a MySQL database
// backend. It simply reports the MySQL commands which can be input
// into a MySQL client application.
if (m_bOutputDB)
{
m_pLog->AddLine(_T("*** DB OUTPUT START ***"));
m_pLog->AddLine(_T("INSERT INTO `quant` (`key`, `make`, `model`, "));
m_pLog->AddLine(_T("`qual`, `subsamp`, `lum_00`, `lum_01`, `lum_02`, `lum_03`, `lum_04`, "));
m_pLog->AddLine(_T("`lum_05`, `lum_06`, `lum_07`, `chr_00`, `chr_01`, `chr_02`, "));
m_pLog->AddLine(_T("`chr_03`, `chr_04`, `chr_05`, `chr_06`, `chr_07`, `qual_lum`, `qual_chr`) VALUES ("));
strFull = _T("'*KEY*', "); // key -- need to override
// Might need to change m_strImgExifMake to be lowercase
strTmp.Format(_T("'%s', "),(LPCTSTR)m_strImgExifMake);
strFull += strTmp; // make
strTmp.Format(_T("'%s', "),(LPCTSTR)m_strImgExifModel);
strFull += strTmp; // model
strTmp.Format(_T("'%s', "),(LPCTSTR)m_strImgQualExif);
strFull += strTmp; // quality
strTmp.Format(_T("'%s', "),(LPCTSTR)m_strImgQuantCss);
strFull += strTmp; // subsampling
m_pLog->AddLine(strFull);
// Step through both quantization tables (0=lum,1=chr)
unsigned nMatrixInd;
for (unsigned nDqtInd=0;nDqtInd<2;nDqtInd++) {
strFull = _T("");
for (unsigned nY=0;nY<8;nY++) {
strFull += _T("'");
for (unsigned nX=0;nX<8;nX++) {
// Rotate the matrix if necessary!
nMatrixInd = (m_eImgLandscape!=ENUM_LANDSCAPE_NO)?(nY*8+nX):(nX*8+nY);
strTmp.Format(_T("%u"),m_anImgDqtTbl[nDqtInd][nMatrixInd]);
strFull += strTmp;
if (nX!=7) { strFull += _T(","); }
}
strFull += _T("', ");
if (nY==3) {
m_pLog->AddLine(strFull);
strFull = _T("");
}
}
m_pLog->AddLine(strFull);
}
strFull = _T("");
// Output quality ratings
strTmp.Format(_T("'%f', "),m_adImgDqtQual[0]);
strFull += strTmp;
// Don't put out comma separator on last line!
strTmp.Format(_T("'%f'"),m_adImgDqtQual[1]);
strFull += strTmp;
strFull += _T(");");
m_pLog->AddLine(strFull);
m_pLog->AddLine(_T("*** DB OUTPUT END ***"));
}
}
// Generate the compression signatures (both unrotated and
// rotated) in advance of submitting to the database.
void CjfifDecode::PrepareSignature()
{
// Set m_strHash
PrepareSignatureSingle(false);
// Set m_strHashRot
PrepareSignatureSingle(true);
}
// Prepare the image signature for later submission
// NOTE: ASCII vars are used (instead of unicode) to support usage of MD5 library
void CjfifDecode::PrepareSignatureSingle(bool bRotate)
{
CStringA strTmp;
CStringA strSet;
CStringA strHashIn;
unsigned char pHashIn[2000];
CStringA strDqt;
MD5_CTX sMd5;
unsigned nLenHashIn;
unsigned nInd;
ASSERT(m_eImgLandscape!=ENUM_LANDSCAPE_UNSET);
// -----------------------------------------------------------
// Calculate the MD5 hash for online/internal database!
// signature "00" : DQT0,DQT1,CSS
// signature "01" : salt,DQT0,DQT1,..DQTx(if defined)
// Build the source string
// NOTE: For the purposes of the hash, we need to rotate the DQT tables
// if we detect that the photo is in portrait orientation! This keeps everything
// consistent.
// If no DQT tables have been defined (e.g. could have loaded text file!)
// then override the sig generation!
bool bDqtDefined = false;
for (unsigned nSet=0;nSet<4;nSet++) {
if (m_abImgDqtSet[nSet]) {
bDqtDefined = true;
}
}
if (!bDqtDefined) {
m_strHash = _T("NONE");
m_strHashRot = _T("NONE");
return;
}
// NOTE:
// The following MD5 code depends on an ASCII string for input
// We are therefore using CStringA for the hash input instead
// of the generic text functions. No special (non-ASCII)
// characters are expected in this string.
if (DB_SIG_VER == 0x00) {
strHashIn = "";
} else {
strHashIn = "JPEGsnoop";
}
// Need to duplicate DQT0 if we only have one DQT table
for (unsigned nSet=0;nSet<4;nSet++) {
if (m_abImgDqtSet[nSet]) {
strSet = "";
strSet.Format("*DQT%u,",nSet);
strHashIn += strSet;
for (unsigned i=0;i<64;i++) {
nInd = (!bRotate)?i:glb_anQuantRotate[i];
strTmp.Format("%03u,",m_anImgDqtTbl[nSet][nInd]);
strHashIn += strTmp;
}
} // if DQTx defined
} // loop through sets (DQT0..DQT3)
// Removed CSS from signature after version 0x00
if (DB_SIG_VER == 0x00) {
strHashIn += "*CSS,";
strHashIn += m_strImgQuantCss;
strHashIn += ",";
}
strHashIn += "*END";
nLenHashIn = strlen(strHashIn);
// Display hash input
for (unsigned i=0;i<nLenHashIn;i+=80) {
strTmp = "";
strTmp.Format("In%u: [",i/80);
strTmp += strHashIn.Mid(i,80);
strTmp += "]";
#ifdef DEBUG_SIG
m_pLog->AddLine(strTmp);
#endif
}
// Copy into buffer
ASSERT(nLenHashIn < 2000);
for (unsigned i=0;i<nLenHashIn;i++) {
pHashIn[i] = strHashIn.GetAt(i);
}
// Calculate the hash
MD5Init(&sMd5, 0);
MD5Update(&sMd5, pHashIn, nLenHashIn);
MD5Final(&sMd5);
// Overwrite top 8 bits for signature version number
sMd5.digest32[0] = (sMd5.digest32[0] & 0x00FFFFFF) + (DB_SIG_VER << 24);
// Convert hash to string format
// The hexadecimal string is converted to Unicode (if that is build directive)
if (!bRotate) {
m_strHash.Format(_T("%08X%08X%08X%08X"),sMd5.digest32[0],sMd5.digest32[1],sMd5.digest32[2],sMd5.digest32[3]);
} else {
m_strHashRot.Format(_T("%08X%08X%08X%08X"),sMd5.digest32[0],sMd5.digest32[1],sMd5.digest32[2],sMd5.digest32[3]);
}
}
// Generate the compression signatures for the thumbnails
void CjfifDecode::PrepareSignatureThumb()
{
// Generate m_strHashThumb
PrepareSignatureThumbSingle(false);
// Generate m_strHashThumbRot
PrepareSignatureThumbSingle(true);
}
// Prepare the image signature for later submission
// NOTE: ASCII vars are used (instead of unicode) to support usage of MD5 library
void CjfifDecode::PrepareSignatureThumbSingle(bool bRotate)
{
CStringA strTmp;
CStringA strSet;
CStringA strHashIn;
unsigned char pHashIn[2000];
CStringA strDqt;
MD5_CTX sMd5;
unsigned nLenHashIn;
unsigned nInd;
// -----------------------------------------------------------
// Calculate the MD5 hash for online/internal database!
// signature "00" : DQT0,DQT1,CSS
// signature "01" : salt,DQT0,DQT1
// Build the source string
// NOTE: For the purposes of the hash, we need to rotate the DQT tables
// if we detect that the photo is in portrait orientation! This keeps everything
// consistent.
// If no DQT tables have been defined (e.g. could have loaded text file!)
// then override the sig generation!
bool bDqtDefined = false;
for (unsigned nSet=0;nSet<4;nSet++) {
if (m_abImgDqtThumbSet[nSet]) {
bDqtDefined = true;
}
}
if (!bDqtDefined) {
m_strHashThumb = _T("NONE");
m_strHashThumbRot = _T("NONE");
return;
}
if (DB_SIG_VER == 0x00) {
strHashIn = _T("");
} else {
strHashIn = _T("JPEGsnoop");
}
//tblSelY = m_anSofQuantTblSel_Tqi[0]; // Y
//tblSelC = m_anSofQuantTblSel_Tqi[1]; // Cb (should be same as for Cr)
// Need to duplicate DQT0 if we only have one DQT table
for (unsigned nSet=0;nSet<4;nSet++) {
if (m_abImgDqtThumbSet[nSet]) {
strSet = "";
strSet.Format("*DQT%u,",nSet);
strHashIn += strSet;
for (unsigned i=0;i<64;i++) {
nInd = (!bRotate)?i:glb_anQuantRotate[i];
strTmp.Format("%03u,",m_anImgThumbDqt[nSet][nInd]);
strHashIn += strTmp;
}
} // if DQTx defined
} // loop through sets (DQT0..DQT3)
// Removed CSS from signature after version 0x00
if (DB_SIG_VER == 0x00) {
strHashIn += "*CSS,";
strHashIn += m_strImgQuantCss;
strHashIn += ",";
}
strHashIn += "*END";
nLenHashIn = strlen(strHashIn);
// Display hash input
for (unsigned i=0;i<nLenHashIn;i+=80) {
strTmp = "";
strTmp.Format("In%u: [",i/80);
strTmp += strHashIn.Mid(i,80);
strTmp += "]";
#ifdef DEBUG_SIG
m_pLog->AddLine(strTmp);
#endif
}
// Copy into buffer
ASSERT(nLenHashIn < 2000);
for (unsigned i=0;i<nLenHashIn;i++) {
pHashIn[i] = strHashIn.GetAt(i);
}
// Calculate the hash
MD5Init(&sMd5, 0);
MD5Update(&sMd5, pHashIn, nLenHashIn);
MD5Final(&sMd5);
// Overwrite top 8 bits for signature version number
sMd5.digest32[0] = (sMd5.digest32[0] & 0x00FFFFFF) + (DB_SIG_VER << 24);
// Convert hash to string format
if (!bRotate) {
m_strHashThumb.Format(_T("%08X%08X%08X%08X"),sMd5.digest32[0],sMd5.digest32[1],sMd5.digest32[2],sMd5.digest32[3]);
} else {
m_strHashThumbRot.Format(_T("%08X%08X%08X%08X"),sMd5.digest32[0],sMd5.digest32[1],sMd5.digest32[2],sMd5.digest32[3]);
}
}
// Compare the image compression signature & metadata against the database.
// This is the routine that is also responsible for creating an
// "Image Assessment" -- ie. whether the image may have been edited or not.
//
// PRE: m_strHash signature has already been calculated by PrepareSignature()
bool CjfifDecode::CompareSignature(bool bQuiet=false)
{
CString strTmp;
CString strHashOut;
CString locationStr;
unsigned ind;
bool bCurXsw = false;
bool bCurXmm = false;
bool bCurXmkr = false;
bool bCurXextrasw = false; // EXIF Extra fields match software indicator
bool bCurXcomsw = false; // EXIF COM field match software indicator
bool bCurXps = false; // EXIF photoshop IRB present
bool bSrchXsw = false;
bool bSrchXswUsig = false;
bool bSrchXmmUsig = false;
bool bSrchUsig = false;
bool bMatchIjg = false;
CString sMatchIjgQual = _T("");
ASSERT(m_strHash != _T("NONE"));
ASSERT(m_strHashRot != _T("NONE"));
if (bQuiet) { m_pLog->Disable(); }
m_pLog->AddLine(_T(""));
m_pLog->AddLineHdr(_T("*** Searching Compression Signatures ***"));
m_pLog->AddLine(_T(""));
// Output the hash
strHashOut = _T(" Signature: ");
strHashOut += m_strHash;
m_pLog->AddLine(strHashOut);
strHashOut = _T(" Signature (Rotated): ");
strHashOut += m_strHashRot;
m_pLog->AddLine(strHashOut);
strTmp.Format(_T(" File Offset: %lu bytes"),m_pAppConfig->nPosStart);
m_pLog->AddLine(strTmp);
// Output the CSS
strTmp.Format(_T(" Chroma subsampling: %s"),(LPCTSTR)m_strImgQuantCss);
m_pLog->AddLine(strTmp);
// Calculate the final fields
// Add Photoshop IRB entries
// Note that we always add an entry to the m_strImgExtras even if
// there are no photoshop tags detected. It will appear as "[PS]:[0/0]"
strTmp = _T("");
strTmp.Format(_T("[PS]:[%u/%u],"),m_nImgQualPhotoshopSa,m_nImgQualPhotoshopSfw);
m_strImgExtras += strTmp;
// --------------------------------------
// Determine current entry fields
// Note that some cameras/phones have an empty Make, but use the Model! (eg. Palm Treo)
if ((m_strImgExifMake == _T("???")) && (m_strImgExifModel == _T("???"))) {
m_pLog->AddLine(_T(" EXIF Make/Model: NONE"));
bCurXmm = false;
} else {
strTmp.Format(_T(" EXIF Make/Model: OK [%s] [%s]"),(LPCTSTR)m_strImgExifMake,(LPCTSTR)m_strImgExifModel);
m_pLog->AddLine(strTmp);
bCurXmm = true;
}
if (m_bImgExifMakernotes) {
m_pLog->AddLine(_T(" EXIF Makernotes: OK "));
bCurXmkr = true;
} else {
m_pLog->AddLine(_T(" EXIF Makernotes: NONE"));
bCurXmkr = false;
}
if (_tcslen(m_strSoftware) == 0) {
m_pLog->AddLine(_T(" EXIF Software: NONE"));
bCurXsw = false;
} else {
strTmp.Format(_T(" EXIF Software: OK [%s]"),(LPCTSTR)m_strSoftware);
m_pLog->AddLine(strTmp);
// EXIF software field is non-empty
bCurXsw = true;
}
m_pLog->AddLine(_T(""));
// --------------------------------------
// Determine search results
// All of the rest of the search results require searching
// through the database entries
bSrchXswUsig = false;
bSrchXmmUsig = false;
bSrchUsig = false;
bMatchIjg = false;
sMatchIjgQual = _T("");
unsigned nSigsInternal = theApp.m_pDbSigs->GetNumSigsInternal();
unsigned nSigsExtra = theApp.m_pDbSigs->GetNumSigsExtra();
strTmp.Format(_T(" Searching Compression Signatures: (%u built-in, %u user(*) )"),nSigsInternal,nSigsExtra);
m_pLog->AddLine(strTmp);
// Now in SIG version 0x01 and later, we are not including
// the CSS in the signature. Therefore, we need to compare it
// manually.
bool curMatchMm;
bool curMatchSw;
bool curMatchSig;
bool curMatchSigCss;
// Check on Extras field
// Noted that Canon EOS Viewer Utility (EVU) seems to convert RAWs with
// the only identifying information being this:
// e.g. "[Canon.ImageType]:[CRW:EOS 300D DIGITAL CMOS RAW],_T("
if (m_strImgExtras.Find(_T(")[Canon.ImageType]:[CRW:")) != -1) {
bCurXextrasw = true;
}
if (m_strImgExtras.Find(_T("[Nikon1.Quality]:[RAW")) != -1) {
bCurXextrasw = true;
}
if (m_strImgExtras.Find(_T("[Nikon2.Quality]:[RAW")) != -1) {
bCurXextrasw = true;
}
if (m_strImgExtras.Find(_T("[Nikon3.Quality]:[RAW")) != -1) {
bCurXextrasw = true;
}
if ((m_nImgQualPhotoshopSa != 0) || (m_nImgQualPhotoshopSfw != 0)) {
bCurXps = true;
}
// Search for known COMment field indicators
if (theApp.m_pDbSigs->SearchCom(m_strComment)) {
bCurXcomsw = true;
}
m_pLog->AddLine(_T(""));
m_pLog->AddLine(_T(" EXIF.Make / Software EXIF.Model Quality Subsamp Match?"));
m_pLog->AddLine(_T(" ------------------------- ----------------------------------- ---------------- --------------"));
CompSig pEntry;
unsigned ind_max = theApp.m_pDbSigs->GetDBNumEntries();
for (ind=0;ind<ind_max;ind++) {
theApp.m_pDbSigs->GetDBEntry(ind,&pEntry);
// Reset current entry state
curMatchMm = false;
curMatchSw = false;
curMatchSig = false;
curMatchSigCss = false;
// Compare make/model (only for digicams)
if ((pEntry.eEditor == ENUM_EDITOR_CAM) &&
(bCurXmm == true) &&
(pEntry.strXMake == m_strImgExifMake) &&
(pEntry.strXModel == m_strImgExifModel) )
{
curMatchMm = true;
}
// For software entries, do a loose search
if ((pEntry.eEditor == ENUM_EDITOR_SW) &&
(bCurXsw == true) &&
(pEntry.strMSwTrim != _T("")) &&
(m_strSoftware.Find(pEntry.strMSwTrim) != -1) )
{
// Software field matches known software string
bSrchXsw = true;
curMatchSw = true;
}
// Compare signature (and CSS for digicams)
if ( (pEntry.strCSig == m_strHash) || (pEntry.strCSigRot == m_strHash) ||
(pEntry.strCSig == m_strHashRot) || (pEntry.strCSigRot == m_strHashRot) )
{
curMatchSig = true;
// If Database entry is for an editor, sig matches irrespective of CSS
if (pEntry.eEditor == ENUM_EDITOR_SW) {
bSrchUsig = true;
curMatchSigCss = true; // FIXME: do I need this?
// For special case of IJG
if (pEntry.strMSwDisp == _T("IJG Library")) {
bMatchIjg = true;
sMatchIjgQual = pEntry.strUmQual;
}
} else {
// Database entry is for a digicam, sig match only if CSS matches too
if (pEntry.strXSubsamp == m_strImgQuantCss) {
bSrchUsig = true;
curMatchSigCss = true;
} else {
curMatchSigCss = false;
}
} // editor
} else {
// sig doesn't match
curMatchSig = false;
curMatchSigCss = false;
}
// For digicams:
if (curMatchMm && curMatchSigCss) {
bSrchXmmUsig = true;
}
// For software:
if (curMatchSw && curMatchSig) {
bSrchXswUsig = true;
}
if (theApp.m_pDbSigs->IsDBEntryUser(ind)) {
locationStr = _T("*");
} else {
locationStr = _T(" ");
}
// Display entry if it is a good match
if (curMatchSig) {
if (pEntry.eEditor==ENUM_EDITOR_CAM) {
strTmp.Format(_T(" %s%4s[%-25s] [%-35s] [%-16s] %-5s %-5s %-5s"),(LPCTSTR)locationStr,_T("CAM:"),
(LPCTSTR)pEntry.strXMake.Left(25),(LPCTSTR)pEntry.strXModel.Left(35),(LPCTSTR)pEntry.strUmQual.Left(16),
(curMatchSigCss?_T("Yes"):_T("No")),_T(""),_T(""));
} else if (pEntry.eEditor==ENUM_EDITOR_SW) {
strTmp.Format(_T(" %s%4s[%-25s] %-35s [%-16s] %-5s %-5s %-5s"),(LPCTSTR)locationStr,_T("SW :"),
(LPCTSTR)pEntry.strMSwDisp.Left(25),_T(""),(LPCTSTR)pEntry.strUmQual.Left(16),
_T(""),_T(""),_T(""));
} else {
strTmp.Format(_T(" %s%4s[%-25s] [%-35s] [%-16s] %-5s %-5s %-5s"),(LPCTSTR)locationStr,_T("?? :"),
(LPCTSTR)pEntry.strXMake.Left(25),(LPCTSTR)pEntry.strXModel.Left(35),(LPCTSTR)pEntry.strUmQual.Left(16),
_T(""),_T(""),_T(""));
}
if (curMatchMm || curMatchSw) {
m_pLog->AddLineGood(strTmp);
} else {
m_pLog->AddLine(strTmp);
}
}
} // loop through DB
CString strSw;
// If it matches an IJG signature, report other possible sources:
if (bMatchIjg) {
m_pLog->AddLine(_T(""));
m_pLog->AddLine(_T(" The following IJG-based editors also match this signature:"));
unsigned nIjgNum;
CString strIjgSw;
nIjgNum = theApp.m_pDbSigs->GetIjgNum();
for (ind=0;ind<nIjgNum;ind++)
{
strIjgSw = theApp.m_pDbSigs->GetIjgEntry(ind);
strTmp.Format(_T(" %4s[%-25s] %-35s [%-16s] %-5s %-5s %-5s"),_T("SW :"),
(LPCTSTR)strIjgSw.Left(25),_T(""),(LPCTSTR)sMatchIjgQual.Left(16),
_T(""),_T(""),_T(""));
m_pLog->AddLine(strTmp);
}
}
//m_pLog->AddLine(_T(" -------------------- ----------------------------------- ---------------- --------------"));
m_pLog->AddLine(_T(""));
if (bCurXps) {
m_pLog->AddLine(_T(" NOTE: Photoshop IRB detected"));
}
if (bCurXextrasw) {
m_pLog->AddLine(_T(" NOTE: Additional EXIF fields indicate software processing"));
}
if (bSrchXsw) {
m_pLog->AddLine(_T(" NOTE: EXIF Software field recognized as from editor"));
}
if (bCurXcomsw) {
m_pLog->AddLine(_T(" NOTE: JFIF COMMENT field is known software"));
}
// ============================================
// Image Assessment Algorithm
// ============================================
bool bEditDefinite = false;
bool bEditLikely = false;
bool bEditNot = false;
bool bEditNotUnknownSw = false;
if (bCurXps) {
bEditDefinite = true;
}
if (!bCurXmm) {
bEditDefinite = true;
}
if (bCurXextrasw) {
bEditDefinite = true;
}
if (bCurXcomsw) {
bEditDefinite = true;
}
if (bSrchXsw) {
// Software field matches known software string
bEditDefinite = true;
}
if (theApp.m_pDbSigs->LookupExcMmIsEdit(m_strImgExifMake,m_strImgExifModel)) {
// Make/Model is in exception list of ones that mark known software
bEditDefinite = true;
}
if (!bCurXmkr) {
// If we are missing maker notes, we are almost always dealing with
// edited images. There are some known exceptions, so far:
// - Very old digicams
// - Certain camera phones
// - Blackberry
// Perhaps we can make an exception for particular digicams (based on
// make/model) that this determination will not apply. This means that
// we open up the doors for these files being edited and not caught.
if (theApp.m_pDbSigs->LookupExcMmNoMkr(m_strImgExifMake,m_strImgExifModel)) {
// This is a known exception!
} else {
bEditLikely = true;
}
}
// Filter down remaining scenarios
if (!bEditDefinite && !bEditLikely) {
if (bSrchXmmUsig) {
// DB cam signature matches DQT & make/model
if (!bCurXsw) {
// EXIF software field is empty
//
// We can now be pretty confident that this file has not
// been edited by all the means that we are checking
bEditNot = true;
} else {
// EXIF software field is set
//
// This field is often used by:
// - Software editors (edited)
// - RAW converter software (edited)
// - Digicams to indicate firmware (original)
// - Phones to indicate firmware (original)
//
// However, in generating bEditDefinite, we have already
// checked for bSrchXsw which looked for known software
// strings. Therefore, we will primarily be left with
// firmware strings, etc.
//
// We will mark this as NOT EDITED but with caution of unknown SW field
bEditNot = true;
bEditNotUnknownSw = true;
}
} else {
// No DB cam signature matches DQT & make/model
// According to EXIF data, this file does not appear to be edited,
// but no compression signatures in the database match this
// particular make/model. Therefore, result is UNSURE.
}
}
// Now make final assessment call
// Determine if image has been processed/edited
m_eImgEdited = EDITED_UNSET;
if (bEditDefinite) {
m_eImgEdited = EDITED_YES;
} else if (bEditLikely) {
m_eImgEdited = EDITED_YESPROB;
} else if (bEditNot) {
// Images that fall into this category will have:
// - No Photoshop tags
// - Make/Model is present
// - Makernotes present
// - No extra software tags (eg. IFD)
// - No comment field with known software
// - No software field or it does not match known software
// - Signature matches DB for this make/model
m_eImgEdited = EDITED_NO;
} else {
// Images that fall into this category will have:
// - Same as EDITED_NO but:
// - Signature does not match DB for this make/model
// In all likelihood, this image will in fact be original
m_eImgEdited = EDITED_UNSURE;
}
// If the file offset is non-zero, then don't ask for submit or show assessment
if (m_pAppConfig->nPosStart != 0) {
m_pLog->AddLine(_T(" ASSESSMENT not done as file offset non-zero"));
if (bQuiet) { m_pLog->Enable(); }
return false;
}
// ============================================
// Display final assessment
// ============================================
m_pLog->AddLine(_T(" Based on the analysis of compression characteristics and EXIF metadata:"));
m_pLog->AddLine(_T(""));
if (m_eImgEdited == EDITED_YES) {
m_pLog->AddLine(_T(" ASSESSMENT: Class 1 - Image is processed/edited"));
} else if (m_eImgEdited == EDITED_YESPROB) {
m_pLog->AddLine(_T(" ASSESSMENT: Class 2 - Image has high probability of being processed/edited"));
} else if (m_eImgEdited == EDITED_NO) {
m_pLog->AddLine(_T(" ASSESSMENT: Class 3 - Image has high probability of being original"));
// In case the EXIF Software field was detected,
if (bEditNotUnknownSw) {
m_pLog->AddLine(_T(" Note that EXIF Software field is set (typically contains Firmware version)"));
}
} else if (m_eImgEdited == EDITED_UNSURE) {
m_pLog->AddLine(_T(" ASSESSMENT: Class 4 - Uncertain if processed or original"));
m_pLog->AddLine(_T(" While the EXIF fields indicate original, no compression signatures "));
m_pLog->AddLine(_T(" in the current database were found matching this make/model"));
} else {
m_pLog->AddLineErr(_T(" ASSESSMENT: *** Failed to complete ***"));
}
m_pLog->AddLine(_T(""));
// Determine if user should add entry to DB
bool bDbReqAdd = false; // Ask user to add
bool bDbReqAddAuto = false; // Automatically add (in batch operation)
// TODO: This section should be rewritten to reduce complexity
m_eDbReqSuggest = DB_ADD_SUGGEST_UNSET;
if (m_eImgEdited == EDITED_NO) {
bDbReqAdd = false;
m_eDbReqSuggest = DB_ADD_SUGGEST_CAM;
} else if (m_eImgEdited == EDITED_UNSURE) {
bDbReqAdd = true;
bDbReqAddAuto = true;
m_eDbReqSuggest = DB_ADD_SUGGEST_CAM;
m_pLog->AddLine(_T(" Appears to be new signature for known camera."));
m_pLog->AddLine(_T(" If the camera/software doesn't appear in list above,"));
m_pLog->AddLineWarn(_T(" PLEASE ADD TO DATABASE with [Tools->Add Camera to DB]"));
} else if (bCurXps && bSrchUsig) {
// Photoshop and we already have sig
bDbReqAdd = false;
m_eDbReqSuggest = DB_ADD_SUGGEST_SW;
} else if (bCurXps && !bSrchUsig) {
// Photoshop and we don't already have sig
bDbReqAdd = true;
bDbReqAddAuto = true;
m_eDbReqSuggest = DB_ADD_SUGGEST_SW;
m_pLog->AddLine(_T(" Appears to be new signature for Photoshop."));
m_pLog->AddLine(_T(" If it doesn't appear in list above,"));
m_pLog->AddLineWarn(_T(" PLEASE ADD TO DATABASE with [Tools->Add Camera to DB]"));
} else if (bCurXsw && bSrchXsw && bSrchXswUsig) {
bDbReqAdd = false;
m_eDbReqSuggest = DB_ADD_SUGGEST_SW;
} else if (bCurXextrasw) {
bDbReqAdd = false;
m_eDbReqSuggest = DB_ADD_SUGGEST_SW;
} else if (bCurXsw && bSrchXsw && !bSrchXswUsig) {
bDbReqAdd = true;
//bDbReqAddAuto = true;
m_eDbReqSuggest = DB_ADD_SUGGEST_SW;
m_pLog->AddLine(_T(" Appears to be new signature for known software."));
m_pLog->AddLine(_T(" If the camera/software doesn't appear in list above,"));
m_pLog->AddLineWarn(_T(" PLEASE ADD TO DATABASE with [Tools->Add Camera to DB]"));
} else if (bCurXmm && bCurXmkr && !bSrchXsw && !bSrchXmmUsig) {
// unsure if cam, so ask user
bDbReqAdd = true;
bDbReqAddAuto = true;
m_eDbReqSuggest = DB_ADD_SUGGEST_CAM;
m_pLog->AddLine(_T(" This may be a new camera for the database."));
m_pLog->AddLine(_T(" If this file is original, and camera doesn't appear in list above,"));
m_pLog->AddLineWarn(_T(" PLEASE ADD TO DATABASE with [Tools->Add Camera to DB]"));
} else if (!bCurXmm && !bCurXmkr && !bSrchXsw) {
// unsure if SW, so ask user
bDbReqAdd = true;
m_eDbReqSuggest = DB_ADD_SUGGEST_SW;
m_pLog->AddLine(_T(" This may be a new software editor for the database."));
m_pLog->AddLine(_T(" If this file is processed, and editor doesn't appear in list above,"));
m_pLog->AddLineWarn(_T(" PLEASE ADD TO DATABASE with [Tools->Add Camera to DB]"));
}
m_pLog->AddLine(_T(""));
// -----------------------------------------------------------
if (bQuiet) { m_pLog->Enable(); }
#ifdef BATCH_DO_DBSUBMIT_ALL
bDbReqAddAuto = true;
#endif
// Return a value that indicates whether or not we should add this
// entry to the database
return bDbReqAddAuto;
}
// Build the image data string that will be sent to the database repository
// This data string contains the compression siganture and a few special
// fields such as image dimensions, etc.
//
// If Portrait, Rotates DQT table, Width/Height.
// m_strImgQuantCss is already rotated by ProcessFile()
// PRE: m_strHash already defined
void CjfifDecode::PrepareSendSubmit(CString strQual,teSource eUserSource,CString strUserSoftware,CString strUserNotes)
{
// Generate the DQT arrays suitable for posting
CString strTmp1;
CString asDqt[4];
unsigned nMatrixInd;
ASSERT(m_strHash != _T("NONE"));
ASSERT(m_eImgLandscape!=ENUM_LANDSCAPE_UNSET);
for (unsigned nSet=0;nSet<4;nSet++) {
asDqt[nSet] = _T("");
if (m_abImgDqtSet[nSet]) {
for (unsigned nInd=0;nInd<64;nInd++) {
// FIXME: Still consider rotating DQT table even though we
// don't know for sure if m_eImgLandscape is accurate
// Not a big deal if we get it wrong as we still add
// both pre- and post-rotated sigs.
nMatrixInd = (m_eImgLandscape!=ENUM_LANDSCAPE_NO)?nInd:glb_anQuantRotate[nInd];
if ((nInd%8 == 0) && (nInd != 0)) {
asDqt[nSet].Append(_T("!"));
}
asDqt[nSet].AppendFormat(_T("%u"),m_anImgDqtTbl[nSet][nMatrixInd]);
if (nInd%8 != 7) {
asDqt[nSet].Append(_T(","));
}
}
} // set defined?
} // up to 4 sets
unsigned nOrigW,nOrigH;
nOrigW = (m_eImgLandscape!=ENUM_LANDSCAPE_NO)?m_nSofSampsPerLine_X:m_nSofNumLines_Y;
nOrigH = (m_eImgLandscape!=ENUM_LANDSCAPE_NO)?m_nSofNumLines_Y:m_nSofSampsPerLine_X;
unsigned nOrigThumbW,nOrigThumbH;
nOrigThumbW = (m_eImgLandscape!=ENUM_LANDSCAPE_NO)?m_nImgThumbSampsPerLine:m_nImgThumbNumLines;
nOrigThumbH = (m_eImgLandscape!=ENUM_LANDSCAPE_NO)?m_nImgThumbNumLines:m_nImgThumbSampsPerLine;
teMaker eMaker;
eMaker = (m_bImgExifMakernotes)?ENUM_MAKER_PRESENT:ENUM_MAKER_NONE;
// Sort sig additions
// To create some determinism in the database, arrange the sigs
// to be in numerical order
CString strSig0,strSig1,strSigThm0,strSigThm1;
if (m_strHash <= m_strHashRot) {
strSig0 = m_strHash;
strSig1 = m_strHashRot;
} else {
strSig0 = m_strHashRot;
strSig1 = m_strHash;
}
if (m_strHashThumb <= m_strHashThumbRot) {
strSigThm0 = m_strHashThumb;
strSigThm1 = m_strHashThumbRot;
} else {
strSigThm0 = m_strHashThumbRot;
strSigThm1 = m_strHashThumb;
}
SendSubmit(m_strImgExifMake,m_strImgExifModel,strQual,asDqt[0],asDqt[1],asDqt[2],asDqt[3],m_strImgQuantCss,
strSig0,strSig1,strSigThm0,strSigThm1,(float)m_adImgDqtQual[0],(float)m_adImgDqtQual[1],nOrigW,nOrigH,
m_strSoftware,m_strComment,eMaker,eUserSource,strUserSoftware,m_strImgExtras,
strUserNotes,m_eImgLandscape,nOrigThumbW,nOrigThumbH);
}
// Send the compression signature string to the local database file
// in addition to the web repository if the user has enabled it.
void CjfifDecode::SendSubmit(CString strExifMake, CString strExifModel, CString strQual,
CString strDqt0, CString strDqt1, CString strDqt2, CString strDqt3,
CString strCss,
CString strSig, CString strSigRot, CString strSigThumb,
CString strSigThumbRot, float fQFact0, float fQFact1, unsigned nImgW, unsigned nImgH,
CString strExifSoftware, CString strComment, teMaker eMaker,
teSource eUserSource, CString strUserSoftware, CString strExtra,
CString strUserNotes, unsigned nExifLandscape,
unsigned nThumbX,unsigned nThumbY)
{
// NOTE: This assumes that we've already run PrepareSignature()
// which usually happens when we process a file.
ASSERT(strSig != _T(""));
ASSERT(strSigRot != _T(""));
CUrlString curls;
CString DB_SUBMIT_WWW_VER = _T("02");
#ifndef BATCH_DO
if (m_bSigExactInDB) {
if (m_pAppConfig->bInteractive)
AfxMessageBox(_T("Compression signature already in database"));
} else {
// Now append it to the local database and resave
theApp.m_pDbSigs->DatabaseExtraAdd(strExifMake,strExifModel,
strQual,strSig,strSigRot,strCss,eUserSource,strUserSoftware);
if (m_pAppConfig->bInteractive)
AfxMessageBox(_T("Added Compression signature to database"));
}
#endif
// Is automatic internet update enabled?
if (!theApp.m_pAppConfig->bDbSubmitNet) {
return;
}
CString strTmp;
CString strFormat;
CString strFormDataPre;
CString strFormData;
unsigned nFormDataLen;
unsigned nChecksum=32;
CString strSubmitHost;
CString strSubmitPage;
strSubmitHost = IA_HOST;
strSubmitPage = IA_DB_SUBMIT_PAGE;
for (unsigned i=0;i<_tcslen(IA_HOST);i++) {
nChecksum += strSubmitHost.GetAt(i);
nChecksum += 3*strSubmitPage.GetAt(i);
}
//if ( (m_pAppConfig->bIsWindowsNTorLater) && (nChecksum == 9678) ) {
if (nChecksum == 9678) {
// Submit to online database
CString strHeaders =
_T("Content-Type: application/x-www-form-urlencoded");
// URL-encoded form variables -
strFormat = _T("ver=%s&x_make=%s&x_model=%s&strUmQual=%s&x_dqt0=%s&x_dqt1=%s&x_dqt2=%s&x_dqt3=%s");
strFormat += _T("&strXSubsamp=%s&strCSig=%s&strCSigRot=%s&c_qfact0=%f&c_qfact1=%f&x_img_w=%u&x_img_h=%u");
strFormat += _T("&x_sw=%s&x_com=%s&x_maker=%u&u_source=%d&u_sw=%s");
strFormat += _T("&x_extra=%s&u_notes=%s&c_sigthumb=%s&c_sigthumbrot=%s&x_landscape=%u");
strFormat += _T("&x_thumbx=%u&x_thumby=%u");
strFormDataPre.Format(strFormat,
DB_SUBMIT_WWW_VER,strExifMake,strExifModel,
strQual,strDqt0,strDqt1,strDqt2,strDqt3,strCss,strSig,strSigRot,fQFact0,fQFact1,nImgW,nImgH,
strExifSoftware,strComment,
eMaker,eUserSource,strUserSoftware,
strExtra,strUserNotes,
strSigThumb,strSigThumbRot,nExifLandscape,nThumbX,nThumbY);
//*** Need to sanitize data for URL submission!
// Search for "&", "?", "="
strFormData.Format(strFormat,
DB_SUBMIT_WWW_VER,curls.Encode(strExifMake),curls.Encode(strExifModel),
strQual,strDqt0,strDqt1,strDqt2,strDqt3,strCss,strSig,strSigRot,fQFact0,fQFact1,nImgW,nImgH,
curls.Encode(strExifSoftware),curls.Encode(strComment),
eMaker,eUserSource,curls.Encode(strUserSoftware),
curls.Encode(strExtra),curls.Encode(strUserNotes),
strSigThumb,strSigThumbRot,nExifLandscape,nThumbX,nThumbY);
nFormDataLen = strFormData.GetLength();
#ifdef DEBUG_SIG
if (m_pAppConfig->bInteractive) {
AfxMessageBox(strFormDataPre);
AfxMessageBox(strFormData);
}
#endif
#ifdef WWW_WININET
//static LPSTR astrAcceptTypes[2]={"*/*", NULL};
HINTERNET hINet, hConnection, hData;
hINet = InternetOpen(_T("JPEGsnoop/1.0"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );
if ( !hINet )
{
if (m_pAppConfig->bInteractive)
AfxMessageBox(_T("InternetOpen Failed"));
return;
}
try
{
hConnection = InternetConnect( hINet, (LPCTSTR)strSubmitHost, 80, NULL,NULL, INTERNET_SERVICE_HTTP, 0, 1 );
if ( !hConnection )
{
InternetCloseHandle(hINet);
return;
}
hData = HttpOpenRequest( hConnection, _T("POST"), (LPCTSTR)strSubmitPage, NULL, NULL, NULL, 0, 1 );
if ( !hData )
{
InternetCloseHandle(hConnection);
InternetCloseHandle(hINet);
return;
}
// GET HttpSendRequest( hData, NULL, 0, NULL, 0);
HttpSendRequest( hData, (LPCTSTR)strHeaders, strHeaders.GetLength(), strFormData.GetBuffer(), strFormData.GetLength());
}
catch( CInternetException* e)
{
e->ReportError();
e->Delete();
//AfxMessageBox(_T("EXCEPTION!"));
}
InternetCloseHandle(hConnection);
InternetCloseHandle(hINet);
InternetCloseHandle(hData);
#endif
#ifdef WWW_WINHTTP
CInternetSession sSession;
CHttpConnection* pConnection;
CHttpFile* pFile;
BOOL bResult;
DWORD dwRet;
// *** NOTE: Will not work on Windows 95/98!
// This section is avoided in early OSes otherwise we get an Illegal Op
try {
pConnection = sSession.GetHttpConnection(submit_host);
ASSERT (pConnection);
pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST,_T(submit_page));
ASSERT (pFile);
bResult = pFile->SendRequest(
strHeaders,(LPVOID)(LPCTSTR)strFormData, strFormData.GetLength());
ASSERT (bResult != 0);
pFile->QueryInfoStatusCode(dwRet);
ASSERT (dwRet == HTTP_STATUS_OK);
// Clean up!
if (pFile) {
pFile->Close();
delete pFile;
pFile = NULL;
}
if (pConnection) {
pConnection->Close();
delete pConnection;
pConnection = NULL;
}
sSession.Close();
}
catch (CInternetException* pEx)
{
// catch any exceptions from WinINet
TCHAR szErr[MAX_BUF_EX_ERR_MSG];
szErr[0] = '\0';
if(!pEx->GetErrorMessage(szErr, MAX_BUF_EX_ERR_MSG))
_tcscpy(szErr,_T("Unknown error"));
TRACE("Submit Failed! - %s",szErr);
if (m_pAppConfig->bInteractive)
AfxMessageBox(szErr);
pEx->Delete();
if(pFile)
delete pFile;
if(pConnection)
delete pConnection;
session.Close();
return;
}
#endif
}
}
// Parse the embedded JPEG thumbnail. This routine is a much-reduced
// version of the main JFIF parser, in that it focuses primarily on the
// DQT tables.
void CjfifDecode::DecodeEmbeddedThumb()
{
CString strTmp;
CString strMarker;
unsigned nPosSaved;
unsigned nPosSaved_sof;
unsigned nPosEnd;
bool bDone;
unsigned nCode;
bool bRet;
CString strFull;
unsigned nDqtPrecision_Pq;
unsigned nDqtQuantDestId_Tq;
unsigned nImgPrecision;
unsigned nLength;
unsigned nTmpVal;
bool bScanSkipDone;
bool bErrorAny = false;
bool bErrorThumbLenZero = false;
unsigned nSkipCount;
nPosSaved = m_nPos;
// Examine the EXIF embedded thumbnail (if it exists)
if (m_nImgExifThumbComp == 6) {
m_pLog->AddLine(_T(""));
m_pLog->AddLineHdr(_T("*** Embedded JPEG Thumbnail ***"));
strTmp.Format(_T(" Offset: 0x%08X"),m_nImgExifThumbOffset);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" Length: 0x%08X (%u)"),m_nImgExifThumbLen,m_nImgExifThumbLen);
m_pLog->AddLine(strTmp);
// Quick scan for DQT tables
m_nPos = m_nImgExifThumbOffset;
bDone = false;
while (!bDone) {
// For some reason, I have found files that have a nLength of 0
if (m_nImgExifThumbLen != 0) {
if ((m_nPos-m_nImgExifThumbOffset) > m_nImgExifThumbLen) {
strTmp.Format(_T("ERROR: Read more than specified EXIF thumb nLength (%u bytes) before EOI"),m_nImgExifThumbLen);
m_pLog->AddLineErr(strTmp);
bErrorAny = true;
bDone = true;
}
} else {
// Don't try to process if nLength is 0!
// Seen this in a Canon 1ds file (processed by photoshop)
bDone = true;
bErrorAny = true;
bErrorThumbLenZero = true;
}
if ((!bDone) && (Buf(m_nPos++) != 0xFF)) {
strTmp.Format(_T("ERROR: Expected marker 0xFF, got 0x%02X @ offset 0x%08X"),Buf(m_nPos-1),(m_nPos-1));
m_pLog->AddLineErr(strTmp);
bErrorAny = true;
bDone = true;
}
if (!bDone) {
nCode = Buf(m_nPos++);
m_pLog->AddLine(_T(""));
switch (nCode) {
case JFIF_SOI: // SOI
m_pLog->AddLine(_T(" * Embedded Thumb Marker: SOI"));
break;
case JFIF_DQT: // Define quantization tables
m_pLog->AddLine(_T(" * Embedded Thumb Marker: DQT"));
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
nPosEnd = m_nPos+nLength;
m_nPos+=2;
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
while (nPosEnd > m_nPos)
{
strTmp.Format(_T(" ----"));
m_pLog->AddLine(strTmp);
nTmpVal = Buf(m_nPos++);
nDqtPrecision_Pq = (nTmpVal & 0xF0) >> 4;
nDqtQuantDestId_Tq = nTmpVal & 0x0F;
CString strPrecision = _T("");
if (nDqtPrecision_Pq == 0) {
strPrecision = _T("8 bits");
} else if (nDqtPrecision_Pq == 1) {
strPrecision = _T("16 bits");
} else {
strPrecision.Format(_T("??? unknown [value=%u]"),nDqtPrecision_Pq);
}
strTmp.Format(_T(" Precision=%s"),(LPCTSTR)strPrecision);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" Destination ID=%u"),nDqtQuantDestId_Tq);
// NOTE: The mapping between destination IDs and the actual
// usage is defined in the SOF marker which is often later.
// In nearly all images, the following is true. However, I have
// seen some test images that set Tbl 3 = Lum, Tbl 0=Chr,
// Tbl1=Chr, and Tbl2 undefined
if (nDqtQuantDestId_Tq == 0) {
strTmp += _T(" (Luminance, typically)");
}
else if (nDqtQuantDestId_Tq == 1) {
strTmp += _T(" (Chrominance, typically)");
}
else if (nDqtQuantDestId_Tq == 2) {
strTmp += _T(" (Chrominance, typically)");
}
else {
strTmp += _T(" (???)");
}
m_pLog->AddLine(strTmp);
if (nDqtQuantDestId_Tq >= 4) {
strTmp.Format(_T("ERROR: nDqtQuantDestId_Tq = %u, >= 4"),nDqtQuantDestId_Tq);
m_pLog->AddLineErr(strTmp);
bDone = true;
bErrorAny = true;
break;
}
for (unsigned nInd=0;nInd<=63;nInd++)
{
nTmpVal = Buf(m_nPos++);
m_anImgThumbDqt[nDqtQuantDestId_Tq][glb_anZigZag[nInd]] = nTmpVal;
}
m_abImgDqtThumbSet[nDqtQuantDestId_Tq] = true;
// Now display the table
for (unsigned nY=0;nY<8;nY++) {
strFull.Format(_T(" DQT, Row #%u: "),nY);
for (unsigned nX=0;nX<8;nX++) {
strTmp.Format(_T("%3u "),m_anImgThumbDqt[nDqtQuantDestId_Tq][nY*8+nX]);
strFull += strTmp;
// Store the DQT entry into the Image DenCoder
bRet = m_pImgDec->SetDqtEntry(nDqtQuantDestId_Tq,nY*8+nX,
glb_anUnZigZag[nY*8+nX],m_anImgDqtTbl[nDqtQuantDestId_Tq][nY*8+nX]);
DecodeErrCheck(bRet);
}
m_pLog->AddLine(strFull);
}
}
break;
case JFIF_SOF0:
m_pLog->AddLine(_T(" * Embedded Thumb Marker: SOF"));
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
nPosSaved_sof = m_nPos;
m_nPos+=2;
strTmp.Format(_T(" Frame header length = %u"),nLength);
m_pLog->AddLine(strTmp);
nImgPrecision = Buf(m_nPos++);
strTmp.Format(_T(" Precision = %u"),nImgPrecision);
m_pLog->AddLine(strTmp);
m_nImgThumbNumLines = Buf(m_nPos)*256 + Buf(m_nPos+1);
m_nPos += 2;
strTmp.Format(_T(" Number of Lines = %u"),m_nImgThumbNumLines);
m_pLog->AddLine(strTmp);
m_nImgThumbSampsPerLine = Buf(m_nPos)*256 + Buf(m_nPos+1);
m_nPos += 2;
strTmp.Format(_T(" Samples per Line = %u"),m_nImgThumbSampsPerLine);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" Image Size = %u x %u"),m_nImgThumbSampsPerLine,m_nImgThumbNumLines);
m_pLog->AddLine(strTmp);
m_nPos = nPosSaved_sof+nLength;
break;
case JFIF_SOS: // SOS
m_pLog->AddLine(_T(" * Embedded Thumb Marker: SOS"));
m_pLog->AddLine(_T(" Skipping scan data"));
bScanSkipDone = false;
nSkipCount = 0;
while (!bScanSkipDone) {
if ((Buf(m_nPos) == 0xFF) && (Buf(m_nPos+1) != 0x00)) {
// Was it a restart marker?
if ((Buf(m_nPos+1) >= JFIF_RST0) && (Buf(m_nPos+1) <= JFIF_RST7)) {
m_nPos++;
} else {
// No... it's a real marker
bScanSkipDone = true;
}
} else {
m_nPos++;
nSkipCount++;
}
}
strTmp.Format(_T(" Skipped %u bytes"),nSkipCount);
m_pLog->AddLine(strTmp);
break;
case JFIF_EOI:
m_pLog->AddLine(_T(" * Embedded Thumb Marker: EOI"));
bDone = true;
break;
case JFIF_RST0:
case JFIF_RST1:
case JFIF_RST2:
case JFIF_RST3:
case JFIF_RST4:
case JFIF_RST5:
case JFIF_RST6:
case JFIF_RST7:
break;
default:
GetMarkerName(nCode,strMarker);
strTmp.Format(_T(" * Embedded Thumb Marker: %s"),(LPCTSTR)strMarker);
m_pLog->AddLine(strTmp);
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
m_nPos += nLength;
break;
}
} // if !bDone
} // while !bDone
// Now calculate the signature
if (!bErrorAny) {
PrepareSignatureThumb();
m_pLog->AddLine(_T(""));
strTmp.Format(_T(" * Embedded Thumb Signature: %s"),(LPCTSTR)m_strHashThumb);
m_pLog->AddLine(strTmp);
}
if (bErrorThumbLenZero) {
m_strHashThumb = _T("ERR: Len=0");
m_strHashThumbRot = _T("ERR: Len=0");
}
} // if JPEG compressed
m_nPos = nPosSaved;
}
// Lookup the EXIF marker name from the code value
bool CjfifDecode::GetMarkerName(unsigned nCode,CString &markerStr)
{
bool bDone = false;
bool bFound = false;
unsigned nInd=0;
while (!bDone)
{
if (m_pMarkerNames[nInd].nCode==0) {
bDone = true;
} else if (m_pMarkerNames[nInd].nCode==nCode) {
bDone = true;
bFound = true;
markerStr = m_pMarkerNames[nInd].strName;
return true;
} else {
nInd++;
}
}
if (!bFound) {
markerStr = _T("");
markerStr.Format(_T("(0xFF%02X)"),nCode);
return false;
}
return true;
}
// Determine if the file is an AVI MJPEG.
// If so, parse the headers.
// TODO: Expand this function to use sub-functions for each block type
bool CjfifDecode::DecodeAvi()
{
CString strTmp;
unsigned nPosSaved;
m_bAvi = false;
m_bAviMjpeg = false;
// Perhaps start from file position 0?
nPosSaved = m_nPos;
// Start from file position 0
m_nPos = 0;
bool bSwap = true;
CString strRiff;
unsigned nRiffLen;
CString strForm;
strRiff = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
nRiffLen = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
strForm = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
if ((strRiff == _T("RIFF")) && (strForm == _T("AVI "))) {
m_bAvi = true;
m_pLog->AddLine(_T(""));
m_pLog->AddLineHdr(_T("*** AVI File Decoding ***"));
m_pLog->AddLine(_T("Decoding RIFF AVI format..."));
m_pLog->AddLine(_T(""));
} else {
// Reset file position
m_nPos = nPosSaved;
return false;
}
CString strHeader;
unsigned nChunkSize;
unsigned nChunkDataStart;
bool done = false;
while (!done) {
if (m_nPos >= m_pWBuf->GetPosEof()) {
done = true;
break;
}
strHeader = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
strTmp.Format(_T(" %s"),(LPCTSTR)strHeader);
m_pLog->AddLine(strTmp);
nChunkSize = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
nChunkDataStart = m_nPos;
if (strHeader == _T("LIST")) {
// --- LIST ---
CString strListType;
strListType = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
strTmp.Format(_T(" %s"),(LPCTSTR)strListType);
m_pLog->AddLine(strTmp);
if (strListType == _T("hdrl")) {
// --- hdrl ---
unsigned nPosHdrlStart;
CString strHdrlId;
strHdrlId = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
unsigned nHdrlLen;
nHdrlLen = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
nPosHdrlStart = m_nPos;
// nHdrlLen should be 14*4 bytes
m_nPos = nPosHdrlStart + nHdrlLen;
} else if (strListType == _T("strl")) {
// --- strl ---
// strhHEADER
unsigned nPosStrlStart;
CString strStrlId;
strStrlId = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
unsigned nStrhLen;
nStrhLen = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
nPosStrlStart = m_nPos;
CString fccType;
CString fccHandler;
unsigned dwFlags,dwReserved1,dwInitialFrames,dwScale,dwRate;
unsigned dwStart,dwLength,dwSuggestedBufferSize,dwQuality;
unsigned dwSampleSize,xdwQuality,xdwSampleSize;
fccType = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
fccHandler = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
dwFlags = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwReserved1 = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwInitialFrames = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwScale = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwRate = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwStart = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwLength = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwSuggestedBufferSize = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwQuality = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwSampleSize = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
xdwQuality = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
xdwSampleSize = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
CString fccTypeDecode = _T("");
if (fccType == _T("vids")) { fccTypeDecode = _T("[vids] Video"); }
else if (fccType == _T("auds")) { fccTypeDecode = _T("[auds] Audio"); }
else if (fccType == _T("txts")) { fccTypeDecode = _T("[txts] Subtitle"); }
else { fccTypeDecode.Format(_T("[%s]"),(LPCTSTR)fccType); }
strTmp.Format(_T(" -[FourCC Type] = %s"),(LPCTSTR)fccTypeDecode);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" -[FourCC Codec] = [%s]"),(LPCTSTR)fccHandler);
m_pLog->AddLine(strTmp);
float fSampleRate = 0;
if (dwScale != 0) {
fSampleRate = (float)dwRate / (float)dwScale;
}
strTmp.Format(_T(" -[Sample Rate] = [%.2f]"),fSampleRate);
if (fccType == _T("vids")) { strTmp.Append(_T(" frames/sec")); }
else if (fccType == _T("auds")) { strTmp.Append(_T(" samples/sec")); }
m_pLog->AddLine(strTmp);
m_nPos = nPosStrlStart + nStrhLen; // Skip
strTmp.Format(_T(" %s"),(LPCTSTR)fccType);
m_pLog->AddLine(strTmp);
if (fccType == _T("vids")) {
// --- vids ---
// Is it MJPEG?
//strTmp.Format(_T(" -[Video Stream FourCC]=[%s]"),fccHandler);
//m_pLog->AddLine(strTmp);
if (fccHandler == _T("mjpg")) {
m_bAviMjpeg = true;
}
if (fccHandler == _T("MJPG")) {
m_bAviMjpeg = true;
}
// strfHEADER_BIH
CString strSkipId;
unsigned nSkipLen;
unsigned nSkipStart;
strSkipId = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
nSkipLen = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
nSkipStart = m_nPos;
m_nPos = nSkipStart + nSkipLen; // Skip
} else if (fccType == _T("auds")) {
// --- auds ---
// strfHEADER_WAVE
CString strSkipId;
unsigned nSkipLen;
unsigned nSkipStart;
strSkipId = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
nSkipLen = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
nSkipStart = m_nPos;
m_nPos = nSkipStart + nSkipLen; // Skip
} else {
// strfHEADER
CString strSkipId;
unsigned nSkipLen;
unsigned nSkipStart;
strSkipId = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
nSkipLen = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
nSkipStart = m_nPos;
m_nPos = nSkipStart + nSkipLen; // Skip
}
// strnHEADER
unsigned nPosStrnStart;
CString strStrnId;
strStrnId = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
unsigned nStrnLen;
nStrnLen = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
nPosStrnStart = m_nPos;
// FIXME: Can we rewrite in terms of ChunkSize and ChunkDataStart?
//ASSERT ((nPosStrnStart + nStrnLen + (nStrnLen%2)) == (nChunkDataStart + nChunkSize + (nChunkSize%2)));
//m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
m_nPos = nPosStrnStart + nStrnLen + (nStrnLen%2); // Skip
} else if (strListType == _T("movi")) {
// movi
m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
} else if (strListType == _T("INFO")) {
// INFO
unsigned nInfoStart;
nInfoStart = m_nPos;
CString strInfoId;
unsigned nInfoLen;
strInfoId = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
nInfoLen = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
if (strInfoId == _T("ISFT")) {
CString strIsft=_T("");
strIsft = m_pWBuf->BufReadStrn(m_nPos,nChunkSize);
strIsft.TrimRight();
strTmp.Format(_T(" -[Software] = [%s]"),(LPCTSTR)strIsft);
m_pLog->AddLine(strTmp);
}
m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
} else {
// ?
m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
}
} else if (strHeader == _T("JUNK")) {
// Junk
m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
} else if (strHeader == _T("IDIT")) {
// Timestamp info (Canon, etc.)
CString strIditTimestamp=_T("");
strIditTimestamp = m_pWBuf->BufReadStrn(m_nPos,nChunkSize);
strIditTimestamp.TrimRight();
strTmp.Format(_T(" -[Timestamp] = [%s]"),(LPCTSTR)strIditTimestamp);
m_pLog->AddLine(strTmp);
m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
} else if (strHeader == _T("indx")) {
// Index
m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
} else if (strHeader == _T("idx1")) {
// Index
unsigned nIdx1Entries = nChunkSize / (4*4);
m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
} else {
// Unsupported
m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
}
}
m_pLog->AddLine(_T(""));
if (m_bAviMjpeg) {
m_strImgExtras += _T("[AVI]:[mjpg],");
m_pLog->AddLineGood(_T(" AVI is MotionJPEG"));
m_pLog->AddLineWarn(_T(" Use [Tools->Img Search Fwd] to locate next frame"));
} else {
m_strImgExtras += _T("[AVI]:[????],");
m_pLog->AddLineWarn(_T(" AVI is not MotionJPEG. [Img Search Fwd/Rev] unlikely to find frames."));
}
m_pLog->AddLine(_T(""));
// Reset file position
m_nPos = nPosSaved;
return m_bAviMjpeg;
}
// This is the primary JFIF parsing routine.
// The main loop steps through all of the JFIF markers and calls
// DecodeMarker() each time until we reach the end of file or an error.
// Finally, we invoke the compression signature search function.
//
// Processing starts at the file offset m_pAppConfig->nPosStart
//
// INPUT:
// - inFile = Input file pointer
//
// PRE:
// - m_pAppConfig->nPosStart = Starting file offset for decode
//
void CjfifDecode::ProcessFile(CFile* inFile)
{
CString strTmp;
// Reset the JFIF decoder state as we may be redoing another file
Reset();
// Reset the IMG Decoder state
if (m_pImgSrcDirty) {
m_pImgDec->ResetState();
}
// Set the statusbar text to Processing...
// Ensure the status bar has been allocated
// NOTE: The stat bar is NULL if we drag & drop a file onto
// the JPEGsnoop app icon.
if (m_pStatBar) {
m_pStatBar->SetPaneText(0,_T("Processing..."));
}
// Note that we don't clear out the logger (with m_pLog->Reset())
// as we want top-level caller to do this. This way we can
// still insert extra lines from top level.
// GetLength returns ULONGLONG. Abort on large files (>=4GB)
ULONGLONG nPosFileEnd;
nPosFileEnd = inFile->GetLength();
if (nPosFileEnd > 0xFFFFFFFFUL) {
CString strTmp = _T("File too large. Skipping.");
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return;
}
m_nPosFileEnd = static_cast<unsigned long>(nPosFileEnd);
unsigned nStartPos;
nStartPos = m_pAppConfig->nPosStart;
m_nPos = nStartPos;
m_nPosEmbedStart = nStartPos; // Save the embedded file start position
strTmp.Format(_T("Start Offset: 0x%08X"),nStartPos);
m_pLog->AddLine(strTmp);
// ----------------------------------------------------------------
// Test for AVI file
// - Detect header
// - start from beginning of file
DecodeAvi();
// TODO: Should we skip decode of file if not MJPEG?
// ----------------------------------------------------------------
// Test for PSD file
// - Detect header
// - FIXME: start from current offset?
unsigned nWidth=0;
unsigned nHeight=0;
#ifdef PS_IMG_DEC_EN
// If PSD image decoding is enabled, associate the PSD parsing with
// the current DIB. After decoding, flag the DIB as ready for display.
// Attempt decode as PSD
bool bDecPsdOk;
bDecPsdOk = m_pPsDec->DecodePsd(nStartPos,&m_pImgDec->m_pDibTemp,nWidth,nHeight);
if (bDecPsdOk) {
// FIXME: The following is a bit of a hack
m_pImgDec->m_bDibTempReady = true;
m_pImgDec->m_bPreviewIsJpeg = false; // MCU/Block info not available
m_pImgDec->SetImageDimensions(nWidth,nHeight);
// Clear the image information
// The primary reason for this is to ensure we don't have stale information from a previous
// JPEG image (eg. real image border inside MCU border which would be overlayed during draw).
m_pImgDec->SetImageDetails(0,0,0,0,false,0);
// No more processing of file
// - Otherwise we'd continue to attempt to decode as JPEG
return;
}
#else
// Don't attempt to display Photoshop image data
if (m_pPsDec->DecodePsd(nStartPos,NULL,nWidth,nHeight)) {
return;
}
#endif
// ----------------------------------------------------------------
// Disable DICOM for now until fully tested
#ifdef SUPPORT_DICOM
// Test for DICOM
// - Detect header
// - start from beginning of file
bool bDicom = false;
unsigned long nPosJpeg = 0; // File offset to embedded JPEG in DICOM
bDicom = m_pDecDicom->DecodeDicom(0,m_nPosFileEnd,nPosJpeg);
if (bDicom) {
// Adjust start of JPEG decoding if we are currently without an offset
if (nStartPos == 0) {
m_pAppConfig->nPosStart = nPosJpeg;
nStartPos = m_pAppConfig->nPosStart;
m_nPos = nStartPos;
m_nPosEmbedStart = nStartPos; // Save the embedded file start position
strTmp.Format(_T("Adjusting Start Offset to: 0x%08X"),nStartPos);
m_pLog->AddLine(strTmp);
m_pLog->AddLine(_T(""));
}
}
#endif
// ----------------------------------------------------------------
// Decode as JPEG JFIF file
// If we are in a non-zero offset, add this to extras
if (m_pAppConfig->nPosStart!=0) {
strTmp.Format(_T("[Offset]=[%lu],"),m_pAppConfig->nPosStart);
m_strImgExtras += strTmp;
}
unsigned nDataAfterEof = 0;
BOOL bDone = FALSE;
while (!bDone)
{
// Allow some other threads to jump in
// Return value 0 - OK
// 1 - Error
// 2 - EOI
if (DecodeMarker() != DECMARK_OK) {
bDone = TRUE;
if (m_nPosFileEnd >= m_nPosEoi) {
nDataAfterEof = m_nPosFileEnd - m_nPosEoi;
}
} else {
if (m_nPos > m_pWBuf->GetPosEof()) {
m_pLog->AddLineErr(_T("ERROR: Early EOF - file may be missing EOI"));
bDone = TRUE;
}
}
}
// -----------------------------------------------------------
// Perform any other informational calculations that require all tables
// to be present.
// Determine the CSS Ratio
// Save the subsampling string. Assume component 2 is representative of the overall chrominance.
// NOTE: Ensure that we don't execute the following code if we haven't
// completed our read (ie. get bad marker earlier in processing).
// TODO: What is the best way to determine all is OK?
m_strImgQuantCss = _T("?x?");
m_strHash = _T("NONE");
m_strHashRot = _T("NONE");
if (m_bImgOK) {
ASSERT(m_eImgLandscape!=ENUM_LANDSCAPE_UNSET);
if (m_nSofNumComps_Nf == NUM_CHAN_YCC) {
// We only try to determine the chroma subsampling ratio if we have 3 components (assume YCC)
// In general, we should be able to use the 2nd or 3rd component
// NOTE: The following assumes m_anSofHorzSampFact_Hi and m_anSofVertSampFact_Vi
// are non-zero as otherwise we'll have a divide-by-0 exception.
unsigned nCompIdent = m_anSofQuantCompId[SCAN_COMP_CB];
unsigned nCssFactH = m_nSofHorzSampFactMax_Hmax/m_anSofHorzSampFact_Hi[nCompIdent];
unsigned nCssFactV = m_nSofVertSampFactMax_Vmax/m_anSofVertSampFact_Vi[nCompIdent];
if (m_eImgLandscape!=ENUM_LANDSCAPE_NO) {
// Landscape orientation
m_strImgQuantCss.Format(_T("%ux%u"),nCssFactH,nCssFactV);
}
else {
// Portrait orientation (flip subsampling ratio)
m_strImgQuantCss.Format(_T("%ux%u"),nCssFactV,nCssFactH);
}
} else if (m_nSofNumComps_Nf == NUM_CHAN_GRAYSCALE) {
m_strImgQuantCss = _T("Gray");
}
DecodeEmbeddedThumb();
// Generate the signature
PrepareSignature();
// Compare compression signature
if (m_pAppConfig->bSigSearch) {
// In the case of lossless files, there won't be any DQT and
// hence no compression signatures to compare. Therefore, skip this process.
if (m_strHash == _T("NONE")) {
m_pLog->AddLineWarn(_T("Skipping compression signature search as no DQT"));
} else {
CompareSignature();
}
}
if (nDataAfterEof > 0) {
m_pLog->AddLine(_T(""));
m_pLog->AddLineHdr(_T("*** Additional Info ***"));
strTmp.Format(_T("NOTE: Data exists after EOF, range: 0x%08X-0x%08X (%u bytes)"),
m_nPosEoi,m_nPosFileEnd,nDataAfterEof);
m_pLog->AddLine(strTmp);
}
// Print out the special-purpose outputs
OutputSpecial();
}
// Reset the status bar text
if (m_pStatBar) {
m_pStatBar->SetPaneText(0,_T("Done"));
}
// Mark the file as closed
//m_pWBuf->BufFileUnset();
}
// Determine if the analyzed file is in a state ready for image
// extraction. Confirms that the important JFIF markers have been
// detected in the previous analysis.
//
// PRE:
// - m_nPosEmbedStart
// - m_nPosEmbedEnd
// - m_nPosFileEnd
//
// RETURN:
// - True if image is ready for extraction
//
bool CjfifDecode::ExportJpegPrepare(CString strFileIn,bool bForceSoi,bool bForceEoi,bool bIgnoreEoi)
{
// Extract from current file
// [m_nPosEmbedStart ... m_nPosEmbedEnd]
// If state is valid (i.e. file opened)
CString strTmp = _T("");
m_pLog->AddLine(_T(""));
m_pLog->AddLineHdr(_T("*** Exporting JPEG ***"));
strTmp.Format(_T(" Exporting from: [%s]"),(LPCTSTR)strFileIn);
m_pLog->AddLine(strTmp);
// Only bother to extract if all main sections are present
bool bExtractWarn = false;
CString strMissing = _T("");
if (!m_bStateEoi) {
if (!bForceEoi && !bIgnoreEoi) {
strTmp.Format(_T(" ERROR: Missing marker: %s"),_T("EOI"));
m_pLog->AddLineErr(strTmp);
m_pLog->AddLineErr(_T(" Aborting export. Consider enabling [Force EOI] or [Ignore Missing EOI] option"));
return false;
} else if (bIgnoreEoi) {
// Ignore the EOI, so mark the end of file, but don't
// set the flag where we force one.
m_nPosEmbedEnd = m_nPosFileEnd;
} else {
// We're missing the EOI but the user has requested
// that we force an EOI, so let's fix things up
m_nPosEmbedEnd = m_nPosFileEnd;
}
}
if ((m_nPosEmbedStart == 0) && (m_nPosEmbedEnd == 0)) {
strTmp.Format(_T(" No frame found at this position in file. Consider using [Img Search]"));
m_pLog->AddLineErr(strTmp);
return false;
}
if (!m_bStateSoi) {
if (!bForceSoi) {
strTmp.Format(_T(" ERROR: Missing marker: %s"),_T("SOI"));
m_pLog->AddLineErr(strTmp);
m_pLog->AddLineErr(_T(" Aborting export. Consider enabling [Force SOI] option"));
return false;
} else {
// We're missing the SOI but the user has requested
// that we force an SOI, so let's fix things up
}
}
if (!m_bStateSos) {
strTmp.Format(_T(" ERROR: Missing marker: %s"),_T("SOS"));
m_pLog->AddLineErr(strTmp);
m_pLog->AddLineErr(_T(" Aborting export"));
return false;
}
if (!m_bStateDqt) { bExtractWarn = true; strMissing += _T("DQT "); }
if (!m_bStateDht) { bExtractWarn = true; strMissing += _T("DHT "); }
if (!m_bStateSof) { bExtractWarn = true; strMissing += _T("SOF "); }
if (bExtractWarn) {
strTmp.Format(_T(" NOTE: Missing marker: %s"),(LPCTSTR)strMissing);
m_pLog->AddLineWarn(strTmp);
m_pLog->AddLineWarn(_T(" Exported JPEG may not be valid"));
}
if (m_nPosEmbedEnd < m_nPosEmbedStart) {
strTmp.Format(_T("ERROR: Invalid SOI-EOI order. Export aborted."));
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return false;
}
return true;
}
#define EXPORT_BUF_SIZE 131072
// Export the embedded JPEG image at the current position in the file (with overlays)
// (may be the primary image or even an embedded thumbnail).
bool CjfifDecode::ExportJpegDo(CString strFileIn, CString strFileOut,
unsigned long nFileLen, bool bOverlayEn,bool bDhtAviInsert,bool bForceSoi,bool bForceEoi)
{
CFile* pFileOutput;
CString strTmp = _T("");
strTmp.Format(_T(" Exporting to: [%s]"),(LPCTSTR)strFileOut);
m_pLog->AddLine(strTmp);
if (strFileIn == strFileOut) {
strTmp.Format(_T("ERROR: Can't overwrite source file. Aborting export."));
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return false;
}
ASSERT(strFileIn != _T(""));
if (strFileIn == _T("")) {
strTmp.Format(_T("ERROR: Export but source filename empty"));
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return false;
}
try
{
// Open specified file
// Added in shareDenyNone as this apparently helps resolve some people's troubles
// with an error showing: Couldn't open file "Sharing Violation"
pFileOutput = new CFile(strFileOut, CFile::modeCreate| CFile::modeWrite | CFile::typeBinary | CFile::shareDenyNone);
}
catch (CFileException* e)
{
TCHAR msg[MAX_BUF_EX_ERR_MSG];
CString strError;
e->GetErrorMessage(msg,MAX_BUF_EX_ERR_MSG);
e->Delete();
strError.Format(_T("ERROR: Couldn't open file for write [%s]: [%s]"),
(LPCTSTR)strFileOut, (LPCTSTR)msg);
m_pLog->AddLineErr(strError);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strError);
pFileOutput = NULL;
return false;
}
// Don't attempt to load buffer with zero length file!
if (nFileLen==0) {
strTmp.Format(_T("ERROR: Source file length error. Please Reprocess first."));
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
if (pFileOutput) { delete pFileOutput; pFileOutput = NULL; }
return false;
}
// Need to insert fake DHT. Assume we have enough buffer allocated.
//
// Step 1: Copy from SOI -> SOS (not incl)
// Step 2: Insert Fake DHT
// Step 3: Copy from SOS -> EOI
unsigned nCopyStart;
unsigned nCopyEnd;
unsigned nCopyLeft;
unsigned ind;
BYTE* pBuf;
pBuf = new BYTE[EXPORT_BUF_SIZE+10];
if (!pBuf) {
if (pFileOutput) { delete pFileOutput; pFileOutput = NULL; }
return false;
}
// Step 1
// If we need to force an SOI, do it now
if (!m_bStateSoi && bForceSoi) {
m_pLog->AddLine(_T(" Forcing SOI Marker"));
BYTE anBufSoi[2] = {0xFF,JFIF_SOI};
pFileOutput->Write(&anBufSoi,2);
}
nCopyStart = m_nPosEmbedStart;
nCopyEnd = (m_nPosSos-1);
ind = nCopyStart;
while (ind<nCopyEnd) {
nCopyLeft = nCopyEnd-ind+1;
if (nCopyLeft>EXPORT_BUF_SIZE) { nCopyLeft = EXPORT_BUF_SIZE; }
for (unsigned ind1=0;ind1<nCopyLeft;ind1++) {
pBuf[ind1] = Buf(ind+ind1,!bOverlayEn);
}
pFileOutput->Write(pBuf,nCopyLeft);
ind += nCopyLeft;
// NOTE: We ensure nFileLen != 0 earlier
ASSERT(nFileLen>0);
strTmp.Format(_T("Exporting %3u%%..."),ind*100/nFileLen);
SetStatusText(strTmp);
}
if (bDhtAviInsert) {
// Step 2. The following struct includes the JFIF marker too
strTmp.Format(_T(" Inserting standard AVI DHT huffman table"));
m_pLog->AddLine(strTmp);
pFileOutput->Write(m_abMJPGDHTSeg,JFIF_DHT_FAKE_SZ);
}
// Step 3
nCopyStart = m_nPosSos;
nCopyEnd = m_nPosEmbedEnd-1;
ind = nCopyStart;
while (ind<nCopyEnd) {
nCopyLeft = nCopyEnd-ind+1;
if (nCopyLeft>EXPORT_BUF_SIZE) { nCopyLeft = EXPORT_BUF_SIZE; }
for (unsigned ind1=0;ind1<nCopyLeft;ind1++) {
pBuf[ind1] = Buf(ind+ind1,!bOverlayEn);
}
pFileOutput->Write(pBuf,nCopyLeft);
ind += nCopyLeft;
// NOTE: We ensure nFileLen != 0 earlier
ASSERT(nFileLen>0);
strTmp.Format(_T("Exporting %3u%%..."),ind*100/nFileLen);
SetStatusText(strTmp);
}
// Now optionally insert the EOI Marker
if (bForceEoi) {
m_pLog->AddLine(_T(" Forcing EOI Marker"));
BYTE anBufEoi[2] = {0xFF,JFIF_EOI};
pFileOutput->Write(&anBufEoi,2);
}
// Free up space
pFileOutput->Close();
if (pBuf) {
delete [] pBuf;
pBuf = NULL;
}
if (pFileOutput) {
delete pFileOutput;
pFileOutput = NULL;
}
SetStatusText(_T(""));
strTmp.Format(_T(" Export done"));
m_pLog->AddLine(strTmp);
return true;
}
// Export a subset of the file with no overlays or mods
bool CjfifDecode::ExportJpegDoRange(CString strFileIn, CString strFileOut,
unsigned long nStart, unsigned long nEnd)
{
CFile* pFileOutput;
CString strTmp = _T("");
strTmp.Format(_T(" Exporting range to: [%s]"),(LPCTSTR)strFileOut);
m_pLog->AddLine(strTmp);
if (strFileIn == strFileOut) {
strTmp.Format(_T("ERROR: Can't overwrite source file. Aborting export."));
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return false;
}
ASSERT(strFileIn != _T(""));
if (strFileIn == _T("")) {
strTmp.Format(_T("ERROR: Export but source filename empty"));
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return false;
}
try
{
// Open specified file
// Added in shareDenyNone as this apparently helps resolve some people's troubles
// with an error showing: Couldn't open file "Sharing Violation"
pFileOutput = new CFile(strFileOut, CFile::modeCreate| CFile::modeWrite | CFile::typeBinary | CFile::shareDenyNone);
}
catch (CFileException* e)
{
TCHAR msg[MAX_BUF_EX_ERR_MSG];
CString strError;
e->GetErrorMessage(msg,MAX_BUF_EX_ERR_MSG);
e->Delete();
strError.Format(_T("ERROR: Couldn't open file for write [%s]: [%s]"),
(LPCTSTR)strFileOut, (LPCTSTR)msg);
m_pLog->AddLineErr(strError);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strError);
pFileOutput = NULL;
return false;
}
unsigned nCopyStart;
unsigned nCopyEnd;
unsigned nCopyLeft;
unsigned ind;
BYTE* pBuf;
pBuf = new BYTE[EXPORT_BUF_SIZE+10];
if (!pBuf) {
if (pFileOutput) { delete pFileOutput; pFileOutput = NULL; }
return false;
}
// Step 1
nCopyStart = nStart;
nCopyEnd = nEnd;
ind = nCopyStart;
while (ind<nCopyEnd) {
nCopyLeft = nCopyEnd-ind+1;
if (nCopyLeft>EXPORT_BUF_SIZE) { nCopyLeft = EXPORT_BUF_SIZE; }
for (unsigned ind1=0;ind1<nCopyLeft;ind1++) {
pBuf[ind1] = Buf(ind+ind1,false);
}
pFileOutput->Write(pBuf,nCopyLeft);
ind += nCopyLeft;
strTmp.Format(_T("Exporting %3u%%..."),ind*100/(nCopyEnd-nCopyStart));
SetStatusText(strTmp);
}
// Free up space
pFileOutput->Close();
if (pBuf) {
delete [] pBuf;
pBuf = NULL;
}
if (pFileOutput) {
delete pFileOutput;
pFileOutput = NULL;
}
SetStatusText(_T(""));
strTmp.Format(_T(" Export range done"));
m_pLog->AddLine(strTmp);
return true;
}
// ====================================================================================
// JFIF Decoder Constants
// ====================================================================================
// List of the JFIF markers
const MarkerNameTable CjfifDecode::m_pMarkerNames[] = {
{JFIF_SOF0,_T("SOF0")},
{JFIF_SOF1,_T("SOF1")},
{JFIF_SOF2,_T("SOF2")},
{JFIF_SOF3,_T("SOF3")},
{JFIF_SOF5,_T("SOF5")},
{JFIF_SOF6,_T("SOF6")},
{JFIF_SOF7,_T("SOF7")},
{JFIF_JPG,_T("JPG")},
{JFIF_SOF9,_T("SOF9")},
{JFIF_SOF10,_T("SOF10")},
{JFIF_SOF11,_T("SOF11")},
{JFIF_SOF13,_T("SOF13")},
{JFIF_SOF14,_T("SOF14")},
{JFIF_SOF15,_T("SOF15")},
{JFIF_DHT,_T("DHT")},
{JFIF_DAC,_T("DAC")},
{JFIF_RST0,_T("RST0")},
{JFIF_RST1,_T("RST1")},
{JFIF_RST2,_T("RST2")},
{JFIF_RST3,_T("RST3")},
{JFIF_RST4,_T("RST4")},
{JFIF_RST5,_T("RST5")},
{JFIF_RST6,_T("RST6")},
{JFIF_RST7,_T("RST7")},
{JFIF_SOI,_T("SOI")},
{JFIF_EOI,_T("EOI")},
{JFIF_SOS,_T("SOS")},
{JFIF_DQT,_T("DQT")},
{JFIF_DNL,_T("DNL")},
{JFIF_DRI,_T("DRI")},
{JFIF_DHP,_T("DHP")},
{JFIF_EXP,_T("EXP")},
{JFIF_APP0,_T("APP0")},
{JFIF_APP1,_T("APP1")},
{JFIF_APP2,_T("APP2")},
{JFIF_APP3,_T("APP3")},
{JFIF_APP4,_T("APP4")},
{JFIF_APP5,_T("APP5")},
{JFIF_APP6,_T("APP6")},
{JFIF_APP7,_T("APP7")},
{JFIF_APP8,_T("APP8")},
{JFIF_APP9,_T("APP9")},
{JFIF_APP10,_T("APP10")},
{JFIF_APP11,_T("APP11")},
{JFIF_APP12,_T("APP12")},
{JFIF_APP13,_T("APP13")},
{JFIF_APP14,_T("APP14")},
{JFIF_APP15,_T("APP15")},
{JFIF_JPG0,_T("JPG0")},
{JFIF_JPG1,_T("JPG1")},
{JFIF_JPG2,_T("JPG2")},
{JFIF_JPG3,_T("JPG3")},
{JFIF_JPG4,_T("JPG4")},
{JFIF_JPG5,_T("JPG5")},
{JFIF_JPG6,_T("JPG6")},
{JFIF_JPG7,_T("JPG7")},
{JFIF_JPG8,_T("JPG8")},
{JFIF_JPG9,_T("JPG9")},
{JFIF_JPG10,_T("JPG10")},
{JFIF_JPG11,_T("JPG11")},
{JFIF_JPG12,_T("JPG12")},
{JFIF_JPG13,_T("JPG13")},
{JFIF_COM,_T("COM")},
{JFIF_TEM,_T("TEM")},
//{JFIF_RES*,_T("RES")},
{0x00,_T("*")},
};
// For Motion JPEG, define the DHT tables that we use since they won't exist
// in each frame within the AVI. This table will be read in during
// DecodeDHT()'s call to Buf().
const BYTE CjfifDecode::m_abMJPGDHTSeg[JFIF_DHT_FAKE_SZ] = {
/* JPEG DHT Segment for YCrCb omitted from MJPG data */
0xFF,0xC4,0x01,0xA2,
0x00,0x00,0x01,0x05,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x01,0x00,0x03,0x01,0x01,0x01,0x01,
0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,
0x08,0x09,0x0A,0x0B,0x10,0x00,0x02,0x01,0x03,0x03,0x02,0x04,0x03,0x05,0x05,0x04,0x04,0x00,
0x00,0x01,0x7D,0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,
0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xA1,0x08,0x23,0x42,0xB1,0xC1,0x15,0x52,0xD1,0xF0,0x24,
0x33,0x62,0x72,0x82,0x09,0x0A,0x16,0x17,0x18,0x19,0x1A,0x25,0x26,0x27,0x28,0x29,0x2A,0x34,
0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x53,0x54,0x55,0x56,
0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78,
0x79,0x7A,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,
0x9A,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,
0xBA,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,
0xDA,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,
0xF8,0xF9,0xFA,0x11,0x00,0x02,0x01,0x02,0x04,0x04,0x03,0x04,0x07,0x05,0x04,0x04,0x00,0x01,
0x02,0x77,0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,0xA1,0xB1,0xC1,0x09,0x23,0x33,0x52,0xF0,0x15,0x62,
0x72,0xD1,0x0A,0x16,0x24,0x34,0xE1,0x25,0xF1,0x17,0x18,0x19,0x1A,0x26,0x27,0x28,0x29,0x2A,
0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x53,0x54,0x55,0x56,
0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78,
0x79,0x7A,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
0x99,0x9A,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,
0xB9,0xBA,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,
0xD9,0xDA,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,
0xF9,0xFA
};
// TODO: Add ITU-T Example DQT & DHT
// These will be useful for GeoRaster decode (ie. JPEG-B)
CString glb_strMsgStopDecode = _T(" Stopping decode. Use [Relaxed Parsing] to continue."); | ./CrossVul/dataset_final_sorted/CWE-369/cpp/good_2528_0 |
crossvul-cpp_data_bad_2528_0 | // JPEGsnoop - JPEG Image Decoder & Analysis Utility
// Copyright (C) 2015 - Calvin Hass
// http://www.impulseadventure.com/photo/jpeg-snoop.html
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#include "stdafx.h"
#include "JfifDecode.h"
#include "snoop.h"
#include "JPEGsnoop.h" // for m_pAppConfig get
#include "WindowBuf.h"
#include "Md5.h"
#include "afxinet.h"
#include "windows.h"
#include "UrlString.h"
#include "DbSigs.h"
#include "General.h"
// Maximum number of component values to extract into array for display
#define MAX_anValues 64
// Clear out internal members
void CjfifDecode::Reset()
{
// File handling
m_nPos = 0;
m_nPosSos = 0;
m_nPosEoi = 0;
m_nPosEmbedStart = 0;
m_nPosEmbedEnd = 0;
m_nPosFileEnd = 0;
// SOS / SOF handling
m_nSofNumLines_Y = 0;
m_nSofSampsPerLine_X = 0;
m_nSofNumComps_Nf = 0;
// Quantization tables
ClearDQT();
// Photoshop
m_nImgQualPhotoshopSfw = 0;
m_nImgQualPhotoshopSa = 0;
m_nApp14ColTransform = -1;
// Restart marker
m_nImgRstEn = false;
m_nImgRstInterval = 0;
// Basic metadata
m_strImgExifMake = _T("???");
m_nImgExifMakeSubtype = 0;
m_strImgExifModel = _T("???");
m_bImgExifMakernotes = false;
m_strImgExtras = _T("");
m_strComment = _T("");
m_strSoftware = _T("");
m_bImgProgressive = false;
m_bImgSofUnsupported = false;
_tcscpy_s(m_acApp0Identifier,_T(""));
// Derived metadata
m_strHash = _T("NONE");
m_strHashRot = _T("NONE");
m_eImgLandscape = ENUM_LANDSCAPE_UNSET;
m_strImgQualExif = _T("");
m_bAvi = false;
m_bAviMjpeg = false;
m_bPsd = false;
// Misc
m_bImgOK = false; // Set during SOF to indicate further proc OK
m_bBufFakeDHT = false; // Start in normal Buf mode
m_eImgEdited = EDITED_UNSET;
m_eDbReqSuggest = DB_ADD_SUGGEST_UNSET;
m_bSigExactInDB = false;
// Embedded thumbnail
m_nImgExifThumbComp = 0;
m_nImgExifThumbOffset = 0;
m_nImgExifThumbLen = 0;
m_strHashThumb = _T("NONE"); // Will go into DB to say NONE!
m_strHashThumbRot = _T("NONE"); // Will go into DB to say NONE!
m_nImgThumbNumLines = 0;
m_nImgThumbSampsPerLine = 0;
// Now clear out any previously generated bitmaps
// or image decoding parameters
if (m_pImgDec) {
if (m_pImgSrcDirty) {
m_pImgDec->Reset();
}
}
// Reset the decoding state checks
// These are to help ensure we don't start decoding SOS
// if we haven't seen other valid markers yet! Otherwise
// we could run into very bad loops (e.g. .PSD files)
// just because we saw FFD8FF first then JFIF_SOS
m_bStateAbort = false;
m_bStateSoi = false;
m_bStateDht = false;
m_bStateDhtOk = false;
m_bStateDhtFake = false;
m_bStateDqt = false;
m_bStateDqtOk = false;
m_bStateSof = false;
m_bStateSofOk = false;
m_bStateSos = false;
m_bStateSosOk = false;
m_bStateEoi = false;
}
// Initialize the JFIF decoder. Several class pointers are provided
// as parameters, so that we can directly access the output log, the
// file buffer and the image scan decoder.
// Loads up the signature database.
//
// INPUT:
// - pLog Ptr to log file class
// - pWBuf Ptr to Window Buf class
// - pImgDec Ptr to Image Decoder class
//
// PRE:
// - Requires that CDocLog, CwindowBuf and CimgDecode classes
// are already initialized
//
CjfifDecode::CjfifDecode(CDocLog* pLog,CwindowBuf* pWBuf,CimgDecode* pImgDec)
{
// Ideally this would be passed by constructor, but simply access
// directly for now.
CJPEGsnoopApp* pApp;
pApp = (CJPEGsnoopApp*)AfxGetApp();
m_pAppConfig = pApp->m_pAppConfig;
ASSERT(m_pAppConfig);
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CjfifDecode::CjfifDecode() Begin"));
ASSERT(pLog);
ASSERT(pWBuf);
ASSERT(pImgDec);
// Need to zero out the private members
m_bOutputDB = FALSE; // mySQL output for web
// Enable verbose reporting
m_bVerbose = FALSE;
m_pImgSrcDirty = TRUE;
// Generate lookup tables for Huffman codes
GenLookupHuffMask();
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CjfifDecode::CjfifDecode() Checkpoint 1"));
// Window status bar is not ready yet, wait for call to SetStatusBar()
m_pStatBar = NULL;
// Save copies of other class pointers
m_pLog = pLog;
m_pWBuf = pWBuf;
m_pImgDec = pImgDec;
// Reset decoding state
Reset();
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CjfifDecode::CjfifDecode() Checkpoint 2"));
// Load the local database (if it exists)
theApp.m_pDbSigs->DatabaseExtraLoad();
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CjfifDecode::CjfifDecode() Checkpoint 3"));
// Allocate the Photoshop decoder
m_pPsDec = new CDecodePs(pWBuf,pLog);
if (!m_pPsDec) {
ASSERT(false);
return;
}
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CjfifDecode::CjfifDecode() Checkpoint 4"));
#ifdef SUPPORT_DICOM
// Allocate the DICOM decoder
m_pDecDicom = new CDecodeDicom(pWBuf,pLog);
if (!m_pDecDicom) {
ASSERT(false);
return;
}
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CjfifDecode::CjfifDecode() Checkpoint 5"));
#endif
if (DEBUG_EN) m_pAppConfig->DebugLogAdd(_T("CjfifDecode::CjfifDecode() End"));
}
// Destructor
CjfifDecode::~CjfifDecode()
{
// Free the Photoshop decoder
if (m_pPsDec) {
delete m_pPsDec;
m_pPsDec = NULL;
}
#ifdef SUPPORT_DICOM
// Free the DICOM decoder
if (m_pDecDicom) {
delete m_pDecDicom;
m_pDecDicom = NULL;
}
#endif
}
// Asynchronously update a local pointer to the status bar once
// it becomes available. Note that the status bar is not ready by
// the time of the CjfifDecode class constructor call.
//
// INPUT:
// - pStatBar Ptr to status bar
//
// POST:
// - m_pStatBar
//
void CjfifDecode::SetStatusBar(CStatusBar* pStatBar)
{
m_pStatBar = pStatBar;
}
// Indicate that the source of the image scan data
// has been dirtied. Either the source has changed
// or some of the View2 options have changed.
//
// POST:
// - m_pImgSrcDirty
//
void CjfifDecode::ImgSrcChanged()
{
m_pImgSrcDirty = true;
}
// Set the AVI mode flag for this file
//
// POST:
// - m_bAvi
// - m_bAviMjpeg
//
void CjfifDecode::SetAviMode(bool bIsAvi,bool bIsMjpeg)
{
m_bAvi = bIsAvi;
m_bAviMjpeg = bIsMjpeg;
}
// Fetch the AVI mode flag for this file
//
// PRE:
// - m_bAvi
// - m_bAviMjpeg
//
// OUTPUT:
// - bIsAvi
// - bIsMjpeg
//
void CjfifDecode::GetAviMode(bool &bIsAvi,bool &bIsMjpeg)
{
bIsAvi = m_bAvi;
bIsMjpeg = m_bAviMjpeg;
}
// Fetch the starting file position of the embedded thumbnail
//
// PRE:
// - m_nPosEmbedStart
//
// RETURN:
// - File position
//
unsigned long CjfifDecode::GetPosEmbedStart()
{
return m_nPosEmbedStart;
}
// Fetch the ending file position of the embedded thumbnail
//
// PRE:
// - m_nPosEmbedEnd
//
// RETURN:
// - File position
//
unsigned long CjfifDecode::GetPosEmbedEnd()
{
return m_nPosEmbedEnd;
}
// Determine if the last analysis revealed a JFIF with known markers
//
// RETURN:
// - TRUE if file (at position during analysis) appeared to decode OK
//
bool CjfifDecode::GetDecodeStatus()
{
return m_bImgOK;
}
// Fetch a summary of the JFIF decoder results
// These details are used in preparation of signature submission to the DB
//
// PRE:
// - m_strHash
// - m_strHashRot
// - m_strImgExifMake
// - m_strImgExifModel
// - m_strImgQualExif
// - m_strSoftware
// - m_eDbReqSuggest
//
// OUTPUT:
// - strHash
// - strHashRot
// - strImgExifMake
// - strImgExifModel
// - strImgQualExif
// - strSoftware
// - nDbReqSuggest
//
void CjfifDecode::GetDecodeSummary(CString &strHash,CString &strHashRot,CString &strImgExifMake,CString &strImgExifModel,
CString &strImgQualExif,CString &strSoftware,teDbAdd &eDbReqSuggest)
{
strHash = m_strHash;
strHashRot = m_strHashRot;
strImgExifMake = m_strImgExifMake;
strImgExifModel = m_strImgExifModel;
strImgQualExif = m_strImgQualExif;
strSoftware = m_strSoftware;
eDbReqSuggest = m_eDbReqSuggest;
}
// Fetch an element from the "standard" luminance quantization table
//
// PRE:
// - glb_anStdQuantLum[]
//
// RETURN:
// - DQT matrix element
//
unsigned CjfifDecode::GetDqtQuantStd(unsigned nInd)
{
if (nInd < MAX_DQT_COEFF) {
return glb_anStdQuantLum[nInd];
} else {
#ifdef DEBUG_LOG
CString strTmp;
CString strDebug;
strTmp.Format(_T("GetDqtQuantStd() with nInd out of range. nInd=[%u]"),nInd);
strDebug.Format(_T("## File=[%-100s] Block=[%-10s] Error=[%s]\n"),(LPCTSTR)m_pAppConfig->strCurFname,
_T("JfifDecode"),(LPCTSTR)strTmp);
OutputDebugString(strDebug);
#else
ASSERT(false);
#endif
return 0;
}
}
// Fetch the DQT ordering index (with optional zigzag sequence)
//
// INPUT:
// - nInd Coefficient index
// - bZigZag Use zig-zag ordering
//
// RETURN:
// - Sequence index
//
unsigned CjfifDecode::GetDqtZigZagIndex(unsigned nInd,bool bZigZag)
{
if (nInd < MAX_DQT_COEFF) {
if (bZigZag) {
return nInd;
} else {
return glb_anZigZag[nInd];
}
} else {
#ifdef DEBUG_LOG
CString strTmp;
CString strDebug;
strTmp.Format(_T("GetDqtZigZagIndex() with nInd out of range. nInd=[%u]"),nInd);
strDebug.Format(_T("## File=[%-100s] Block=[%-10s] Error=[%s]\n"),(LPCTSTR)m_pAppConfig->strCurFname,
_T("JfifDecode"),(LPCTSTR)strTmp);
OutputDebugString(strDebug);
#else
ASSERT(false);
#endif
return 0;
}
}
// Reset the DQT tables
//
// POST:
// - m_anImgDqtTbl[][]
// - m_anImgThumbDqt[][]
// - m_adImgDqtQual[]
// - m_abImgDqtSet[]
// - m_abImgDqtThumbSet[]
//
void CjfifDecode::ClearDQT()
{
for (unsigned nTblInd=0;nTblInd<MAX_DQT_DEST_ID;nTblInd++)
{
for (unsigned nCoeffInd=0;nCoeffInd<MAX_DQT_COEFF;nCoeffInd++)
{
m_anImgDqtTbl[nTblInd][nCoeffInd] = 0;
m_anImgThumbDqt[nTblInd][nCoeffInd] = 0;
}
m_adImgDqtQual[nTblInd] = 0;
m_abImgDqtSet[nTblInd] = false;
m_abImgDqtThumbSet[nTblInd] = false;
}
}
// Set the DQT matrix element
//
// INPUT:
// - dqt0[] Matrix array for table 0
// - dqt1[] Matrix array for table 1
//
// POST:
// - m_anImgDqtTbl[][]
// - m_eImgLandscape
// - m_abImgDqtSet[]
// - m_strImgQuantCss
//
void CjfifDecode::SetDQTQuick(unsigned anDqt0[64],unsigned anDqt1[64])
{
m_eImgLandscape = ENUM_LANDSCAPE_YES;
for (unsigned ind=0;ind<MAX_DQT_COEFF;ind++)
{
m_anImgDqtTbl[0][ind] = anDqt0[ind];
m_anImgDqtTbl[1][ind] = anDqt1[ind];
}
m_abImgDqtSet[0] = true;
m_abImgDqtSet[1] = true;
m_strImgQuantCss = _T("NA");
}
// Construct a lookup table for the Huffman code masks
// The result is a simple bit sequence of zeros followed by
// an increasing number of 1 bits.
// 00000000...00000001
// 00000000...00000011
// 00000000...00000111
// ...
// 01111111...11111111
// 11111111...11111111
//
// POST:
// - m_anMaskLookup[]
//
void CjfifDecode::GenLookupHuffMask()
{
unsigned int mask;
for (unsigned len=0;len<32;len++)
{
mask = (1 << (len))-1;
mask <<= 32-len;
m_anMaskLookup[len] = mask;
}
}
// Provide a short-hand alias for the m_pWBuf buffer
// Also support redirection to a local table in case we are
// faking out the DHT (eg. for MotionJPEG files).
//
// PRE:
// - m_bBufFakeDHT Flag to include Fake DHT table
// - m_abMJPGDHTSeg[] DHT table used if m_bBufFakeDHT=true
//
// INPUT:
// - nOffset File offset to read from
// - bClean Forcibly disables any redirection to Fake DHT table
//
// POST:
// - m_pLog
//
// RETURN:
// - Byte from file (or local table)
//
BYTE CjfifDecode::Buf(unsigned long nOffset,bool bClean=false)
{
// Buffer can be redirected to internal array for AVI DHT
// tables, so check for it here.
if (m_bBufFakeDHT) {
return m_abMJPGDHTSeg[nOffset];
} else {
return m_pWBuf->Buf(nOffset,bClean);
}
}
// Write out a line to the log buffer if we are in verbose mode
//
// PRE:
// - m_bVerbose Verbose mode
//
// INPUT:
// - strLine String to output
//
// OUTPUT:
// - none
//
// POST:
// - m_pLog
//
// RETURN:
// - none
//
void CjfifDecode::DbgAddLine(LPCTSTR strLine)
{
if (m_bVerbose)
{
m_pLog->AddLine(strLine);
}
}
// Convert a UINT32 and decompose into 4 bytes, but support
// either endian byte-swap mode
//
// PRE:
// - m_nImgExifEndian Byte swap mode (0=little, 1=big)
//
// INPUT:
// - nVal Input UINT32
//
// OUTPUT:
// - nByte0 Byte #1
// - nByte1 Byte #2
// - nByte2 Byte #3
// - nByte3 Byte #4
//
// RETURN:
// - none
//
void CjfifDecode::UnByteSwap4(unsigned nVal,unsigned &nByte0,unsigned &nByte1,unsigned &nByte2,unsigned &nByte3)
{
if (m_nImgExifEndian == 0) {
// Little Endian
nByte3 = (nVal & 0xFF000000) >> 24;
nByte2 = (nVal & 0x00FF0000) >> 16;
nByte1 = (nVal & 0x0000FF00) >> 8;
nByte0 = (nVal & 0x000000FF);
} else {
// Big Endian
nByte0 = (nVal & 0xFF000000) >> 24;
nByte1 = (nVal & 0x00FF0000) >> 16;
nByte2 = (nVal & 0x0000FF00) >> 8;
nByte3 = (nVal & 0x000000FF);
}
}
// Perform conversion from 4 bytes into UINT32 with
// endian byte-swapping support
//
// PRE:
// - m_nImgExifEndian Byte swap mode (0=little, 1=big)
//
// INPUT:
// - nByte0 Byte #1
// - nByte1 Byte #2
// - nByte2 Byte #3
// - nByte3 Byte #4
//
// RETURN:
// - UINT32
//
unsigned CjfifDecode::ByteSwap4(unsigned nByte0,unsigned nByte1, unsigned nByte2, unsigned nByte3)
{
unsigned nVal;
if (m_nImgExifEndian == 0) {
// Little endian, byte swap required
nVal = (nByte3<<24) + (nByte2<<16) + (nByte1<<8) + nByte0;
} else {
// Big endian, no swap required
nVal = (nByte0<<24) + (nByte1<<16) + (nByte2<<8) + nByte3;
}
return nVal;
}
// Perform conversion from 2 bytes into half-word with
// endian byte-swapping support
//
// PRE:
// - m_nImgExifEndian Byte swap mode (0=little, 1=big)
//
// INPUT:
// - nByte0 Byte #1
// - nByte1 Byte #2
//
// RETURN:
// - UINT16
//
unsigned CjfifDecode::ByteSwap2(unsigned nByte0,unsigned nByte1)
{
unsigned nVal;
if (m_nImgExifEndian == 0) {
// Little endian, byte swap required
nVal = (nByte1<<8) + nByte0;
} else {
// Big endian, no swap required
nVal = (nByte0<<8) + nByte1;
}
return nVal;
}
// Decode Canon Makernotes
// Only the most common makernotes are supported; there are a large
// number of makernotes that have not been documented anywhere.
CStr2 CjfifDecode::LookupMakerCanonTag(unsigned nMainTag,unsigned nSubTag,unsigned nVal)
{
CString strTmp;
CStr2 sRetVal;
sRetVal.strTag = _T("???");
sRetVal.bUnknown = false; // Set to true in default clauses
sRetVal.strVal.Format(_T("%u"),nVal); // Provide default value
unsigned nValHi,nValLo;
nValHi = (nVal & 0xff00) >> 8;
nValLo = (nVal & 0x00ff);
switch(nMainTag)
{
case 0x0001:
switch(nSubTag)
{
case 0x0001: sRetVal.strTag = _T("Canon.Cs1.Macro");break; // Short Macro mode
case 0x0002: sRetVal.strTag = _T("Canon.Cs1.Selftimer");break; // Short Self timer
case 0x0003: sRetVal.strTag = _T("Canon.Cs1.Quality");
if (nVal == 2) { sRetVal.strVal = _T("norm"); }
else if (nVal == 3) { sRetVal.strVal = _T("fine"); }
else if (nVal == 5) { sRetVal.strVal = _T("superfine"); }
else {
sRetVal.strVal = _T("?");
}
// Save the quality string for later
m_strImgQualExif = sRetVal.strVal;
break; // Short Quality
case 0x0004: sRetVal.strTag = _T("Canon.Cs1.FlashMode");break; // Short Flash mode setting
case 0x0005: sRetVal.strTag = _T("Canon.Cs1.DriveMode");break; // Short Drive mode setting
case 0x0007: sRetVal.strTag = _T("Canon.Cs1.FocusMode"); // Short Focus mode setting
switch(nVal) {
case 0 : sRetVal.strVal = _T("One-shot");break;
case 1 : sRetVal.strVal = _T("AI Servo");break;
case 2 : sRetVal.strVal = _T("AI Focus");break;
case 3 : sRetVal.strVal = _T("Manual Focus");break;
case 4 : sRetVal.strVal = _T("Single");break;
case 5 : sRetVal.strVal = _T("Continuous");break;
case 6 : sRetVal.strVal = _T("Manual Focus");break;
default : sRetVal.strVal = _T("?");break;
}
break;
case 0x000a: sRetVal.strTag = _T("Canon.Cs1.ImageSize"); // Short Image size
if (nVal == 0) { sRetVal.strVal = _T("Large"); }
else if (nVal == 1) { sRetVal.strVal = _T("Medium"); }
else if (nVal == 2) { sRetVal.strVal = _T("Small"); }
else {
sRetVal.strVal = _T("?");
}
break;
case 0x000b: sRetVal.strTag = _T("Canon.Cs1.EasyMode");break; // Short Easy shooting mode
case 0x000c: sRetVal.strTag = _T("Canon.Cs1.DigitalZoom");break; // Short Digital zoom
case 0x000d: sRetVal.strTag = _T("Canon.Cs1.Contrast");break; // Short Contrast setting
case 0x000e: sRetVal.strTag = _T("Canon.Cs1.Saturation");break; // Short Saturation setting
case 0x000f: sRetVal.strTag = _T("Canon.Cs1.Sharpness");break; // Short Sharpness setting
case 0x0010: sRetVal.strTag = _T("Canon.Cs1.ISOSpeed");break; // Short ISO speed setting
case 0x0011: sRetVal.strTag = _T("Canon.Cs1.MeteringMode");break; // Short Metering mode setting
case 0x0012: sRetVal.strTag = _T("Canon.Cs1.FocusType");break; // Short Focus type setting
case 0x0013: sRetVal.strTag = _T("Canon.Cs1.AFPoint");break; // Short AF point selected
case 0x0014: sRetVal.strTag = _T("Canon.Cs1.ExposureProgram");break; // Short Exposure mode setting
case 0x0016: sRetVal.strTag = _T("Canon.Cs1.LensType");break; //
case 0x0017: sRetVal.strTag = _T("Canon.Cs1.Lens");break; // Short 'long' and 'short' focal length of lens (in 'focal m_nImgUnits') and 'focal m_nImgUnits' per mm
case 0x001a: sRetVal.strTag = _T("Canon.Cs1.MaxAperture");break; //
case 0x001b: sRetVal.strTag = _T("Canon.Cs1.MinAperture");break; //
case 0x001c: sRetVal.strTag = _T("Canon.Cs1.FlashActivity");break; // Short Flash activity
case 0x001d: sRetVal.strTag = _T("Canon.Cs1.FlashDetails");break; // Short Flash details
case 0x0020: sRetVal.strTag = _T("Canon.Cs1.FocusMode");break; // Short Focus mode setting
default:
sRetVal.strTag.Format(_T("Canon.Cs1.x%04X"),nSubTag);
sRetVal.bUnknown = true;
break;
} // switch nSubTag
break;
case 0x0004:
switch(nSubTag)
{
case 0x0002: sRetVal.strTag = _T("Canon.Cs2.ISOSpeed");break; // Short ISO speed used
case 0x0004: sRetVal.strTag = _T("Canon.Cs2.TargetAperture");break; // Short Target Aperture
case 0x0005: sRetVal.strTag = _T("Canon.Cs2.TargetShutterSpeed");break; // Short Target shutter speed
case 0x0007: sRetVal.strTag = _T("Canon.Cs2.WhiteBalance");break; // Short White balance setting
case 0x0009: sRetVal.strTag = _T("Canon.Cs2.Sequence");break; // Short Sequence number (if in a continuous burst)
case 0x000e: sRetVal.strTag = _T("Canon.Cs2.AFPointUsed");break; // Short AF point used
case 0x000f: sRetVal.strTag = _T("Canon.Cs2.FlashBias");break; // Short Flash bias
case 0x0013: sRetVal.strTag = _T("Canon.Cs2.SubjectDistance");break; // Short Subject distance (m_nImgUnits are not clear)
case 0x0015: sRetVal.strTag = _T("Canon.Cs2.ApertureValue");break; // Short Aperture
case 0x0016: sRetVal.strTag = _T("Canon.Cs2.ShutterSpeedValue");break; // Short Shutter speed
default:
sRetVal.strTag.Format(_T("Canon.Cs2.x%04X"),nSubTag);
sRetVal.bUnknown = true;
break;
} // switch nSubTag
break;
case 0x000F:
// CustomFunctions are different! Tag given by high byte, value by low
// Index order (usually the nSubTag) is not used.
sRetVal.strVal.Format(_T("%u"),nValLo); // Provide default value
switch(nValHi)
{
case 0x0001: sRetVal.strTag = _T("Canon.Cf.NoiseReduction");break; // Short Long exposure noise reduction
case 0x0002: sRetVal.strTag = _T("Canon.Cf.ShutterAeLock");break; // Short Shutter/AE lock buttons
case 0x0003: sRetVal.strTag = _T("Canon.Cf.MirrorLockup");break; // Short Mirror lockup
case 0x0004: sRetVal.strTag = _T("Canon.Cf.ExposureLevelIncrements");break; // Short Tv/Av and exposure level
case 0x0005: sRetVal.strTag = _T("Canon.Cf.AFAssist");break; // Short AF assist light
case 0x0006: sRetVal.strTag = _T("Canon.Cf.FlashSyncSpeedAv");break; // Short Shutter speed in Av mode
case 0x0007: sRetVal.strTag = _T("Canon.Cf.AEBSequence");break; // Short AEB sequence/auto cancellation
case 0x0008: sRetVal.strTag = _T("Canon.Cf.ShutterCurtainSync");break; // Short Shutter curtain sync
case 0x0009: sRetVal.strTag = _T("Canon.Cf.LensAFStopButton");break; // Short Lens AF stop button Fn. Switch
case 0x000a: sRetVal.strTag = _T("Canon.Cf.FillFlashAutoReduction");break; // Short Auto reduction of fill flash
case 0x000b: sRetVal.strTag = _T("Canon.Cf.MenuButtonReturn");break; // Short Menu button return position
case 0x000c: sRetVal.strTag = _T("Canon.Cf.SetButtonFunction");break; // Short SET button func. when shooting
case 0x000d: sRetVal.strTag = _T("Canon.Cf.SensorCleaning");break; // Short Sensor cleaning
case 0x000e: sRetVal.strTag = _T("Canon.Cf.SuperimposedDisplay");break; // Short Superimposed display
case 0x000f: sRetVal.strTag = _T("Canon.Cf.ShutterReleaseNoCFCard");break; // Short Shutter Release W/O CF Card
default:
sRetVal.strTag.Format(_T("Canon.Cf.x%04X"),nValHi);
sRetVal.bUnknown = true;
break;
} // switch nSubTag
break;
/*
// Other ones assumed to use high-byte/low-byte method:
case 0x00C0:
sRetVal.strVal.Format(_T("%u"),nValLo); // Provide default value
switch(nValHi)
{
//case 0x0001: sRetVal.strTag = _T("Canon.x00C0.???");break; //
default:
sRetVal.strTag.Format(_T("Canon.x00C0.x%04X"),nValHi);
break;
}
break;
case 0x00C1:
sRetVal.strVal.Format(_T("%u"),nValLo); // Provide default value
switch(nValHi)
{
//case 0x0001: sRetVal.strTag = _T("Canon.x00C1.???");break; //
default:
sRetVal.strTag.Format(_T("Canon.x00C1.x%04X"),nValHi);
break;
}
break;
*/
case 0x0012:
switch(nSubTag)
{
case 0x0002: sRetVal.strTag = _T("Canon.Pi.ImageWidth");break; //
case 0x0003: sRetVal.strTag = _T("Canon.Pi.ImageHeight");break; //
case 0x0004: sRetVal.strTag = _T("Canon.Pi.ImageWidthAsShot");break; //
case 0x0005: sRetVal.strTag = _T("Canon.Pi.ImageHeightAsShot");break; //
case 0x0016: sRetVal.strTag = _T("Canon.Pi.AFPointsUsed");break; //
case 0x001a: sRetVal.strTag = _T("Canon.Pi.AFPointsUsed20D");break; //
default:
sRetVal.strTag.Format(_T("Canon.Pi.x%04X"),nSubTag);
sRetVal.bUnknown = true;
break;
} // switch nSubTag
break;
default:
sRetVal.strTag.Format(_T("Canon.x%04X.x%04X"),nMainTag,nSubTag);
sRetVal.bUnknown = true;
break;
} // switch mainTag
return sRetVal;
}
// Perform decode of EXIF IFD tags including MakerNote tags
//
// PRE:
// - m_strImgExifMake Used for MakerNote decode
//
// INPUT:
// - strSect IFD section
// - nTag Tag code value
//
// OUTPUT:
// - bUnknown Was the tag unknown?
//
// RETURN:
// - Formatted string
//
CString CjfifDecode::LookupExifTag(CString strSect,unsigned nTag,bool &bUnknown)
{
CString strTmp;
bUnknown = false;
if (strSect == _T("IFD0"))
{
switch(nTag)
{
case 0x010E: return _T("ImageDescription");break; // ascii string Describes image
case 0x010F: return _T("Make");break; // ascii string Shows manufacturer of digicam
case 0x0110: return _T("Model");break; // ascii string Shows model number of digicam
case 0x0112: return _T("Orientation");break; // unsigned short 1 The orientation of the camera relative to the scene, when the image was captured. The start point of stored data is, '1' means upper left, '3' lower right, '6' upper right, '8' lower left, '9' undefined.
case 0x011A: return _T("XResolution");break; // unsigned rational 1 Display/Print resolution of image. Large number of digicam uses 1/72inch, but it has no mean because personal computer doesn't use this value to display/print out.
case 0x011B: return _T("YResolution");break; // unsigned rational 1
case 0x0128: return _T("ResolutionUnit");break; // unsigned short 1 Unit of XResolution(0x011a)/YResolution(0x011b). '1' means no-unit, '2' means inch, '3' means centimeter.
case 0x0131: return _T("Software");break; // ascii string Shows firmware(internal software of digicam) version number.
case 0x0132: return _T("DateTime");break; // ascii string 20 Date/Time of image was last modified. Data format is "YYYY:MM:DD HH:MM:SS"+0x00, total 20bytes. In usual, it has the same value of DateTimeOriginal(0x9003)
case 0x013B: return _T("Artist");break; // Seems to be here and not only in SubIFD (maybe instead of SubIFD)
case 0x013E: return _T("WhitePoint");break; // unsigned rational 2 Defines chromaticity of white point of the image. If the image uses CIE Standard Illumination D65(known as international standard of 'daylight'), the values are '3127/10000,3290/10000'.
case 0x013F: return _T("PrimChromaticities");break; // unsigned rational 6 Defines chromaticity of the primaries of the image. If the image uses CCIR Recommendation 709 primearies, values are '640/1000,330/1000,300/1000,600/1000,150/1000,0/1000'.
case 0x0211: return _T("YCbCrCoefficients");break; // unsigned rational 3 When image format is YCbCr, this value shows a constant to translate it to RGB format. In usual, values are '0.299/0.587/0.114'.
case 0x0213: return _T("YCbCrPositioning");break; // unsigned short 1 When image format is YCbCr and uses 'Subsampling'(cropping of chroma data, all the digicam do that), defines the chroma sample point of subsampling pixel array. '1' means the center of pixel array, '2' means the datum point.
case 0x0214: return _T("ReferenceBlackWhite");break; // unsigned rational 6 Shows reference value of black point/white point. In case of YCbCr format, first 2 show black/white of Y, next 2 are Cb, last 2 are Cr. In case of RGB format, first 2 show black/white of R, next 2 are G, last 2 are B.
case 0x8298: return _T("Copyright");break; // ascii string Shows copyright information
case 0x8769: return _T("ExifOffset");break; //unsigned long 1 Offset to Exif Sub IFD
case 0x8825: return _T("GPSOffset");break; //unsigned long 1 Offset to Exif GPS IFD
//NEW:
case 0x9C9B: return _T("XPTitle");break;
case 0x9C9C: return _T("XPComment");break;
case 0x9C9D: return _T("XPAuthor");break;
case 0x9C9e: return _T("XPKeywords");break;
case 0x9C9f: return _T("XPSubject");break;
//NEW: The following were found in IFD0 even though they should just be SubIFD?
case 0xA401: return _T("CustomRendered");break;
case 0xA402: return _T("ExposureMode");break;
case 0xA403: return _T("WhiteBalance");break;
case 0xA406: return _T("SceneCaptureType");break;
default:
strTmp.Format(_T("IFD0.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} else if (strSect == _T("SubIFD")) {
switch(nTag)
{
case 0x00fe: return _T("NewSubfileType");break; // unsigned long 1
case 0x00ff: return _T("SubfileType");break; // unsigned short 1
case 0x012d: return _T("TransferFunction");break; // unsigned short 3
case 0x013b: return _T("Artist");break; // ascii string
case 0x013d: return _T("Predictor");break; // unsigned short 1
case 0x0142: return _T("TileWidth");break; // unsigned short 1
case 0x0143: return _T("TileLength");break; // unsigned short 1
case 0x0144: return _T("TileOffsets");break; // unsigned long
case 0x0145: return _T("TileByteCounts");break; // unsigned short
case 0x014a: return _T("SubIFDs");break; // unsigned long
case 0x015b: return _T("JPEGTables");break; // undefined
case 0x828d: return _T("CFARepeatPatternDim");break; // unsigned short 2
case 0x828e: return _T("CFAPattern");break; // unsigned byte
case 0x828f: return _T("BatteryLevel");break; // unsigned rational 1
case 0x829A: return _T("ExposureTime");break;
case 0x829D: return _T("FNumber");break;
case 0x83bb: return _T("IPTC/NAA");break; // unsigned long
case 0x8773: return _T("InterColorProfile");break; // undefined
case 0x8822: return _T("ExposureProgram");break;
case 0x8824: return _T("SpectralSensitivity");break; // ascii string
case 0x8825: return _T("GPSInfo");break; // unsigned long 1
case 0x8827: return _T("ISOSpeedRatings");break;
case 0x8828: return _T("OECF");break; // undefined
case 0x8829: return _T("Interlace");break; // unsigned short 1
case 0x882a: return _T("TimeZoneOffset");break; // signed short 1
case 0x882b: return _T("SelfTimerMode");break; // unsigned short 1
case 0x9000: return _T("ExifVersion");break;
case 0x9003: return _T("DateTimeOriginal");break;
case 0x9004: return _T("DateTimeDigitized");break;
case 0x9101: return _T("ComponentsConfiguration");break;
case 0x9102: return _T("CompressedBitsPerPixel");break;
case 0x9201: return _T("ShutterSpeedValue");break;
case 0x9202: return _T("ApertureValue");break;
case 0x9203: return _T("BrightnessValue");break;
case 0x9204: return _T("ExposureBiasValue");break;
case 0x9205: return _T("MaxApertureValue");break;
case 0x9206: return _T("SubjectDistance");break;
case 0x9207: return _T("MeteringMode");break;
case 0x9208: return _T("LightSource");break;
case 0x9209: return _T("Flash");break;
case 0x920A: return _T("FocalLength");break;
case 0x920b: return _T("FlashEnergy");break; // unsigned rational 1
case 0x920c: return _T("SpatialFrequencyResponse");break; // undefined
case 0x920d: return _T("Noise");break; // undefined
case 0x9211: return _T("ImageNumber");break; // unsigned long 1
case 0x9212: return _T("SecurityClassification");break; // ascii string 1
case 0x9213: return _T("ImageHistory");break; // ascii string
case 0x9214: return _T("SubjectLocation");break; // unsigned short 4
case 0x9215: return _T("ExposureIndex");break; // unsigned rational 1
case 0x9216: return _T("TIFF/EPStandardID");break; // unsigned byte 4
case 0x927C: return _T("MakerNote");break;
case 0x9286: return _T("UserComment");break;
case 0x9290: return _T("SubSecTime");break; // ascii string
case 0x9291: return _T("SubSecTimeOriginal");break; // ascii string
case 0x9292: return _T("SubSecTimeDigitized");break; // ascii string
case 0xA000: return _T("FlashPixVersion");break;
case 0xA001: return _T("ColorSpace");break;
case 0xA002: return _T("ExifImageWidth");break;
case 0xA003: return _T("ExifImageHeight");break;
case 0xA004: return _T("RelatedSoundFile");break;
case 0xA005: return _T("ExifInteroperabilityOffset");break;
case 0xa20b: return _T("FlashEnergy unsigned");break; // rational 1
case 0xa20c: return _T("SpatialFrequencyResponse");break; // unsigned short 1
case 0xA20E: return _T("FocalPlaneXResolution");break;
case 0xA20F: return _T("FocalPlaneYResolution");break;
case 0xA210: return _T("FocalPlaneResolutionUnit");break;
case 0xa214: return _T("SubjectLocation");break; // unsigned short 1
case 0xa215: return _T("ExposureIndex");break; // unsigned rational 1
case 0xA217: return _T("SensingMethod");break;
case 0xA300: return _T("FileSource");break;
case 0xA301: return _T("SceneType");break;
case 0xa302: return _T("CFAPattern");break; // undefined 1
case 0xa401: return _T("CustomRendered");break; // Short Custom image processing
case 0xa402: return _T("ExposureMode");break; // Short Exposure mode
case 0xa403: return _T("WhiteBalance");break; // Short White balance
case 0xa404: return _T("DigitalZoomRatio");break; // Rational Digital zoom ratio
case 0xa405: return _T("FocalLengthIn35mmFilm");break; // Short Focal length in 35 mm film
case 0xa406: return _T("SceneCaptureType");break; // Short Scene capture type
case 0xa407: return _T("GainControl");break; // Rational Gain control
case 0xa408: return _T("Contrast");break; // Short Contrast
case 0xa409: return _T("Saturation");break; // Short Saturation
case 0xa40a: return _T("Sharpness");break; // Short Sharpness
case 0xa40b: return _T("DeviceSettingDescription");break; // Undefined Device settings description
case 0xa40c: return _T("SubjectDistanceRange");break; // Short Subject distance range
case 0xa420: return _T("ImageUniqueID");break; // Ascii Unique image ID
default:
strTmp.Format(_T("SubIFD.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} else if (strSect == _T("IFD1")) {
switch(nTag)
{
case 0x0100: return _T("ImageWidth");break; // unsigned short/long 1 Shows size of thumbnail image.
case 0x0101: return _T("ImageLength");break; // unsigned short/long 1
case 0x0102: return _T("BitsPerSample");break; // unsigned short 3 When image format is no compression, this value shows the number of bits per component for each pixel. Usually this value is '8,8,8'
case 0x0103: return _T("Compression");break; // unsigned short 1 Shows compression method. '1' means no compression, '6' means JPEG compression.
case 0x0106: return _T("PhotometricInterpretation");break; // unsigned short 1 Shows the color space of the image data components. '1' means monochrome, '2' means RGB, '6' means YCbCr.
case 0x0111: return _T("StripOffsets");break; // unsigned short/long When image format is no compression, this value shows offset to image data. In some case image data is striped and this value is plural.
case 0x0115: return _T("SamplesPerPixel");break; // unsigned short 1 When image format is no compression, this value shows the number of components stored for each pixel. At color image, this value is '3'.
case 0x0116: return _T("RowsPerStrip");break; // unsigned short/long 1 When image format is no compression and image has stored as strip, this value shows how many rows stored to each strip. If image has not striped, this value is the same as ImageLength(0x0101).
case 0x0117: return _T("StripByteConunts");break; // unsigned short/long When image format is no compression and stored as strip, this value shows how many bytes used for each strip and this value is plural. If image has not stripped, this value is single and means whole data size of image.
case 0x011a: return _T("XResolution");break; // unsigned rational 1 Display/Print resolution of image. Large number of digicam uses 1/72inch, but it has no mean because personal computer doesn't use this value to display/print out.
case 0x011b: return _T("YResolution");break; // unsigned rational 1
case 0x011c: return _T("PlanarConfiguration");break; // unsigned short 1 When image format is no compression YCbCr, this value shows byte aligns of YCbCr data. If value is '1', Y/Cb/Cr value is chunky format, contiguous for each subsampling pixel. If value is '2', Y/Cb/Cr value is separated and stored to Y plane/Cb plane/Cr plane format.
case 0x0128: return _T("ResolutionUnit");break; // unsigned short 1 Unit of XResolution(0x011a)/YResolution(0x011b). '1' means inch, '2' means centimeter.
case 0x0201: return _T("JpegIFOffset");break; // unsigned long 1 When image format is JPEG, this value show offset to JPEG data stored.
case 0x0202: return _T("JpegIFByteCount");break; // unsigned long 1 When image format is JPEG, this value shows data size of JPEG image.
case 0x0211: return _T("YCbCrCoefficients");break; // unsigned rational 3 When image format is YCbCr, this value shows constants to translate it to RGB format. In usual, '0.299/0.587/0.114' are used.
case 0x0212: return _T("YCbCrSubSampling");break; // unsigned short 2 When image format is YCbCr and uses subsampling(cropping of chroma data, all the digicam do that), this value shows how many chroma data subsampled. First value shows horizontal, next value shows vertical subsample rate.
case 0x0213: return _T("YCbCrPositioning");break; // unsigned short 1 When image format is YCbCr and uses 'Subsampling'(cropping of chroma data, all the digicam do that), this value defines the chroma sample point of subsampled pixel array. '1' means the center of pixel array, '2' means the datum point(0,0).
case 0x0214: return _T("ReferenceBlackWhite");break; // unsigned rational 6 Shows reference value of black point/white point. In case of YCbCr format, first 2 show black/white of Y, next 2 are Cb, last 2 are Cr. In case of RGB format, first 2 show black/white of R, next 2 are G, last 2 are B.
default:
strTmp.Format(_T("IFD1.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} else if (strSect == _T("InteropIFD")) {
switch(nTag) {
case 0x0001: return _T("InteroperabilityIndex");break;
case 0x0002: return _T("InteroperabilityVersion");break;
case 0x1000: return _T("RelatedImageFileFormat");break;
case 0x1001: return _T("RelatedImageWidth");break;
case 0x1002: return _T("RelatedImageLength");break;
default:
strTmp.Format(_T("Interop.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} else if (strSect == _T("GPSIFD")) {
switch(nTag) {
case 0x0000: return _T("GPSVersionID");break;
case 0x0001: return _T("GPSLatitudeRef");break;
case 0x0002: return _T("GPSLatitude");break;
case 0x0003: return _T("GPSLongitudeRef");break;
case 0x0004: return _T("GPSLongitude");break;
case 0x0005: return _T("GPSAltitudeRef");break;
case 0x0006: return _T("GPSAltitude");break;
case 0x0007: return _T("GPSTimeStamp");break;
case 0x0008: return _T("GPSSatellites");break;
case 0x0009: return _T("GPSStatus");break;
case 0x000A: return _T("GPSMeasureMode");break;
case 0x000B: return _T("GPSDOP");break;
case 0x000C: return _T("GPSSpeedRef");break;
case 0x000D: return _T("GPSSpeed");break;
case 0x000E: return _T("GPSTrackRef");break;
case 0x000F: return _T("GPSTrack");break;
case 0x0010: return _T("GPSImgDirectionRef");break;
case 0x0011: return _T("GPSImgDirection");break;
case 0x0012: return _T("GPSMapDatum");break;
case 0x0013: return _T("GPSDestLatitudeRef");break;
case 0x0014: return _T("GPSDestLatitude");break;
case 0x0015: return _T("GPSDestLongitudeRef");break;
case 0x0016: return _T("GPSDestLongitude");break;
case 0x0017: return _T("GPSDestBearingRef");break;
case 0x0018: return _T("GPSDestBearing");break;
case 0x0019: return _T("GPSDestDistanceRef");break;
case 0x001A: return _T("GPSDestDistance");break;
case 0x001B: return _T("GPSProcessingMethod");break;
case 0x001C: return _T("GPSAreaInformation");break;
case 0x001D: return _T("GPSDateStamp");break;
case 0x001E: return _T("GPSDifferential");break;
default:
strTmp.Format(_T("GPS.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} else if (strSect == _T("MakerIFD")) {
// Makernotes need special handling
// We only support a few different manufacturers for makernotes.
// A few Canon tags are supported in this routine, the rest are
// handled by the LookupMakerCanonTag() call.
if (m_strImgExifMake == _T("Canon")) {
switch(nTag)
{
case 0x0001: return _T("Canon.CameraSettings1");break;
case 0x0004: return _T("Canon.CameraSettings2");break;
case 0x0006: return _T("Canon.ImageType");break;
case 0x0007: return _T("Canon.FirmwareVersion");break;
case 0x0008: return _T("Canon.ImageNumber");break;
case 0x0009: return _T("Canon.OwnerName");break;
case 0x000C: return _T("Canon.SerialNumber");break;
case 0x000F: return _T("Canon.CustomFunctions");break;
case 0x0012: return _T("Canon.PictureInfo");break;
case 0x00A9: return _T("Canon.WhiteBalanceTable");break;
default:
strTmp.Format(_T("Canon.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} // Canon
else if (m_strImgExifMake == _T("SIGMA"))
{
switch(nTag)
{
case 0x0002: return _T("Sigma.SerialNumber");break; // Ascii Camera serial number
case 0x0003: return _T("Sigma.DriveMode");break; // Ascii Drive Mode
case 0x0004: return _T("Sigma.ResolutionMode");break; // Ascii Resolution Mode
case 0x0005: return _T("Sigma.AutofocusMode");break; // Ascii Autofocus mode
case 0x0006: return _T("Sigma.FocusSetting");break; // Ascii Focus setting
case 0x0007: return _T("Sigma.WhiteBalance");break; // Ascii White balance
case 0x0008: return _T("Sigma.ExposureMode");break; // Ascii Exposure mode
case 0x0009: return _T("Sigma.MeteringMode");break; // Ascii Metering mode
case 0x000a: return _T("Sigma.LensRange");break; // Ascii Lens focal length range
case 0x000b: return _T("Sigma.ColorSpace");break; // Ascii Color space
case 0x000c: return _T("Sigma.Exposure");break; // Ascii Exposure
case 0x000d: return _T("Sigma.Contrast");break; // Ascii Contrast
case 0x000e: return _T("Sigma.Shadow");break; // Ascii Shadow
case 0x000f: return _T("Sigma.Highlight");break; // Ascii Highlight
case 0x0010: return _T("Sigma.Saturation");break; // Ascii Saturation
case 0x0011: return _T("Sigma.Sharpness");break; // Ascii Sharpness
case 0x0012: return _T("Sigma.FillLight");break; // Ascii X3 Fill light
case 0x0014: return _T("Sigma.ColorAdjustment");break; // Ascii Color adjustment
case 0x0015: return _T("Sigma.AdjustmentMode");break; // Ascii Adjustment mode
case 0x0016: return _T("Sigma.Quality");break; // Ascii Quality
case 0x0017: return _T("Sigma.Firmware");break; // Ascii Firmware
case 0x0018: return _T("Sigma.Software");break; // Ascii Software
case 0x0019: return _T("Sigma.AutoBracket");break; // Ascii Auto bracket
default:
strTmp.Format(_T("Sigma.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} // SIGMA
else if (m_strImgExifMake == _T("SONY"))
{
switch(nTag)
{
case 0xb021: return _T("Sony.ColorTemperature");break;
case 0xb023: return _T("Sony.SceneMode");break;
case 0xb024: return _T("Sony.ZoneMatching");break;
case 0xb025: return _T("Sony.DynamicRangeOptimizer");break;
case 0xb026: return _T("Sony.ImageStabilization");break;
case 0xb027: return _T("Sony.LensID");break;
case 0xb029: return _T("Sony.ColorMode");break;
case 0xb040: return _T("Sony.Macro");break;
case 0xb041: return _T("Sony.ExposureMode");break;
case 0xb047: return _T("Sony.Quality");break;
case 0xb04e: return _T("Sony.LongExposureNoiseReduction");break;
default:
// No real info is known
strTmp.Format(_T("Sony.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} // SONY
else if (m_strImgExifMake == _T("FUJIFILM"))
{
switch(nTag)
{
case 0x0000: return _T("Fujifilm.Version");break; // Undefined Fujifilm Makernote version
case 0x1000: return _T("Fujifilm.Quality");break; // Ascii Image quality setting
case 0x1001: return _T("Fujifilm.Sharpness");break; // Short Sharpness setting
case 0x1002: return _T("Fujifilm.WhiteBalance");break; // Short White balance setting
case 0x1003: return _T("Fujifilm.Color");break; // Short Chroma saturation setting
case 0x1004: return _T("Fujifilm.Tone");break; // Short Contrast setting
case 0x1010: return _T("Fujifilm.FlashMode");break; // Short Flash firing mode setting
case 0x1011: return _T("Fujifilm.FlashStrength");break; // SRational Flash firing strength compensation setting
case 0x1020: return _T("Fujifilm.Macro");break; // Short Macro mode setting
case 0x1021: return _T("Fujifilm.FocusMode");break; // Short Focusing mode setting
case 0x1030: return _T("Fujifilm.SlowSync");break; // Short Slow synchro mode setting
case 0x1031: return _T("Fujifilm.PictureMode");break; // Short Picture mode setting
case 0x1100: return _T("Fujifilm.Continuous");break; // Short Continuous shooting or auto bracketing setting
case 0x1210: return _T("Fujifilm.FinePixColor");break; // Short Fuji FinePix Color setting
case 0x1300: return _T("Fujifilm.BlurWarning");break; // Short Blur warning status
case 0x1301: return _T("Fujifilm.FocusWarning");break; // Short Auto Focus warning status
case 0x1302: return _T("Fujifilm.AeWarning");break; // Short Auto Exposure warning status
default:
strTmp.Format(_T("Fujifilm.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
} // FUJIFILM
else if (m_strImgExifMake == _T("NIKON"))
{
if (m_nImgExifMakeSubtype == 1) {
// Type 1
switch(nTag)
{
case 0x0001: return _T("Nikon1.Version");break; // Undefined Nikon Makernote version
case 0x0002: return _T("Nikon1.ISOSpeed");break; // Short ISO speed setting
case 0x0003: return _T("Nikon1.ColorMode");break; // Ascii Color mode
case 0x0004: return _T("Nikon1.Quality");break; // Ascii Image quality setting
case 0x0005: return _T("Nikon1.WhiteBalance");break; // Ascii White balance
case 0x0006: return _T("Nikon1.Sharpening");break; // Ascii Image sharpening setting
case 0x0007: return _T("Nikon1.Focus");break; // Ascii Focus mode
case 0x0008: return _T("Nikon1.Flash");break; // Ascii Flash mode
case 0x000f: return _T("Nikon1.ISOSelection");break; // Ascii ISO selection
case 0x0010: return _T("Nikon1.DataDump");break; // Undefined Data dump
case 0x0080: return _T("Nikon1.ImageAdjustment");break; // Ascii Image adjustment setting
case 0x0082: return _T("Nikon1.Adapter");break; // Ascii Adapter used
case 0x0085: return _T("Nikon1.FocusDistance");break; // Rational Manual focus distance
case 0x0086: return _T("Nikon1.DigitalZoom");break; // Rational Digital zoom setting
case 0x0088: return _T("Nikon1.AFFocusPos");break; // Undefined AF focus position
default:
strTmp.Format(_T("Nikon1.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
}
else if (m_nImgExifMakeSubtype == 2)
{
// Type 2
switch(nTag)
{
case 0x0003: return _T("Nikon2.Quality");break; // Short Image quality setting
case 0x0004: return _T("Nikon2.ColorMode");break; // Short Color mode
case 0x0005: return _T("Nikon2.ImageAdjustment");break; // Short Image adjustment setting
case 0x0006: return _T("Nikon2.ISOSpeed");break; // Short ISO speed setting
case 0x0007: return _T("Nikon2.WhiteBalance");break; // Short White balance
case 0x0008: return _T("Nikon2.Focus");break; // Rational Focus mode
case 0x000a: return _T("Nikon2.DigitalZoom");break; // Rational Digital zoom setting
case 0x000b: return _T("Nikon2.Adapter");break; // Short Adapter used
default:
strTmp.Format(_T("Nikon2.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
}
else if (m_nImgExifMakeSubtype == 3)
{
// Type 3
switch(nTag)
{
case 0x0001: return _T("Nikon3.Version");break; // Undefined Nikon Makernote version
case 0x0002: return _T("Nikon3.ISOSpeed");break; // Short ISO speed used
case 0x0003: return _T("Nikon3.ColorMode");break; // Ascii Color mode
case 0x0004: return _T("Nikon3.Quality");break; // Ascii Image quality setting
case 0x0005: return _T("Nikon3.WhiteBalance");break; // Ascii White balance
case 0x0006: return _T("Nikon3.Sharpening");break; // Ascii Image sharpening setting
case 0x0007: return _T("Nikon3.Focus");break; // Ascii Focus mode
case 0x0008: return _T("Nikon3.FlashSetting");break; // Ascii Flash setting
case 0x0009: return _T("Nikon3.FlashMode");break; // Ascii Flash mode
case 0x000b: return _T("Nikon3.WhiteBalanceBias");break; // SShort White balance bias
case 0x000e: return _T("Nikon3.ExposureDiff");break; // Undefined Exposure difference
case 0x000f: return _T("Nikon3.ISOSelection");break; // Ascii ISO selection
case 0x0010: return _T("Nikon3.DataDump");break; // Undefined Data dump
case 0x0011: return _T("Nikon3.ThumbOffset");break; // Long Thumbnail IFD offset
case 0x0012: return _T("Nikon3.FlashComp");break; // Undefined Flash compensation setting
case 0x0013: return _T("Nikon3.ISOSetting");break; // Short ISO speed setting
case 0x0016: return _T("Nikon3.ImageBoundary");break; // Short Image boundry
case 0x0018: return _T("Nikon3.FlashBracketComp");break; // Undefined Flash bracket compensation applied
case 0x0019: return _T("Nikon3.ExposureBracketComp");break; // SRational AE bracket compensation applied
case 0x0080: return _T("Nikon3.ImageAdjustment");break; // Ascii Image adjustment setting
case 0x0081: return _T("Nikon3.ToneComp");break; // Ascii Tone compensation setting (contrast)
case 0x0082: return _T("Nikon3.AuxiliaryLens");break; // Ascii Auxiliary lens (adapter)
case 0x0083: return _T("Nikon3.LensType");break; // Byte Lens type
case 0x0084: return _T("Nikon3.Lens");break; // Rational Lens
case 0x0085: return _T("Nikon3.FocusDistance");break; // Rational Manual focus distance
case 0x0086: return _T("Nikon3.DigitalZoom");break; // Rational Digital zoom setting
case 0x0087: return _T("Nikon3.FlashType");break; // Byte Type of flash used
case 0x0088: return _T("Nikon3.AFFocusPos");break; // Undefined AF focus position
case 0x0089: return _T("Nikon3.Bracketing");break; // Short Bracketing
case 0x008b: return _T("Nikon3.LensFStops");break; // Undefined Number of lens stops
case 0x008c: return _T("Nikon3.ToneCurve");break; // Undefined Tone curve
case 0x008d: return _T("Nikon3.ColorMode");break; // Ascii Color mode
case 0x008f: return _T("Nikon3.SceneMode");break; // Ascii Scene mode
case 0x0090: return _T("Nikon3.LightingType");break; // Ascii Lighting type
case 0x0092: return _T("Nikon3.HueAdjustment");break; // SShort Hue adjustment
case 0x0094: return _T("Nikon3.Saturation");break; // SShort Saturation adjustment
case 0x0095: return _T("Nikon3.NoiseReduction");break; // Ascii Noise reduction
case 0x0096: return _T("Nikon3.CompressionCurve");break; // Undefined Compression curve
case 0x0097: return _T("Nikon3.ColorBalance2");break; // Undefined Color balance 2
case 0x0098: return _T("Nikon3.LensData");break; // Undefined Lens data
case 0x0099: return _T("Nikon3.NEFThumbnailSize");break; // Short NEF thumbnail size
case 0x009a: return _T("Nikon3.SensorPixelSize");break; // Rational Sensor pixel size
case 0x00a0: return _T("Nikon3.SerialNumber");break; // Ascii Camera serial number
case 0x00a7: return _T("Nikon3.ShutterCount");break; // Long Number of shots taken by camera
case 0x00a9: return _T("Nikon3.ImageOptimization");break; // Ascii Image optimization
case 0x00aa: return _T("Nikon3.Saturation");break; // Ascii Saturation
case 0x00ab: return _T("Nikon3.VariProgram");break; // Ascii Vari program
default:
strTmp.Format(_T("Nikon3.0x%04X"),nTag);
bUnknown = true;
return strTmp;
break;
}
}
} // NIKON
} // if strSect
bUnknown = true;
return _T("???");
}
// Interpret the MakerNote header to determine any applicable MakerNote subtype.
//
// PRE:
// - m_strImgExifMake
// - buffer
//
// INPUT:
// - none
//
// RETURN:
// - Decode success
//
// POST:
// - m_nImgExifMakeSubtype
//
bool CjfifDecode::DecodeMakerSubType()
{
CString strTmp;
m_nImgExifMakeSubtype = 0;
if (m_strImgExifMake == _T("NIKON"))
{
strTmp = _T("");
for (unsigned nInd=0;nInd<5;nInd++) {
strTmp += (char)Buf(m_nPos+nInd);
}
if (strTmp == _T("Nikon")) {
if (Buf(m_nPos+6) == 1) {
// Type 1
m_pLog->AddLine(_T(" Nikon Makernote Type 1 detected"));
m_nImgExifMakeSubtype = 1;
m_nPos += 8;
} else if (Buf(m_nPos+6) == 2) {
// Type 3
m_pLog->AddLine(_T(" Nikon Makernote Type 3 detected"));
m_nImgExifMakeSubtype = 3;
m_nPos += 18;
} else {
CString strTmp = _T("ERROR: Unknown Nikon Makernote Type");
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return FALSE;
}
} else {
// Type 2
m_pLog->AddLine(_T(" Nikon Makernote Type 2 detected"));
//m_nImgExifMakeSubtype = 2;
// tests on D1 seem to indicate that it uses Type 1 headers
m_nImgExifMakeSubtype = 1;
m_nPos += 0;
}
}
else if (m_strImgExifMake == _T("SIGMA"))
{
strTmp = _T("");
for (unsigned ind=0;ind<8;ind++) {
if (Buf(m_nPos+ind) != 0)
strTmp += (char)Buf(m_nPos+ind);
}
if ( (strTmp == _T("SIGMA")) ||
(strTmp == _T("FOVEON")) )
{
// Valid marker
// Now skip over the 8-chars and 2 unknown chars
m_nPos += 10;
} else {
CString strTmp = _T("ERROR: Unknown SIGMA Makernote identifier");
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return FALSE;
}
} // SIGMA
else if (m_strImgExifMake == _T("FUJIFILM"))
{
strTmp = _T("");
for (unsigned ind=0;ind<8;ind++) {
if (Buf(m_nPos+ind) != 0)
strTmp += (char)Buf(m_nPos+ind);
}
if (strTmp == _T("FUJIFILM"))
{
// Valid marker
// Now skip over the 8-chars and 4 Pointer chars
// FIXME: Do I need to dereference this pointer?
m_nPos += 12;
} else {
CString strTmp = _T("ERROR: Unknown FUJIFILM Makernote identifier");
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return FALSE;
}
} // FUJIFILM
else if (m_strImgExifMake == _T("SONY"))
{
strTmp = _T("");
for (unsigned ind=0;ind<12;ind++) {
if (Buf(m_nPos+ind) != 0)
strTmp += (char)Buf(m_nPos+ind);
}
if (strTmp == _T("SONY DSC "))
{
// Valid marker
// Now skip over the 9-chars and 3 null chars
m_nPos += 12;
} else {
CString strTmp = _T("ERROR: Unknown SONY Makernote identifier");
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return FALSE;
}
} // SONY
return TRUE;
}
// Read two UINT32 from the buffer (8B) and interpret
// as a rational entry. Convert to floating point.
// Byte swap as required
//
// INPUT:
// - pos Buffer position
// - val Floating point value
//
// RETURN:
// - Was the conversion successful?
//
bool CjfifDecode::DecodeValRational(unsigned nPos,float &nVal)
{
int nValNumer;
int nValDenom;
nVal = 0;
nValNumer = ByteSwap4(Buf(nPos+0),Buf(nPos+1),Buf(nPos+2),Buf(nPos+3));
nValDenom = ByteSwap4(Buf(nPos+4),Buf(nPos+5),Buf(nPos+6),Buf(nPos+7));
if (nValDenom == 0) {
// Divide by zero!
return false;
} else {
nVal = (float)nValNumer/(float)nValDenom;
return true;
}
}
// Read two UINT32 from the buffer (8B) to create a formatted
// fraction string. Byte swap as required
//
// INPUT:
// - pos Buffer position
//
// RETURN:
// - Formatted string
//
CString CjfifDecode::DecodeValFraction(unsigned nPos)
{
CString strTmp;
int nValNumer = ReadSwap4(nPos+0);
int nValDenom = ReadSwap4(nPos+4);
strTmp.Format(_T("%d/%d"),nValNumer,nValDenom);
return strTmp;
}
// Convert multiple coordinates into a formatted GPS string
//
// INPUT:
// - nCount Number of coordinates (1,2,3)
// - fCoord1 Coordinate #1
// - fCoord2 Coordinate #2
// - fCoord3 Coordinate #3
//
// OUTPUT:
// - strCoord The formatted GPS string
//
// RETURN:
// - Was the conversion successful?
//
bool CjfifDecode::PrintValGPS(unsigned nCount, float fCoord1, float fCoord2, float fCoord3,CString &strCoord)
{
float fTemp;
unsigned nCoordDeg;
unsigned nCoordMin;
float fCoordSec;
// TODO: Extend to support 1 & 2 coordinate GPS entries
if (nCount == 3) {
nCoordDeg = unsigned(fCoord1);
nCoordMin = unsigned(fCoord2);
if (fCoord3 == 0) {
fTemp = fCoord2 - (float)nCoordMin;
fCoordSec = fTemp * (float)60.0;
} else {
fCoordSec = fCoord3;
}
strCoord.Format(_T("%u deg %u' %.3f\""),nCoordDeg,nCoordMin,fCoordSec);
return true;
} else {
strCoord.Format(_T("ERROR: Can't handle %u-comonent GPS coords"),nCount);
return false;
}
}
// Read in 3 rational values from the buffer and output as a formatted GPS string
//
// INPUT:
// - pos Buffer position
//
// OUTPUT:
// - strCoord The formatted GPS string
//
// RETURN:
// - Was the conversion successful?
//
bool CjfifDecode::DecodeValGPS(unsigned nPos,CString &strCoord)
{
float fCoord1,fCoord2,fCoord3;
bool bRet;
bRet = true;
if (bRet) { bRet = DecodeValRational(nPos,fCoord1); nPos += 8; }
if (bRet) { bRet = DecodeValRational(nPos,fCoord2); nPos += 8; }
if (bRet) { bRet = DecodeValRational(nPos,fCoord3); nPos += 8; }
if (!bRet) {
strCoord.Format(_T("???"));
return false;
} else {
return PrintValGPS(3,fCoord1,fCoord2,fCoord3,strCoord);
}
}
// Read a UINT16 from the buffer, byte swap as required
//
// INPUT:
// - nPos Buffer position
//
// RETURN:
// - UINT16 from buffer
//
unsigned CjfifDecode::ReadSwap2(unsigned nPos)
{
return ByteSwap2(Buf(nPos+0),Buf(nPos+1));
}
// Read a UINT32 from the buffer, byte swap as required
//
// INPUT:
// - nPos Buffer position
//
// RETURN:
// - UINT32 from buffer
//
unsigned CjfifDecode::ReadSwap4(unsigned nPos)
{
return ByteSwap4(Buf(nPos),Buf(nPos+1),Buf(nPos+2),Buf(nPos+3));
}
// Read a UINT32 from the buffer, force as big endian
//
// INPUT:
// - nPos Buffer position
//
// RETURN:
// - UINT32 from buffer
//
unsigned CjfifDecode::ReadBe4(unsigned nPos)
{
// Big endian, no swap required
return (Buf(nPos)<<24) + (Buf(nPos+1)<<16) + (Buf(nPos+2)<<8) + Buf(nPos+3);
}
// Print hex from array of unsigned char
//
// INPUT:
// - anBytes Array of unsigned chars
// - nCount Indicates the number of array entries originally specified
// but the printing routine limits it to the maximum array depth
// allocated (MAX_anValues) and add an ellipsis "..."
// RETURN:
// - A formatted string
//
CString CjfifDecode::PrintAsHexUC(unsigned char* anBytes,unsigned nCount)
{
CString strVal;
CString strFull;
strFull = _T("0x[");
unsigned nMaxDisplay = MAX_anValues;
bool bExceedMaxDisplay;
bExceedMaxDisplay = (nCount > nMaxDisplay);
for (unsigned nInd=0;nInd<nCount;nInd++)
{
if (nInd < nMaxDisplay) {
if ((nInd % 4) == 0) {
if (nInd == 0) {
// Don't do anything for first value!
} else {
// Every 16 add big spacer / break
strFull += _T(" ");
}
} else {
//strFull += _T(" ");
}
strVal.Format(_T("%02X"),anBytes[nInd]);
strFull += strVal;
}
if ((nInd == nMaxDisplay) && (bExceedMaxDisplay)) {
strFull += _T("...");
}
}
strFull += _T("]");
return strFull;
}
// Print hex from array of unsigned bytes
//
// INPUT:
// - anBytes Array is passed as UINT32* even though it only
// represents a byte per entry
// - nCount Indicates the number of array entries originally specified
// but the printing routine limits it to the maximum array depth
// allocated (MAX_anValues) and add an ellipsis "..."
//
// RETURN:
// - A formatted string
//
CString CjfifDecode::PrintAsHex8(unsigned* anBytes,unsigned nCount)
{
CString strVal;
CString strFull;
unsigned nMaxDisplay = MAX_anValues;
bool bExceedMaxDisplay;
strFull = _T("0x[");
bExceedMaxDisplay = (nCount > nMaxDisplay);
for (unsigned nInd=0;nInd<nCount;nInd++)
{
if (nInd < nMaxDisplay) {
if ((nInd % 4) == 0) {
if (nInd == 0) {
// Don't do anything for first value!
} else {
// Every 16 add big spacer / break
strFull += _T(" ");
}
}
strVal.Format(_T("%02X"),anBytes[nInd]);
strFull += strVal;
}
if ((nInd == nMaxDisplay) && (bExceedMaxDisplay)) {
strFull += _T("...");
}
}
strFull += _T("]");
return strFull;
}
// Print hex from array of unsigned words
//
// INPUT:
// - anWords Array of UINT32 is passed
// - nCount Indicates the number of array entries originally specified
// but the printing routine limits it to the maximum array depth
// allocated (MAX_anValues) and add an ellipsis "..."
//
// RETURN:
// - A formatted string
//
CString CjfifDecode::PrintAsHex32(unsigned* anWords,unsigned nCount)
{
CString strVal;
CString strFull;
strFull = _T("0x[");
unsigned nMaxDisplay = MAX_anValues/4; // Reduce number of words to display since each is 32b not 8b
bool bExceedMaxDisplay;
bExceedMaxDisplay = (nCount > nMaxDisplay);
for (unsigned nInd=0;nInd<nCount;nInd++)
{
if (nInd < nMaxDisplay) {
if (nInd == 0) {
// Don't do anything for first value!
} else {
// Every word add a spacer
strFull += _T(" ");
}
strVal.Format(_T("%08X"),anWords[nInd]); // 32-bit words
strFull += strVal;
}
if ((nInd == nMaxDisplay) && (bExceedMaxDisplay)) {
strFull += _T("...");
}
}
strFull += _T("]");
return strFull;
}
// Process all of the entries within an EXIF IFD directory
// This is used for the main EXIF IFDs as well as MakerNotes
//
// INPUT:
// - ifdStr The IFD section that we are processing
// - pos_exif_start
// - start_ifd_ptr
//
// PRE:
// - m_strImgExifMake
// - m_bImgExifMakeSupported
// - m_nImgExifMakeSubtype
// - m_nImgExifMakerPtr
//
// RETURN:
// - 0 Decoding OK
// - 2 Decoding failure
//
// POST:
// - m_nPos
// - m_strImgExifMake
// - m_strImgExifModel
// - m_strImgQualExif
// - m_strImgExtras
// - m_strImgExifMake
// - m_nImgExifSubIfdPtr
// - m_nImgExifGpsIfdPtr
// - m_nImgExifInteropIfdPtr
// - m_bImgExifMakeSupported
// - m_bImgExifMakernotes
// - m_nImgExifMakerPtr
// - m_nImgExifThumbComp
// - m_nImgExifThumbOffset
// - m_nImgExifThumbLen
// - m_strSoftware
//
// NOTE:
// - IFD1 typically contains the thumbnail
//
unsigned CjfifDecode::DecodeExifIfd(CString strIfd,unsigned nPosExifStart,unsigned nStartIfdPtr)
{
// Temp variables
bool bRet;
CString strTmp;
CStr2 strRetVal;
CString strValTmp;
float fValReal;
CString strMaker;
// Display output variables
CString strFull;
CString strValOut;
BOOL bExtraDecode;
// Primary IFD variables
char acIfdValOffsetStr[5];
unsigned nIfdDirLen;
unsigned nIfdTagVal;
unsigned nIfdFormat;
unsigned nIfdNumComps;
bool nIfdTagUnknown;
unsigned nCompsToDisplay; // Maximum number of values to capture for display
unsigned anValues[MAX_anValues]; // Array of decoded values (Uint32)
signed anValuesS[MAX_anValues]; // Array of decoded values (Int32)
float afValues[MAX_anValues]; // Array of decoded values (float)
unsigned nIfdOffset; // First DWORD decode, usually offset
// Clear values array
for (unsigned ind=0;ind<MAX_anValues;ind++) {
anValues[ind] = 0;
anValuesS[ind] = 0;
afValues[ind] = 0;
}
// ==========================================================================
// Process IFD directory header
// ==========================================================================
// Move the file pointer to the start of the IFD
m_nPos = nPosExifStart+nStartIfdPtr;
strTmp.Format(_T(" EXIF %s @ Absolute 0x%08X"),(LPCTSTR)strIfd,m_nPos);
m_pLog->AddLine(strTmp);
////////////
// NOTE: Nikon type 3 starts out with the ASCII string "Nikon\0"
// before the rest of the items.
// TODO: need to process type1,type2,type3
// see: http://www.gvsoft.homedns.org/exif/makernote-nikon.html
strTmp.Format(_T("strIfd=[%s] m_strImgExifMake=[%s]"),(LPCTSTR)strIfd,(LPCTSTR)m_strImgExifMake);
DbgAddLine(strTmp);
// If this is the MakerNotes section, then we may want to skip
// altogether. Check to see if we are configured to process this
// section or if it is a supported manufacturer.
if (strIfd == _T("MakerIFD"))
{
// Mark the image as containing Makernotes
m_bImgExifMakernotes = true;
if (!m_pAppConfig->bDecodeMaker) {
strTmp.Format(_T(" Makernote decode option not enabled."));
m_pLog->AddLine(strTmp);
// If user didn't enable makernote decode, don't exit, just
// hide output. We still want to get at some info (such as Quality setting).
// At end, we'll need to re-enable it again.
m_pLog->Disable();
}
// If this Make is not supported, we'll need to exit
if (!m_bImgExifMakeSupported) {
strTmp.Format(_T(" Makernotes not yet supported for [%s]"),(LPCTSTR)m_strImgExifMake);
m_pLog->AddLine(strTmp);
m_pLog->Enable();
return 2;
}
// Determine the sub-type of the Maker field (if applicable)
// and advance the m_nPos pointer past the custom header.
// This call uses the class members: Buf(),m_nPos
if (!DecodeMakerSubType())
{
// If the subtype decode failed, skip the processing
m_pLog->Enable();
return 2;
}
}
// ==========================================================================
// Process IFD directory entries
// ==========================================================================
CString strIfdTag;
// =========== EXIF IFD Header (Start) ===========
// - Defined in Exif 2.2 Standard (JEITA CP-3451) section 4.6.2
// - Contents (2 bytes total)
// - Number of fields (2 bytes)
nIfdDirLen = ReadSwap2(m_nPos);
m_nPos+=2;
strTmp.Format(_T(" Dir Length = 0x%04X"),nIfdDirLen);
m_pLog->AddLine(strTmp);
// =========== EXIF IFD Header (End) ===========
// Start of IFD processing
// Step through each IFD entry and determine the type and
// decode accordingly.
for (unsigned nIfdEntryInd=0;nIfdEntryInd<nIfdDirLen;nIfdEntryInd++)
{
// By default, show single-line value summary
// bExtraDecode is used to indicate that additional special
// parsing output is available for this entry
bExtraDecode = FALSE;
strTmp.Format(_T(" Entry #%02u:"),nIfdEntryInd);
DbgAddLine(strTmp);
// =========== EXIF IFD Interoperability entry (Start) ===========
// - Defined in Exif 2.2 Standard (JEITA CP-3451) section 4.6.2
// - Contents (12 bytes total)
// - Tag (2 bytes)
// - Type (2 bytes)
// - Count (4 bytes)
// - Value Offset (4 bytes)
// Read Tag #
nIfdTagVal = ReadSwap2(m_nPos);
m_nPos+=2;
nIfdTagUnknown = false;
strIfdTag = LookupExifTag(strIfd,nIfdTagVal,nIfdTagUnknown);
strTmp.Format(_T(" Tag # = 0x%04X = [%s]"),nIfdTagVal,(LPCTSTR)strIfdTag);
DbgAddLine(strTmp);
// Read Format (or Type)
nIfdFormat = ReadSwap2(m_nPos);
m_nPos+=2;
strTmp.Format(_T(" Format # = 0x%04X"),nIfdFormat);
DbgAddLine(strTmp);
// Read number of Components
nIfdNumComps = ReadSwap4(m_nPos);
m_nPos+=4;
strTmp.Format(_T(" # Comps = 0x%08X"),nIfdNumComps);
DbgAddLine(strTmp);
// Check to see how many components have been listed.
// This helps trap errors in corrupted IFD segments, otherwise
// we will hang trying to decode millions of entries!
// See issue & testcase #1148
if (nIfdNumComps > 4000) {
// Warn user that we have clippped the component list.
// Note that this condition is only relevant when we are
// processing the general array fields. Fields such as MakerNote
// will also enter this condition so we shouldn't warn in those cases.
//
// TODO: Defer this warning message until after we are sure that we
// didn't handle the large dataset elsewhere.
// For now, only report this warning if we are not processing MakerNote
if (strIfdTag.Compare(_T("MakerNote"))!=0) {
strTmp.Format(_T(" Excessive # components (%u). Limiting to first 4000."),nIfdNumComps);
m_pLog->AddLineWarn(strTmp);
}
nIfdNumComps = 4000;
}
// Read Component Value / Offset
// We first treat it as a string and then re-interpret it as an integer
// ... first as a string (just in case length <=4)
for (unsigned i=0;i<4;i++) {
acIfdValOffsetStr[i] = (char)Buf(m_nPos+i);
}
acIfdValOffsetStr[4] = '\0';
// ... now as an unsigned value
// This assignment is general-purpose, typically used when
// we know that the IFD Value/Offset is just an offset
nIfdOffset = ReadSwap4(m_nPos);
strTmp.Format(_T(" # Val/Offset = 0x%08X"),nIfdOffset);
DbgAddLine(strTmp);
// =========== EXIF IFD Interoperability entry (End) ===========
// ==========================================================================
// Extract the IFD component entries
// ==========================================================================
// The EXIF IFD entries can appear in a wide range of
// formats / data types. The formats that have been
// publicly documented include:
// EXIF_FORMAT_BYTE = 1,
// EXIF_FORMAT_ASCII = 2,
// EXIF_FORMAT_SHORT = 3,
// EXIF_FORMAT_LONG = 4,
// EXIF_FORMAT_RATIONAL = 5,
// EXIF_FORMAT_SBYTE = 6,
// EXIF_FORMAT_UNDEFINED = 7,
// EXIF_FORMAT_SSHORT = 8,
// EXIF_FORMAT_SLONG = 9,
// EXIF_FORMAT_SRATIONAL = 10,
// EXIF_FORMAT_FLOAT = 11,
// EXIF_FORMAT_DOUBLE = 12
// The IFD variable formatter logic operates in two stages:
// In the first stage, the format type is decoded, which results
// in a generic decode for the IFD entry. Then, we start a second
// stage which re-interprets the values for a number of known
// special types.
switch(nIfdFormat)
{
// ----------------------------------------
// --- IFD Entry Type: Unsigned Byte
// ----------------------------------------
case 1:
strFull = _T(" Unsigned Byte=[");
strValOut = _T("");
// Limit display output
nCompsToDisplay = min(MAX_anValues,nIfdNumComps);
// If only a single value, use decimal, else use hex
if (nIfdNumComps == 1) {
anValues[0] = Buf(m_nPos+0);
strTmp.Format(_T("%u"),anValues[0]);
strValOut += strTmp;
} else {
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++)
{
if (nIfdNumComps <= 4) {
// Components fit inside 4B inline region
anValues[nInd] = Buf(m_nPos+nInd);
} else {
// Since the components don't fit inside 4B inline region
// we need to dereference
anValues[nInd] = Buf(nPosExifStart+nIfdOffset+nInd);
}
}
strValOut = PrintAsHex8(anValues,nIfdNumComps);
}
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
break;
// ----------------------------------------
// --- IFD Entry Type: ASCII string
// ----------------------------------------
case 2:
strFull = _T(" String=");
strValOut = _T("");
char cVal;
BYTE nVal;
// Limit display output
// TODO: Decide what an appropriate string limit would be
nCompsToDisplay = min(250,nIfdNumComps);
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++)
{
if (nIfdNumComps<=4) {
nVal = acIfdValOffsetStr[nInd];
}
else
{
// TODO: See if this can be migrated to the "custom decode"
// section later in the code. Decoding makernotes here is
// less desirable but unfortunately some Nikon makernotes use
// a non-standard offset value.
if ( (strIfd == _T("MakerIFD")) && (m_strImgExifMake == _T("NIKON")) && (m_nImgExifMakeSubtype == 3) )
{
// It seems that pointers in the Nikon Makernotes are
// done relative to the start of Maker IFD
// But why 10? Is this 10 = 18-8?
nVal = Buf(nPosExifStart+m_nImgExifMakerPtr+nIfdOffset+10+nInd);
} else if ( (strIfd == _T("MakerIFD")) && (m_strImgExifMake == _T("NIKON")) )
{
// It seems that pointers in the Nikon Makernotes are
// done relative to the start of Maker IFD
nVal = Buf(nPosExifStart+nIfdOffset+0+nInd);
} else {
// Canon Makernotes seem to be relative to the start
// of the EXIF IFD
nVal = Buf(nPosExifStart+nIfdOffset+nInd);
}
}
// Just in case the string has been null-terminated early
// or we have garbage, replace with '.'
// TODO: Clean this up
if (nVal != 0) {
cVal = (char)nVal;
if (!isprint(nVal)) {
cVal = '.';
}
strValOut += cVal;
}
}
strFull += strValOut;
DbgAddLine(strFull);
// TODO: Ideally, we would use a different string for display
// purposes that is wrapped in quotes. Currently "strValOut" is used
// in other sections of code (eg. in assignment to EXIF Make/Model/Software, etc.)
// so we don't want to affect that.
break;
// ----------------------------------------
// --- IFD Entry Type: Unsigned Short (2 bytes)
// ----------------------------------------
case 3:
// Limit display output
nCompsToDisplay = min(MAX_anValues,nIfdNumComps);
// Unsigned Short (2 bytes)
if (nIfdNumComps == 1) {
strFull = _T(" Unsigned Short=[");
// TODO: Confirm endianness is correct here
// Refer to Exif2-2 spec, page 14.
// Currently selecting 2 byte conversion from [1:0] out of [3:0]
anValues[0] = ReadSwap2(m_nPos);
strValOut.Format(_T("%u"),anValues[0]);
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
} else if (nIfdNumComps == 2) {
strFull = _T(" Unsigned Short=[");
// 2 unsigned shorts in 1 word
anValues[0] = ReadSwap2(m_nPos+0);
anValues[1] = ReadSwap2(m_nPos+2);
strValOut.Format(_T("%u, %u"),anValues[0],anValues[1]);
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
} else if (nIfdNumComps > MAX_IFD_COMPS) {
strValTmp.Format(_T(" Unsigned Short=[Too many entries (%u) to display]"),nIfdNumComps);
DbgAddLine(strValTmp);
strValOut.Format(_T("[Too many entries (%u) to display]"),nIfdNumComps);
} else {
// Try to handle multiple entries... note that this
// is used by the Maker notes IFD decode
strValOut = _T("");
strFull = _T(" Unsigned Short=[");
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++) {
if (nInd!=0) { strValOut += _T(", "); }
anValues[nInd] = ReadSwap2(nPosExifStart+nIfdOffset+(2*nInd));
strValTmp.Format(_T("%u"),anValues[nInd]);
strValOut += strValTmp;
}
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
}
break;
// ----------------------------------------
// --- IFD Entry Type: Unsigned Long (4 bytes)
// ----------------------------------------
case 4:
strFull = _T(" Unsigned Long=[");
strValOut = _T("");
// Limit display output
nCompsToDisplay = min(MAX_anValues,nIfdNumComps);
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++)
{
if (nIfdNumComps == 1) {
// Components fit inside 4B inline region
anValues[nInd] = ReadSwap4(m_nPos+(nInd*4));
} else {
// Since the components don't fit inside 4B inline region
// we need to dereference
anValues[nInd] = ReadSwap4(nPosExifStart+nIfdOffset+(nInd*4));
}
}
strValOut = PrintAsHex32(anValues,nIfdNumComps);
// If we only have a single component, then display both the hex and decimal
if (nCompsToDisplay==1) {
strTmp.Format(_T("%s / %u"),(LPCTSTR)strValOut,anValues[0]);
strValOut = strTmp;
}
break;
// ----------------------------------------
// --- IFD Entry Type: Unsigned Rational (8 bytes)
// ----------------------------------------
case 5:
// Unsigned Rational
strFull = _T(" Unsigned Rational=[");
strValOut = _T("");
// Limit display output
nCompsToDisplay = min(MAX_anValues,nIfdNumComps);
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++)
{
if (nInd!=0) { strValOut += _T(", "); }
strValTmp = DecodeValFraction(nPosExifStart+nIfdOffset+(nInd*8));
bRet = DecodeValRational(nPosExifStart+nIfdOffset+(nInd*8),fValReal);
afValues[nInd] = fValReal;
strValOut += strValTmp;
}
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
break;
// ----------------------------------------
// --- IFD Entry Type: Undefined (?)
// ----------------------------------------
case 7:
// Undefined -- assume 1 word long
// This is supposed to be a series of 8-bit bytes
// It is usually used for 32-bit pointers (in case of offsets), but could
// also represent ExifVersion, etc.
strFull = _T(" Undefined=[");
strValOut = _T("");
// Limit display output
nCompsToDisplay = min(MAX_anValues,nIfdNumComps);
if (nIfdNumComps <= 4) {
// This format is not defined, so output as hex for now
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++) {
anValues[nInd] = Buf(m_nPos+nInd);
}
strValOut = PrintAsHex8(anValues,nIfdNumComps);
strFull += strValOut;
} else {
// Dereference pointer
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++) {
anValues[nInd] = Buf(nPosExifStart+nIfdOffset+nInd);
}
strValOut = PrintAsHex8(anValues,nIfdNumComps);
strFull += strValOut;
}
strFull += _T("]");
DbgAddLine(strFull);
break;
// ----------------------------------------
// --- IFD Entry Type: Signed Short (2 bytes)
// ----------------------------------------
case 8:
// Limit display output
nCompsToDisplay = min(MAX_anValues,nIfdNumComps);
// Signed Short (2 bytes)
if (nIfdNumComps == 1) {
strFull = _T(" Signed Short=[");
// TODO: Confirm endianness is correct here
// Refer to Exif2-2 spec, page 14.
// Currently selecting 2 byte conversion from [1:0] out of [3:0]
// TODO: Ensure that ReadSwap2 handles signed notation properly
anValuesS[0] = ReadSwap2(m_nPos);
strValOut.Format(_T("%d"),anValuesS[0]);
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
} else if (nIfdNumComps == 2) {
strFull = _T(" Signed Short=[");
// 2 signed shorts in 1 word
// TODO: Ensure that ReadSwap2 handles signed notation properly
anValuesS[0] = ReadSwap2(m_nPos+0);
anValuesS[1] = ReadSwap2(m_nPos+2);
strValOut.Format(_T("%d, %d"),anValuesS[0],anValuesS[0]);
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
} else if (nIfdNumComps > MAX_IFD_COMPS) {
// Only print it out if it has less than MAX_IFD_COMPS entries
strValTmp.Format(_T(" Signed Short=[Too many entries (%u) to display]"),nIfdNumComps);
DbgAddLine(strValTmp);
strValOut.Format(_T("[Too many entries (%u) to display]"),nIfdNumComps);
} else {
// Try to handle multiple entries... note that this
// is used by the Maker notes IFD decode
// Note that we don't call LookupMakerCanonTag() here
// as that is only needed for the "unsigned short", not
// "signed short".
strValOut = _T("");
strFull = _T(" Signed Short=[");
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++) {
if (nInd!=0) { strValOut += _T(", "); }
anValuesS[nInd] = ReadSwap2(nPosExifStart+nIfdOffset+(2*nInd));
strValTmp.Format(_T("%d"),anValuesS[nInd]);
strValOut += strValTmp;
}
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
}
break;
// ----------------------------------------
// --- IFD Entry Type: Signed Rational (8 bytes)
// ----------------------------------------
case 10:
// Signed Rational
strFull = _T(" Signed Rational=[");
strValOut = _T("");
// Limit display output
nCompsToDisplay = min(MAX_anValues,nIfdNumComps);
for (unsigned nInd=0;nInd<nCompsToDisplay;nInd++)
{
if (nInd!=0) { strValOut += _T(", "); }
strValTmp = DecodeValFraction(nPosExifStart+nIfdOffset+(nInd*8));
bRet = DecodeValRational(nPosExifStart+nIfdOffset+(nInd*8),fValReal);
afValues[nInd] = fValReal;
strValOut += strValTmp;
}
strFull += strValOut;
strFull += _T("]");
DbgAddLine(strFull);
break;
default:
strTmp.Format(_T("ERROR: Unsupported format [%d]"),nIfdFormat);
anValues[0] = ReadSwap4(m_nPos);
strValOut.Format(_T("0x%08X???"),anValues[0]);
m_pLog->Enable();
return 2;
break;
} // switch nIfdTagVal
// ==========================================================================
// Custom Value String decodes
// ==========================================================================
// At this point we might re-format the values, thereby
// overriding the default strValOut. We have access to the
// anValues[] (array of unsigned int)
// anValuesS[] (array of signed int)
// afValues[] (array of float)
// Re-format special output items
// This will override "strValOut" that may have previously been defined
if ((strIfdTag == _T("GPSLatitude")) ||
(strIfdTag == _T("GPSLongitude"))) {
bRet = PrintValGPS(nIfdNumComps,afValues[0],afValues[1],afValues[2],strValOut);
} else if (strIfdTag == _T("GPSVersionID")) {
strValOut.Format(_T("%u.%u.%u.%u"),anValues[0],anValues[1],anValues[2],anValues[3]);
} else if (strIfdTag == _T("GPSAltitudeRef")) {
switch (anValues[0]) {
case 0 : strValOut = _T("Above Sea Level"); break;
case 1 : strValOut = _T("Below Sea Level"); break;
}
} else if (strIfdTag == _T("GPSStatus")) {
switch (acIfdValOffsetStr[0]) {
case 'A' : strValOut = _T("Measurement in progress"); break;
case 'V' : strValOut = _T("Measurement Interoperability"); break;
}
} else if (strIfdTag == _T("GPSMeasureMode")) {
switch (acIfdValOffsetStr[0]) {
case '2' : strValOut = _T("2-dimensional"); break;
case '3' : strValOut = _T("3-dimensional"); break;
}
} else if ((strIfdTag == _T("GPSSpeedRef")) ||
(strIfdTag == _T("GPSDestDistanceRef"))) {
switch (acIfdValOffsetStr[0]) {
case 'K' : strValOut = _T("km/h"); break;
case 'M' : strValOut = _T("mph"); break;
case 'N' : strValOut = _T("knots"); break;
}
} else if ((strIfdTag == _T("GPSTrackRef")) ||
(strIfdTag == _T("GPSImgDirectionRef")) ||
(strIfdTag == _T("GPSDestBearingRef"))) {
switch (acIfdValOffsetStr[0]) {
case 'T' : strValOut = _T("True direction"); break;
case 'M' : strValOut = _T("Magnetic direction"); break;
}
} else if (strIfdTag == _T("GPSDifferential")) {
switch (anValues[0]) {
case 0 : strValOut = _T("Measurement without differential correction"); break;
case 1 : strValOut = _T("Differential correction applied"); break;
}
} else if (strIfdTag == _T("GPSAltitude")) {
strValOut.Format(_T("%.3f m"),afValues[0]);
} else if (strIfdTag == _T("GPSSpeed")) {
strValOut.Format(_T("%.3f"),afValues[0]);
} else if (strIfdTag == _T("GPSTimeStamp")) {
strValOut.Format(_T("%.0f:%.0f:%.2f"),afValues[0],afValues[1],afValues[2]);
} else if (strIfdTag == _T("GPSTrack")) {
strValOut.Format(_T("%.2f"),afValues[0]);
} else if (strIfdTag == _T("GPSDOP")) {
strValOut.Format(_T("%.4f"),afValues[0]);
}
if (strIfdTag == _T("Compression")) {
switch (anValues[0]) {
case 1 : strValOut = _T("None"); break;
case 6 : strValOut = _T("JPEG"); break;
}
} else if (strIfdTag == _T("ExposureTime")) {
// Assume only one
strValTmp = strValOut;
strValOut.Format(_T("%s s"),(LPCTSTR)strValTmp);
} else if (strIfdTag == _T("FNumber")) {
// Assume only one
strValOut.Format(_T("F%.1f"),afValues[0]);
} else if (strIfdTag == _T("FocalLength")) {
// Assume only one
strValOut.Format(_T("%.0f mm"),afValues[0]);
} else if (strIfdTag == _T("ExposureBiasValue")) {
// Assume only one
// TODO: Need to test negative numbers
strValOut.Format(_T("%0.2f eV"),afValues[0]);
} else if (strIfdTag == _T("ExifVersion")) {
// Assume only one
strValOut.Format(_T("%c%c.%c%c"),anValues[0],anValues[1],anValues[2],anValues[3]);
} else if (strIfdTag == _T("FlashPixVersion")) {
// Assume only one
strValOut.Format(_T("%c%c.%c%c"),anValues[0],anValues[1],anValues[2],anValues[3]);
} else if (strIfdTag == _T("PhotometricInterpretation")) {
switch (anValues[0]) {
case 1 : strValOut = _T("Monochrome"); break;
case 2 : strValOut = _T("RGB"); break;
case 6 : strValOut = _T("YCbCr"); break;
}
} else if (strIfdTag == _T("Orientation")) {
switch (anValues[0]) {
case 1 : strValOut = _T("1 = Row 0: top, Col 0: left"); break;
case 2 : strValOut = _T("2 = Row 0: top, Col 0: right"); break;
case 3 : strValOut = _T("3 = Row 0: bottom, Col 0: right"); break;
case 4 : strValOut = _T("4 = Row 0: bottom, Col 0: left"); break;
case 5 : strValOut = _T("5 = Row 0: left, Col 0: top"); break;
case 6 : strValOut = _T("6 = Row 0: right, Col 0: top"); break;
case 7 : strValOut = _T("7 = Row 0: right, Col 0: bottom"); break;
case 8 : strValOut = _T("8 = Row 0: left, Col 0: bottom"); break;
}
} else if (strIfdTag == _T("PlanarConfiguration")) {
switch (anValues[0]) {
case 1 : strValOut = _T("Chunky format"); break;
case 2 : strValOut = _T("Planar format"); break;
}
} else if (strIfdTag == _T("YCbCrSubSampling")) {
switch (anValues[0]*65536 + anValues[1]) {
case 0x00020001 : strValOut = _T("4:2:2"); break;
case 0x00020002 : strValOut = _T("4:2:0"); break;
}
} else if (strIfdTag == _T("YCbCrPositioning")) {
switch (anValues[0]) {
case 1 : strValOut = _T("Centered"); break;
case 2 : strValOut = _T("Co-sited"); break;
}
} else if (strIfdTag == _T("ResolutionUnit")) {
switch (anValues[0]) {
case 1 : strValOut = _T("None"); break;
case 2 : strValOut = _T("Inch"); break;
case 3 : strValOut = _T("Centimeter"); break;
}
} else if (strIfdTag == _T("FocalPlaneResolutionUnit")) {
switch (anValues[0]) {
case 1 : strValOut = _T("None"); break;
case 2 : strValOut = _T("Inch"); break;
case 3 : strValOut = _T("Centimeter"); break;
}
} else if (strIfdTag == _T("ColorSpace")) {
switch (anValues[0]) {
case 1 : strValOut = _T("sRGB"); break;
case 0xFFFF : strValOut = _T("Uncalibrated"); break;
}
} else if (strIfdTag == _T("ComponentsConfiguration")) {
// Undefined type, assume 4 bytes
strValOut = _T("[");
for (unsigned vind=0;vind<4;vind++) {
if (vind != 0) { strValOut += _T(" "); }
switch (anValues[vind]) {
case 0 : strValOut += _T("."); break;
case 1 : strValOut += _T("Y"); break;
case 2 : strValOut += _T("Cb"); break;
case 3 : strValOut += _T("Cr"); break;
case 4 : strValOut += _T("R"); break;
case 5 : strValOut += _T("G"); break;
case 6 : strValOut += _T("B"); break;
default : strValOut += _T("?"); break;
}
}
strValOut += _T("]");
} else if ( (strIfdTag == _T("XPTitle")) ||
(strIfdTag == _T("XPComment")) ||
(strIfdTag == _T("XPAuthor")) ||
(strIfdTag == _T("XPKeywords")) ||
(strIfdTag == _T("XPSubject")) ) {
strValOut = _T("\"");
CString strVal;
strVal = m_pWBuf->BufReadUniStr2(nPosExifStart+nIfdOffset,nIfdNumComps);
strValOut += strVal;
strValOut += _T("\"");
} else if (strIfdTag == _T("UserComment")) {
// Character code
unsigned anCharCode[8];
for (unsigned vInd=0;vInd<8;vInd++) {
anCharCode[vInd] = Buf(nPosExifStart+nIfdOffset+0+vInd);
}
// Actual string
strValOut = _T("\"");
bool bDone = false;
char cTmp;
for (unsigned vInd=0;(vInd<nIfdNumComps-8)&&(!bDone);vInd++) {
cTmp = (char)Buf(nPosExifStart+nIfdOffset+8+vInd);
if (cTmp == 0) { bDone = true; } else { strValOut += cTmp; }
}
strValOut += _T("\"");
} else if (strIfdTag == _T("MeteringMode")) {
switch (anValues[0]) {
case 0 : strValOut = _T("Unknown"); break;
case 1 : strValOut = _T("Average"); break;
case 2 : strValOut = _T("CenterWeightedAverage"); break;
case 3 : strValOut = _T("Spot"); break;
case 4 : strValOut = _T("MultiSpot"); break;
case 5 : strValOut = _T("Pattern"); break;
case 6 : strValOut = _T("Partial"); break;
case 255 : strValOut = _T("Other"); break;
}
} else if (strIfdTag == _T("ExposureProgram")) {
switch (anValues[0]) {
case 0 : strValOut = _T("Not defined"); break;
case 1 : strValOut = _T("Manual"); break;
case 2 : strValOut = _T("Normal program"); break;
case 3 : strValOut = _T("Aperture priority"); break;
case 4 : strValOut = _T("Shutter priority"); break;
case 5 : strValOut = _T("Creative program (depth of field)"); break;
case 6 : strValOut = _T("Action program (fast shutter speed)"); break;
case 7 : strValOut = _T("Portrait mode"); break;
case 8 : strValOut = _T("Landscape mode"); break;
}
} else if (strIfdTag == _T("Flash")) {
switch (anValues[0] & 1) {
case 0 : strValOut = _T("Flash did not fire"); break;
case 1 : strValOut = _T("Flash fired"); break;
}
// TODO: Add other bitfields?
} else if (strIfdTag == _T("SensingMethod")) {
switch (anValues[0]) {
case 1 : strValOut = _T("Not defined"); break;
case 2 : strValOut = _T("One-chip color area sensor"); break;
case 3 : strValOut = _T("Two-chip color area sensor"); break;
case 4 : strValOut = _T("Three-chip color area sensor"); break;
case 5 : strValOut = _T("Color sequential area sensor"); break;
case 7 : strValOut = _T("Trilinear sensor"); break;
case 8 : strValOut = _T("Color sequential linear sensor"); break;
}
} else if (strIfdTag == _T("FileSource")) {
switch (anValues[0]) {
case 3 : strValOut = _T("DSC"); break;
}
} else if (strIfdTag == _T("CustomRendered")) {
switch (anValues[0]) {
case 0 : strValOut = _T("Normal process"); break;
case 1 : strValOut = _T("Custom process"); break;
}
} else if (strIfdTag == _T("ExposureMode")) {
switch (anValues[0]) {
case 0 : strValOut = _T("Auto exposure"); break;
case 1 : strValOut = _T("Manual exposure"); break;
case 2 : strValOut = _T("Auto bracket"); break;
}
} else if (strIfdTag == _T("WhiteBalance")) {
switch (anValues[0]) {
case 0 : strValOut = _T("Auto white balance"); break;
case 1 : strValOut = _T("Manual white balance"); break;
}
} else if (strIfdTag == _T("SceneCaptureType")) {
switch (anValues[0]) {
case 0 : strValOut = _T("Standard"); break;
case 1 : strValOut = _T("Landscape"); break;
case 2 : strValOut = _T("Portrait"); break;
case 3 : strValOut = _T("Night scene"); break;
}
} else if (strIfdTag == _T("SceneType")) {
switch (anValues[0]) {
case 1 : strValOut = _T("A directly photographed image"); break;
}
} else if (strIfdTag == _T("LightSource")) {
switch (anValues[0]) {
case 0 : strValOut = _T("unknown"); break;
case 1 : strValOut = _T("Daylight"); break;
case 2 : strValOut = _T("Fluorescent"); break;
case 3 : strValOut = _T("Tungsten (incandescent light)"); break;
case 4 : strValOut = _T("Flash"); break;
case 9 : strValOut = _T("Fine weather"); break;
case 10 : strValOut = _T("Cloudy weather"); break;
case 11 : strValOut = _T("Shade"); break;
case 12 : strValOut = _T("Daylight fluorescent (D 5700 � 7100K)"); break;
case 13 : strValOut = _T("Day white fluorescent (N 4600 � 5400K)"); break;
case 14 : strValOut = _T("Cool white fluorescent (W 3900 � 4500K)"); break;
case 15 : strValOut = _T("White fluorescent (WW 3200 � 3700K)"); break;
case 17 : strValOut = _T("Standard light A"); break;
case 18 : strValOut = _T("Standard light B"); break;
case 19 : strValOut = _T("Standard light C"); break;
case 20 : strValOut = _T("D55"); break;
case 21 : strValOut = _T("D65"); break;
case 22 : strValOut = _T("D75"); break;
case 23 : strValOut = _T("D50"); break;
case 24 : strValOut = _T("ISO studio tungsten"); break;
case 255 : strValOut = _T("other light source"); break;
}
} else if (strIfdTag == _T("SubjectArea")) {
switch (nIfdNumComps) {
case 2 :
// coords
strValOut.Format(_T("Coords: Center=[%u,%u]"),
anValues[0],anValues[1]);
break;
case 3 :
// circle
strValOut.Format(_T("Coords (Circle): Center=[%u,%u] Diameter=%u"),
anValues[0],anValues[1],anValues[2]);
break;
case 4 :
// rectangle
strValOut.Format(_T("Coords (Rect): Center=[%u,%u] Width=%u Height=%u"),
anValues[0],anValues[1],anValues[2],anValues[3]);
break;
default:
// Leave default decode, unexpected value
break;
}
}
if (strIfdTag == _T("CFAPattern")) {
unsigned nHorzRepeat,nVertRepeat;
unsigned anCfaVal[16][16];
unsigned nInd=0;
unsigned nVal;
CString strLine,strCol;
nHorzRepeat = anValues[nInd+0]*256+anValues[nInd+1];
nVertRepeat = anValues[nInd+2]*256+anValues[nInd+3];
nInd+=4;
if ((nHorzRepeat < 16) && (nVertRepeat < 16)) {
bExtraDecode = TRUE;
strTmp.Format(_T(" [%-36s] ="),(LPCTSTR)strIfdTag);
m_pLog->AddLine(strTmp);
for (unsigned nY=0;nY<nVertRepeat;nY++) {
strLine.Format(_T(" %-36s = [ " ),_T(""));
for (unsigned nX=0;nX<nHorzRepeat;nX++) {
if (nInd<MAX_anValues) {
nVal = anValues[nInd++];
anCfaVal[nY][nX] = nVal;
switch(nVal) {
case 0: strCol = _T("Red");break;
case 1: strCol = _T("Grn");break;
case 2: strCol = _T("Blu");break;
case 3: strCol = _T("Cya");break;
case 4: strCol = _T("Mgn");break;
case 5: strCol = _T("Yel");break;
case 6: strCol = _T("Wht");break;
default: strCol.Format(_T("x%02X"),nVal);break;
}
strLine.AppendFormat(_T("%s "),(LPCTSTR)strCol);
}
}
strLine.Append(_T("]"));
m_pLog->AddLine(strLine);
}
}
}
if ((strIfd == _T("InteropIFD")) && (strIfdTag == _T("InteroperabilityVersion"))) {
// Assume only one
strValOut.Format(_T("%c%c.%c%c"),anValues[0],anValues[1],anValues[2],anValues[3]);
}
// ==========================================================================
// ----------------------------------------
// Handle certain MakerNotes
// For Canon, we have a special parser routine to handle these
// ----------------------------------------
if (strIfd == _T("MakerIFD")) {
if ((m_strImgExifMake == _T("Canon")) && (nIfdFormat == 3) && (nIfdNumComps > 4)) {
// Print summary line now, before sub details
// Disable later summary line
bExtraDecode = TRUE;
if ((!m_pAppConfig->bExifHideUnknown) || (!nIfdTagUnknown)) {
strTmp.Format(_T(" [%-36s]"),(LPCTSTR)strIfdTag);
m_pLog->AddLine(strTmp);
// Assume it is a maker field with subentries!
for (unsigned ind=0;ind<nIfdNumComps;ind++) {
// Limit the number of entries (in case there was a decode error
// or simply too many to report)
if (ind<MAX_anValues) {
strValOut.Format(_T("#%u=%u "),ind,anValues[ind]);
strRetVal = LookupMakerCanonTag(nIfdTagVal,ind,anValues[ind]);
strMaker = strRetVal.strTag;
strValTmp.Format(_T(" [%-34s] = %s"),(LPCTSTR)strMaker,(LPCTSTR)(strRetVal.strVal));
if ((!m_pAppConfig->bExifHideUnknown) || (!strRetVal.bUnknown)) {
m_pLog->AddLine(strValTmp);
}
} else if (ind == MAX_anValues) {
m_pLog->AddLine(_T(" [... etc ...]"));
} else {
// Don't print!
}
}
}
strValOut = _T("...");
}
// For Nikon & Sigma, we simply support the quality field
if ( (strIfdTag=="Nikon1.Quality") ||
(strIfdTag=="Nikon2.Quality") ||
(strIfdTag=="Nikon3.Quality") ||
(strIfdTag=="Sigma.Quality") )
{
m_strImgQualExif = strValOut;
// Collect extra details (for later DB submission)
strTmp = _T("");
strTmp.Format(_T("[%s]:[%s],"),(LPCTSTR)strIfdTag,(LPCTSTR)strValOut);
m_strImgExtras += strTmp;
}
// Collect extra details (for later DB submission)
if (strIfdTag==_T("Canon.ImageType")) {
strTmp = _T("");
strTmp.Format(_T("[%s]:[%s],"),(LPCTSTR)strIfdTag,(LPCTSTR)strValOut);
m_strImgExtras += strTmp;
}
}
// ----------------------------------------
// Now extract some of the important offsets / pointers
if ((strIfd == _T("IFD0")) && (strIfdTag == _T("ExifOffset"))) {
// EXIF SubIFD - Pointer
m_nImgExifSubIfdPtr = nIfdOffset;
strValOut.Format(_T("@ 0x%04X"),nIfdOffset);
}
if ((strIfd == _T("IFD0")) && (strIfdTag == _T("GPSOffset"))) {
// GPS SubIFD - Pointer
m_nImgExifGpsIfdPtr = nIfdOffset;
strValOut.Format(_T("@ 0x%04X"),nIfdOffset);
}
// TODO: Add Interoperability IFD (0xA005)?
if ((strIfd == _T("SubIFD")) && (strIfdTag == _T("ExifInteroperabilityOffset"))) {
m_nImgExifInteropIfdPtr = nIfdOffset;
strValOut.Format(_T("@ 0x%04X"),nIfdOffset);
}
// Extract software field
if ((strIfd == _T("IFD0")) && (strIfdTag == _T("Software"))) {
m_strSoftware = strValOut;
}
// -------------------------
// IFD0 - ExifMake
// -------------------------
if ((strIfd == _T("IFD0")) && (strIfdTag == _T("Make"))) {
m_strImgExifMake = strValOut;
m_strImgExifMake.Trim(); // Trim whitespace (e.g. Pentax)
}
// -------------------------
// IFD0 - ExifModel
// -------------------------
if ((strIfd == _T("IFD0")) && (strIfdTag == _T("Model"))) {
m_strImgExifModel= strValOut;
m_strImgExifModel.Trim();
}
if ((strIfd == _T("SubIFD")) && (strIfdTag == _T("MakerNote"))) {
// Maker IFD - Pointer
m_nImgExifMakerPtr = nIfdOffset;
strValOut.Format(_T("@ 0x%04X"),nIfdOffset);
}
// -------------------------
// IFD1 - Embedded Thumbnail
// -------------------------
if ((strIfd == _T("IFD1")) && (strIfdTag == _T("Compression"))) {
// Embedded thumbnail, compression format
m_nImgExifThumbComp = ReadSwap4(m_nPos);
}
if ((strIfd == _T("IFD1")) && (strIfdTag == _T("JpegIFOffset"))) {
// Embedded thumbnail, offset
m_nImgExifThumbOffset = nIfdOffset + nPosExifStart;
strValOut.Format(_T("@ +0x%04X = @ 0x%04X"),nIfdOffset,m_nImgExifThumbOffset);
}
if ((strIfd == _T("IFD1")) && (strIfdTag == _T("JpegIFByteCount"))) {
// Embedded thumbnail, length
m_nImgExifThumbLen = ReadSwap4(m_nPos);
}
// ==========================================================================
// Determine MakerNote support
// ==========================================================================
if (m_strImgExifMake != _T("")) {
// 1) Identify the supported MakerNotes
// 2) Remap variations of the Maker field (e.g. Nikon)
// as some manufacturers have been inconsistent in their
// use of the Make field
m_bImgExifMakeSupported = FALSE;
if (m_strImgExifMake == _T("Canon")) {
m_bImgExifMakeSupported = TRUE;
}
else if (m_strImgExifMake == _T("PENTAX Corporation")) {
m_strImgExifMake = _T("PENTAX");
}
else if (m_strImgExifMake == _T("NIKON CORPORATION")) {
m_strImgExifMake = _T("NIKON");
m_bImgExifMakeSupported = TRUE;
}
else if (m_strImgExifMake == _T("NIKON")) {
m_strImgExifMake = _T("NIKON");
m_bImgExifMakeSupported = TRUE;
}
else if (m_strImgExifMake == _T("SIGMA")) {
m_bImgExifMakeSupported = TRUE;
}
else if (m_strImgExifMake == _T("SONY")) {
m_bImgExifMakeSupported = TRUE;
}
else if (m_strImgExifMake == _T("FUJIFILM")) {
// TODO:
// FUJIFILM Maker notes apparently use
// big endian format even though main section uses little.
// Need to switch if in maker section for FUJI
// For now, disable support
m_bImgExifMakeSupported = FALSE;
}
}
// Now advance the m_nPos ptr as we have finished with valoffset
m_nPos+=4;
// ==========================================================================
// SUMMARY REPORT
// ==========================================================================
// If we haven't already output a detailed decode of this field
// then we can output the generic representation here
if (!bExtraDecode)
{
// Provide option to skip unknown fields
if ((!m_pAppConfig->bExifHideUnknown) || (!nIfdTagUnknown)) {
// If the tag is an ASCII string, we want to wrap with quote marks
if (nIfdFormat == 2) {
strTmp.Format(_T(" [%-36s] = \"%s\""),(LPCTSTR)strIfdTag,(LPCTSTR)strValOut);
} else {
strTmp.Format(_T(" [%-36s] = %s"),(LPCTSTR)strIfdTag,(LPCTSTR)strValOut);
}
m_pLog->AddLine(strTmp);
}
}
DbgAddLine(_T(""));
} // for nIfdEntryInd
// =========== EXIF IFD (End) ===========
// - Defined in Exif 2.2 Standard (JEITA CP-3451) section 4.6.2
// - Is completed by 4-byte offset to next IFD, which is
// read in next iteration.
m_pLog->Enable();
return 0;
}
// Handle APP13 marker
// This includes:
// - Photoshop "Save As" and "Save for Web" quality settings
// - IPTC entries
// PRE:
// - m_nPos
// POST:
// - m_nImgQualPhotoshopSa
unsigned CjfifDecode::DecodeApp13Ps()
{
// Photoshop APP13 marker definition doesn't appear to have a
// well-defined length, so I will read until I encounter a
// non-"8BIM" entry, then we reset the position counter
// and move on to the next marker.
// FIXME: This does not appear to be very robust
CString strTmp;
CString strBimName;
bool bDone = false;
unsigned nVal = 0x8000;
unsigned nSaveFormat = 0;
CString strVal;
CString strByte;
CString strBimSig;
// Reset PsDec decoder state
m_pPsDec->Reset();
while (!bDone)
{
// FIXME: Need to check for actual marker section extent, not
// just the lack of an 8BIM signature as the terminator!
// Check the signature but don't advance the file pointer
strBimSig = m_pWBuf->BufReadStrn(m_nPos,4);
// Check for signature "8BIM"
if (strBimSig == _T("8BIM")) {
m_pPsDec->PhotoshopParseImageResourceBlock(m_nPos,3);
} else {
// Not 8BIM?
bDone = true;
}
}
// Now that we've finished with the PsDec decoder we can fetch
// some of the parser state
// TODO: Migrate into accessor
m_nImgQualPhotoshopSa = m_pPsDec->m_nQualitySaveAs;
m_nImgQualPhotoshopSfw = m_pPsDec->m_nQualitySaveForWeb;
m_bPsd = m_pPsDec->m_bPsd;
return 0;
}
// Start decoding a single ICC header segment @ nPos
unsigned CjfifDecode::DecodeIccHeader(unsigned nPos)
{
CString strTmp,strTmp1;
// Profile header
unsigned nProfSz;
unsigned nPrefCmmType;
unsigned nProfVer;
unsigned nProfDevClass;
unsigned nDataColorSpace;
unsigned nPcs;
unsigned anDateTimeCreated[3];
unsigned nProfFileSig;
unsigned nPrimPlatSig;
unsigned nProfFlags;
unsigned nDevManuf;
unsigned nDevModel;
unsigned anDevAttrib[2];
unsigned nRenderIntent;
unsigned anIllumPcsXyz[3];
unsigned nProfCreatorSig;
unsigned anProfId[4];
unsigned anRsvd[7];
// Read in all of the ICC header bytes
nProfSz = ReadBe4(nPos);nPos+=4;
nPrefCmmType = ReadBe4(nPos);nPos+=4;
nProfVer = ReadBe4(nPos);nPos+=4;
nProfDevClass = ReadBe4(nPos);nPos+=4;
nDataColorSpace = ReadBe4(nPos);nPos+=4;
nPcs = ReadBe4(nPos);nPos+=4;
anDateTimeCreated[2] = ReadBe4(nPos);nPos+=4;
anDateTimeCreated[1] = ReadBe4(nPos);nPos+=4;
anDateTimeCreated[0] = ReadBe4(nPos);nPos+=4;
nProfFileSig = ReadBe4(nPos);nPos+=4;
nPrimPlatSig = ReadBe4(nPos);nPos+=4;
nProfFlags = ReadBe4(nPos);nPos+=4;
nDevManuf = ReadBe4(nPos);nPos+=4;
nDevModel = ReadBe4(nPos);nPos+=4;
anDevAttrib[1] = ReadBe4(nPos);nPos+=4;
anDevAttrib[0] = ReadBe4(nPos);nPos+=4;
nRenderIntent = ReadBe4(nPos);nPos+=4;
anIllumPcsXyz[2] = ReadBe4(nPos);nPos+=4;
anIllumPcsXyz[1] = ReadBe4(nPos);nPos+=4;
anIllumPcsXyz[0] = ReadBe4(nPos);nPos+=4;
nProfCreatorSig = ReadBe4(nPos);nPos+=4;
anProfId[3] = ReadBe4(nPos);nPos+=4;
anProfId[2] = ReadBe4(nPos);nPos+=4;
anProfId[1] = ReadBe4(nPos);nPos+=4;
anProfId[0] = ReadBe4(nPos);nPos+=4;
anRsvd[6] = ReadBe4(nPos);nPos+=4;
anRsvd[5] = ReadBe4(nPos);nPos+=4;
anRsvd[4] = ReadBe4(nPos);nPos+=4;
anRsvd[3] = ReadBe4(nPos);nPos+=4;
anRsvd[2] = ReadBe4(nPos);nPos+=4;
anRsvd[1] = ReadBe4(nPos);nPos+=4;
anRsvd[0] = ReadBe4(nPos);nPos+=4;
// Now output the formatted version of the above data structures
strTmp.Format(_T(" %-33s : %u bytes"),_T("Profile Size"),nProfSz);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : %s"),_T("Preferred CMM Type"),(LPCTSTR)Uint2Chars(nPrefCmmType));
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : %u.%u.%u.%u (0x%08X)"),_T("Profile Version"),
((nProfVer & 0xF0000000)>>28),
((nProfVer & 0x0F000000)>>24),
((nProfVer & 0x00F00000)>>20),
((nProfVer & 0x000F0000)>>16),
nProfVer);
m_pLog->AddLine(strTmp);
switch (nProfDevClass) {
case 'scnr':
strTmp1.Format(_T("Input Device profile"));break;
case 'mntr':
strTmp1.Format(_T("Display Device profile"));break;
case 'prtr':
strTmp1.Format(_T("Output Device profile"));break;
case 'link':
strTmp1.Format(_T("DeviceLink Device profile"));break;
case 'spac':
strTmp1.Format(_T("ColorSpace Conversion profile"));break;
case 'abst':
strTmp1.Format(_T("Abstract profile"));break;
case 'nmcl':
strTmp1.Format(_T("Named colour profile"));break;
default:
strTmp1.Format(_T("? (0x%08X)"),nProfDevClass);
break;
}
strTmp.Format(_T(" %-33s : %s (%s)"),_T("Profile Device/Class"),(LPCTSTR)strTmp1,(LPCTSTR)Uint2Chars(nProfDevClass));
m_pLog->AddLine(strTmp);
switch (nDataColorSpace) {
case 'XYZ ':
strTmp1.Format(_T("XYZData"));break;
case 'Lab ':
strTmp1.Format(_T("labData"));break;
case 'Luv ':
strTmp1.Format(_T("lubData"));break;
case 'YCbr':
strTmp1.Format(_T("YCbCrData"));break;
case 'Yxy ':
strTmp1.Format(_T("YxyData"));break;
case 'RGB ':
strTmp1.Format(_T("rgbData"));break;
case 'GRAY':
strTmp1.Format(_T("grayData"));break;
case 'HSV ':
strTmp1.Format(_T("hsvData"));break;
case 'HLS ':
strTmp1.Format(_T("hlsData"));break;
case 'CMYK':
strTmp1.Format(_T("cmykData"));break;
case 'CMY ':
strTmp1.Format(_T("cmyData"));break;
case '2CLR':
strTmp1.Format(_T("2colourData"));break;
case '3CLR':
strTmp1.Format(_T("3colourData"));break;
case '4CLR':
strTmp1.Format(_T("4colourData"));break;
case '5CLR':
strTmp1.Format(_T("5colourData"));break;
case '6CLR':
strTmp1.Format(_T("6colourData"));break;
case '7CLR':
strTmp1.Format(_T("7colourData"));break;
case '8CLR':
strTmp1.Format(_T("8colourData"));break;
case '9CLR':
strTmp1.Format(_T("9colourData"));break;
case 'ACLR':
strTmp1.Format(_T("10colourData"));break;
case 'BCLR':
strTmp1.Format(_T("11colourData"));break;
case 'CCLR':
strTmp1.Format(_T("12colourData"));break;
case 'DCLR':
strTmp1.Format(_T("13colourData"));break;
case 'ECLR':
strTmp1.Format(_T("14colourData"));break;
case 'FCLR':
strTmp1.Format(_T("15colourData"));break;
default:
strTmp1.Format(_T("? (0x%08X)"),nDataColorSpace);
break;
}
strTmp.Format(_T(" %-33s : %s (%s)"),_T("Data Colour Space"),(LPCTSTR)strTmp1,(LPCTSTR)Uint2Chars(nDataColorSpace));
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : %s"),_T("Profile connection space (PCS)"),(LPCTSTR)Uint2Chars(nPcs));
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : %s"),_T("Profile creation date"),(LPCTSTR)DecodeIccDateTime(anDateTimeCreated));
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : %s"),_T("Profile file signature"),(LPCTSTR)Uint2Chars(nProfFileSig));
m_pLog->AddLine(strTmp);
switch (nPrimPlatSig) {
case 'APPL':
strTmp1.Format(_T("Apple Computer, Inc."));break;
case 'MSFT':
strTmp1.Format(_T("Microsoft Corporation"));break;
case 'SGI ':
strTmp1.Format(_T("Silicon Graphics, Inc."));break;
case 'SUNW':
strTmp1.Format(_T("Sun Microsystems, Inc."));break;
default:
strTmp1.Format(_T("? (0x%08X)"),nPrimPlatSig);
break;
}
strTmp.Format(_T(" %-33s : %s (%s)"),_T("Primary platform"),(LPCTSTR)strTmp1,(LPCTSTR)Uint2Chars(nPrimPlatSig));
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : 0x%08X"),_T("Profile flags"),nProfFlags);
m_pLog->AddLine(strTmp);
strTmp1 = (TestBit(nProfFlags,0))?"Embedded profile":"Profile not embedded";
strTmp.Format(_T(" %-35s > %s"),_T("Profile flags"),(LPCTSTR)strTmp1);
m_pLog->AddLine(strTmp);
strTmp1 = (TestBit(nProfFlags,1))?"Profile can be used independently of embedded":"Profile can't be used independently of embedded";
strTmp.Format(_T(" %-35s > %s"),_T("Profile flags"),(LPCTSTR)strTmp1);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : %s"),_T("Device Manufacturer"),(LPCTSTR)Uint2Chars(nDevManuf));
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : %s"),_T("Device Model"),(LPCTSTR)Uint2Chars(nDevModel));
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : 0x%08X_%08X"),_T("Device attributes"),anDevAttrib[1],anDevAttrib[0]);
m_pLog->AddLine(strTmp);
strTmp1 = (TestBit(anDevAttrib[0],0))?"Transparency":"Reflective";
strTmp.Format(_T(" %-35s > %s"),_T("Device attributes"),(LPCTSTR)strTmp1);
m_pLog->AddLine(strTmp);
strTmp1 = (TestBit(anDevAttrib[0],1))?"Matte":"Glossy";
strTmp.Format(_T(" %-35s > %s"),_T("Device attributes"),(LPCTSTR)strTmp1);
m_pLog->AddLine(strTmp);
strTmp1 = (TestBit(anDevAttrib[0],2))?"Media polarity = positive":"Media polarity = negative";
strTmp.Format(_T(" %-35s > %s"),_T("Device attributes"),(LPCTSTR)strTmp1);
m_pLog->AddLine(strTmp);
strTmp1 = (TestBit(anDevAttrib[0],3))?"Colour media":"Black & white media";
strTmp.Format(_T(" %-35s > %s"),_T("Device attributes"),(LPCTSTR)strTmp1);
m_pLog->AddLine(strTmp);
switch(nRenderIntent) {
case 0x00000000: strTmp1.Format(_T("Perceptual"));break;
case 0x00000001: strTmp1.Format(_T("Media-Relative Colorimetric"));break;
case 0x00000002: strTmp1.Format(_T("Saturation"));break;
case 0x00000003: strTmp1.Format(_T("ICC-Absolute Colorimetric"));break;
default:
strTmp1.Format(_T("0x%08X"),nRenderIntent);
break;
}
strTmp.Format(_T(" %-33s : %s"),_T("Rendering intent"),(LPCTSTR)strTmp1);
m_pLog->AddLine(strTmp);
// PCS illuminant
strTmp.Format(_T(" %-33s : %s"),_T("Profile creator"),(LPCTSTR)Uint2Chars(nProfCreatorSig));
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" %-33s : 0x%08X_%08X_%08X_%08X"),_T("Profile ID"),
anProfId[3],anProfId[2],anProfId[1],anProfId[0]);
m_pLog->AddLine(strTmp);
return 0;
}
// Provide special output formatter for ICC Date/Time
// NOTE: It appears that the nParts had to be decoded in the
// reverse order from what I had expected, so one should
// confirm that the byte order / endianness is appropriate.
CString CjfifDecode::DecodeIccDateTime(unsigned anVal[3])
{
CString strDate;
unsigned short anParts[6];
anParts[0] = (anVal[2] & 0xFFFF0000) >> 16; // Year
anParts[1] = (anVal[2] & 0x0000FFFF); // Mon
anParts[2] = (anVal[1] & 0xFFFF0000) >> 16; // Day
anParts[3] = (anVal[1] & 0x0000FFFF); // Hour
anParts[4] = (anVal[0] & 0xFFFF0000) >> 16; // Min
anParts[5] = (anVal[0] & 0x0000FFFF); // Sec
strDate.Format(_T("%04u-%02u-%02u %02u:%02u:%02u"),
anParts[0],anParts[1],anParts[2],anParts[3],anParts[4],anParts[5]);
return strDate;
}
// Parser for APP2 ICC profile marker
unsigned CjfifDecode::DecodeApp2IccProfile(unsigned nLen)
{
CString strTmp;
unsigned nMarkerSeqNum; // Byte
unsigned nNumMarkers; // Byte
unsigned nPayloadLen; // Len of this ICC marker payload
unsigned nMarkerPosStart;
nMarkerSeqNum = Buf(m_nPos++);
nNumMarkers = Buf(m_nPos++);
nPayloadLen = nLen - 2 - 12 - 2; // TODO: check?
strTmp.Format(_T(" Marker Number = %u of %u"),nMarkerSeqNum,nNumMarkers);
m_pLog->AddLine(strTmp);
if (nMarkerSeqNum == 1) {
nMarkerPosStart = m_nPos;
DecodeIccHeader(nMarkerPosStart);
} else {
m_pLog->AddLineWarn(_T(" Only support decode of 1st ICC Marker"));
}
return 0;
}
// Parser for APP2 FlashPix marker
unsigned CjfifDecode::DecodeApp2Flashpix()
{
CString strTmp;
unsigned nFpxVer;
unsigned nFpxSegType;
unsigned nFpxInteropCnt;
unsigned nFpxEntitySz;
unsigned nFpxDefault;
bool bFpxStorage;
CString strFpxStorageClsStr;
unsigned nFpxStIndexCont;
unsigned nFpxStOffset;
unsigned nFpxStWByteOrder;
unsigned nFpxStWFormat;
CString strFpxStClsidStr;
unsigned nFpxStDwOsVer;
unsigned nFpxStRsvd;
CString streamStr;
nFpxVer = Buf(m_nPos++);
nFpxSegType = Buf(m_nPos++);
// FlashPix segments: Contents List or Stream Data
if (nFpxSegType == 1) {
// Contents List
strTmp.Format(_T(" Segment: CONTENTS LIST"));
m_pLog->AddLine(strTmp);
nFpxInteropCnt = (Buf(m_nPos++)<<8) + Buf(m_nPos++);
strTmp.Format(_T(" Interoperability Count = %u"),nFpxInteropCnt);
m_pLog->AddLine(strTmp);
for (unsigned ind=0;ind<nFpxInteropCnt;ind++) {
strTmp.Format(_T(" Entity Index #%u"),ind);
m_pLog->AddLine(strTmp);
nFpxEntitySz = (Buf(m_nPos++)<<24) + (Buf(m_nPos++)<<16) + (Buf(m_nPos++)<<8) + Buf(m_nPos++);
// If the "entity size" field is 0xFFFFFFFF, then it should be treated as
// a "storage". It looks like we should probably be using this to determine
// that we have a "storage"
bFpxStorage = false;
if (nFpxEntitySz == 0xFFFFFFFF) {
bFpxStorage = true;
}
if (!bFpxStorage) {
strTmp.Format(_T(" Entity Size = %u"),nFpxEntitySz);
m_pLog->AddLine(strTmp);
} else {
strTmp.Format(_T(" Entity is Storage"));
m_pLog->AddLine(strTmp);
}
nFpxDefault = Buf(m_nPos++);
// BUG: #1112
//streamStr = m_pWBuf->BufReadUniStr(m_nPos);
streamStr = m_pWBuf->BufReadUniStr2(m_nPos,MAX_BUF_READ_STR);
m_nPos += 2*((unsigned)_tcslen(streamStr)+1); // 2x because unicode
strTmp.Format(_T(" Stream Name = [%s]"),(LPCTSTR)streamStr);
m_pLog->AddLine(strTmp);
// In the case of "storage", we decode the next 16 bytes as the class
if (bFpxStorage) {
// FIXME:
// NOTE: Very strange reordering required here. Doesn't seem consistent
// This means that other fields are probably wrong as well (endian)
strFpxStorageClsStr.Format(_T("%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X"),
Buf(m_nPos+3),Buf(m_nPos+2),Buf(m_nPos+1),Buf(m_nPos+0),
Buf(m_nPos+5),Buf(m_nPos+4),
Buf(m_nPos+7),Buf(m_nPos+6),
Buf(m_nPos+8),Buf(m_nPos+9),
Buf(m_nPos+10),Buf(m_nPos+11),Buf(m_nPos+12),Buf(m_nPos+13),Buf(m_nPos+14),Buf(m_nPos+15) );
m_nPos+= 16;
strTmp.Format(_T(" Storage Class = [%s]"),(LPCTSTR)strFpxStorageClsStr);
m_pLog->AddLine(strTmp);
}
}
return 0;
} else if (nFpxSegType == 2) {
// Stream Data
strTmp.Format(_T(" Segment: STREAM DATA"));
m_pLog->AddLine(strTmp);
nFpxStIndexCont = (Buf(m_nPos++)<<8) + Buf(m_nPos++);
strTmp.Format(_T(" Index in Contents List = %u"),nFpxStIndexCont);
m_pLog->AddLine(strTmp);
nFpxStOffset = (Buf(m_nPos++)<<24) + (Buf(m_nPos++)<<16) + (Buf(m_nPos++)<<8) + Buf(m_nPos++);
strTmp.Format(_T(" Offset in stream = %u (0x%08X)"),nFpxStOffset,nFpxStOffset);
m_pLog->AddLine(strTmp);
// Now decode the Property Set Header
// NOTE: Should only decode this if we are doing first part of stream
// TODO: How do we know this? First reference to index #?
nFpxStWByteOrder = (Buf(m_nPos++)<<8) + Buf(m_nPos++);
nFpxStWFormat = (Buf(m_nPos++)<<8) + Buf(m_nPos++);
nFpxStDwOsVer = (Buf(m_nPos++)<<24) + (Buf(m_nPos++)<<16) + (Buf(m_nPos++)<<8) + Buf(m_nPos++);
// FIXME:
// NOTE: Very strange reordering required here. Doesn't seem consistent!
// This means that other fields are probably wrong as well (endian)
strFpxStClsidStr.Format(_T("%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X"),
Buf(m_nPos+3),Buf(m_nPos+2),Buf(m_nPos+1),Buf(m_nPos+0),
Buf(m_nPos+5),Buf(m_nPos+4),
Buf(m_nPos+7),Buf(m_nPos+6),
Buf(m_nPos+8),Buf(m_nPos+9),
Buf(m_nPos+10),Buf(m_nPos+11),Buf(m_nPos+12),Buf(m_nPos+13),Buf(m_nPos+14),Buf(m_nPos+15) );
m_nPos+= 16;
nFpxStRsvd = (Buf(m_nPos++)<<8) + Buf(m_nPos++);
strTmp.Format(_T(" ByteOrder = 0x%04X"),nFpxStWByteOrder);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" Format = 0x%04X"),nFpxStWFormat);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" OSVer = 0x%08X"),nFpxStDwOsVer);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" clsid = %s"),(LPCTSTR)strFpxStClsidStr);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" reserved = 0x%08X"),nFpxStRsvd);
m_pLog->AddLine(strTmp);
// ....
return 2;
} else {
strTmp.Format(_T(" Reserved Segment. Stopping."));
m_pLog->AddLineErr(strTmp);
return 1;
}
}
// Decode the DHT marker segment (Huffman Tables)
// In some cases (such as for MotionJPEG), we fake out
// the DHT tables (when bInject=true) with a standard table
// as each JPEG frame in the MJPG does not include the DHT.
// In all other cases (bInject=false), we simply read the
// DHT table from the file buffer via Buf()
//
// ITU-T standard indicates that we can expect up to a
// maximum of 16-bit huffman code bitstrings.
void CjfifDecode::DecodeDHT(bool bInject)
{
unsigned nLength;
unsigned nTmpVal;
CString strTmp,strFull;
unsigned nPosEnd;
unsigned nPosSaved;
bool bRet;
if (bInject) {
// Redirect Buf() to DHT table in MJPGDHTSeg[]
// ... so change mode that Buf() call uses
m_bBufFakeDHT = true;
// Preserve the "m_nPos" pointer, at end we undo it
// And we also start at 2 which is just after FFC4 in array
nPosSaved = m_nPos;
m_nPos = 2;
}
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
nPosEnd = m_nPos+nLength;
m_nPos+=2;
strTmp.Format(_T(" Huffman table length = %u"),nLength);
m_pLog->AddLine(strTmp);
unsigned nDhtClass_Tc; // Range 0..1
unsigned nDhtHuffTblId_Th; // Range 0..3
// In various places, added m_bStateAbort check to allow us
// to escape in case we get in excessive number of DHT entries
// See BUG FIX #1003
while ((!m_bStateAbort)&&(nPosEnd > m_nPos))
{
m_pLog->AddLine(_T(" ----"));
nTmpVal = Buf(m_nPos++);
nDhtClass_Tc = (nTmpVal & 0xF0) >> 4; // Tc, range 0..1
nDhtHuffTblId_Th = nTmpVal & 0x0F; // Th, range 0..3
strTmp.Format(_T(" Destination ID = %u"),nDhtHuffTblId_Th);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" Class = %u (%s)"),nDhtClass_Tc,(nDhtClass_Tc?_T("AC Table"):_T("DC / Lossless Table")));
m_pLog->AddLine(strTmp);
// Add in some error checking to prevent
if (nDhtClass_Tc >= MAX_DHT_CLASS) {
strTmp.Format(_T("ERROR: Invalid DHT Class (%u). Aborting DHT Load."),nDhtClass_Tc);
m_pLog->AddLineErr(strTmp);
m_nPos = nPosEnd;
//m_bStateAbort = true; // Stop decoding
break;
}
if (nDhtHuffTblId_Th >= MAX_DHT_DEST_ID) {
strTmp.Format(_T("ERROR: Invalid DHT Dest ID (%u). Aborting DHT Load."),nDhtHuffTblId_Th);
m_pLog->AddLineErr(strTmp);
m_nPos = nPosEnd;
//m_bStateAbort = true; // Stop decoding
break;
}
// Read in the array of DHT code lengths
for (unsigned int i=1;i<=MAX_DHT_CODELEN;i++)
{
m_anDhtNumCodesLen_Li[i] = Buf(m_nPos++); // Li, range 0..255
}
#define DECODE_DHT_MAX_DHT 256
unsigned int anDhtCodeVal[DECODE_DHT_MAX_DHT+1]; // Should only need max 162 codes
unsigned int nDhtInd;
unsigned int nDhtCodesTotal;
// Clear out the code list
for (nDhtInd = 0;nDhtInd <DECODE_DHT_MAX_DHT;nDhtInd++)
{
anDhtCodeVal[nDhtInd] = 0xFFFF; // Dummy value
}
// Now read in all of the DHT codes according to the lengths
// read in earlier
nDhtCodesTotal = 0;
nDhtInd = 0;
for (unsigned int nIndLen=1;((!m_bStateAbort)&&(nIndLen<=MAX_DHT_CODELEN));nIndLen++)
{
// Keep a total count of the number of DHT codes read
nDhtCodesTotal += m_anDhtNumCodesLen_Li[nIndLen];
strFull.Format(_T(" Codes of length %02u bits (%03u total): "),nIndLen,m_anDhtNumCodesLen_Li[nIndLen]);
for (unsigned int nIndCode=0;((!m_bStateAbort)&&(nIndCode<m_anDhtNumCodesLen_Li[nIndLen]));nIndCode++)
{
// Start a new line for every 16 codes
if ( (nIndCode != 0) && ((nIndCode % 16) == 0) ) {
strFull = _T(" ");
}
nTmpVal = Buf(m_nPos++);
strTmp.Format(_T("%02X "),nTmpVal);
strFull += strTmp;
// Only write 16 codes per line
if ((nIndCode % 16) == 15) {
m_pLog->AddLine(strFull);
strFull = _T("");
}
// Save the huffman code
// Just in case we have more DHT codes than we expect, trap
// the range check here, otherwise we'll have buffer overrun!
if (nDhtInd < DECODE_DHT_MAX_DHT) {
anDhtCodeVal[nDhtInd++] = nTmpVal; // Vij, range 0..255
} else {
nDhtInd++;
strTmp.Format(_T("Excessive DHT entries (%u)... skipping"),nDhtInd);
m_pLog->AddLineErr(strTmp);
if (!m_bStateAbort) { DecodeErrCheck(true); }
}
}
m_pLog->AddLine(strFull);
}
strTmp.Format(_T(" Total number of codes: %03u"),nDhtCodesTotal);
m_pLog->AddLine(strTmp);
unsigned int nDhtLookupInd = 0;
// Now print out the actual binary strings!
unsigned long nBitVal = 0;
unsigned int nCodeVal = 0;
nDhtInd = 0;
if (m_pAppConfig->bOutputDHTexpand) {
m_pLog->AddLine(_T(""));
m_pLog->AddLine(_T(" Expanded Form of Codes:"));
}
for (unsigned int nBitLen=1;((!m_bStateAbort)&&(nBitLen<=16));nBitLen++)
{
if (m_anDhtNumCodesLen_Li[nBitLen] > 0)
{
if (m_pAppConfig->bOutputDHTexpand) {
strTmp.Format(_T(" Codes of length %02u bits:"),nBitLen);
m_pLog->AddLine(strTmp);
}
// Codes exist for this bit-length
// Walk through and generate the bitvalues
for (unsigned int bit_ind=1;((!m_bStateAbort)&&(bit_ind<=m_anDhtNumCodesLen_Li[nBitLen]));bit_ind++)
{
unsigned int nDecVal = nCodeVal;
unsigned int nBinBit;
TCHAR acBinStr[17] = _T("");
unsigned int nBinStrLen = 0;
// If the user has enabled output of DHT expanded tables,
// report the bit-string sequences.
if (m_pAppConfig->bOutputDHTexpand) {
for (unsigned int nBinInd=nBitLen;nBinInd>=1;nBinInd--)
{
nBinBit = (nDecVal >> (nBinInd-1)) & 1;
acBinStr[nBinStrLen++] = (nBinBit)?'1':'0';
}
acBinStr[nBinStrLen] = '\0';
strFull.Format(_T(" %s = %02X"),acBinStr,anDhtCodeVal[nDhtInd]);
// The following are only valid for AC components
// Bug [3442132]
if (nDhtClass_Tc == DHT_CLASS_AC) {
if (anDhtCodeVal[nDhtInd] == 0x00) { strFull += _T(" (EOB)"); }
if (anDhtCodeVal[nDhtInd] == 0xF0) { strFull += _T(" (ZRL)"); }
}
strTmp.Format(_T("%-40s (Total Len = %2u)"),(LPCTSTR)strFull,nBitLen + (anDhtCodeVal[nDhtInd] & 0xF));
m_pLog->AddLine(strTmp);
}
// Store the lookup value
// Shift left to MSB of 32-bit
unsigned nTmpMask = m_anMaskLookup[nBitLen];
unsigned nTmpBits = nDecVal << (32-nBitLen);
unsigned nTmpCode = anDhtCodeVal[nDhtInd];
bRet = m_pImgDec->SetDhtEntry(nDhtHuffTblId_Th,nDhtClass_Tc,nDhtLookupInd,nBitLen,
nTmpBits,nTmpMask,nTmpCode);
DecodeErrCheck(bRet);
nDhtLookupInd++;
// Move to the next code
nCodeVal++;
nDhtInd++;
}
}
// For each loop iteration (on bit length), we shift the code value
nCodeVal <<= 1;
}
// Now store the dht_lookup_size
unsigned nTmpSize = nDhtLookupInd;
bRet = m_pImgDec->SetDhtSize(nDhtHuffTblId_Th,nDhtClass_Tc,nTmpSize);
if (!m_bStateAbort) { DecodeErrCheck(bRet); }
m_pLog->AddLine(_T(""));
}
if (bInject) {
// Restore position (as if we didn't move)
m_nPos = nPosSaved;
m_bBufFakeDHT = false;
}
}
// Check return value of previous call. If failed, then ask
// user if they wish to continue decoding. If no, then flag to
// the decoder that we're done (avoids continuous failures)
void CjfifDecode::DecodeErrCheck(bool bRet)
{
if (!bRet) {
if (m_pAppConfig->bInteractive) {
if (AfxMessageBox(_T("Do you want to continue decoding?"),MB_YESNO|MB_ICONQUESTION)== IDNO) {
m_bStateAbort = true;
}
}
}
}
// This routine is called after the expected fields of the marker segment
// have been processed. The file position should line up with the offset
// dictated by the marker length. If a mismatch is detected, report an
// error.
//
// RETURN:
// - True if decode error is fatal (configurable)
//
bool CjfifDecode::ExpectMarkerEnd(unsigned long nMarkerStart,unsigned nMarkerLen)
{
CString strTmp;
unsigned long nMarkerEnd = nMarkerStart + nMarkerLen;
unsigned long nMarkerExtra = nMarkerEnd - m_nPos;
if (m_nPos < nMarkerEnd) {
// The length indicates that there is more data than we processed
strTmp.Format(_T(" WARNING: Marker length longer than expected"));
m_pLog->AddLineWarn(strTmp);
if (!m_pAppConfig->bRelaxedParsing) {
// Abort
m_pLog->AddLineErr(_T(" Stopping decode"));
m_pLog->AddLineErr(_T(" Use [Img Search Fwd/Rev] to locate other valid embedded JPEGs"));
return false;
} else {
// Warn and skip
strTmp.Format(_T(" Skipping remainder [%u bytes]"),nMarkerExtra);
m_pLog->AddLineWarn(strTmp);
m_nPos += nMarkerExtra;
}
} else if (m_nPos > nMarkerEnd) {
// The length indicates that there is less data than we processed
strTmp.Format(_T(" WARNING: Marker length shorter than expected"));
m_pLog->AddLineWarn(strTmp);
if (!m_pAppConfig->bRelaxedParsing) {
// Abort
m_pLog->AddLineErr(_T(" Stopping decode"));
m_pLog->AddLineErr(_T(" Use [Img Search Fwd/Rev] to locate other valid embedded JPEGs"));
return false;
} else {
// Warn but no skip
// Note that we can't skip as the length would imply a rollback
// Most resilient solution is probably to assume length was
// wrong and continue from where the marker should have ended.
// For resiliency, attempt two methods to find point to resume:
// 1) Current position
// 2) Actual length defined in marker
if (Buf(m_nPos) == 0xFF) {
// Using actual data expected seems more promising
m_pLog->AddLineWarn(_T(" Resuming decode"));
} else if (Buf(nMarkerEnd) == 0xFF) {
// Using actual length seems more promising
m_nPos = nMarkerEnd;
m_pLog->AddLineWarn(_T(" Rolling back pointer to end indicated by length"));
m_pLog->AddLineWarn(_T(" Resuming decode"));
} else {
// No luck. Expect marker failure now
m_pLog->AddLineWarn(_T(" Resuming decode"));
}
}
}
// If we get here, then we haven't seen a fatal issue
return true;
}
// Validate an unsigned value to ensure it is in allowable range
// - If the value is outside the range, an error is shown and
// the parsing stops if relaxed parsing is not enabled
// - An optional override value is provided for the resume case
//
// INPUT:
// - nVal Input value (unsigned 32-bit)
// - nMin Minimum allowed value
// - nMax Maximum allowed value
// - strName Name of the field
// - bOverride Should we override the value upon out-of-range?
// - nOverrideVal Value to override if bOverride and out-of-range
//
// PRE:
// - m_pAppConfig
//
// OUTPUT:
// - nVal Output value (including any override)
//
bool CjfifDecode::ValidateValue(unsigned &nVal,unsigned nMin,unsigned nMax,CString strName,bool bOverride,unsigned nOverrideVal)
{
CString strErr;
if ((nVal >= nMin) && (nVal <= nMax)) {
// Value is within range
return true;
} else {
if (nVal < nMin) {
strErr.Format(_T(" ERROR: %s value too small (Actual = %u, Expected >= %u)"),
(LPCTSTR)strName,nVal,nMin);
m_pLog->AddLineErr(strErr);
} else if (nVal > nMax) {
strErr.Format(_T(" ERROR: %s value too large (Actual = %u, Expected <= %u)"),
(LPCTSTR)strName,nVal,nMax);
m_pLog->AddLineErr(strErr);
}
if (!m_pAppConfig->bRelaxedParsing) {
// Defined as fatal error
// TODO: Replace with glb_strMsgStopDecode?
m_pLog->AddLineErr(_T(" Stopping decode"));
m_pLog->AddLineErr(_T(" Use [Relaxed Parsing] to continue"));
return false;
} else {
// Non-fatal
if (bOverride) {
// Update value with override
nVal = nOverrideVal;
strErr.Format(_T(" WARNING: Forcing value to [%u]"),nOverrideVal);
m_pLog->AddLineWarn(strErr);
m_pLog->AddLineWarn(_T(" Resuming decode"));
} else {
// No override
strErr.Format(_T(" Resuming decode"));
m_pLog->AddLineWarn(strErr);
}
return true;
}
}
}
// This is the primary JFIF marker parser. It reads the
// marker value at the current file position and launches the
// specific parser routine. This routine exits when
#define DECMARK_OK 0
#define DECMARK_ERR 1
#define DECMARK_EOI 2
unsigned CjfifDecode::DecodeMarker()
{
TCHAR acIdentifier[MAX_IDENTIFIER];
CString strTmp;
CString strFull; // Used for concatenation
unsigned nLength; // General purpose
unsigned nTmpVal;
unsigned nCode;
unsigned long nPosEnd;
unsigned long nPosSaved; // General-purpose saved position in file
unsigned long nPosExifStart;
unsigned nRet; // General purpose return value
bool bRet;
unsigned long nPosMarkerStart; // Offset for current marker
unsigned nColTransform = 0; // Color Transform from APP14 marker
// For DQT
CString strDqtPrecision = _T("");
CString strDqtZigZagOrder = _T("");
if (Buf(m_nPos) != 0xFF) {
if (m_nPos == 0) {
// Don't give error message if we've already alerted them of AVI / PSD
if ((!m_bAvi) && (!m_bPsd)) {
strTmp.Format(_T("NOTE: File did not start with JPEG marker. Consider using [Tools->Img Search Fwd] to locate embedded JPEG."));
m_pLog->AddLineErr(strTmp);
}
} else {
strTmp.Format(_T("ERROR: Expected marker 0xFF, got 0x%02X @ offset 0x%08X. Consider using [Tools->Img Search Fwd/Rev]."),Buf(m_nPos),m_nPos);
m_pLog->AddLineErr(strTmp);
}
m_nPos++;
return DECMARK_ERR;
}
m_nPos++;
// Read the current marker code
nCode = Buf(m_nPos++);
// Handle Marker Padding
//
// According to Section B.1.1.2:
// "Any marker may optionally be preceded by any number of fill bytes, which are bytes assigned code X�FF�."
//
unsigned nSkipMarkerPad = 0;
while (nCode == 0xFF) {
// Count the pad
nSkipMarkerPad++;
// Read another byte
nCode = Buf(m_nPos++);
}
// Report out any padding
if (nSkipMarkerPad>0) {
strTmp.Format(_T("*** Skipped %u marker pad bytes ***"),nSkipMarkerPad);
m_pLog->AddLineHdr(strTmp);
}
// Save the current marker offset
nPosMarkerStart = m_nPos;
AddHeader(nCode);
switch (nCode)
{
case JFIF_SOI: // SOI
m_bStateSoi = true;
break;
case JFIF_APP12:
// Photoshop DUCKY (Save For Web)
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
//nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian);
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
nPosSaved = m_nPos;
m_nPos += 2; // Move past length now that we've used it
_tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1));
acIdentifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case
strTmp.Format(_T(" Identifier = [%s]"),acIdentifier);
m_pLog->AddLine(strTmp);
m_nPos += (unsigned)_tcslen(acIdentifier)+1;
if (_tcscmp(acIdentifier,_T("Ducky")) != 0)
{
m_pLog->AddLine(_T(" Not Photoshop DUCKY. Skipping remainder."));
}
else // Photoshop
{
// Please see reference on http://cpan.uwinnipeg.ca/htdocs/Image-ExifTool/Image/ExifTool/APP12.pm.html
// A direct indexed approach should be safe
m_nImgQualPhotoshopSfw = Buf(m_nPos+6);
strTmp.Format(_T(" Photoshop Save For Web Quality = [%d]"),m_nImgQualPhotoshopSfw);
m_pLog->AddLine(strTmp);
}
// Restore original position in file to a point
// after the section
m_nPos = nPosSaved+nLength;
break;
case JFIF_APP14:
// JPEG Adobe tag
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
nPosSaved = m_nPos;
// Some files had very short segment (eg. nLength=2)
if (nLength < 2+12) {
m_pLog->AddLine(_T(" Segment too short for Identifier. Skipping remainder."));
m_nPos = nPosSaved+nLength;
break;
}
m_nPos += 2; // Move past length now that we've used it
// TODO: Confirm Adobe flag
m_nPos += 5;
nTmpVal = Buf(m_nPos+0)*256 + Buf(m_nPos+1);
strTmp.Format(_T(" DCTEncodeVersion = %u"),nTmpVal);
m_pLog->AddLine(strTmp);
nTmpVal = Buf(m_nPos+2)*256 + Buf(m_nPos+3);
strTmp.Format(_T(" APP14Flags0 = %u"),nTmpVal);
m_pLog->AddLine(strTmp);
nTmpVal = Buf(m_nPos+4)*256 + Buf(m_nPos+5);
strTmp.Format(_T(" APP14Flags1 = %u"),nTmpVal);
m_pLog->AddLine(strTmp);
nColTransform = Buf(m_nPos+6);
switch (nColTransform) {
case APP14_COLXFM_UNK_RGB:
strTmp.Format(_T(" ColorTransform = %u [Unknown (RGB or CMYK)]"),nColTransform);
break;
case APP14_COLXFM_YCC:
strTmp.Format(_T(" ColorTransform = %u [YCbCr]"),nColTransform);
break;
case APP14_COLXFM_YCCK:
strTmp.Format(_T(" ColorTransform = %u [YCCK]"),nColTransform);
break;
default:
strTmp.Format(_T(" ColorTransform = %u [???]"),nColTransform);
break;
}
m_pLog->AddLine(strTmp);
m_nApp14ColTransform = (nColTransform & 0xFF);
// Restore original position in file to a point
// after the section
m_nPos = nPosSaved+nLength;
break;
case JFIF_APP13:
// Photoshop (Save As)
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
//nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian);
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
nPosSaved = m_nPos;
// Some files had very short segment (eg. nLength=2)
if (nLength < 2+20) {
m_pLog->AddLine(_T(" Segment too short for Identifier. Skipping remainder."));
m_nPos = nPosSaved+nLength;
break;
}
m_nPos += 2; // Move past length now that we've used it
_tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1));
acIdentifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case
strTmp.Format(_T(" Identifier = [%s]"),acIdentifier);
m_pLog->AddLine(strTmp);
m_nPos += (unsigned)_tcslen(acIdentifier)+1;
if (_tcscmp(acIdentifier,_T("Photoshop 3.0")) != 0)
{
m_pLog->AddLine(_T(" Not Photoshop. Skipping remainder."));
}
else // Photoshop
{
DecodeApp13Ps();
}
// Restore original position in file to a point
// after the section
m_nPos = nPosSaved+nLength;
break;
case JFIF_APP1:
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
//nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian);
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
nPosSaved = m_nPos;
m_nPos += 2; // Move past length now that we've used it
_tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1));
acIdentifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case
strTmp.Format(_T(" Identifier = [%s]"),acIdentifier);
m_pLog->AddLine(strTmp);
m_nPos += (unsigned)_tcslen(acIdentifier);
if (!_tcsnccmp(acIdentifier,_T("http://ns.adobe.com/xap/1.0/\x00"),29) != 0) {
// XMP
m_pLog->AddLine(_T(" XMP = "));
m_nPos++;
unsigned nPosMarkerEnd = nPosSaved+nLength-1;
unsigned sXmpLen = nPosMarkerEnd-m_nPos;
char cXmpChar;
bool bNonSpace;
CString strLine;
// Reset state
strLine = _T(" |");
bNonSpace = false;
for (unsigned nInd=0;nInd<sXmpLen;nInd++) {
// Get the next char
cXmpChar = (char)m_pWBuf->Buf(m_nPos+nInd);
// Detect a non-space in line
if ((cXmpChar != 0x20) && (cXmpChar != 0x0A)) {
bNonSpace = true;
}
// Detect Linefeed, print out line
if (cXmpChar == 0x0A) {
// Only print line if some non-space elements!
if (bNonSpace) {
m_pLog->AddLine(strLine);
}
// Reset state
strLine = _T(" |");
bNonSpace = false;
} else {
// Add the char
strLine.AppendChar(cXmpChar);
}
}
}
else if (!_tcscmp(acIdentifier,_T("Exif")) != 0)
{
// Only decode it further if it is EXIF format
m_nPos += 2; // Skip two 00 bytes
nPosExifStart = m_nPos; // Save m_nPos @ start of EXIF used for all IFD offsets
// =========== EXIF TIFF Header (Start) ===========
// - Defined in Exif 2.2 Standard (JEITA CP-3451) section 4.5.2
// - Contents (8 bytes total)
// - Byte order (2 bytes)
// - 0x002A (2 bytes)
// - Offset of 0th IFD (4 bytes)
unsigned char acIdentifierTiff[9];
strFull = _T("");
strTmp = _T("");
strFull = _T(" Identifier TIFF = ");
for (unsigned int i=0;i<8;i++) {
acIdentifierTiff[i] = (unsigned char)Buf(m_nPos++);
}
strTmp = PrintAsHexUC(acIdentifierTiff,8);
strFull += strTmp;
m_pLog->AddLine(strFull);
switch (acIdentifierTiff[0]*256+acIdentifierTiff[1])
{
case 0x4949: // "II"
// Intel alignment
m_nImgExifEndian = 0;
m_pLog->AddLine(_T(" Endian = Intel (little)"));
break;
case 0x4D4D: // "MM"
// Motorola alignment
m_nImgExifEndian = 1;
m_pLog->AddLine(_T(" Endian = Motorola (big)"));
break;
}
// We expect the TAG mark of 0x002A (depending on endian mode)
unsigned test_002a;
test_002a = ByteSwap2(acIdentifierTiff[2],acIdentifierTiff[3]);
strTmp.Format(_T(" TAG Mark x002A = 0x%04X"),test_002a);
m_pLog->AddLine(strTmp);
unsigned nIfdCount; // Current IFD #
unsigned nOffsetIfd1;
// Mark pointer to EXIF Sub IFD as 0 so that we can
// detect if the tag never showed up.
m_nImgExifSubIfdPtr = 0;
m_nImgExifMakerPtr = 0;
m_nImgExifGpsIfdPtr = 0;
m_nImgExifInteropIfdPtr = 0;
bool exif_done = FALSE;
nOffsetIfd1 = ByteSwap4(acIdentifierTiff[4],acIdentifierTiff[5],
acIdentifierTiff[6],acIdentifierTiff[7]);
// =========== EXIF TIFF Header (End) ===========
// =========== EXIF IFD 0 ===========
// Do we start the 0th IFD for the "Primary Image Data"?
// Even though the nOffsetIfd1 pointer should indicate to
// us where the IFD should start (0x0008 if immediately after
// EXIF TIFF Header), I have observed JPEG files that
// do not contain the IFD. Therefore, we must check for this
// condition by comparing against the APP marker length.
// Example file: http://img9.imageshack.us/img9/194/90114543.jpg
if ((nPosSaved + nLength) <= (nPosExifStart+nOffsetIfd1)) {
// We've run out of space for any IFD, so cancel now
exif_done = true;
m_pLog->AddLine(_T(" NOTE: No IFD entries"));
}
nIfdCount = 0;
while (!exif_done) {
m_pLog->AddLine(_T(""));
strTmp.Format(_T("IFD%u"),nIfdCount);
// Process the IFD
nRet = DecodeExifIfd(strTmp,nPosExifStart,nOffsetIfd1);
// Now that we have gone through all entries in the IFD directory,
// we read the offset to the next IFD
nOffsetIfd1 = ByteSwap4(Buf(m_nPos+0),Buf(m_nPos+1),Buf(m_nPos+2),Buf(m_nPos+3));
m_nPos += 4;
strTmp.Format(_T(" Offset to Next IFD = 0x%08X"),nOffsetIfd1);
m_pLog->AddLine(strTmp);
if (nRet != 0) {
// Error condition (DecodeExifIfd returned error)
nOffsetIfd1 = 0x00000000;
}
if (nOffsetIfd1 == 0x00000000) {
// Either error condition or truly end of IFDs
exif_done = TRUE;
} else {
nIfdCount++;
}
} // while ! exif_done
// If EXIF SubIFD was defined, then handle it now
if (m_nImgExifSubIfdPtr != 0)
{
m_pLog->AddLine(_T(""));
DecodeExifIfd(_T("SubIFD"),nPosExifStart,m_nImgExifSubIfdPtr);
}
if (m_nImgExifMakerPtr != 0)
{
m_pLog->AddLine(_T(""));
DecodeExifIfd(_T("MakerIFD"),nPosExifStart,m_nImgExifMakerPtr);
}
if (m_nImgExifGpsIfdPtr != 0)
{
m_pLog->AddLine(_T(""));
DecodeExifIfd(_T("GPSIFD"),nPosExifStart,m_nImgExifGpsIfdPtr);
}
if (m_nImgExifInteropIfdPtr != 0)
{
m_pLog->AddLine(_T(""));
DecodeExifIfd(_T("InteropIFD"),nPosExifStart,m_nImgExifInteropIfdPtr);
}
} else {
strTmp.Format(_T("Identifier [%s] not supported. Skipping remainder."),(LPCTSTR)acIdentifier);
m_pLog->AddLine(strTmp);
}
//////////
// Dump out Makernote area
// TODO: Disabled for now
#if 0
unsigned ptr_base;
if (m_bVerbose)
{
if (m_nImgExifMakerPtr != 0)
{
// FIXME: Seems that nPosExifStart is not initialized in VERBOSE mode
ptr_base = nPosExifStart+m_nImgExifMakerPtr;
m_pLog->AddLine(_T("Exif Maker IFD DUMP"));
strFull.Format(_T(" MarkerOffset @ 0x%08X"),ptr_base);
m_pLog->AddLine(strFull);
}
}
#endif
// End of dump out makernote area
// Restore file position
m_nPos = nPosSaved;
// Restore original position in file to a point
// after the section
m_nPos = nPosSaved+nLength;
break;
case JFIF_APP2:
// Typically used for Flashpix and possibly ICC profiles
// Photoshop (Save As)
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
//nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian);
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
nPosSaved = m_nPos;
m_nPos += 2; // Move past length now that we've used it
_tcscpy_s(acIdentifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1));
acIdentifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case
strTmp.Format(_T(" Identifier = [%s]"),acIdentifier);
m_pLog->AddLine(strTmp);
m_nPos += (unsigned)_tcslen(acIdentifier)+1;
if (_tcscmp(acIdentifier,_T("FPXR")) == 0) {
// Photoshop
m_pLog->AddLine(_T(" FlashPix:"));
DecodeApp2Flashpix();
} else if (_tcscmp(acIdentifier,_T("ICC_PROFILE")) == 0) {
// ICC Profile
m_pLog->AddLine(_T(" ICC Profile:"));
DecodeApp2IccProfile(nLength);
} else {
m_pLog->AddLine(_T(" Not supported. Skipping remainder."));
}
// Restore original position in file to a point
// after the section
m_nPos = nPosSaved+nLength;
break;
case JFIF_APP3:
case JFIF_APP4:
case JFIF_APP5:
case JFIF_APP6:
case JFIF_APP7:
case JFIF_APP8:
case JFIF_APP9:
case JFIF_APP10:
case JFIF_APP11:
//case JFIF_APP12: // Handled separately
//case JFIF_APP13: // Handled separately
//case JFIF_APP14: // Handled separately
case JFIF_APP15:
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
//nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian);
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
if (m_bVerbose)
{
strFull = _T("");
for (unsigned int i=0;i<nLength;i++)
{
// Start a new line for every 16 codes
if ((i % 16) == 0) {
strFull.Format(_T(" MarkerOffset [%04X]: "),i);
} else if ((i % 8) == 0) {
strFull += _T(" ");
}
nTmpVal = Buf(m_nPos+i);
strTmp.Format(_T("%02X "),nTmpVal);
strFull += strTmp;
if ((i%16) == 15) {
m_pLog->AddLine(strFull);
strFull = _T("");
}
}
m_pLog->AddLine(strFull);
strFull = _T("");
for (unsigned int i=0;i<nLength;i++)
{
// Start a new line for every 16 codes
if ((i % 32) == 0) {
strFull.Format(_T(" MarkerOffset [%04X]: "),i);
} else if ((i % 8) == 0) {
strFull += _T(" ");
}
nTmpVal = Buf(m_nPos+i);
if (_istprint(nTmpVal)) {
strTmp.Format(_T("%c"),nTmpVal);
strFull += strTmp;
} else {
strFull += _T(".");
}
if ((i%32)==31) {
m_pLog->AddLine(strFull);
}
}
m_pLog->AddLine(strFull);
} // nVerbose
m_nPos += nLength;
break;
case JFIF_APP0: // APP0
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
//nLength = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian);
m_nPos+=2;
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
_tcscpy_s(m_acApp0Identifier,MAX_IDENTIFIER,m_pWBuf->BufReadStrn(m_nPos,MAX_IDENTIFIER-1));
m_acApp0Identifier[MAX_IDENTIFIER-1] = 0; // Null terminate just in case
strTmp.Format(_T(" Identifier = [%s]"),m_acApp0Identifier);
m_pLog->AddLine(strTmp);
if (!_tcscmp(m_acApp0Identifier,_T("JFIF")))
{
// Only process remainder if it is JFIF. This marker
// is also used for application-specific functions.
m_nPos += (unsigned)(_tcslen(m_acApp0Identifier)+1);
m_nImgVersionMajor = Buf(m_nPos++);
m_nImgVersionMinor = Buf(m_nPos++);
strTmp.Format(_T(" version = [%u.%u]"),m_nImgVersionMajor,m_nImgVersionMinor);
m_pLog->AddLine(strTmp);
m_nImgUnits = Buf(m_nPos++);
m_nImgDensityX = Buf(m_nPos)*256 + Buf(m_nPos+1);
//m_nImgDensityX = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian);
m_nPos+=2;
m_nImgDensityY = Buf(m_nPos)*256 + Buf(m_nPos+1);
//m_nImgDensityY = m_pWBuf->BufX(m_nPos,2,!m_nImgExifEndian);
m_nPos+=2;
strTmp.Format(_T(" density = %u x %u "),m_nImgDensityX,m_nImgDensityY);
strFull = strTmp;
switch (m_nImgUnits)
{
case 0:
strFull += _T("(aspect ratio)");
m_pLog->AddLine(strFull);
break;
case 1:
strFull += _T("DPI (dots per inch)");
m_pLog->AddLine(strFull);
break;
case 2:
strFull += _T("DPcm (dots per cm)");
m_pLog->AddLine(strFull);
break;
default:
strTmp.Format(_T("ERROR: Unknown ImgUnits parameter [%u]"),m_nImgUnits);
strFull += strTmp;
m_pLog->AddLineWarn(strFull);
//return DECMARK_ERR;
break;
}
m_nImgThumbSizeX = Buf(m_nPos++);
m_nImgThumbSizeY = Buf(m_nPos++);
strTmp.Format(_T(" thumbnail = %u x %u"),m_nImgThumbSizeX,m_nImgThumbSizeY);
m_pLog->AddLine(strTmp);
// Unpack the thumbnail:
unsigned thumbnail_r,thumbnail_g,thumbnail_b;
if (m_nImgThumbSizeX && m_nImgThumbSizeY) {
for (unsigned y=0;y<m_nImgThumbSizeY;y++) {
strFull.Format(_T(" Thumb[%03u] = "),y);
for (unsigned x=0;x<m_nImgThumbSizeX;x++) {
thumbnail_r = Buf(m_nPos++);
thumbnail_g = Buf(m_nPos++);
thumbnail_b = Buf(m_nPos++);
strTmp.Format(_T("(0x%02X,0x%02X,0x%02X) "),thumbnail_r,thumbnail_g,thumbnail_b);
strFull += strTmp;
m_pLog->AddLine(strFull);
}
}
}
// TODO:
// - In JPEG-B mode (GeoRaster), we will need to fake out
// the DHT & DQT tables here. Unfortunately, we'll have to
// rely on the user to put us into this mode as there is nothing
// in the file that specifies this mode.
/*
// TODO: Need to ensure that Faked DHT is correct table
AddHeader(JFIF_DHT_FAKE);
DecodeDHT(true);
// Need to mark DHT tables as OK
m_bStateDht = true;
m_bStateDhtFake = true;
m_bStateDhtOk = true;
// ... same for DQT
*/
} else if (!_tcsnccmp(m_acApp0Identifier,_T("AVI1"),4))
{
// AVI MJPEG type
// Need to fill in predefined DHT table from spec:
// OpenDML file format for AVI, section "Proposed Data Chunk Format"
// Described in MMREG.H
m_pLog->AddLine(_T(" Detected MotionJPEG"));
m_pLog->AddLine(_T(" Importing standard Huffman table..."));
m_pLog->AddLine(_T(""));
AddHeader(JFIF_DHT_FAKE);
DecodeDHT(true);
// Need to mark DHT tables as OK
m_bStateDht = true;
m_bStateDhtFake = true;
m_bStateDhtOk = true;
m_nPos += nLength-2; // Skip over, and undo length short read
} else {
// Not JFIF or AVI1
m_pLog->AddLine(_T(" Not known APP0 type. Skipping remainder."));
m_nPos += nLength-2;
}
if (!ExpectMarkerEnd(nPosMarkerStart,nLength))
return DECMARK_ERR;
break;
case JFIF_DQT: // Define quantization tables
m_bStateDqt = true;
unsigned nDqtPrecision_Pq;
unsigned nDqtQuantDestId_Tq;
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Lq
nPosEnd = m_nPos+nLength;
m_nPos+=2;
//XXX strTmp.Format(_T(" Table length <Lq> = %u"),nLength);
strTmp.Format(_T(" Table length = %u"),nLength);
m_pLog->AddLine(strTmp);
while (nPosEnd > m_nPos)
{
strTmp.Format(_T(" ----"));
m_pLog->AddLine(strTmp);
nTmpVal = Buf(m_nPos++); // Pq | Tq
nDqtPrecision_Pq = (nTmpVal & 0xF0) >> 4; // Pq, range 0-1
nDqtQuantDestId_Tq = nTmpVal & 0x0F; // Tq, range 0-3
// Decode per ITU-T.81 standard
#if 1
if (nDqtPrecision_Pq == 0) {
strDqtPrecision = _T("8 bits");
} else if (nDqtPrecision_Pq == 1) {
strDqtPrecision = _T("16 bits");
} else {
strTmp.Format(_T(" Unsupported precision value [%u]"),nDqtPrecision_Pq);
m_pLog->AddLineWarn(strTmp);
strDqtPrecision = _T("???");
// FIXME: Consider terminating marker parsing early
}
if (!ValidateValue(nDqtPrecision_Pq,0,1,_T("DQT Precision <Pq>"),true,0)) return DECMARK_ERR;
if (!ValidateValue(nDqtQuantDestId_Tq,0,3,_T("DQT Destination ID <Tq>"),true,0)) return DECMARK_ERR;
strTmp.Format(_T(" Precision=%s"),(LPCTSTR)strDqtPrecision);
m_pLog->AddLine(strTmp);
#else
// Decode with additional DQT extension (ITU-T-JPEG-Plus-Proposal_R3.doc)
if ((nDqtPrecision_Pq & 0xE) == 0) {
// Per ITU-T.81 Standard
if (nDqtPrecision_Pq == 0) {
strDqtPrecision = _T("8 bits");
} else if (nDqtPrecision_Pq == 1) {
strDqtPrecision = _T("16 bits");
}
strTmp.Format(_T(" Precision=%s"),strDqtPrecision);
m_pLog->AddLine(strTmp);
} else {
// Non-standard
// JPEG-Plus-Proposal-R3:
// - Alternative sub-block-wise sequence
strTmp.Format(_T(" Non-Standard DQT Extension detected"));
m_pLog->AddLineWarn(strTmp);
// FIXME: Should prevent attempt to decode until this is implemented
if (nDqtPrecision_Pq == 0) {
strDqtPrecision = _T("8 bits");
} else if (nDqtPrecision_Pq == 1) {
strDqtPrecision = _T("16 bits");
}
strTmp.Format(_T(" Precision=%s"),strDqtPrecision);
m_pLog->AddLine(strTmp);
if ((nDqtPrecision_Pq & 0x2) == 0) {
strDqtZigZagOrder = _T("Diagonal zig-zag coeff scan seqeunce");
} else if ((nDqtPrecision_Pq & 0x2) == 1) {
strDqtZigZagOrder = _T("Alternate coeff scan seqeunce");
}
strTmp.Format(_T(" Coeff Scan Sequence=%s"),strDqtZigZagOrder);
m_pLog->AddLine(strTmp);
if ((nDqtPrecision_Pq & 0x4) == 1) {
strTmp.Format(_T(" Custom coeff scan sequence"));
m_pLog->AddLine(strTmp);
// Now expect sequence of 64 coefficient entries
CString strSequence = _T("");
for (unsigned nInd=0;nInd<64;nInd++) {
nTmpVal = Buf(m_nPos++);
strTmp.Format(_T("%u"),nTmpVal);
strSequence += strTmp;
if (nInd!=63) {
strSequence += _T(", ");
}
}
strTmp.Format(_T(" Custom sequence = [ %s ]"),strSequence);
m_pLog->AddLine(strTmp);
}
}
#endif
strTmp.Format(_T(" Destination ID=%u"),nDqtQuantDestId_Tq);
if (nDqtQuantDestId_Tq == 0) {
strTmp += _T(" (Luminance)");
}
else if (nDqtQuantDestId_Tq == 1) {
strTmp += _T(" (Chrominance)");
}
else if (nDqtQuantDestId_Tq == 2) {
strTmp += _T(" (Chrominance)");
}
else {
strTmp += _T(" (???)");
}
m_pLog->AddLine(strTmp);
// FIXME: The following is somewhat superseded by ValidateValue() above
// with the exception of skipping remainder
if (nDqtQuantDestId_Tq >= MAX_DQT_DEST_ID) {
strTmp.Format(_T("ERROR: Destination ID <Tq> = %u, >= %u"),nDqtQuantDestId_Tq,MAX_DQT_DEST_ID);
m_pLog->AddLineErr(strTmp);
if (!m_pAppConfig->bRelaxedParsing) {
m_pLog->AddLineErr(_T(" Stopping decode"));
return DECMARK_ERR;
} else {
// Now skip remainder of DQT
// FIXME
strTmp.Format(_T(" Skipping remainder of marker [%u bytes]"),nPosMarkerStart + nLength - m_nPos);
m_pLog->AddLineWarn(strTmp);
m_pLog->AddLine(_T(""));
m_nPos = nPosMarkerStart + nLength;
return DECMARK_OK;
}
}
bool bQuantAllOnes = true;
double dComparePercent;
double dSumPercent=0;
double dSumPercentSqr=0;
for (unsigned nCoeffInd=0;nCoeffInd<MAX_DQT_COEFF;nCoeffInd++)
{
nTmpVal = Buf(m_nPos++);
if (nDqtPrecision_Pq == 1) {
// 16-bit DQT entries!
nTmpVal <<= 8;
nTmpVal += Buf(m_nPos++);
}
m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]] = nTmpVal;
/* scaling factor in percent */
// Now calculate the comparison with the Annex sample
// FIXME: Should probably use check for landscape orientation and
// rotate comparison matrix accordingly
if (nDqtQuantDestId_Tq == 0) {
if (m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]] != 0) {
m_afStdQuantLumCompare[glb_anZigZag[nCoeffInd]] =
(float)(glb_anStdQuantLum[glb_anZigZag[nCoeffInd]]) /
(float)(m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]]);
dComparePercent = 100.0 *
(double)(m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]]) /
(double)(glb_anStdQuantLum[glb_anZigZag[nCoeffInd]]);
} else {
m_afStdQuantLumCompare[glb_anZigZag[nCoeffInd]] = (float)999.99;
dComparePercent = 999.99;
}
} else {
if (m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]] != 0) {
m_afStdQuantChrCompare[glb_anZigZag[nCoeffInd]] =
(float)(glb_anStdQuantChr[glb_anZigZag[nCoeffInd]]) /
(float)(m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]]);
dComparePercent = 100.0 *
(double)(m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]]) /
(double)(glb_anStdQuantChr[glb_anZigZag[nCoeffInd]]);
} else {
m_afStdQuantChrCompare[glb_anZigZag[nCoeffInd]] = (float)999.99;
}
}
dSumPercent += dComparePercent;
dSumPercentSqr += dComparePercent * dComparePercent;
// Check just in case entire table are ones (Quality 100)
if (m_anImgDqtTbl[nDqtQuantDestId_Tq][glb_anZigZag[nCoeffInd]] != 1) bQuantAllOnes = 0;
} // 0..63
// Note that the DQT table that we are saving is already
// after doing zigzag reordering:
// From high freq -> low freq
// To X,Y, left-to-right, top-to-bottom
// Flag this DQT table as being set!
m_abImgDqtSet[nDqtQuantDestId_Tq] = true;
unsigned nCoeffInd;
// Now display the table
for (unsigned nDqtY=0;nDqtY<8;nDqtY++) {
strFull.Format(_T(" DQT, Row #%u: "),nDqtY);
for (unsigned nDqtX=0;nDqtX<8;nDqtX++) {
nCoeffInd = nDqtY*8+nDqtX;
strTmp.Format(_T("%3u "),m_anImgDqtTbl[nDqtQuantDestId_Tq][nCoeffInd]);
strFull += strTmp;
// Store the DQT entry into the Image Decoder
bRet = m_pImgDec->SetDqtEntry(nDqtQuantDestId_Tq,nCoeffInd,glb_anUnZigZag[nCoeffInd],
m_anImgDqtTbl[nDqtQuantDestId_Tq][nCoeffInd]);
DecodeErrCheck(bRet);
}
// Now add the compare with Annex K
// Decided to disable this as it was confusing users
/*
strFull += _T(" AnnexRatio: <");
for (unsigned nDqtX=0;nDqtX<8;nDqtX++) {
nCoeffInd = nDqtY*8+nDqtX;
if (nDqtQuantDestId_Tq == 0) {
strTmp.Format(_T("%5.1f "),m_afStdQuantLumCompare[nCoeffInd]);
} else {
strTmp.Format(_T("%5.1f "),m_afStdQuantChrCompare[nCoeffInd]);
}
strFull += strTmp;
}
strFull += _T(">");
*/
m_pLog->AddLine(strFull);
}
// Perform some statistical analysis of the quality factor
// to determine the likelihood of the current quantization
// table being a scaled version of the "standard" tables.
// If the variance is high, it is unlikely to be the case.
double dQuality;
double dVariance;
dSumPercent /= 64.0; /* mean scale factor */
dSumPercentSqr /= 64.0;
dVariance = dSumPercentSqr - (dSumPercent * dSumPercent); /* variance */
// Generate the equivalent IJQ "quality" factor
if (bQuantAllOnes) /* special case for all-ones table */
dQuality = 100.0;
else if (dSumPercent <= 100.0)
dQuality = (200.0 - dSumPercent) / 2.0;
else
dQuality = 5000.0 / dSumPercent;
// Save the quality rating for later
m_adImgDqtQual[nDqtQuantDestId_Tq] = dQuality;
strTmp.Format(_T(" Approx quality factor = %.2f (scaling=%.2f variance=%.2f)"),
dQuality,dSumPercent,dVariance);
m_pLog->AddLine(strTmp);
}
m_bStateDqtOk = true;
if (!ExpectMarkerEnd(nPosMarkerStart,nLength))
return DECMARK_ERR;
break;
case JFIF_DAC: // DAC (Arithmetic Coding)
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // La
m_nPos+=2;
//XXX strTmp.Format(_T(" Arithmetic coding header length <La> = %u"),nLength);
strTmp.Format(_T(" Arithmetic coding header length = %u"),nLength);
m_pLog->AddLine(strTmp);
unsigned nDAC_n;
unsigned nDAC_Tc,nDAC_Tb;
unsigned nDAC_Cs;
nDAC_n = (nLength>2)?(nLength-2)/2:0;
for (unsigned nInd=0;nInd<nDAC_n;nInd++) {
nTmpVal = Buf(m_nPos++); // Tc,Tb
nDAC_Tc = (nTmpVal & 0xF0) >> 4;
nDAC_Tb = (nTmpVal & 0x0F);
//XXX strTmp.Format(_T(" #%02u: Table class <Tc> = %u"),nInd+1,nDAC_Tc);
strTmp.Format(_T(" #%02u: Table class = %u"),nInd+1,nDAC_Tc);
m_pLog->AddLine(strTmp);
//XXX strTmp.Format(_T(" #%02u: Table destination identifier <Tb> = %u"),nInd+1,nDAC_Tb);
strTmp.Format(_T(" #%02u: Table destination identifier = %u"),nInd+1,nDAC_Tb);
m_pLog->AddLine(strTmp);
nDAC_Cs = Buf(m_nPos++); // Cs
//XXX strTmp.Format(_T(" #%02u: Conditioning table value <Cs> = %u"),nInd+1,nDAC_Cs);
strTmp.Format(_T(" #%02u: Conditioning table value = %u"),nInd+1,nDAC_Cs);
m_pLog->AddLine(strTmp);
if (!ValidateValue(nDAC_Tc,0,1,_T("Table class <Tc>"),true,0)) return DECMARK_ERR;
if (!ValidateValue(nDAC_Tb,0,3,_T("Table destination ID <Tb>"),true,0)) return DECMARK_ERR;
// Parameter range constraints per Table B.6:
// ------------|-------------------------|-------------------|------------
// | Sequential DCT | Progressive DCT | Lossless
// Parameter | Baseline Extended | |
// ------------|-----------|-------------|-------------------|------------
// Cs | Undef | Tc=0: 0-255 | Tc=0: 0-255 | 0-255
// | | Tc=1: 1-63 | Tc=1: 1-63 |
// ------------|-----------|-------------|-------------------|------------
// However, to keep it simple (and not depend on lossless mode),
// we will only check the maximal range
if (!ValidateValue(nDAC_Cs,0,255,_T("Conditioning table value <Cs>"),true,0)) return DECMARK_ERR;
}
if (!ExpectMarkerEnd(nPosMarkerStart,nLength))
return DECMARK_ERR;
break;
case JFIF_DNL: // DNL (Define number of lines)
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Ld
m_nPos+=2;
//XXX strTmp.Format(_T(" Header length <Ld> = %u"),nLength);
strTmp.Format(_T(" Header length = %u"),nLength);
m_pLog->AddLine(strTmp);
nTmpVal = Buf(m_nPos)*256 + Buf(m_nPos+1); // NL
m_nPos+=2;
//XXX strTmp.Format(_T(" Number of lines <NL> = %u"),nTmpVal);
strTmp.Format(_T(" Number of lines = %u"),nTmpVal);
m_pLog->AddLine(strTmp);
if (!ValidateValue(nTmpVal,1,65535,_T("Number of lines <NL>"),true,1)) return DECMARK_ERR;
if (!ExpectMarkerEnd(nPosMarkerStart,nLength))
return DECMARK_ERR;
break;
case JFIF_EXP:
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Le
m_nPos+=2;
//XXX strTmp.Format(_T(" Header length <Le> = %u"),nLength);
strTmp.Format(_T(" Header length = %u"),nLength);
m_pLog->AddLine(strTmp);
unsigned nEXP_Eh,nEXP_Ev;
nTmpVal = Buf(m_nPos)*256 + Buf(m_nPos+1); // Eh,Ev
nEXP_Eh = (nTmpVal & 0xF0) >> 4;
nEXP_Ev = (nTmpVal & 0x0F);
m_nPos+=2;
//XXX strTmp.Format(_T(" Expand horizontally <Eh> = %u"),nEXP_Eh);
strTmp.Format(_T(" Expand horizontally = %u"),nEXP_Eh);
m_pLog->AddLine(strTmp);
//XXX strTmp.Format(_T(" Expand vertically <Ev> = %u"),nEXP_Ev);
strTmp.Format(_T(" Expand vertically = %u"),nEXP_Ev);
m_pLog->AddLine(strTmp);
if (!ValidateValue(nEXP_Eh,0,1,_T("Expand horizontally <Eh>"),true,0)) return DECMARK_ERR;
if (!ValidateValue(nEXP_Ev,0,1,_T("Expand vertically <Ev>"),true,0)) return DECMARK_ERR;
if (!ExpectMarkerEnd(nPosMarkerStart,nLength))
return DECMARK_ERR;
break;
case JFIF_SOF0: // SOF0 (Baseline DCT)
case JFIF_SOF1: // SOF1 (Extended sequential)
case JFIF_SOF2: // SOF2 (Progressive)
case JFIF_SOF3:
case JFIF_SOF5:
case JFIF_SOF6:
case JFIF_SOF7:
case JFIF_SOF9:
case JFIF_SOF10:
case JFIF_SOF11:
case JFIF_SOF13:
case JFIF_SOF14:
case JFIF_SOF15:
// TODO:
// - JFIF_DHP should be able to reuse the JFIF_SOF marker parsing
// however as we don't support hierarchical image decode, we
// would want to skip the update of class members.
m_bStateSof = true;
// Determine if this is a SOF mode that we support
// At this time, we only support Baseline DCT & Extended Sequential Baseline DCT
// (non-differential) with Huffman coding. Progressive, Lossless,
// Differential and Arithmetic coded modes are not supported.
m_bImgSofUnsupported = true;
if (nCode == JFIF_SOF0) { m_bImgSofUnsupported = false; }
if (nCode == JFIF_SOF1) { m_bImgSofUnsupported = false; }
// For reference, note progressive scan files even though
// we don't currently support their decode
if (nCode == JFIF_SOF2) { m_bImgProgressive = true; }
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Lf
m_nPos+=2;
//XXX strTmp.Format(_T(" Frame header length <Lf> = %u"),nLength);
strTmp.Format(_T(" Frame header length = %u"),nLength);
m_pLog->AddLine(strTmp);
m_nSofPrecision_P = Buf(m_nPos++); // P
//XXX strTmp.Format(_T(" Precision <P> = %u"),m_nSofPrecision_P);
strTmp.Format(_T(" Precision = %u"),m_nSofPrecision_P);
m_pLog->AddLine(strTmp);
if (!ValidateValue(m_nSofPrecision_P,2,16,_T("Precision <P>"),true,8)) return DECMARK_ERR;
m_nSofNumLines_Y = Buf(m_nPos)*256 + Buf(m_nPos+1); // Y
m_nPos += 2;
//XXX strTmp.Format(_T(" Number of Lines <Y> = %u"),m_nSofNumLines_Y);
strTmp.Format(_T(" Number of Lines = %u"),m_nSofNumLines_Y);
m_pLog->AddLine(strTmp);
if (!ValidateValue(m_nSofNumLines_Y,0,65535,_T("Number of Lines <Y>"),true,0)) return DECMARK_ERR;
m_nSofSampsPerLine_X = Buf(m_nPos)*256 + Buf(m_nPos+1); // X
m_nPos += 2;
//XXX strTmp.Format(_T(" Samples per Line <X> = %u"),m_nSofSampsPerLine_X);
strTmp.Format(_T(" Samples per Line = %u"),m_nSofSampsPerLine_X);
m_pLog->AddLine(strTmp);
if (!ValidateValue(m_nSofSampsPerLine_X,1,65535,_T("Samples per Line <X>"),true,1)) return DECMARK_ERR;
strTmp.Format(_T(" Image Size = %u x %u"),m_nSofSampsPerLine_X,m_nSofNumLines_Y);
m_pLog->AddLine(strTmp);
// Determine orientation
// m_nSofSampsPerLine_X = X
// m_nSofNumLines_Y = Y
m_eImgLandscape = ENUM_LANDSCAPE_YES;
if (m_nSofNumLines_Y > m_nSofSampsPerLine_X)
m_eImgLandscape = ENUM_LANDSCAPE_NO;
strTmp.Format(_T(" Raw Image Orientation = %s"),(m_eImgLandscape==ENUM_LANDSCAPE_YES)?_T("Landscape"):_T("Portrait"));
m_pLog->AddLine(strTmp);
m_nSofNumComps_Nf = Buf(m_nPos++); // Nf, range 1..255
//XXX strTmp.Format(_T(" Number of Img components <Nf> = %u"),m_nSofNumComps_Nf);
strTmp.Format(_T(" Number of Img components = %u"),m_nSofNumComps_Nf);
m_pLog->AddLine(strTmp);
if (!ValidateValue(m_nSofNumComps_Nf,1,255,_T("Number of Img components <Nf>"),true,1)) return DECMARK_ERR;
unsigned nCompIdent;
unsigned anSofSampFact[MAX_SOF_COMP_NF];
m_nSofHorzSampFactMax_Hmax = 0;
m_nSofVertSampFactMax_Vmax = 0;
// Now clear the output image content (all components)
// TODO: Migrate some of the bitmap allocation / clearing from
// DecodeScanImg() into ResetImageContent() and call here
//m_pImgDec->ResetImageContent();
// Per JFIF v1.02:
// - Nf = 1 or 3
// - C1 = Y
// - C2 = Cb
// - C3 = Cr
for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++)
{
nCompIdent = Buf(m_nPos++); // Ci, range 0..255
m_anSofQuantCompId[nCompInd] = nCompIdent;
//if (!ValidateValue(m_anSofQuantCompId[nCompInd],0,255,_T("Component ID <Ci>"),true,0)) return DECMARK_ERR;
anSofSampFact[nCompIdent] = Buf(m_nPos++);
m_anSofQuantTblSel_Tqi[nCompIdent] = Buf(m_nPos++); // Tqi, range 0..3
//if (!ValidateValue(m_anSofQuantTblSel_Tqi[nCompIdent],0,3,_T("Table Destination ID <Tqi>"),true,0)) return DECMARK_ERR;
// NOTE: We protect against bad input here as replication ratios are
// determined later that depend on dividing by sampling factor (hence
// possibility of div by 0).
m_anSofHorzSampFact_Hi[nCompIdent] = (anSofSampFact[nCompIdent] & 0xF0) >> 4; // Hi, range 1..4
m_anSofVertSampFact_Vi[nCompIdent] = (anSofSampFact[nCompIdent] & 0x0F); // Vi, range 1..4
//if (!ValidateValue(m_anSofHorzSampFact_Hi[nCompIdent],1,4,_T("Horizontal Sampling Factor <Hi>"),true,1)) return DECMARK_ERR;
//if (!ValidateValue(m_anSofVertSampFact_Vi[nCompIdent],1,4,_T("Vertical Sampling Factor <Vi>"),true,1)) return DECMARK_ERR;
}
// Calculate max sampling factors
for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++)
{
nCompIdent = m_anSofQuantCompId[nCompInd];
// Calculate maximum sampling factor for the SOF. This is only
// used for later generation of m_strImgQuantCss an the SOF
// reporting below. The CimgDecode block is responsible for
// calculating the maximum sampling factor on a per-scan basis.
m_nSofHorzSampFactMax_Hmax = max(m_nSofHorzSampFactMax_Hmax,m_anSofHorzSampFact_Hi[nCompIdent]);
m_nSofVertSampFactMax_Vmax = max(m_nSofVertSampFactMax_Vmax,m_anSofVertSampFact_Vi[nCompIdent]);
}
// Report per-component sampling factors and quantization table selectors
for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++)
{
nCompIdent = m_anSofQuantCompId[nCompInd];
// Create subsampling ratio
// - Protect against division-by-zero
CString strSubsampH = _T("?");
CString strSubsampV = _T("?");
if (m_anSofHorzSampFact_Hi[nCompIdent] > 0) {
strSubsampH.Format(_T("%u"),m_nSofHorzSampFactMax_Hmax/m_anSofHorzSampFact_Hi[nCompIdent]);
}
if (m_anSofVertSampFact_Vi[nCompIdent] > 0) {
strSubsampV.Format(_T("%u"),m_nSofVertSampFactMax_Vmax/m_anSofVertSampFact_Vi[nCompIdent]);
}
strFull.Format(_T(" Component[%u]: "),nCompInd); // Note i in Ci is 1-based
//XXX strTmp.Format(_T("ID=0x%02X, Samp Fac <Hi,Vi>=0x%02X (Subsamp %u x %u), Quant Tbl Sel <Tqi>=0x%02X"),
strTmp.Format(_T("ID=0x%02X, Samp Fac=0x%02X (Subsamp %s x %s), Quant Tbl Sel=0x%02X"),
nCompIdent,anSofSampFact[nCompIdent],
(LPCTSTR)strSubsampH,(LPCTSTR)strSubsampV,
m_anSofQuantTblSel_Tqi[nCompIdent]);
strFull += strTmp;
// Mapping from component index (not ID) to colour channel per JFIF
if (m_nSofNumComps_Nf == 1) {
// Assume grayscale
strFull += _T(" (Lum: Y)");
} else if (m_nSofNumComps_Nf == 3) {
// Assume YCC
if (nCompInd == SCAN_COMP_Y) {
strFull += _T(" (Lum: Y)");
}
else if (nCompInd == SCAN_COMP_CB) {
strFull += _T(" (Chrom: Cb)");
}
else if (nCompInd == SCAN_COMP_CR) {
strFull += _T(" (Chrom: Cr)");
}
} else if (m_nSofNumComps_Nf == 4) {
// Assume YCCK
if (nCompInd == 1) {
strFull += _T(" (Y)");
}
else if (nCompInd == 2) {
strFull += _T(" (Cb)");
}
else if (nCompInd == 3) {
strFull += _T(" (Cr)");
}
else if (nCompInd == 4) {
strFull += _T(" (K)");
}
} else {
strFull += _T(" (???)"); // Unknown
}
m_pLog->AddLine(strFull);
}
// Test for bad input, clean up if bad
for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++)
{
nCompIdent = m_anSofQuantCompId[nCompInd];
if (!ValidateValue(m_anSofQuantCompId[nCompInd],0,255,_T("Component ID <Ci>"),true,0)) return DECMARK_ERR;
if (!ValidateValue(m_anSofQuantTblSel_Tqi[nCompIdent],0,3,_T("Table Destination ID <Tqi>"),true,0)) return DECMARK_ERR;
if (!ValidateValue(m_anSofHorzSampFact_Hi[nCompIdent],1,4,_T("Horizontal Sampling Factor <Hi>"),true,1)) return DECMARK_ERR;
if (!ValidateValue(m_anSofVertSampFact_Vi[nCompIdent],1,4,_T("Vertical Sampling Factor <Vi>"),true,1)) return DECMARK_ERR;
}
// Finally, assign the cleaned values to the decoder
for (unsigned nCompInd=1;((!m_bStateAbort)&&(nCompInd<=m_nSofNumComps_Nf));nCompInd++)
{
nCompIdent = m_anSofQuantCompId[nCompInd];
// Store the DQT Table selection for the Image Decoder
// Param values: Nf,Tqi
// Param ranges: 1..255,0..3
// Note that the Image Decoder doesn't need to see the Component Identifiers
bRet = m_pImgDec->SetDqtTables(nCompInd,m_anSofQuantTblSel_Tqi[nCompIdent]);
DecodeErrCheck(bRet);
// Store the Precision (to handle 12-bit decode)
m_pImgDec->SetPrecision(m_nSofPrecision_P);
}
if (!m_bStateAbort) {
// Set the component sampling factors (chroma subsampling)
// FIXME: check ranging
for (unsigned nCompInd=1;nCompInd<=m_nSofNumComps_Nf;nCompInd++) {
// nCompInd is component index (1...Nf)
// nCompIdent is Component Identifier (Ci)
// Note that the Image Decoder doesn't need to see the Component Identifiers
nCompIdent = m_anSofQuantCompId[nCompInd];
m_pImgDec->SetSofSampFactors(nCompInd,m_anSofHorzSampFact_Hi[nCompIdent],m_anSofVertSampFact_Vi[nCompIdent]);
}
// Now mark the image as been somewhat OK (ie. should
// also be suitable for EmbeddedThumb() and PrepareSignature()
m_bImgOK = true;
m_bStateSofOk = true;
}
if (!ExpectMarkerEnd(nPosMarkerStart,nLength))
return DECMARK_ERR;
break;
case JFIF_COM: // COM
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
m_nPos+=2;
strTmp.Format(_T(" Comment length = %u"),nLength);
m_pLog->AddLine(strTmp);
// Check for JPEG COM vulnerability
// http://marc.info/?l=bugtraq&m=109524346729948
// Note that the recovery is not very graceful. It will assume that the
// field is actually zero-length, which will make the next byte trigger the
// "Expected marker 0xFF" error message and probably abort. There is no
// obvious way to
if ( (nLength == 0) || (nLength == 1) ) {
strTmp.Format(_T(" JPEG Comment Field Vulnerability detected!"));
m_pLog->AddLineErr(strTmp);
strTmp.Format(_T(" Skipping data until next marker..."));
m_pLog->AddLineErr(strTmp);
nLength = 2;
bool bDoneSearch = false;
unsigned nSkipStart = m_nPos;
while (!bDoneSearch) {
if (Buf(m_nPos) != 0xFF) {
m_nPos++;
} else {
bDoneSearch = true;
}
if (m_nPos >= m_pWBuf->GetPosEof()) {
bDoneSearch = true;
}
}
strTmp.Format(_T(" Skipped %u bytes"),m_nPos - nSkipStart);
m_pLog->AddLineErr(strTmp);
// Break out of case statement
break;
}
// Assume COM field valid length (ie. >= 2)
strFull = _T(" Comment=");
m_strComment = _T("");
for (unsigned ind=0;ind<nLength-2;ind++)
{
nTmpVal = Buf(m_nPos++);
if (_istprint(nTmpVal)) {
strTmp.Format(_T("%c"),nTmpVal);
m_strComment += strTmp;
} else {
m_strComment += _T(".");
}
}
strFull += m_strComment;
m_pLog->AddLine(strFull);
break;
case JFIF_DHT: // DHT
m_bStateDht = true;
DecodeDHT(false);
m_bStateDhtOk = true;
break;
case JFIF_SOS: // SOS
unsigned long nPosScanStart; // Byte count at start of scan data segment
m_bStateSos = true;
// NOTE: Only want to capture position of first SOS
// This should make other function such as AVI frame extract
// more robust in case we get multiple SOS segments.
// We assume that this value is reset when we start a new decode
if (m_nPosSos == 0) {
m_nPosSos = m_nPos-2; // Used for Extract. Want to include actual marker
}
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
m_nPos+=2;
// Ensure that we have seen proper markers before we try this one!
if (!m_bStateSofOk) {
strTmp.Format(_T(" ERROR: SOS before valid SOF defined"));
m_pLog->AddLineErr(strTmp);
return DECMARK_ERR;
}
strTmp.Format(_T(" Scan header length = %u"),nLength);
m_pLog->AddLine(strTmp);
m_nSosNumCompScan_Ns = Buf(m_nPos++); // Ns, range 1..4
//XXX strTmp.Format(_T(" Number of image components <Ns> = %u"),m_nSosNumCompScan_Ns);
strTmp.Format(_T(" Number of img components = %u"),m_nSosNumCompScan_Ns);
m_pLog->AddLine(strTmp);
// Just in case something got corrupted, don't want to get out
// of range here. Note that this will be a hard abort, and
// will not resume decoding.
if (m_nSosNumCompScan_Ns > MAX_SOS_COMP_NS) {
strTmp.Format(_T(" ERROR: Scan decode does not support > %u components"),MAX_SOS_COMP_NS);
m_pLog->AddLineErr(strTmp);
return DECMARK_ERR;
}
unsigned nSosCompSel_Cs;
unsigned nSosHuffTblSel;
unsigned nSosHuffTblSelDc_Td;
unsigned nSosHuffTblSelAc_Ta;
// Max range of components indices is between 1..4
for (unsigned int nScanCompInd=1;((nScanCompInd<=m_nSosNumCompScan_Ns) && (!m_bStateAbort));nScanCompInd++)
{
strFull.Format(_T(" Component[%u]: "),nScanCompInd);
nSosCompSel_Cs = Buf(m_nPos++); // Cs, range 0..255
nSosHuffTblSel = Buf(m_nPos++);
nSosHuffTblSelDc_Td = (nSosHuffTblSel & 0xf0)>>4; // Td, range 0..3
nSosHuffTblSelAc_Ta = (nSosHuffTblSel & 0x0f); // Ta, range 0..3
strTmp.Format(_T("selector=0x%02X, table=%u(DC),%u(AC)"),nSosCompSel_Cs,nSosHuffTblSelDc_Td,nSosHuffTblSelAc_Ta);
strFull += strTmp;
m_pLog->AddLine(strFull);
bRet = m_pImgDec->SetDhtTables(nScanCompInd,nSosHuffTblSelDc_Td,nSosHuffTblSelAc_Ta);
DecodeErrCheck(bRet);
}
m_nSosSpectralStart_Ss = Buf(m_nPos++);
m_nSosSpectralEnd_Se = Buf(m_nPos++);
m_nSosSuccApprox_A = Buf(m_nPos++);
strTmp.Format(_T(" Spectral selection = %u .. %u"),m_nSosSpectralStart_Ss,m_nSosSpectralEnd_Se);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" Successive approximation = 0x%02X"),m_nSosSuccApprox_A);
m_pLog->AddLine(strTmp);
if (m_pAppConfig->bOutputScanDump) {
m_pLog->AddLine(_T(""));
m_pLog->AddLine(_T(" Scan Data: (after bitstuff removed)"));
}
// Save the scan data segment position
nPosScanStart = m_nPos;
// Skip over the Scan Data segment
// Pass 1) Quick, allowing for bOutputScanDump to dump first 640B.
// Pass 2) If bDecodeScanImg, we redo the process but in detail decoding.
// FIXME: Not sure why, but if I skip over Pass 1 (eg if I leave in the
// following line uncommented), then I get an error at the end of the
// pass 2 decode (indicating that EOI marker not seen, and expecting
// marker).
// if (m_pAppConfig->bOutputScanDump) {
// --- PASS 1 ---
bool bSkipDone;
unsigned nSkipCount;
unsigned nSkipData;
unsigned nSkipPos;
bool bScanDumpTrunc;
bSkipDone = false;
nSkipCount = 0;
nSkipPos = 0;
bScanDumpTrunc = FALSE;
strFull = _T("");
while (!bSkipDone)
{
nSkipCount++;
nSkipPos++;
nSkipData = Buf(m_nPos++);
if (nSkipData == 0xFF) {
// this could either be a marker or a byte stuff
nSkipData = Buf(m_nPos++);
nSkipCount++;
if (nSkipData == 0x00) {
// Byte stuff
nSkipData = 0xFF;
} else if ((nSkipData >= JFIF_RST0) && (nSkipData <= JFIF_RST7)) {
// Skip over
} else {
// Marker
bSkipDone = true;
m_nPos -= 2;
}
}
if (m_pAppConfig->bOutputScanDump && (!bSkipDone) ) {
// Only display 20 lines of scan data
if (nSkipPos > 640) {
if (!bScanDumpTrunc) {
m_pLog->AddLineWarn(_T(" WARNING: Dump truncated."));
bScanDumpTrunc = TRUE;
}
} else {
if ( ((nSkipPos-1) == 0) || (((nSkipPos-1) % 32) == 0) ) {
strFull = _T(" ");
}
strTmp.Format(_T("%02x "),nSkipData);
strFull += strTmp;
if (((nSkipPos-1) % 32) == 31) {
m_pLog->AddLine(strFull);
strFull = _T("");
}
}
}
// Did we run out of bytes?
// FIXME:
// NOTE: This line here doesn't allow us to attempt to
// decode images that are missing EOI. Maybe this is
// not the best solution here? Instead, we should be
// checking m_nPos against file length? .. and not
// return but "break".
if (!m_pWBuf->GetBufOk()) {
strTmp.Format(_T("ERROR: Ran out of buffer before EOI during phase 1 of Scan decode @ 0x%08X"),m_nPos);
m_pLog->AddLineErr(strTmp);
break;
}
}
m_pLog->AddLine(strFull);
// }
// --- PASS 2 ---
// If the option is set, start parsing!
if (m_pAppConfig->bDecodeScanImg && m_bImgSofUnsupported) {
// SOF marker was of type we don't support, so skip decoding
m_pLog->AddLineWarn(_T(" NOTE: Scan parsing doesn't support this SOF mode."));
#ifndef DEBUG_YCCK
} else if (m_pAppConfig->bDecodeScanImg && (m_nSofNumComps_Nf == 4)) {
m_pLog->AddLineWarn(_T(" NOTE: Scan parsing doesn't support CMYK files yet."));
#endif
} else if (m_pAppConfig->bDecodeScanImg && !m_bImgSofUnsupported) {
if (!m_bStateSofOk) {
m_pLog->AddLineWarn(_T(" NOTE: Scan decode disabled as SOF not decoded."));
} else if (!m_bStateDqtOk) {
m_pLog->AddLineWarn(_T(" NOTE: Scan decode disabled as DQT not decoded."));
} else if (!m_bStateDhtOk) {
m_pLog->AddLineWarn(_T(" NOTE: Scan decode disabled as DHT not decoded."));
} else {
m_pLog->AddLine(_T(""));
// Set the primary image details
m_pImgDec->SetImageDetails(m_nSofSampsPerLine_X,m_nSofNumLines_Y,
m_nSofNumComps_Nf,m_nSosNumCompScan_Ns,m_nImgRstEn,m_nImgRstInterval);
// Only recalculate the scan decoding if we need to (i.e. file
// changed, offset changed, scan option changed)
// TODO: In order to decode multiple scans, we will need to alter the
// way that m_pImgSrcDirty is set
if (m_pImgSrcDirty) {
m_pImgDec->DecodeScanImg(nPosScanStart,true,false);
m_pImgSrcDirty = false;
}
}
}
m_bStateSosOk = true;
break;
case JFIF_DRI:
unsigned nVal;
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
nVal = Buf(m_nPos+2)*256 + Buf(m_nPos+3);
// According to ITU-T spec B.2.4.4, we only expect
// restart markers if DRI value is non-zero!
m_nImgRstInterval = nVal;
if (nVal != 0) {
m_nImgRstEn = true;
} else {
m_nImgRstEn = false;
}
strTmp.Format(_T(" interval = %u"),m_nImgRstInterval);
m_pLog->AddLine(strTmp);
m_nPos += 4;
if (!ExpectMarkerEnd(nPosMarkerStart,nLength))
return DECMARK_ERR;
break;
case JFIF_EOI: // EOI
m_pLog->AddLine(_T(""));
// Save the EOI file position
// NOTE: If the file is missing the EOI, then this variable will be
// set to mark the end of file.
m_nPosEmbedEnd = m_nPos;
m_nPosEoi = m_nPos;
m_bStateEoi = true;
return DECMARK_EOI;
break;
// Markers that are not yet supported in JPEGsnoop
case JFIF_DHP:
// Markers defined for future use / extensions
case JFIF_JPG:
case JFIF_JPG0:
case JFIF_JPG1:
case JFIF_JPG2:
case JFIF_JPG3:
case JFIF_JPG4:
case JFIF_JPG5:
case JFIF_JPG6:
case JFIF_JPG7:
case JFIF_JPG8:
case JFIF_JPG9:
case JFIF_JPG10:
case JFIF_JPG11:
case JFIF_JPG12:
case JFIF_JPG13:
case JFIF_TEM:
// Unsupported marker
// - Provide generic decode based on length
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1); // Length
strTmp.Format(_T(" Header length = %u"),nLength);
m_pLog->AddLine(strTmp);
m_pLog->AddLineWarn(_T(" Skipping unsupported marker"));
m_nPos += nLength;
break;
case JFIF_RST0:
case JFIF_RST1:
case JFIF_RST2:
case JFIF_RST3:
case JFIF_RST4:
case JFIF_RST5:
case JFIF_RST6:
case JFIF_RST7:
// We don't expect to see restart markers outside the entropy coded segment.
// NOTE: RST# are standalone markers, so no length indicator exists
// But for the sake of robustness, we can check here to see if treating
// as a standalone marker will arrive at another marker (ie. OK). If not,
// proceed to assume there is a length indicator.
strTmp.Format(_T(" WARNING: Restart marker [0xFF%02X] detected outside scan"),nCode);
m_pLog->AddLineWarn(strTmp);
if (!m_pAppConfig->bRelaxedParsing) {
// Abort
m_pLog->AddLineErr(_T(" Stopping decode"));
m_pLog->AddLine(_T(" Use [Img Search Fwd/Rev] to locate other valid embedded JPEGs"));
return DECMARK_ERR;
} else {
// Ignore
// Check to see if standalone marker treatment looks OK
if (Buf(m_nPos+2) == 0xFF) {
// Looks like standalone
m_pLog->AddLineWarn(_T(" Ignoring standalone marker. Proceeding with decode."));
m_nPos += 2;
} else {
// Looks like marker with length
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
strTmp.Format(_T(" Header length = %u"),nLength);
m_pLog->AddLine(strTmp);
m_pLog->AddLineWarn(_T(" Skipping marker"));
m_nPos += nLength;
}
}
break;
default:
strTmp.Format(_T(" WARNING: Unknown marker [0xFF%02X]"),nCode);
m_pLog->AddLineWarn(strTmp);
if (!m_pAppConfig->bRelaxedParsing) {
// Abort
m_pLog->AddLineErr(_T(" Stopping decode"));
m_pLog->AddLine(_T(" Use [Img Search Fwd/Rev] to locate other valid embedded JPEGs"));
return DECMARK_ERR;
} else {
// Skip
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
strTmp.Format(_T(" Header length = %u"),nLength);
m_pLog->AddLine(strTmp);
m_pLog->AddLineWarn(_T(" Skipping marker"));
m_nPos += nLength;
}
}
// Add white-space between each marker
m_pLog->AddLine(_T(" "));
// If we decided to abort for any reason, make sure we trap it now.
// This will stop the ProcessFile() while loop. We can set m_bStateAbort
// if user says that they want to stop.
if (m_bStateAbort) {
return DECMARK_ERR;
}
return DECMARK_OK;
}
// Print out a header for the current JFIF marker code
void CjfifDecode::AddHeader(unsigned nCode)
{
CString strTmp;
switch(nCode)
{
case JFIF_SOI: m_pLog->AddLineHdr(_T("*** Marker: SOI (xFFD8) ***")); break;
case JFIF_APP0: m_pLog->AddLineHdr(_T("*** Marker: APP0 (xFFE0) ***")); break;
case JFIF_APP1: m_pLog->AddLineHdr(_T("*** Marker: APP1 (xFFE1) ***")); break;
case JFIF_APP2: m_pLog->AddLineHdr(_T("*** Marker: APP2 (xFFE2) ***")); break;
case JFIF_APP3: m_pLog->AddLineHdr(_T("*** Marker: APP3 (xFFE3) ***")); break;
case JFIF_APP4: m_pLog->AddLineHdr(_T("*** Marker: APP4 (xFFE4) ***")); break;
case JFIF_APP5: m_pLog->AddLineHdr(_T("*** Marker: APP5 (xFFE5) ***")); break;
case JFIF_APP6: m_pLog->AddLineHdr(_T("*** Marker: APP6 (xFFE6) ***")); break;
case JFIF_APP7: m_pLog->AddLineHdr(_T("*** Marker: APP7 (xFFE7) ***")); break;
case JFIF_APP8: m_pLog->AddLineHdr(_T("*** Marker: APP8 (xFFE8) ***")); break;
case JFIF_APP9: m_pLog->AddLineHdr(_T("*** Marker: APP9 (xFFE9) ***")); break;
case JFIF_APP10: m_pLog->AddLineHdr(_T("*** Marker: APP10 (xFFEA) ***")); break;
case JFIF_APP11: m_pLog->AddLineHdr(_T("*** Marker: APP11 (xFFEB) ***")); break;
case JFIF_APP12: m_pLog->AddLineHdr(_T("*** Marker: APP12 (xFFEC) ***")); break;
case JFIF_APP13: m_pLog->AddLineHdr(_T("*** Marker: APP13 (xFFED) ***")); break;
case JFIF_APP14: m_pLog->AddLineHdr(_T("*** Marker: APP14 (xFFEE) ***")); break;
case JFIF_APP15: m_pLog->AddLineHdr(_T("*** Marker: APP15 (xFFEF) ***")); break;
case JFIF_SOF0: m_pLog->AddLineHdr(_T("*** Marker: SOF0 (Baseline DCT) (xFFC0) ***")); break;
case JFIF_SOF1: m_pLog->AddLineHdr(_T("*** Marker: SOF1 (Extended Sequential DCT, Huffman) (xFFC1) ***")); break;
case JFIF_SOF2: m_pLog->AddLineHdr(_T("*** Marker: SOF2 (Progressive DCT, Huffman) (xFFC2) ***")); break;
case JFIF_SOF3: m_pLog->AddLineHdr(_T("*** Marker: SOF3 (Lossless Process, Huffman) (xFFC3) ***")); break;
case JFIF_SOF5: m_pLog->AddLineHdr(_T("*** Marker: SOF5 (Differential Sequential DCT, Huffman) (xFFC4) ***")); break;
case JFIF_SOF6: m_pLog->AddLineHdr(_T("*** Marker: SOF6 (Differential Progressive DCT, Huffman) (xFFC5) ***")); break;
case JFIF_SOF7: m_pLog->AddLineHdr(_T("*** Marker: SOF7 (Differential Lossless Process, Huffman) (xFFC6) ***")); break;
case JFIF_SOF9: m_pLog->AddLineHdr(_T("*** Marker: SOF9 (Sequential DCT, Arithmetic) (xFFC9) ***")); break;
case JFIF_SOF10: m_pLog->AddLineHdr(_T("*** Marker: SOF10 (Progressive DCT, Arithmetic) (xFFCA) ***")); break;
case JFIF_SOF11: m_pLog->AddLineHdr(_T("*** Marker: SOF11 (Lossless Process, Arithmetic) (xFFCB) ***")); break;
case JFIF_SOF13: m_pLog->AddLineHdr(_T("*** Marker: SOF13 (Differential Sequential, Arithmetic) (xFFCD) ***")); break;
case JFIF_SOF14: m_pLog->AddLineHdr(_T("*** Marker: SOF14 (Differential Progressive DCT, Arithmetic) (xFFCE) ***")); break;
case JFIF_SOF15: m_pLog->AddLineHdr(_T("*** Marker: SOF15 (Differential Lossless Process, Arithmetic) (xFFCF) ***")); break;
case JFIF_JPG: m_pLog->AddLineHdr(_T("*** Marker: JPG (xFFC8) ***")); break;
case JFIF_DAC: m_pLog->AddLineHdr(_T("*** Marker: DAC (xFFCC) ***")); break;
case JFIF_RST0:
case JFIF_RST1:
case JFIF_RST2:
case JFIF_RST3:
case JFIF_RST4:
case JFIF_RST5:
case JFIF_RST6:
case JFIF_RST7:
m_pLog->AddLineHdr(_T("*** Marker: RST# ***"));
break;
case JFIF_DQT: // Define quantization tables
m_pLog->AddLineHdr(_T("*** Marker: DQT (xFFDB) ***"));
m_pLog->AddLineHdrDesc(_T(" Define a Quantization Table."));
break;
case JFIF_COM: // COM
m_pLog->AddLineHdr(_T("*** Marker: COM (Comment) (xFFFE) ***"));
break;
case JFIF_DHT: // DHT
m_pLog->AddLineHdr(_T("*** Marker: DHT (Define Huffman Table) (xFFC4) ***"));
break;
case JFIF_DHT_FAKE: // DHT from standard table (MotionJPEG)
m_pLog->AddLineHdr(_T("*** Marker: DHT from MotionJPEG standard (Define Huffman Table) ***"));
break;
case JFIF_SOS: // SOS
m_pLog->AddLineHdr(_T("*** Marker: SOS (Start of Scan) (xFFDA) ***"));
break;
case JFIF_DRI: // DRI
m_pLog->AddLineHdr(_T("*** Marker: DRI (Restart Interval) (xFFDD) ***"));
break;
case JFIF_EOI: // EOI
m_pLog->AddLineHdr(_T("*** Marker: EOI (End of Image) (xFFD9) ***"));
break;
case JFIF_DNL: m_pLog->AddLineHdr(_T("*** Marker: DNL (Define Number of Lines) (xFFDC) ***")); break;
case JFIF_DHP: m_pLog->AddLineHdr(_T("*** Marker: DHP (Define Hierarchical Progression) (xFFDE) ***")); break;
case JFIF_EXP: m_pLog->AddLineHdr(_T("*** Marker: EXP (Expand Reference Components) (xFFDF) ***")); break;
case JFIF_JPG0: m_pLog->AddLineHdr(_T("*** Marker: JPG0 (JPEG Extension) (xFFF0) ***")); break;
case JFIF_JPG1: m_pLog->AddLineHdr(_T("*** Marker: JPG1 (JPEG Extension) (xFFF1) ***")); break;
case JFIF_JPG2: m_pLog->AddLineHdr(_T("*** Marker: JPG2 (JPEG Extension) (xFFF2) ***")); break;
case JFIF_JPG3: m_pLog->AddLineHdr(_T("*** Marker: JPG3 (JPEG Extension) (xFFF3) ***")); break;
case JFIF_JPG4: m_pLog->AddLineHdr(_T("*** Marker: JPG4 (JPEG Extension) (xFFF4) ***")); break;
case JFIF_JPG5: m_pLog->AddLineHdr(_T("*** Marker: JPG5 (JPEG Extension) (xFFF5) ***")); break;
case JFIF_JPG6: m_pLog->AddLineHdr(_T("*** Marker: JPG6 (JPEG Extension) (xFFF6) ***")); break;
case JFIF_JPG7: m_pLog->AddLineHdr(_T("*** Marker: JPG7 (JPEG Extension) (xFFF7) ***")); break;
case JFIF_JPG8: m_pLog->AddLineHdr(_T("*** Marker: JPG8 (JPEG Extension) (xFFF8) ***")); break;
case JFIF_JPG9: m_pLog->AddLineHdr(_T("*** Marker: JPG9 (JPEG Extension) (xFFF9) ***")); break;
case JFIF_JPG10: m_pLog->AddLineHdr(_T("*** Marker: JPG10 (JPEG Extension) (xFFFA) ***")); break;
case JFIF_JPG11: m_pLog->AddLineHdr(_T("*** Marker: JPG11 (JPEG Extension) (xFFFB) ***")); break;
case JFIF_JPG12: m_pLog->AddLineHdr(_T("*** Marker: JPG12 (JPEG Extension) (xFFFC) ***")); break;
case JFIF_JPG13: m_pLog->AddLineHdr(_T("*** Marker: JPG13 (JPEG Extension) (xFFFD) ***")); break;
case JFIF_TEM: m_pLog->AddLineHdr(_T("*** Marker: TEM (Temporary) (xFF01) ***")); break;
default:
strTmp.Format(_T("*** Marker: ??? (Unknown) (xFF%02X) ***"),nCode);
m_pLog->AddLineHdr(strTmp);
break;
}
// Adjust position to account for the word used in decoding the marker!
strTmp.Format(_T(" OFFSET: 0x%08X"),m_nPos-2);
m_pLog->AddLine(strTmp);
}
// Update the status bar with a message
void CjfifDecode::SetStatusText(CString strText)
{
// Make sure that we have been connected to the status
// bar of the main window first! Note that it is jpegsnoopDoc
// that sets this variable.
if (m_pStatBar) {
m_pStatBar->SetPaneText(0,strText);
}
}
// Generate a special output form of the current image's
// compression signature and other characteristics. This is only
// used during development and batch import to build the MySQL repository.
void CjfifDecode::OutputSpecial()
{
CString strTmp;
CString strFull;
ASSERT(m_eImgLandscape!=ENUM_LANDSCAPE_UNSET);
// This mode of operation is currently only used
// to import the local signature database into a MySQL database
// backend. It simply reports the MySQL commands which can be input
// into a MySQL client application.
if (m_bOutputDB)
{
m_pLog->AddLine(_T("*** DB OUTPUT START ***"));
m_pLog->AddLine(_T("INSERT INTO `quant` (`key`, `make`, `model`, "));
m_pLog->AddLine(_T("`qual`, `subsamp`, `lum_00`, `lum_01`, `lum_02`, `lum_03`, `lum_04`, "));
m_pLog->AddLine(_T("`lum_05`, `lum_06`, `lum_07`, `chr_00`, `chr_01`, `chr_02`, "));
m_pLog->AddLine(_T("`chr_03`, `chr_04`, `chr_05`, `chr_06`, `chr_07`, `qual_lum`, `qual_chr`) VALUES ("));
strFull = _T("'*KEY*', "); // key -- need to override
// Might need to change m_strImgExifMake to be lowercase
strTmp.Format(_T("'%s', "),(LPCTSTR)m_strImgExifMake);
strFull += strTmp; // make
strTmp.Format(_T("'%s', "),(LPCTSTR)m_strImgExifModel);
strFull += strTmp; // model
strTmp.Format(_T("'%s', "),(LPCTSTR)m_strImgQualExif);
strFull += strTmp; // quality
strTmp.Format(_T("'%s', "),(LPCTSTR)m_strImgQuantCss);
strFull += strTmp; // subsampling
m_pLog->AddLine(strFull);
// Step through both quantization tables (0=lum,1=chr)
unsigned nMatrixInd;
for (unsigned nDqtInd=0;nDqtInd<2;nDqtInd++) {
strFull = _T("");
for (unsigned nY=0;nY<8;nY++) {
strFull += _T("'");
for (unsigned nX=0;nX<8;nX++) {
// Rotate the matrix if necessary!
nMatrixInd = (m_eImgLandscape!=ENUM_LANDSCAPE_NO)?(nY*8+nX):(nX*8+nY);
strTmp.Format(_T("%u"),m_anImgDqtTbl[nDqtInd][nMatrixInd]);
strFull += strTmp;
if (nX!=7) { strFull += _T(","); }
}
strFull += _T("', ");
if (nY==3) {
m_pLog->AddLine(strFull);
strFull = _T("");
}
}
m_pLog->AddLine(strFull);
}
strFull = _T("");
// Output quality ratings
strTmp.Format(_T("'%f', "),m_adImgDqtQual[0]);
strFull += strTmp;
// Don't put out comma separator on last line!
strTmp.Format(_T("'%f'"),m_adImgDqtQual[1]);
strFull += strTmp;
strFull += _T(");");
m_pLog->AddLine(strFull);
m_pLog->AddLine(_T("*** DB OUTPUT END ***"));
}
}
// Generate the compression signatures (both unrotated and
// rotated) in advance of submitting to the database.
void CjfifDecode::PrepareSignature()
{
// Set m_strHash
PrepareSignatureSingle(false);
// Set m_strHashRot
PrepareSignatureSingle(true);
}
// Prepare the image signature for later submission
// NOTE: ASCII vars are used (instead of unicode) to support usage of MD5 library
void CjfifDecode::PrepareSignatureSingle(bool bRotate)
{
CStringA strTmp;
CStringA strSet;
CStringA strHashIn;
unsigned char pHashIn[2000];
CStringA strDqt;
MD5_CTX sMd5;
unsigned nLenHashIn;
unsigned nInd;
ASSERT(m_eImgLandscape!=ENUM_LANDSCAPE_UNSET);
// -----------------------------------------------------------
// Calculate the MD5 hash for online/internal database!
// signature "00" : DQT0,DQT1,CSS
// signature "01" : salt,DQT0,DQT1,..DQTx(if defined)
// Build the source string
// NOTE: For the purposes of the hash, we need to rotate the DQT tables
// if we detect that the photo is in portrait orientation! This keeps everything
// consistent.
// If no DQT tables have been defined (e.g. could have loaded text file!)
// then override the sig generation!
bool bDqtDefined = false;
for (unsigned nSet=0;nSet<4;nSet++) {
if (m_abImgDqtSet[nSet]) {
bDqtDefined = true;
}
}
if (!bDqtDefined) {
m_strHash = _T("NONE");
m_strHashRot = _T("NONE");
return;
}
// NOTE:
// The following MD5 code depends on an ASCII string for input
// We are therefore using CStringA for the hash input instead
// of the generic text functions. No special (non-ASCII)
// characters are expected in this string.
if (DB_SIG_VER == 0x00) {
strHashIn = "";
} else {
strHashIn = "JPEGsnoop";
}
// Need to duplicate DQT0 if we only have one DQT table
for (unsigned nSet=0;nSet<4;nSet++) {
if (m_abImgDqtSet[nSet]) {
strSet = "";
strSet.Format("*DQT%u,",nSet);
strHashIn += strSet;
for (unsigned i=0;i<64;i++) {
nInd = (!bRotate)?i:glb_anQuantRotate[i];
strTmp.Format("%03u,",m_anImgDqtTbl[nSet][nInd]);
strHashIn += strTmp;
}
} // if DQTx defined
} // loop through sets (DQT0..DQT3)
// Removed CSS from signature after version 0x00
if (DB_SIG_VER == 0x00) {
strHashIn += "*CSS,";
strHashIn += m_strImgQuantCss;
strHashIn += ",";
}
strHashIn += "*END";
nLenHashIn = strlen(strHashIn);
// Display hash input
for (unsigned i=0;i<nLenHashIn;i+=80) {
strTmp = "";
strTmp.Format("In%u: [",i/80);
strTmp += strHashIn.Mid(i,80);
strTmp += "]";
#ifdef DEBUG_SIG
m_pLog->AddLine(strTmp);
#endif
}
// Copy into buffer
ASSERT(nLenHashIn < 2000);
for (unsigned i=0;i<nLenHashIn;i++) {
pHashIn[i] = strHashIn.GetAt(i);
}
// Calculate the hash
MD5Init(&sMd5, 0);
MD5Update(&sMd5, pHashIn, nLenHashIn);
MD5Final(&sMd5);
// Overwrite top 8 bits for signature version number
sMd5.digest32[0] = (sMd5.digest32[0] & 0x00FFFFFF) + (DB_SIG_VER << 24);
// Convert hash to string format
// The hexadecimal string is converted to Unicode (if that is build directive)
if (!bRotate) {
m_strHash.Format(_T("%08X%08X%08X%08X"),sMd5.digest32[0],sMd5.digest32[1],sMd5.digest32[2],sMd5.digest32[3]);
} else {
m_strHashRot.Format(_T("%08X%08X%08X%08X"),sMd5.digest32[0],sMd5.digest32[1],sMd5.digest32[2],sMd5.digest32[3]);
}
}
// Generate the compression signatures for the thumbnails
void CjfifDecode::PrepareSignatureThumb()
{
// Generate m_strHashThumb
PrepareSignatureThumbSingle(false);
// Generate m_strHashThumbRot
PrepareSignatureThumbSingle(true);
}
// Prepare the image signature for later submission
// NOTE: ASCII vars are used (instead of unicode) to support usage of MD5 library
void CjfifDecode::PrepareSignatureThumbSingle(bool bRotate)
{
CStringA strTmp;
CStringA strSet;
CStringA strHashIn;
unsigned char pHashIn[2000];
CStringA strDqt;
MD5_CTX sMd5;
unsigned nLenHashIn;
unsigned nInd;
// -----------------------------------------------------------
// Calculate the MD5 hash for online/internal database!
// signature "00" : DQT0,DQT1,CSS
// signature "01" : salt,DQT0,DQT1
// Build the source string
// NOTE: For the purposes of the hash, we need to rotate the DQT tables
// if we detect that the photo is in portrait orientation! This keeps everything
// consistent.
// If no DQT tables have been defined (e.g. could have loaded text file!)
// then override the sig generation!
bool bDqtDefined = false;
for (unsigned nSet=0;nSet<4;nSet++) {
if (m_abImgDqtThumbSet[nSet]) {
bDqtDefined = true;
}
}
if (!bDqtDefined) {
m_strHashThumb = _T("NONE");
m_strHashThumbRot = _T("NONE");
return;
}
if (DB_SIG_VER == 0x00) {
strHashIn = _T("");
} else {
strHashIn = _T("JPEGsnoop");
}
//tblSelY = m_anSofQuantTblSel_Tqi[0]; // Y
//tblSelC = m_anSofQuantTblSel_Tqi[1]; // Cb (should be same as for Cr)
// Need to duplicate DQT0 if we only have one DQT table
for (unsigned nSet=0;nSet<4;nSet++) {
if (m_abImgDqtThumbSet[nSet]) {
strSet = "";
strSet.Format("*DQT%u,",nSet);
strHashIn += strSet;
for (unsigned i=0;i<64;i++) {
nInd = (!bRotate)?i:glb_anQuantRotate[i];
strTmp.Format("%03u,",m_anImgThumbDqt[nSet][nInd]);
strHashIn += strTmp;
}
} // if DQTx defined
} // loop through sets (DQT0..DQT3)
// Removed CSS from signature after version 0x00
if (DB_SIG_VER == 0x00) {
strHashIn += "*CSS,";
strHashIn += m_strImgQuantCss;
strHashIn += ",";
}
strHashIn += "*END";
nLenHashIn = strlen(strHashIn);
// Display hash input
for (unsigned i=0;i<nLenHashIn;i+=80) {
strTmp = "";
strTmp.Format("In%u: [",i/80);
strTmp += strHashIn.Mid(i,80);
strTmp += "]";
#ifdef DEBUG_SIG
m_pLog->AddLine(strTmp);
#endif
}
// Copy into buffer
ASSERT(nLenHashIn < 2000);
for (unsigned i=0;i<nLenHashIn;i++) {
pHashIn[i] = strHashIn.GetAt(i);
}
// Calculate the hash
MD5Init(&sMd5, 0);
MD5Update(&sMd5, pHashIn, nLenHashIn);
MD5Final(&sMd5);
// Overwrite top 8 bits for signature version number
sMd5.digest32[0] = (sMd5.digest32[0] & 0x00FFFFFF) + (DB_SIG_VER << 24);
// Convert hash to string format
if (!bRotate) {
m_strHashThumb.Format(_T("%08X%08X%08X%08X"),sMd5.digest32[0],sMd5.digest32[1],sMd5.digest32[2],sMd5.digest32[3]);
} else {
m_strHashThumbRot.Format(_T("%08X%08X%08X%08X"),sMd5.digest32[0],sMd5.digest32[1],sMd5.digest32[2],sMd5.digest32[3]);
}
}
// Compare the image compression signature & metadata against the database.
// This is the routine that is also responsible for creating an
// "Image Assessment" -- ie. whether the image may have been edited or not.
//
// PRE: m_strHash signature has already been calculated by PrepareSignature()
bool CjfifDecode::CompareSignature(bool bQuiet=false)
{
CString strTmp;
CString strHashOut;
CString locationStr;
unsigned ind;
bool bCurXsw = false;
bool bCurXmm = false;
bool bCurXmkr = false;
bool bCurXextrasw = false; // EXIF Extra fields match software indicator
bool bCurXcomsw = false; // EXIF COM field match software indicator
bool bCurXps = false; // EXIF photoshop IRB present
bool bSrchXsw = false;
bool bSrchXswUsig = false;
bool bSrchXmmUsig = false;
bool bSrchUsig = false;
bool bMatchIjg = false;
CString sMatchIjgQual = _T("");
ASSERT(m_strHash != _T("NONE"));
ASSERT(m_strHashRot != _T("NONE"));
if (bQuiet) { m_pLog->Disable(); }
m_pLog->AddLine(_T(""));
m_pLog->AddLineHdr(_T("*** Searching Compression Signatures ***"));
m_pLog->AddLine(_T(""));
// Output the hash
strHashOut = _T(" Signature: ");
strHashOut += m_strHash;
m_pLog->AddLine(strHashOut);
strHashOut = _T(" Signature (Rotated): ");
strHashOut += m_strHashRot;
m_pLog->AddLine(strHashOut);
strTmp.Format(_T(" File Offset: %lu bytes"),m_pAppConfig->nPosStart);
m_pLog->AddLine(strTmp);
// Output the CSS
strTmp.Format(_T(" Chroma subsampling: %s"),(LPCTSTR)m_strImgQuantCss);
m_pLog->AddLine(strTmp);
// Calculate the final fields
// Add Photoshop IRB entries
// Note that we always add an entry to the m_strImgExtras even if
// there are no photoshop tags detected. It will appear as "[PS]:[0/0]"
strTmp = _T("");
strTmp.Format(_T("[PS]:[%u/%u],"),m_nImgQualPhotoshopSa,m_nImgQualPhotoshopSfw);
m_strImgExtras += strTmp;
// --------------------------------------
// Determine current entry fields
// Note that some cameras/phones have an empty Make, but use the Model! (eg. Palm Treo)
if ((m_strImgExifMake == _T("???")) && (m_strImgExifModel == _T("???"))) {
m_pLog->AddLine(_T(" EXIF Make/Model: NONE"));
bCurXmm = false;
} else {
strTmp.Format(_T(" EXIF Make/Model: OK [%s] [%s]"),(LPCTSTR)m_strImgExifMake,(LPCTSTR)m_strImgExifModel);
m_pLog->AddLine(strTmp);
bCurXmm = true;
}
if (m_bImgExifMakernotes) {
m_pLog->AddLine(_T(" EXIF Makernotes: OK "));
bCurXmkr = true;
} else {
m_pLog->AddLine(_T(" EXIF Makernotes: NONE"));
bCurXmkr = false;
}
if (_tcslen(m_strSoftware) == 0) {
m_pLog->AddLine(_T(" EXIF Software: NONE"));
bCurXsw = false;
} else {
strTmp.Format(_T(" EXIF Software: OK [%s]"),(LPCTSTR)m_strSoftware);
m_pLog->AddLine(strTmp);
// EXIF software field is non-empty
bCurXsw = true;
}
m_pLog->AddLine(_T(""));
// --------------------------------------
// Determine search results
// All of the rest of the search results require searching
// through the database entries
bSrchXswUsig = false;
bSrchXmmUsig = false;
bSrchUsig = false;
bMatchIjg = false;
sMatchIjgQual = _T("");
unsigned nSigsInternal = theApp.m_pDbSigs->GetNumSigsInternal();
unsigned nSigsExtra = theApp.m_pDbSigs->GetNumSigsExtra();
strTmp.Format(_T(" Searching Compression Signatures: (%u built-in, %u user(*) )"),nSigsInternal,nSigsExtra);
m_pLog->AddLine(strTmp);
// Now in SIG version 0x01 and later, we are not including
// the CSS in the signature. Therefore, we need to compare it
// manually.
bool curMatchMm;
bool curMatchSw;
bool curMatchSig;
bool curMatchSigCss;
// Check on Extras field
// Noted that Canon EOS Viewer Utility (EVU) seems to convert RAWs with
// the only identifying information being this:
// e.g. "[Canon.ImageType]:[CRW:EOS 300D DIGITAL CMOS RAW],_T("
if (m_strImgExtras.Find(_T(")[Canon.ImageType]:[CRW:")) != -1) {
bCurXextrasw = true;
}
if (m_strImgExtras.Find(_T("[Nikon1.Quality]:[RAW")) != -1) {
bCurXextrasw = true;
}
if (m_strImgExtras.Find(_T("[Nikon2.Quality]:[RAW")) != -1) {
bCurXextrasw = true;
}
if (m_strImgExtras.Find(_T("[Nikon3.Quality]:[RAW")) != -1) {
bCurXextrasw = true;
}
if ((m_nImgQualPhotoshopSa != 0) || (m_nImgQualPhotoshopSfw != 0)) {
bCurXps = true;
}
// Search for known COMment field indicators
if (theApp.m_pDbSigs->SearchCom(m_strComment)) {
bCurXcomsw = true;
}
m_pLog->AddLine(_T(""));
m_pLog->AddLine(_T(" EXIF.Make / Software EXIF.Model Quality Subsamp Match?"));
m_pLog->AddLine(_T(" ------------------------- ----------------------------------- ---------------- --------------"));
CompSig pEntry;
unsigned ind_max = theApp.m_pDbSigs->GetDBNumEntries();
for (ind=0;ind<ind_max;ind++) {
theApp.m_pDbSigs->GetDBEntry(ind,&pEntry);
// Reset current entry state
curMatchMm = false;
curMatchSw = false;
curMatchSig = false;
curMatchSigCss = false;
// Compare make/model (only for digicams)
if ((pEntry.eEditor == ENUM_EDITOR_CAM) &&
(bCurXmm == true) &&
(pEntry.strXMake == m_strImgExifMake) &&
(pEntry.strXModel == m_strImgExifModel) )
{
curMatchMm = true;
}
// For software entries, do a loose search
if ((pEntry.eEditor == ENUM_EDITOR_SW) &&
(bCurXsw == true) &&
(pEntry.strMSwTrim != _T("")) &&
(m_strSoftware.Find(pEntry.strMSwTrim) != -1) )
{
// Software field matches known software string
bSrchXsw = true;
curMatchSw = true;
}
// Compare signature (and CSS for digicams)
if ( (pEntry.strCSig == m_strHash) || (pEntry.strCSigRot == m_strHash) ||
(pEntry.strCSig == m_strHashRot) || (pEntry.strCSigRot == m_strHashRot) )
{
curMatchSig = true;
// If Database entry is for an editor, sig matches irrespective of CSS
if (pEntry.eEditor == ENUM_EDITOR_SW) {
bSrchUsig = true;
curMatchSigCss = true; // FIXME: do I need this?
// For special case of IJG
if (pEntry.strMSwDisp == _T("IJG Library")) {
bMatchIjg = true;
sMatchIjgQual = pEntry.strUmQual;
}
} else {
// Database entry is for a digicam, sig match only if CSS matches too
if (pEntry.strXSubsamp == m_strImgQuantCss) {
bSrchUsig = true;
curMatchSigCss = true;
} else {
curMatchSigCss = false;
}
} // editor
} else {
// sig doesn't match
curMatchSig = false;
curMatchSigCss = false;
}
// For digicams:
if (curMatchMm && curMatchSigCss) {
bSrchXmmUsig = true;
}
// For software:
if (curMatchSw && curMatchSig) {
bSrchXswUsig = true;
}
if (theApp.m_pDbSigs->IsDBEntryUser(ind)) {
locationStr = _T("*");
} else {
locationStr = _T(" ");
}
// Display entry if it is a good match
if (curMatchSig) {
if (pEntry.eEditor==ENUM_EDITOR_CAM) {
strTmp.Format(_T(" %s%4s[%-25s] [%-35s] [%-16s] %-5s %-5s %-5s"),(LPCTSTR)locationStr,_T("CAM:"),
(LPCTSTR)pEntry.strXMake.Left(25),(LPCTSTR)pEntry.strXModel.Left(35),(LPCTSTR)pEntry.strUmQual.Left(16),
(curMatchSigCss?_T("Yes"):_T("No")),_T(""),_T(""));
} else if (pEntry.eEditor==ENUM_EDITOR_SW) {
strTmp.Format(_T(" %s%4s[%-25s] %-35s [%-16s] %-5s %-5s %-5s"),(LPCTSTR)locationStr,_T("SW :"),
(LPCTSTR)pEntry.strMSwDisp.Left(25),_T(""),(LPCTSTR)pEntry.strUmQual.Left(16),
_T(""),_T(""),_T(""));
} else {
strTmp.Format(_T(" %s%4s[%-25s] [%-35s] [%-16s] %-5s %-5s %-5s"),(LPCTSTR)locationStr,_T("?? :"),
(LPCTSTR)pEntry.strXMake.Left(25),(LPCTSTR)pEntry.strXModel.Left(35),(LPCTSTR)pEntry.strUmQual.Left(16),
_T(""),_T(""),_T(""));
}
if (curMatchMm || curMatchSw) {
m_pLog->AddLineGood(strTmp);
} else {
m_pLog->AddLine(strTmp);
}
}
} // loop through DB
CString strSw;
// If it matches an IJG signature, report other possible sources:
if (bMatchIjg) {
m_pLog->AddLine(_T(""));
m_pLog->AddLine(_T(" The following IJG-based editors also match this signature:"));
unsigned nIjgNum;
CString strIjgSw;
nIjgNum = theApp.m_pDbSigs->GetIjgNum();
for (ind=0;ind<nIjgNum;ind++)
{
strIjgSw = theApp.m_pDbSigs->GetIjgEntry(ind);
strTmp.Format(_T(" %4s[%-25s] %-35s [%-16s] %-5s %-5s %-5s"),_T("SW :"),
(LPCTSTR)strIjgSw.Left(25),_T(""),(LPCTSTR)sMatchIjgQual.Left(16),
_T(""),_T(""),_T(""));
m_pLog->AddLine(strTmp);
}
}
//m_pLog->AddLine(_T(" -------------------- ----------------------------------- ---------------- --------------"));
m_pLog->AddLine(_T(""));
if (bCurXps) {
m_pLog->AddLine(_T(" NOTE: Photoshop IRB detected"));
}
if (bCurXextrasw) {
m_pLog->AddLine(_T(" NOTE: Additional EXIF fields indicate software processing"));
}
if (bSrchXsw) {
m_pLog->AddLine(_T(" NOTE: EXIF Software field recognized as from editor"));
}
if (bCurXcomsw) {
m_pLog->AddLine(_T(" NOTE: JFIF COMMENT field is known software"));
}
// ============================================
// Image Assessment Algorithm
// ============================================
bool bEditDefinite = false;
bool bEditLikely = false;
bool bEditNot = false;
bool bEditNotUnknownSw = false;
if (bCurXps) {
bEditDefinite = true;
}
if (!bCurXmm) {
bEditDefinite = true;
}
if (bCurXextrasw) {
bEditDefinite = true;
}
if (bCurXcomsw) {
bEditDefinite = true;
}
if (bSrchXsw) {
// Software field matches known software string
bEditDefinite = true;
}
if (theApp.m_pDbSigs->LookupExcMmIsEdit(m_strImgExifMake,m_strImgExifModel)) {
// Make/Model is in exception list of ones that mark known software
bEditDefinite = true;
}
if (!bCurXmkr) {
// If we are missing maker notes, we are almost always dealing with
// edited images. There are some known exceptions, so far:
// - Very old digicams
// - Certain camera phones
// - Blackberry
// Perhaps we can make an exception for particular digicams (based on
// make/model) that this determination will not apply. This means that
// we open up the doors for these files being edited and not caught.
if (theApp.m_pDbSigs->LookupExcMmNoMkr(m_strImgExifMake,m_strImgExifModel)) {
// This is a known exception!
} else {
bEditLikely = true;
}
}
// Filter down remaining scenarios
if (!bEditDefinite && !bEditLikely) {
if (bSrchXmmUsig) {
// DB cam signature matches DQT & make/model
if (!bCurXsw) {
// EXIF software field is empty
//
// We can now be pretty confident that this file has not
// been edited by all the means that we are checking
bEditNot = true;
} else {
// EXIF software field is set
//
// This field is often used by:
// - Software editors (edited)
// - RAW converter software (edited)
// - Digicams to indicate firmware (original)
// - Phones to indicate firmware (original)
//
// However, in generating bEditDefinite, we have already
// checked for bSrchXsw which looked for known software
// strings. Therefore, we will primarily be left with
// firmware strings, etc.
//
// We will mark this as NOT EDITED but with caution of unknown SW field
bEditNot = true;
bEditNotUnknownSw = true;
}
} else {
// No DB cam signature matches DQT & make/model
// According to EXIF data, this file does not appear to be edited,
// but no compression signatures in the database match this
// particular make/model. Therefore, result is UNSURE.
}
}
// Now make final assessment call
// Determine if image has been processed/edited
m_eImgEdited = EDITED_UNSET;
if (bEditDefinite) {
m_eImgEdited = EDITED_YES;
} else if (bEditLikely) {
m_eImgEdited = EDITED_YESPROB;
} else if (bEditNot) {
// Images that fall into this category will have:
// - No Photoshop tags
// - Make/Model is present
// - Makernotes present
// - No extra software tags (eg. IFD)
// - No comment field with known software
// - No software field or it does not match known software
// - Signature matches DB for this make/model
m_eImgEdited = EDITED_NO;
} else {
// Images that fall into this category will have:
// - Same as EDITED_NO but:
// - Signature does not match DB for this make/model
// In all likelihood, this image will in fact be original
m_eImgEdited = EDITED_UNSURE;
}
// If the file offset is non-zero, then don't ask for submit or show assessment
if (m_pAppConfig->nPosStart != 0) {
m_pLog->AddLine(_T(" ASSESSMENT not done as file offset non-zero"));
if (bQuiet) { m_pLog->Enable(); }
return false;
}
// ============================================
// Display final assessment
// ============================================
m_pLog->AddLine(_T(" Based on the analysis of compression characteristics and EXIF metadata:"));
m_pLog->AddLine(_T(""));
if (m_eImgEdited == EDITED_YES) {
m_pLog->AddLine(_T(" ASSESSMENT: Class 1 - Image is processed/edited"));
} else if (m_eImgEdited == EDITED_YESPROB) {
m_pLog->AddLine(_T(" ASSESSMENT: Class 2 - Image has high probability of being processed/edited"));
} else if (m_eImgEdited == EDITED_NO) {
m_pLog->AddLine(_T(" ASSESSMENT: Class 3 - Image has high probability of being original"));
// In case the EXIF Software field was detected,
if (bEditNotUnknownSw) {
m_pLog->AddLine(_T(" Note that EXIF Software field is set (typically contains Firmware version)"));
}
} else if (m_eImgEdited == EDITED_UNSURE) {
m_pLog->AddLine(_T(" ASSESSMENT: Class 4 - Uncertain if processed or original"));
m_pLog->AddLine(_T(" While the EXIF fields indicate original, no compression signatures "));
m_pLog->AddLine(_T(" in the current database were found matching this make/model"));
} else {
m_pLog->AddLineErr(_T(" ASSESSMENT: *** Failed to complete ***"));
}
m_pLog->AddLine(_T(""));
// Determine if user should add entry to DB
bool bDbReqAdd = false; // Ask user to add
bool bDbReqAddAuto = false; // Automatically add (in batch operation)
// TODO: This section should be rewritten to reduce complexity
m_eDbReqSuggest = DB_ADD_SUGGEST_UNSET;
if (m_eImgEdited == EDITED_NO) {
bDbReqAdd = false;
m_eDbReqSuggest = DB_ADD_SUGGEST_CAM;
} else if (m_eImgEdited == EDITED_UNSURE) {
bDbReqAdd = true;
bDbReqAddAuto = true;
m_eDbReqSuggest = DB_ADD_SUGGEST_CAM;
m_pLog->AddLine(_T(" Appears to be new signature for known camera."));
m_pLog->AddLine(_T(" If the camera/software doesn't appear in list above,"));
m_pLog->AddLineWarn(_T(" PLEASE ADD TO DATABASE with [Tools->Add Camera to DB]"));
} else if (bCurXps && bSrchUsig) {
// Photoshop and we already have sig
bDbReqAdd = false;
m_eDbReqSuggest = DB_ADD_SUGGEST_SW;
} else if (bCurXps && !bSrchUsig) {
// Photoshop and we don't already have sig
bDbReqAdd = true;
bDbReqAddAuto = true;
m_eDbReqSuggest = DB_ADD_SUGGEST_SW;
m_pLog->AddLine(_T(" Appears to be new signature for Photoshop."));
m_pLog->AddLine(_T(" If it doesn't appear in list above,"));
m_pLog->AddLineWarn(_T(" PLEASE ADD TO DATABASE with [Tools->Add Camera to DB]"));
} else if (bCurXsw && bSrchXsw && bSrchXswUsig) {
bDbReqAdd = false;
m_eDbReqSuggest = DB_ADD_SUGGEST_SW;
} else if (bCurXextrasw) {
bDbReqAdd = false;
m_eDbReqSuggest = DB_ADD_SUGGEST_SW;
} else if (bCurXsw && bSrchXsw && !bSrchXswUsig) {
bDbReqAdd = true;
//bDbReqAddAuto = true;
m_eDbReqSuggest = DB_ADD_SUGGEST_SW;
m_pLog->AddLine(_T(" Appears to be new signature for known software."));
m_pLog->AddLine(_T(" If the camera/software doesn't appear in list above,"));
m_pLog->AddLineWarn(_T(" PLEASE ADD TO DATABASE with [Tools->Add Camera to DB]"));
} else if (bCurXmm && bCurXmkr && !bSrchXsw && !bSrchXmmUsig) {
// unsure if cam, so ask user
bDbReqAdd = true;
bDbReqAddAuto = true;
m_eDbReqSuggest = DB_ADD_SUGGEST_CAM;
m_pLog->AddLine(_T(" This may be a new camera for the database."));
m_pLog->AddLine(_T(" If this file is original, and camera doesn't appear in list above,"));
m_pLog->AddLineWarn(_T(" PLEASE ADD TO DATABASE with [Tools->Add Camera to DB]"));
} else if (!bCurXmm && !bCurXmkr && !bSrchXsw) {
// unsure if SW, so ask user
bDbReqAdd = true;
m_eDbReqSuggest = DB_ADD_SUGGEST_SW;
m_pLog->AddLine(_T(" This may be a new software editor for the database."));
m_pLog->AddLine(_T(" If this file is processed, and editor doesn't appear in list above,"));
m_pLog->AddLineWarn(_T(" PLEASE ADD TO DATABASE with [Tools->Add Camera to DB]"));
}
m_pLog->AddLine(_T(""));
// -----------------------------------------------------------
if (bQuiet) { m_pLog->Enable(); }
#ifdef BATCH_DO_DBSUBMIT_ALL
bDbReqAddAuto = true;
#endif
// Return a value that indicates whether or not we should add this
// entry to the database
return bDbReqAddAuto;
}
// Build the image data string that will be sent to the database repository
// This data string contains the compression siganture and a few special
// fields such as image dimensions, etc.
//
// If Portrait, Rotates DQT table, Width/Height.
// m_strImgQuantCss is already rotated by ProcessFile()
// PRE: m_strHash already defined
void CjfifDecode::PrepareSendSubmit(CString strQual,teSource eUserSource,CString strUserSoftware,CString strUserNotes)
{
// Generate the DQT arrays suitable for posting
CString strTmp1;
CString asDqt[4];
unsigned nMatrixInd;
ASSERT(m_strHash != _T("NONE"));
ASSERT(m_eImgLandscape!=ENUM_LANDSCAPE_UNSET);
for (unsigned nSet=0;nSet<4;nSet++) {
asDqt[nSet] = _T("");
if (m_abImgDqtSet[nSet]) {
for (unsigned nInd=0;nInd<64;nInd++) {
// FIXME: Still consider rotating DQT table even though we
// don't know for sure if m_eImgLandscape is accurate
// Not a big deal if we get it wrong as we still add
// both pre- and post-rotated sigs.
nMatrixInd = (m_eImgLandscape!=ENUM_LANDSCAPE_NO)?nInd:glb_anQuantRotate[nInd];
if ((nInd%8 == 0) && (nInd != 0)) {
asDqt[nSet].Append(_T("!"));
}
asDqt[nSet].AppendFormat(_T("%u"),m_anImgDqtTbl[nSet][nMatrixInd]);
if (nInd%8 != 7) {
asDqt[nSet].Append(_T(","));
}
}
} // set defined?
} // up to 4 sets
unsigned nOrigW,nOrigH;
nOrigW = (m_eImgLandscape!=ENUM_LANDSCAPE_NO)?m_nSofSampsPerLine_X:m_nSofNumLines_Y;
nOrigH = (m_eImgLandscape!=ENUM_LANDSCAPE_NO)?m_nSofNumLines_Y:m_nSofSampsPerLine_X;
unsigned nOrigThumbW,nOrigThumbH;
nOrigThumbW = (m_eImgLandscape!=ENUM_LANDSCAPE_NO)?m_nImgThumbSampsPerLine:m_nImgThumbNumLines;
nOrigThumbH = (m_eImgLandscape!=ENUM_LANDSCAPE_NO)?m_nImgThumbNumLines:m_nImgThumbSampsPerLine;
teMaker eMaker;
eMaker = (m_bImgExifMakernotes)?ENUM_MAKER_PRESENT:ENUM_MAKER_NONE;
// Sort sig additions
// To create some determinism in the database, arrange the sigs
// to be in numerical order
CString strSig0,strSig1,strSigThm0,strSigThm1;
if (m_strHash <= m_strHashRot) {
strSig0 = m_strHash;
strSig1 = m_strHashRot;
} else {
strSig0 = m_strHashRot;
strSig1 = m_strHash;
}
if (m_strHashThumb <= m_strHashThumbRot) {
strSigThm0 = m_strHashThumb;
strSigThm1 = m_strHashThumbRot;
} else {
strSigThm0 = m_strHashThumbRot;
strSigThm1 = m_strHashThumb;
}
SendSubmit(m_strImgExifMake,m_strImgExifModel,strQual,asDqt[0],asDqt[1],asDqt[2],asDqt[3],m_strImgQuantCss,
strSig0,strSig1,strSigThm0,strSigThm1,(float)m_adImgDqtQual[0],(float)m_adImgDqtQual[1],nOrigW,nOrigH,
m_strSoftware,m_strComment,eMaker,eUserSource,strUserSoftware,m_strImgExtras,
strUserNotes,m_eImgLandscape,nOrigThumbW,nOrigThumbH);
}
// Send the compression signature string to the local database file
// in addition to the web repository if the user has enabled it.
void CjfifDecode::SendSubmit(CString strExifMake, CString strExifModel, CString strQual,
CString strDqt0, CString strDqt1, CString strDqt2, CString strDqt3,
CString strCss,
CString strSig, CString strSigRot, CString strSigThumb,
CString strSigThumbRot, float fQFact0, float fQFact1, unsigned nImgW, unsigned nImgH,
CString strExifSoftware, CString strComment, teMaker eMaker,
teSource eUserSource, CString strUserSoftware, CString strExtra,
CString strUserNotes, unsigned nExifLandscape,
unsigned nThumbX,unsigned nThumbY)
{
// NOTE: This assumes that we've already run PrepareSignature()
// which usually happens when we process a file.
ASSERT(strSig != _T(""));
ASSERT(strSigRot != _T(""));
CUrlString curls;
CString DB_SUBMIT_WWW_VER = _T("02");
#ifndef BATCH_DO
if (m_bSigExactInDB) {
if (m_pAppConfig->bInteractive)
AfxMessageBox(_T("Compression signature already in database"));
} else {
// Now append it to the local database and resave
theApp.m_pDbSigs->DatabaseExtraAdd(strExifMake,strExifModel,
strQual,strSig,strSigRot,strCss,eUserSource,strUserSoftware);
if (m_pAppConfig->bInteractive)
AfxMessageBox(_T("Added Compression signature to database"));
}
#endif
// Is automatic internet update enabled?
if (!theApp.m_pAppConfig->bDbSubmitNet) {
return;
}
CString strTmp;
CString strFormat;
CString strFormDataPre;
CString strFormData;
unsigned nFormDataLen;
unsigned nChecksum=32;
CString strSubmitHost;
CString strSubmitPage;
strSubmitHost = IA_HOST;
strSubmitPage = IA_DB_SUBMIT_PAGE;
for (unsigned i=0;i<_tcslen(IA_HOST);i++) {
nChecksum += strSubmitHost.GetAt(i);
nChecksum += 3*strSubmitPage.GetAt(i);
}
//if ( (m_pAppConfig->bIsWindowsNTorLater) && (nChecksum == 9678) ) {
if (nChecksum == 9678) {
// Submit to online database
CString strHeaders =
_T("Content-Type: application/x-www-form-urlencoded");
// URL-encoded form variables -
strFormat = _T("ver=%s&x_make=%s&x_model=%s&strUmQual=%s&x_dqt0=%s&x_dqt1=%s&x_dqt2=%s&x_dqt3=%s");
strFormat += _T("&strXSubsamp=%s&strCSig=%s&strCSigRot=%s&c_qfact0=%f&c_qfact1=%f&x_img_w=%u&x_img_h=%u");
strFormat += _T("&x_sw=%s&x_com=%s&x_maker=%u&u_source=%d&u_sw=%s");
strFormat += _T("&x_extra=%s&u_notes=%s&c_sigthumb=%s&c_sigthumbrot=%s&x_landscape=%u");
strFormat += _T("&x_thumbx=%u&x_thumby=%u");
strFormDataPre.Format(strFormat,
DB_SUBMIT_WWW_VER,strExifMake,strExifModel,
strQual,strDqt0,strDqt1,strDqt2,strDqt3,strCss,strSig,strSigRot,fQFact0,fQFact1,nImgW,nImgH,
strExifSoftware,strComment,
eMaker,eUserSource,strUserSoftware,
strExtra,strUserNotes,
strSigThumb,strSigThumbRot,nExifLandscape,nThumbX,nThumbY);
//*** Need to sanitize data for URL submission!
// Search for "&", "?", "="
strFormData.Format(strFormat,
DB_SUBMIT_WWW_VER,curls.Encode(strExifMake),curls.Encode(strExifModel),
strQual,strDqt0,strDqt1,strDqt2,strDqt3,strCss,strSig,strSigRot,fQFact0,fQFact1,nImgW,nImgH,
curls.Encode(strExifSoftware),curls.Encode(strComment),
eMaker,eUserSource,curls.Encode(strUserSoftware),
curls.Encode(strExtra),curls.Encode(strUserNotes),
strSigThumb,strSigThumbRot,nExifLandscape,nThumbX,nThumbY);
nFormDataLen = strFormData.GetLength();
#ifdef DEBUG_SIG
if (m_pAppConfig->bInteractive) {
AfxMessageBox(strFormDataPre);
AfxMessageBox(strFormData);
}
#endif
#ifdef WWW_WININET
//static LPSTR astrAcceptTypes[2]={"*/*", NULL};
HINTERNET hINet, hConnection, hData;
hINet = InternetOpen(_T("JPEGsnoop/1.0"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );
if ( !hINet )
{
if (m_pAppConfig->bInteractive)
AfxMessageBox(_T("InternetOpen Failed"));
return;
}
try
{
hConnection = InternetConnect( hINet, (LPCTSTR)strSubmitHost, 80, NULL,NULL, INTERNET_SERVICE_HTTP, 0, 1 );
if ( !hConnection )
{
InternetCloseHandle(hINet);
return;
}
hData = HttpOpenRequest( hConnection, _T("POST"), (LPCTSTR)strSubmitPage, NULL, NULL, NULL, 0, 1 );
if ( !hData )
{
InternetCloseHandle(hConnection);
InternetCloseHandle(hINet);
return;
}
// GET HttpSendRequest( hData, NULL, 0, NULL, 0);
HttpSendRequest( hData, (LPCTSTR)strHeaders, strHeaders.GetLength(), strFormData.GetBuffer(), strFormData.GetLength());
}
catch( CInternetException* e)
{
e->ReportError();
e->Delete();
//AfxMessageBox(_T("EXCEPTION!"));
}
InternetCloseHandle(hConnection);
InternetCloseHandle(hINet);
InternetCloseHandle(hData);
#endif
#ifdef WWW_WINHTTP
CInternetSession sSession;
CHttpConnection* pConnection;
CHttpFile* pFile;
BOOL bResult;
DWORD dwRet;
// *** NOTE: Will not work on Windows 95/98!
// This section is avoided in early OSes otherwise we get an Illegal Op
try {
pConnection = sSession.GetHttpConnection(submit_host);
ASSERT (pConnection);
pFile = pConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST,_T(submit_page));
ASSERT (pFile);
bResult = pFile->SendRequest(
strHeaders,(LPVOID)(LPCTSTR)strFormData, strFormData.GetLength());
ASSERT (bResult != 0);
pFile->QueryInfoStatusCode(dwRet);
ASSERT (dwRet == HTTP_STATUS_OK);
// Clean up!
if (pFile) {
pFile->Close();
delete pFile;
pFile = NULL;
}
if (pConnection) {
pConnection->Close();
delete pConnection;
pConnection = NULL;
}
sSession.Close();
}
catch (CInternetException* pEx)
{
// catch any exceptions from WinINet
TCHAR szErr[MAX_BUF_EX_ERR_MSG];
szErr[0] = '\0';
if(!pEx->GetErrorMessage(szErr, MAX_BUF_EX_ERR_MSG))
_tcscpy(szErr,_T("Unknown error"));
TRACE("Submit Failed! - %s",szErr);
if (m_pAppConfig->bInteractive)
AfxMessageBox(szErr);
pEx->Delete();
if(pFile)
delete pFile;
if(pConnection)
delete pConnection;
session.Close();
return;
}
#endif
}
}
// Parse the embedded JPEG thumbnail. This routine is a much-reduced
// version of the main JFIF parser, in that it focuses primarily on the
// DQT tables.
void CjfifDecode::DecodeEmbeddedThumb()
{
CString strTmp;
CString strMarker;
unsigned nPosSaved;
unsigned nPosSaved_sof;
unsigned nPosEnd;
bool bDone;
unsigned nCode;
bool bRet;
CString strFull;
unsigned nDqtPrecision_Pq;
unsigned nDqtQuantDestId_Tq;
unsigned nImgPrecision;
unsigned nLength;
unsigned nTmpVal;
bool bScanSkipDone;
bool bErrorAny = false;
bool bErrorThumbLenZero = false;
unsigned nSkipCount;
nPosSaved = m_nPos;
// Examine the EXIF embedded thumbnail (if it exists)
if (m_nImgExifThumbComp == 6) {
m_pLog->AddLine(_T(""));
m_pLog->AddLineHdr(_T("*** Embedded JPEG Thumbnail ***"));
strTmp.Format(_T(" Offset: 0x%08X"),m_nImgExifThumbOffset);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" Length: 0x%08X (%u)"),m_nImgExifThumbLen,m_nImgExifThumbLen);
m_pLog->AddLine(strTmp);
// Quick scan for DQT tables
m_nPos = m_nImgExifThumbOffset;
bDone = false;
while (!bDone) {
// For some reason, I have found files that have a nLength of 0
if (m_nImgExifThumbLen != 0) {
if ((m_nPos-m_nImgExifThumbOffset) > m_nImgExifThumbLen) {
strTmp.Format(_T("ERROR: Read more than specified EXIF thumb nLength (%u bytes) before EOI"),m_nImgExifThumbLen);
m_pLog->AddLineErr(strTmp);
bErrorAny = true;
bDone = true;
}
} else {
// Don't try to process if nLength is 0!
// Seen this in a Canon 1ds file (processed by photoshop)
bDone = true;
bErrorAny = true;
bErrorThumbLenZero = true;
}
if ((!bDone) && (Buf(m_nPos++) != 0xFF)) {
strTmp.Format(_T("ERROR: Expected marker 0xFF, got 0x%02X @ offset 0x%08X"),Buf(m_nPos-1),(m_nPos-1));
m_pLog->AddLineErr(strTmp);
bErrorAny = true;
bDone = true;
}
if (!bDone) {
nCode = Buf(m_nPos++);
m_pLog->AddLine(_T(""));
switch (nCode) {
case JFIF_SOI: // SOI
m_pLog->AddLine(_T(" * Embedded Thumb Marker: SOI"));
break;
case JFIF_DQT: // Define quantization tables
m_pLog->AddLine(_T(" * Embedded Thumb Marker: DQT"));
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
nPosEnd = m_nPos+nLength;
m_nPos+=2;
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
while (nPosEnd > m_nPos)
{
strTmp.Format(_T(" ----"));
m_pLog->AddLine(strTmp);
nTmpVal = Buf(m_nPos++);
nDqtPrecision_Pq = (nTmpVal & 0xF0) >> 4;
nDqtQuantDestId_Tq = nTmpVal & 0x0F;
CString strPrecision = _T("");
if (nDqtPrecision_Pq == 0) {
strPrecision = _T("8 bits");
} else if (nDqtPrecision_Pq == 1) {
strPrecision = _T("16 bits");
} else {
strPrecision.Format(_T("??? unknown [value=%u]"),nDqtPrecision_Pq);
}
strTmp.Format(_T(" Precision=%s"),(LPCTSTR)strPrecision);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" Destination ID=%u"),nDqtQuantDestId_Tq);
// NOTE: The mapping between destination IDs and the actual
// usage is defined in the SOF marker which is often later.
// In nearly all images, the following is true. However, I have
// seen some test images that set Tbl 3 = Lum, Tbl 0=Chr,
// Tbl1=Chr, and Tbl2 undefined
if (nDqtQuantDestId_Tq == 0) {
strTmp += _T(" (Luminance, typically)");
}
else if (nDqtQuantDestId_Tq == 1) {
strTmp += _T(" (Chrominance, typically)");
}
else if (nDqtQuantDestId_Tq == 2) {
strTmp += _T(" (Chrominance, typically)");
}
else {
strTmp += _T(" (???)");
}
m_pLog->AddLine(strTmp);
if (nDqtQuantDestId_Tq >= 4) {
strTmp.Format(_T("ERROR: nDqtQuantDestId_Tq = %u, >= 4"),nDqtQuantDestId_Tq);
m_pLog->AddLineErr(strTmp);
bDone = true;
bErrorAny = true;
break;
}
for (unsigned nInd=0;nInd<=63;nInd++)
{
nTmpVal = Buf(m_nPos++);
m_anImgThumbDqt[nDqtQuantDestId_Tq][glb_anZigZag[nInd]] = nTmpVal;
}
m_abImgDqtThumbSet[nDqtQuantDestId_Tq] = true;
// Now display the table
for (unsigned nY=0;nY<8;nY++) {
strFull.Format(_T(" DQT, Row #%u: "),nY);
for (unsigned nX=0;nX<8;nX++) {
strTmp.Format(_T("%3u "),m_anImgThumbDqt[nDqtQuantDestId_Tq][nY*8+nX]);
strFull += strTmp;
// Store the DQT entry into the Image DenCoder
bRet = m_pImgDec->SetDqtEntry(nDqtQuantDestId_Tq,nY*8+nX,
glb_anUnZigZag[nY*8+nX],m_anImgDqtTbl[nDqtQuantDestId_Tq][nY*8+nX]);
DecodeErrCheck(bRet);
}
m_pLog->AddLine(strFull);
}
}
break;
case JFIF_SOF0:
m_pLog->AddLine(_T(" * Embedded Thumb Marker: SOF"));
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
nPosSaved_sof = m_nPos;
m_nPos+=2;
strTmp.Format(_T(" Frame header length = %u"),nLength);
m_pLog->AddLine(strTmp);
nImgPrecision = Buf(m_nPos++);
strTmp.Format(_T(" Precision = %u"),nImgPrecision);
m_pLog->AddLine(strTmp);
m_nImgThumbNumLines = Buf(m_nPos)*256 + Buf(m_nPos+1);
m_nPos += 2;
strTmp.Format(_T(" Number of Lines = %u"),m_nImgThumbNumLines);
m_pLog->AddLine(strTmp);
m_nImgThumbSampsPerLine = Buf(m_nPos)*256 + Buf(m_nPos+1);
m_nPos += 2;
strTmp.Format(_T(" Samples per Line = %u"),m_nImgThumbSampsPerLine);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" Image Size = %u x %u"),m_nImgThumbSampsPerLine,m_nImgThumbNumLines);
m_pLog->AddLine(strTmp);
m_nPos = nPosSaved_sof+nLength;
break;
case JFIF_SOS: // SOS
m_pLog->AddLine(_T(" * Embedded Thumb Marker: SOS"));
m_pLog->AddLine(_T(" Skipping scan data"));
bScanSkipDone = false;
nSkipCount = 0;
while (!bScanSkipDone) {
if ((Buf(m_nPos) == 0xFF) && (Buf(m_nPos+1) != 0x00)) {
// Was it a restart marker?
if ((Buf(m_nPos+1) >= JFIF_RST0) && (Buf(m_nPos+1) <= JFIF_RST7)) {
m_nPos++;
} else {
// No... it's a real marker
bScanSkipDone = true;
}
} else {
m_nPos++;
nSkipCount++;
}
}
strTmp.Format(_T(" Skipped %u bytes"),nSkipCount);
m_pLog->AddLine(strTmp);
break;
case JFIF_EOI:
m_pLog->AddLine(_T(" * Embedded Thumb Marker: EOI"));
bDone = true;
break;
case JFIF_RST0:
case JFIF_RST1:
case JFIF_RST2:
case JFIF_RST3:
case JFIF_RST4:
case JFIF_RST5:
case JFIF_RST6:
case JFIF_RST7:
break;
default:
GetMarkerName(nCode,strMarker);
strTmp.Format(_T(" * Embedded Thumb Marker: %s"),(LPCTSTR)strMarker);
m_pLog->AddLine(strTmp);
nLength = Buf(m_nPos)*256 + Buf(m_nPos+1);
strTmp.Format(_T(" Length = %u"),nLength);
m_pLog->AddLine(strTmp);
m_nPos += nLength;
break;
}
} // if !bDone
} // while !bDone
// Now calculate the signature
if (!bErrorAny) {
PrepareSignatureThumb();
m_pLog->AddLine(_T(""));
strTmp.Format(_T(" * Embedded Thumb Signature: %s"),(LPCTSTR)m_strHashThumb);
m_pLog->AddLine(strTmp);
}
if (bErrorThumbLenZero) {
m_strHashThumb = _T("ERR: Len=0");
m_strHashThumbRot = _T("ERR: Len=0");
}
} // if JPEG compressed
m_nPos = nPosSaved;
}
// Lookup the EXIF marker name from the code value
bool CjfifDecode::GetMarkerName(unsigned nCode,CString &markerStr)
{
bool bDone = false;
bool bFound = false;
unsigned nInd=0;
while (!bDone)
{
if (m_pMarkerNames[nInd].nCode==0) {
bDone = true;
} else if (m_pMarkerNames[nInd].nCode==nCode) {
bDone = true;
bFound = true;
markerStr = m_pMarkerNames[nInd].strName;
return true;
} else {
nInd++;
}
}
if (!bFound) {
markerStr = _T("");
markerStr.Format(_T("(0xFF%02X)"),nCode);
return false;
}
return true;
}
// Determine if the file is an AVI MJPEG.
// If so, parse the headers.
// TODO: Expand this function to use sub-functions for each block type
bool CjfifDecode::DecodeAvi()
{
CString strTmp;
unsigned nPosSaved;
m_bAvi = false;
m_bAviMjpeg = false;
// Perhaps start from file position 0?
nPosSaved = m_nPos;
// Start from file position 0
m_nPos = 0;
bool bSwap = true;
CString strRiff;
unsigned nRiffLen;
CString strForm;
strRiff = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
nRiffLen = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
strForm = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
if ((strRiff == _T("RIFF")) && (strForm == _T("AVI "))) {
m_bAvi = true;
m_pLog->AddLine(_T(""));
m_pLog->AddLineHdr(_T("*** AVI File Decoding ***"));
m_pLog->AddLine(_T("Decoding RIFF AVI format..."));
m_pLog->AddLine(_T(""));
} else {
// Reset file position
m_nPos = nPosSaved;
return false;
}
CString strHeader;
unsigned nChunkSize;
unsigned nChunkDataStart;
bool done = false;
while (!done) {
if (m_nPos >= m_pWBuf->GetPosEof()) {
done = true;
break;
}
strHeader = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
strTmp.Format(_T(" %s"),(LPCTSTR)strHeader);
m_pLog->AddLine(strTmp);
nChunkSize = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
nChunkDataStart = m_nPos;
if (strHeader == _T("LIST")) {
// --- LIST ---
CString strListType;
strListType = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
strTmp.Format(_T(" %s"),(LPCTSTR)strListType);
m_pLog->AddLine(strTmp);
if (strListType == _T("hdrl")) {
// --- hdrl ---
unsigned nPosHdrlStart;
CString strHdrlId;
strHdrlId = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
unsigned nHdrlLen;
nHdrlLen = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
nPosHdrlStart = m_nPos;
// nHdrlLen should be 14*4 bytes
m_nPos = nPosHdrlStart + nHdrlLen;
} else if (strListType == _T("strl")) {
// --- strl ---
// strhHEADER
unsigned nPosStrlStart;
CString strStrlId;
strStrlId = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
unsigned nStrhLen;
nStrhLen = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
nPosStrlStart = m_nPos;
CString fccType;
CString fccHandler;
unsigned dwFlags,dwReserved1,dwInitialFrames,dwScale,dwRate;
unsigned dwStart,dwLength,dwSuggestedBufferSize,dwQuality;
unsigned dwSampleSize,xdwQuality,xdwSampleSize;
fccType = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
fccHandler = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
dwFlags = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwReserved1 = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwInitialFrames = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwScale = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwRate = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwStart = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwLength = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwSuggestedBufferSize = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwQuality = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
dwSampleSize = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
xdwQuality = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
xdwSampleSize = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
CString fccTypeDecode = _T("");
if (fccType == _T("vids")) { fccTypeDecode = _T("[vids] Video"); }
else if (fccType == _T("auds")) { fccTypeDecode = _T("[auds] Audio"); }
else if (fccType == _T("txts")) { fccTypeDecode = _T("[txts] Subtitle"); }
else { fccTypeDecode.Format(_T("[%s]"),(LPCTSTR)fccType); }
strTmp.Format(_T(" -[FourCC Type] = %s"),(LPCTSTR)fccTypeDecode);
m_pLog->AddLine(strTmp);
strTmp.Format(_T(" -[FourCC Codec] = [%s]"),(LPCTSTR)fccHandler);
m_pLog->AddLine(strTmp);
float fSampleRate = 0;
if (dwScale != 0) {
fSampleRate = (float)dwRate / (float)dwScale;
}
strTmp.Format(_T(" -[Sample Rate] = [%.2f]"),fSampleRate);
if (fccType == _T("vids")) { strTmp.Append(_T(" frames/sec")); }
else if (fccType == _T("auds")) { strTmp.Append(_T(" samples/sec")); }
m_pLog->AddLine(strTmp);
m_nPos = nPosStrlStart + nStrhLen; // Skip
strTmp.Format(_T(" %s"),(LPCTSTR)fccType);
m_pLog->AddLine(strTmp);
if (fccType == _T("vids")) {
// --- vids ---
// Is it MJPEG?
//strTmp.Format(_T(" -[Video Stream FourCC]=[%s]"),fccHandler);
//m_pLog->AddLine(strTmp);
if (fccHandler == _T("mjpg")) {
m_bAviMjpeg = true;
}
if (fccHandler == _T("MJPG")) {
m_bAviMjpeg = true;
}
// strfHEADER_BIH
CString strSkipId;
unsigned nSkipLen;
unsigned nSkipStart;
strSkipId = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
nSkipLen = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
nSkipStart = m_nPos;
m_nPos = nSkipStart + nSkipLen; // Skip
} else if (fccType == _T("auds")) {
// --- auds ---
// strfHEADER_WAVE
CString strSkipId;
unsigned nSkipLen;
unsigned nSkipStart;
strSkipId = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
nSkipLen = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
nSkipStart = m_nPos;
m_nPos = nSkipStart + nSkipLen; // Skip
} else {
// strfHEADER
CString strSkipId;
unsigned nSkipLen;
unsigned nSkipStart;
strSkipId = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
nSkipLen = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
nSkipStart = m_nPos;
m_nPos = nSkipStart + nSkipLen; // Skip
}
// strnHEADER
unsigned nPosStrnStart;
CString strStrnId;
strStrnId = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
unsigned nStrnLen;
nStrnLen = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
nPosStrnStart = m_nPos;
// FIXME: Can we rewrite in terms of ChunkSize and ChunkDataStart?
//ASSERT ((nPosStrnStart + nStrnLen + (nStrnLen%2)) == (nChunkDataStart + nChunkSize + (nChunkSize%2)));
//m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
m_nPos = nPosStrnStart + nStrnLen + (nStrnLen%2); // Skip
} else if (strListType == _T("movi")) {
// movi
m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
} else if (strListType == _T("INFO")) {
// INFO
unsigned nInfoStart;
nInfoStart = m_nPos;
CString strInfoId;
unsigned nInfoLen;
strInfoId = m_pWBuf->BufReadStrn(m_nPos,4); m_nPos+=4;
nInfoLen = m_pWBuf->BufX(m_nPos,4,bSwap); m_nPos+=4;
if (strInfoId == _T("ISFT")) {
CString strIsft=_T("");
strIsft = m_pWBuf->BufReadStrn(m_nPos,nChunkSize);
strIsft.TrimRight();
strTmp.Format(_T(" -[Software] = [%s]"),(LPCTSTR)strIsft);
m_pLog->AddLine(strTmp);
}
m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
} else {
// ?
m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
}
} else if (strHeader == _T("JUNK")) {
// Junk
m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
} else if (strHeader == _T("IDIT")) {
// Timestamp info (Canon, etc.)
CString strIditTimestamp=_T("");
strIditTimestamp = m_pWBuf->BufReadStrn(m_nPos,nChunkSize);
strIditTimestamp.TrimRight();
strTmp.Format(_T(" -[Timestamp] = [%s]"),(LPCTSTR)strIditTimestamp);
m_pLog->AddLine(strTmp);
m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
} else if (strHeader == _T("indx")) {
// Index
m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
} else if (strHeader == _T("idx1")) {
// Index
unsigned nIdx1Entries = nChunkSize / (4*4);
m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
} else {
// Unsupported
m_nPos = nChunkDataStart + nChunkSize + (nChunkSize%2);
}
}
m_pLog->AddLine(_T(""));
if (m_bAviMjpeg) {
m_strImgExtras += _T("[AVI]:[mjpg],");
m_pLog->AddLineGood(_T(" AVI is MotionJPEG"));
m_pLog->AddLineWarn(_T(" Use [Tools->Img Search Fwd] to locate next frame"));
} else {
m_strImgExtras += _T("[AVI]:[????],");
m_pLog->AddLineWarn(_T(" AVI is not MotionJPEG. [Img Search Fwd/Rev] unlikely to find frames."));
}
m_pLog->AddLine(_T(""));
// Reset file position
m_nPos = nPosSaved;
return m_bAviMjpeg;
}
// This is the primary JFIF parsing routine.
// The main loop steps through all of the JFIF markers and calls
// DecodeMarker() each time until we reach the end of file or an error.
// Finally, we invoke the compression signature search function.
//
// Processing starts at the file offset m_pAppConfig->nPosStart
//
// INPUT:
// - inFile = Input file pointer
//
// PRE:
// - m_pAppConfig->nPosStart = Starting file offset for decode
//
void CjfifDecode::ProcessFile(CFile* inFile)
{
CString strTmp;
// Reset the JFIF decoder state as we may be redoing another file
Reset();
// Reset the IMG Decoder state
if (m_pImgSrcDirty) {
m_pImgDec->ResetState();
}
// Set the statusbar text to Processing...
// Ensure the status bar has been allocated
// NOTE: The stat bar is NULL if we drag & drop a file onto
// the JPEGsnoop app icon.
if (m_pStatBar) {
m_pStatBar->SetPaneText(0,_T("Processing..."));
}
// Note that we don't clear out the logger (with m_pLog->Reset())
// as we want top-level caller to do this. This way we can
// still insert extra lines from top level.
// GetLength returns ULONGLONG. Abort on large files (>=4GB)
ULONGLONG nPosFileEnd;
nPosFileEnd = inFile->GetLength();
if (nPosFileEnd > 0xFFFFFFFFUL) {
CString strTmp = _T("File too large. Skipping.");
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return;
}
m_nPosFileEnd = static_cast<unsigned long>(nPosFileEnd);
unsigned nStartPos;
nStartPos = m_pAppConfig->nPosStart;
m_nPos = nStartPos;
m_nPosEmbedStart = nStartPos; // Save the embedded file start position
strTmp.Format(_T("Start Offset: 0x%08X"),nStartPos);
m_pLog->AddLine(strTmp);
// ----------------------------------------------------------------
// Test for AVI file
// - Detect header
// - start from beginning of file
DecodeAvi();
// TODO: Should we skip decode of file if not MJPEG?
// ----------------------------------------------------------------
// Test for PSD file
// - Detect header
// - FIXME: start from current offset?
unsigned nWidth=0;
unsigned nHeight=0;
#ifdef PS_IMG_DEC_EN
// If PSD image decoding is enabled, associate the PSD parsing with
// the current DIB. After decoding, flag the DIB as ready for display.
// Attempt decode as PSD
bool bDecPsdOk;
bDecPsdOk = m_pPsDec->DecodePsd(nStartPos,&m_pImgDec->m_pDibTemp,nWidth,nHeight);
if (bDecPsdOk) {
// FIXME: The following is a bit of a hack
m_pImgDec->m_bDibTempReady = true;
m_pImgDec->m_bPreviewIsJpeg = false; // MCU/Block info not available
m_pImgDec->SetImageDimensions(nWidth,nHeight);
// Clear the image information
// The primary reason for this is to ensure we don't have stale information from a previous
// JPEG image (eg. real image border inside MCU border which would be overlayed during draw).
m_pImgDec->SetImageDetails(0,0,0,0,false,0);
// No more processing of file
// - Otherwise we'd continue to attempt to decode as JPEG
return;
}
#else
// Don't attempt to display Photoshop image data
if (m_pPsDec->DecodePsd(nStartPos,NULL,nWidth,nHeight)) {
return;
}
#endif
// ----------------------------------------------------------------
// Disable DICOM for now until fully tested
#ifdef SUPPORT_DICOM
// Test for DICOM
// - Detect header
// - start from beginning of file
bool bDicom = false;
unsigned long nPosJpeg = 0; // File offset to embedded JPEG in DICOM
bDicom = m_pDecDicom->DecodeDicom(0,m_nPosFileEnd,nPosJpeg);
if (bDicom) {
// Adjust start of JPEG decoding if we are currently without an offset
if (nStartPos == 0) {
m_pAppConfig->nPosStart = nPosJpeg;
nStartPos = m_pAppConfig->nPosStart;
m_nPos = nStartPos;
m_nPosEmbedStart = nStartPos; // Save the embedded file start position
strTmp.Format(_T("Adjusting Start Offset to: 0x%08X"),nStartPos);
m_pLog->AddLine(strTmp);
m_pLog->AddLine(_T(""));
}
}
#endif
// ----------------------------------------------------------------
// Decode as JPEG JFIF file
// If we are in a non-zero offset, add this to extras
if (m_pAppConfig->nPosStart!=0) {
strTmp.Format(_T("[Offset]=[%lu],"),m_pAppConfig->nPosStart);
m_strImgExtras += strTmp;
}
unsigned nDataAfterEof = 0;
BOOL bDone = FALSE;
while (!bDone)
{
// Allow some other threads to jump in
// Return value 0 - OK
// 1 - Error
// 2 - EOI
if (DecodeMarker() != DECMARK_OK) {
bDone = TRUE;
if (m_nPosFileEnd >= m_nPosEoi) {
nDataAfterEof = m_nPosFileEnd - m_nPosEoi;
}
} else {
if (m_nPos > m_pWBuf->GetPosEof()) {
m_pLog->AddLineErr(_T("ERROR: Early EOF - file may be missing EOI"));
bDone = TRUE;
}
}
}
// -----------------------------------------------------------
// Perform any other informational calculations that require all tables
// to be present.
// Determine the CSS Ratio
// Save the subsampling string. Assume component 2 is representative of the overall chrominance.
// NOTE: Ensure that we don't execute the following code if we haven't
// completed our read (ie. get bad marker earlier in processing).
// TODO: What is the best way to determine all is OK?
m_strImgQuantCss = _T("?x?");
m_strHash = _T("NONE");
m_strHashRot = _T("NONE");
if (m_bImgOK) {
ASSERT(m_eImgLandscape!=ENUM_LANDSCAPE_UNSET);
if (m_nSofNumComps_Nf == NUM_CHAN_YCC) {
// We only try to determine the chroma subsampling ratio if we have 3 components (assume YCC)
// In general, we should be able to use the 2nd or 3rd component
// NOTE: The following assumes m_anSofHorzSampFact_Hi and m_anSofVertSampFact_Vi
// are non-zero as otherwise we'll have a divide-by-0 exception.
unsigned nCompIdent = m_anSofQuantCompId[SCAN_COMP_CB];
unsigned nCssFactH = m_nSofHorzSampFactMax_Hmax/m_anSofHorzSampFact_Hi[nCompIdent];
unsigned nCssFactV = m_nSofVertSampFactMax_Vmax/m_anSofVertSampFact_Vi[nCompIdent];
if (m_eImgLandscape!=ENUM_LANDSCAPE_NO) {
// Landscape orientation
m_strImgQuantCss.Format(_T("%ux%u"),nCssFactH,nCssFactV);
}
else {
// Portrait orientation (flip subsampling ratio)
m_strImgQuantCss.Format(_T("%ux%u"),nCssFactV,nCssFactH);
}
} else if (m_nSofNumComps_Nf == NUM_CHAN_GRAYSCALE) {
m_strImgQuantCss = _T("Gray");
}
DecodeEmbeddedThumb();
// Generate the signature
PrepareSignature();
// Compare compression signature
if (m_pAppConfig->bSigSearch) {
// In the case of lossless files, there won't be any DQT and
// hence no compression signatures to compare. Therefore, skip this process.
if (m_strHash == _T("NONE")) {
m_pLog->AddLineWarn(_T("Skipping compression signature search as no DQT"));
} else {
CompareSignature();
}
}
if (nDataAfterEof > 0) {
m_pLog->AddLine(_T(""));
m_pLog->AddLineHdr(_T("*** Additional Info ***"));
strTmp.Format(_T("NOTE: Data exists after EOF, range: 0x%08X-0x%08X (%u bytes)"),
m_nPosEoi,m_nPosFileEnd,nDataAfterEof);
m_pLog->AddLine(strTmp);
}
// Print out the special-purpose outputs
OutputSpecial();
}
// Reset the status bar text
if (m_pStatBar) {
m_pStatBar->SetPaneText(0,_T("Done"));
}
// Mark the file as closed
//m_pWBuf->BufFileUnset();
}
// Determine if the analyzed file is in a state ready for image
// extraction. Confirms that the important JFIF markers have been
// detected in the previous analysis.
//
// PRE:
// - m_nPosEmbedStart
// - m_nPosEmbedEnd
// - m_nPosFileEnd
//
// RETURN:
// - True if image is ready for extraction
//
bool CjfifDecode::ExportJpegPrepare(CString strFileIn,bool bForceSoi,bool bForceEoi,bool bIgnoreEoi)
{
// Extract from current file
// [m_nPosEmbedStart ... m_nPosEmbedEnd]
// If state is valid (i.e. file opened)
CString strTmp = _T("");
m_pLog->AddLine(_T(""));
m_pLog->AddLineHdr(_T("*** Exporting JPEG ***"));
strTmp.Format(_T(" Exporting from: [%s]"),(LPCTSTR)strFileIn);
m_pLog->AddLine(strTmp);
// Only bother to extract if all main sections are present
bool bExtractWarn = false;
CString strMissing = _T("");
if (!m_bStateEoi) {
if (!bForceEoi && !bIgnoreEoi) {
strTmp.Format(_T(" ERROR: Missing marker: %s"),_T("EOI"));
m_pLog->AddLineErr(strTmp);
m_pLog->AddLineErr(_T(" Aborting export. Consider enabling [Force EOI] or [Ignore Missing EOI] option"));
return false;
} else if (bIgnoreEoi) {
// Ignore the EOI, so mark the end of file, but don't
// set the flag where we force one.
m_nPosEmbedEnd = m_nPosFileEnd;
} else {
// We're missing the EOI but the user has requested
// that we force an EOI, so let's fix things up
m_nPosEmbedEnd = m_nPosFileEnd;
}
}
if ((m_nPosEmbedStart == 0) && (m_nPosEmbedEnd == 0)) {
strTmp.Format(_T(" No frame found at this position in file. Consider using [Img Search]"));
m_pLog->AddLineErr(strTmp);
return false;
}
if (!m_bStateSoi) {
if (!bForceSoi) {
strTmp.Format(_T(" ERROR: Missing marker: %s"),_T("SOI"));
m_pLog->AddLineErr(strTmp);
m_pLog->AddLineErr(_T(" Aborting export. Consider enabling [Force SOI] option"));
return false;
} else {
// We're missing the SOI but the user has requested
// that we force an SOI, so let's fix things up
}
}
if (!m_bStateSos) {
strTmp.Format(_T(" ERROR: Missing marker: %s"),_T("SOS"));
m_pLog->AddLineErr(strTmp);
m_pLog->AddLineErr(_T(" Aborting export"));
return false;
}
if (!m_bStateDqt) { bExtractWarn = true; strMissing += _T("DQT "); }
if (!m_bStateDht) { bExtractWarn = true; strMissing += _T("DHT "); }
if (!m_bStateSof) { bExtractWarn = true; strMissing += _T("SOF "); }
if (bExtractWarn) {
strTmp.Format(_T(" NOTE: Missing marker: %s"),(LPCTSTR)strMissing);
m_pLog->AddLineWarn(strTmp);
m_pLog->AddLineWarn(_T(" Exported JPEG may not be valid"));
}
if (m_nPosEmbedEnd < m_nPosEmbedStart) {
strTmp.Format(_T("ERROR: Invalid SOI-EOI order. Export aborted."));
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return false;
}
return true;
}
#define EXPORT_BUF_SIZE 131072
// Export the embedded JPEG image at the current position in the file (with overlays)
// (may be the primary image or even an embedded thumbnail).
bool CjfifDecode::ExportJpegDo(CString strFileIn, CString strFileOut,
unsigned long nFileLen, bool bOverlayEn,bool bDhtAviInsert,bool bForceSoi,bool bForceEoi)
{
CFile* pFileOutput;
CString strTmp = _T("");
strTmp.Format(_T(" Exporting to: [%s]"),(LPCTSTR)strFileOut);
m_pLog->AddLine(strTmp);
if (strFileIn == strFileOut) {
strTmp.Format(_T("ERROR: Can't overwrite source file. Aborting export."));
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return false;
}
ASSERT(strFileIn != _T(""));
if (strFileIn == _T("")) {
strTmp.Format(_T("ERROR: Export but source filename empty"));
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return false;
}
try
{
// Open specified file
// Added in shareDenyNone as this apparently helps resolve some people's troubles
// with an error showing: Couldn't open file "Sharing Violation"
pFileOutput = new CFile(strFileOut, CFile::modeCreate| CFile::modeWrite | CFile::typeBinary | CFile::shareDenyNone);
}
catch (CFileException* e)
{
TCHAR msg[MAX_BUF_EX_ERR_MSG];
CString strError;
e->GetErrorMessage(msg,MAX_BUF_EX_ERR_MSG);
e->Delete();
strError.Format(_T("ERROR: Couldn't open file for write [%s]: [%s]"),
(LPCTSTR)strFileOut, (LPCTSTR)msg);
m_pLog->AddLineErr(strError);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strError);
pFileOutput = NULL;
return false;
}
// Don't attempt to load buffer with zero length file!
if (nFileLen==0) {
strTmp.Format(_T("ERROR: Source file length error. Please Reprocess first."));
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
if (pFileOutput) { delete pFileOutput; pFileOutput = NULL; }
return false;
}
// Need to insert fake DHT. Assume we have enough buffer allocated.
//
// Step 1: Copy from SOI -> SOS (not incl)
// Step 2: Insert Fake DHT
// Step 3: Copy from SOS -> EOI
unsigned nCopyStart;
unsigned nCopyEnd;
unsigned nCopyLeft;
unsigned ind;
BYTE* pBuf;
pBuf = new BYTE[EXPORT_BUF_SIZE+10];
if (!pBuf) {
if (pFileOutput) { delete pFileOutput; pFileOutput = NULL; }
return false;
}
// Step 1
// If we need to force an SOI, do it now
if (!m_bStateSoi && bForceSoi) {
m_pLog->AddLine(_T(" Forcing SOI Marker"));
BYTE anBufSoi[2] = {0xFF,JFIF_SOI};
pFileOutput->Write(&anBufSoi,2);
}
nCopyStart = m_nPosEmbedStart;
nCopyEnd = (m_nPosSos-1);
ind = nCopyStart;
while (ind<nCopyEnd) {
nCopyLeft = nCopyEnd-ind+1;
if (nCopyLeft>EXPORT_BUF_SIZE) { nCopyLeft = EXPORT_BUF_SIZE; }
for (unsigned ind1=0;ind1<nCopyLeft;ind1++) {
pBuf[ind1] = Buf(ind+ind1,!bOverlayEn);
}
pFileOutput->Write(pBuf,nCopyLeft);
ind += nCopyLeft;
// NOTE: We ensure nFileLen != 0 earlier
ASSERT(nFileLen>0);
strTmp.Format(_T("Exporting %3u%%..."),ind*100/nFileLen);
SetStatusText(strTmp);
}
if (bDhtAviInsert) {
// Step 2. The following struct includes the JFIF marker too
strTmp.Format(_T(" Inserting standard AVI DHT huffman table"));
m_pLog->AddLine(strTmp);
pFileOutput->Write(m_abMJPGDHTSeg,JFIF_DHT_FAKE_SZ);
}
// Step 3
nCopyStart = m_nPosSos;
nCopyEnd = m_nPosEmbedEnd-1;
ind = nCopyStart;
while (ind<nCopyEnd) {
nCopyLeft = nCopyEnd-ind+1;
if (nCopyLeft>EXPORT_BUF_SIZE) { nCopyLeft = EXPORT_BUF_SIZE; }
for (unsigned ind1=0;ind1<nCopyLeft;ind1++) {
pBuf[ind1] = Buf(ind+ind1,!bOverlayEn);
}
pFileOutput->Write(pBuf,nCopyLeft);
ind += nCopyLeft;
// NOTE: We ensure nFileLen != 0 earlier
ASSERT(nFileLen>0);
strTmp.Format(_T("Exporting %3u%%..."),ind*100/nFileLen);
SetStatusText(strTmp);
}
// Now optionally insert the EOI Marker
if (bForceEoi) {
m_pLog->AddLine(_T(" Forcing EOI Marker"));
BYTE anBufEoi[2] = {0xFF,JFIF_EOI};
pFileOutput->Write(&anBufEoi,2);
}
// Free up space
pFileOutput->Close();
if (pBuf) {
delete [] pBuf;
pBuf = NULL;
}
if (pFileOutput) {
delete pFileOutput;
pFileOutput = NULL;
}
SetStatusText(_T(""));
strTmp.Format(_T(" Export done"));
m_pLog->AddLine(strTmp);
return true;
}
// Export a subset of the file with no overlays or mods
bool CjfifDecode::ExportJpegDoRange(CString strFileIn, CString strFileOut,
unsigned long nStart, unsigned long nEnd)
{
CFile* pFileOutput;
CString strTmp = _T("");
strTmp.Format(_T(" Exporting range to: [%s]"),(LPCTSTR)strFileOut);
m_pLog->AddLine(strTmp);
if (strFileIn == strFileOut) {
strTmp.Format(_T("ERROR: Can't overwrite source file. Aborting export."));
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return false;
}
ASSERT(strFileIn != _T(""));
if (strFileIn == _T("")) {
strTmp.Format(_T("ERROR: Export but source filename empty"));
m_pLog->AddLineErr(strTmp);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strTmp);
return false;
}
try
{
// Open specified file
// Added in shareDenyNone as this apparently helps resolve some people's troubles
// with an error showing: Couldn't open file "Sharing Violation"
pFileOutput = new CFile(strFileOut, CFile::modeCreate| CFile::modeWrite | CFile::typeBinary | CFile::shareDenyNone);
}
catch (CFileException* e)
{
TCHAR msg[MAX_BUF_EX_ERR_MSG];
CString strError;
e->GetErrorMessage(msg,MAX_BUF_EX_ERR_MSG);
e->Delete();
strError.Format(_T("ERROR: Couldn't open file for write [%s]: [%s]"),
(LPCTSTR)strFileOut, (LPCTSTR)msg);
m_pLog->AddLineErr(strError);
if (m_pAppConfig->bInteractive)
AfxMessageBox(strError);
pFileOutput = NULL;
return false;
}
unsigned nCopyStart;
unsigned nCopyEnd;
unsigned nCopyLeft;
unsigned ind;
BYTE* pBuf;
pBuf = new BYTE[EXPORT_BUF_SIZE+10];
if (!pBuf) {
if (pFileOutput) { delete pFileOutput; pFileOutput = NULL; }
return false;
}
// Step 1
nCopyStart = nStart;
nCopyEnd = nEnd;
ind = nCopyStart;
while (ind<nCopyEnd) {
nCopyLeft = nCopyEnd-ind+1;
if (nCopyLeft>EXPORT_BUF_SIZE) { nCopyLeft = EXPORT_BUF_SIZE; }
for (unsigned ind1=0;ind1<nCopyLeft;ind1++) {
pBuf[ind1] = Buf(ind+ind1,false);
}
pFileOutput->Write(pBuf,nCopyLeft);
ind += nCopyLeft;
strTmp.Format(_T("Exporting %3u%%..."),ind*100/(nCopyEnd-nCopyStart));
SetStatusText(strTmp);
}
// Free up space
pFileOutput->Close();
if (pBuf) {
delete [] pBuf;
pBuf = NULL;
}
if (pFileOutput) {
delete pFileOutput;
pFileOutput = NULL;
}
SetStatusText(_T(""));
strTmp.Format(_T(" Export range done"));
m_pLog->AddLine(strTmp);
return true;
}
// ====================================================================================
// JFIF Decoder Constants
// ====================================================================================
// List of the JFIF markers
const MarkerNameTable CjfifDecode::m_pMarkerNames[] = {
{JFIF_SOF0,_T("SOF0")},
{JFIF_SOF1,_T("SOF1")},
{JFIF_SOF2,_T("SOF2")},
{JFIF_SOF3,_T("SOF3")},
{JFIF_SOF5,_T("SOF5")},
{JFIF_SOF6,_T("SOF6")},
{JFIF_SOF7,_T("SOF7")},
{JFIF_JPG,_T("JPG")},
{JFIF_SOF9,_T("SOF9")},
{JFIF_SOF10,_T("SOF10")},
{JFIF_SOF11,_T("SOF11")},
{JFIF_SOF13,_T("SOF13")},
{JFIF_SOF14,_T("SOF14")},
{JFIF_SOF15,_T("SOF15")},
{JFIF_DHT,_T("DHT")},
{JFIF_DAC,_T("DAC")},
{JFIF_RST0,_T("RST0")},
{JFIF_RST1,_T("RST1")},
{JFIF_RST2,_T("RST2")},
{JFIF_RST3,_T("RST3")},
{JFIF_RST4,_T("RST4")},
{JFIF_RST5,_T("RST5")},
{JFIF_RST6,_T("RST6")},
{JFIF_RST7,_T("RST7")},
{JFIF_SOI,_T("SOI")},
{JFIF_EOI,_T("EOI")},
{JFIF_SOS,_T("SOS")},
{JFIF_DQT,_T("DQT")},
{JFIF_DNL,_T("DNL")},
{JFIF_DRI,_T("DRI")},
{JFIF_DHP,_T("DHP")},
{JFIF_EXP,_T("EXP")},
{JFIF_APP0,_T("APP0")},
{JFIF_APP1,_T("APP1")},
{JFIF_APP2,_T("APP2")},
{JFIF_APP3,_T("APP3")},
{JFIF_APP4,_T("APP4")},
{JFIF_APP5,_T("APP5")},
{JFIF_APP6,_T("APP6")},
{JFIF_APP7,_T("APP7")},
{JFIF_APP8,_T("APP8")},
{JFIF_APP9,_T("APP9")},
{JFIF_APP10,_T("APP10")},
{JFIF_APP11,_T("APP11")},
{JFIF_APP12,_T("APP12")},
{JFIF_APP13,_T("APP13")},
{JFIF_APP14,_T("APP14")},
{JFIF_APP15,_T("APP15")},
{JFIF_JPG0,_T("JPG0")},
{JFIF_JPG1,_T("JPG1")},
{JFIF_JPG2,_T("JPG2")},
{JFIF_JPG3,_T("JPG3")},
{JFIF_JPG4,_T("JPG4")},
{JFIF_JPG5,_T("JPG5")},
{JFIF_JPG6,_T("JPG6")},
{JFIF_JPG7,_T("JPG7")},
{JFIF_JPG8,_T("JPG8")},
{JFIF_JPG9,_T("JPG9")},
{JFIF_JPG10,_T("JPG10")},
{JFIF_JPG11,_T("JPG11")},
{JFIF_JPG12,_T("JPG12")},
{JFIF_JPG13,_T("JPG13")},
{JFIF_COM,_T("COM")},
{JFIF_TEM,_T("TEM")},
//{JFIF_RES*,_T("RES")},
{0x00,_T("*")},
};
// For Motion JPEG, define the DHT tables that we use since they won't exist
// in each frame within the AVI. This table will be read in during
// DecodeDHT()'s call to Buf().
const BYTE CjfifDecode::m_abMJPGDHTSeg[JFIF_DHT_FAKE_SZ] = {
/* JPEG DHT Segment for YCrCb omitted from MJPG data */
0xFF,0xC4,0x01,0xA2,
0x00,0x00,0x01,0x05,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x01,0x00,0x03,0x01,0x01,0x01,0x01,
0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,
0x08,0x09,0x0A,0x0B,0x10,0x00,0x02,0x01,0x03,0x03,0x02,0x04,0x03,0x05,0x05,0x04,0x04,0x00,
0x00,0x01,0x7D,0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,
0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xA1,0x08,0x23,0x42,0xB1,0xC1,0x15,0x52,0xD1,0xF0,0x24,
0x33,0x62,0x72,0x82,0x09,0x0A,0x16,0x17,0x18,0x19,0x1A,0x25,0x26,0x27,0x28,0x29,0x2A,0x34,
0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x53,0x54,0x55,0x56,
0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78,
0x79,0x7A,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,
0x9A,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,
0xBA,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,
0xDA,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,
0xF8,0xF9,0xFA,0x11,0x00,0x02,0x01,0x02,0x04,0x04,0x03,0x04,0x07,0x05,0x04,0x04,0x00,0x01,
0x02,0x77,0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,0xA1,0xB1,0xC1,0x09,0x23,0x33,0x52,0xF0,0x15,0x62,
0x72,0xD1,0x0A,0x16,0x24,0x34,0xE1,0x25,0xF1,0x17,0x18,0x19,0x1A,0x26,0x27,0x28,0x29,0x2A,
0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x53,0x54,0x55,0x56,
0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78,
0x79,0x7A,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
0x99,0x9A,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,
0xB9,0xBA,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,
0xD9,0xDA,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,
0xF9,0xFA
};
// TODO: Add ITU-T Example DQT & DHT
// These will be useful for GeoRaster decode (ie. JPEG-B)
CString glb_strMsgStopDecode = _T(" Stopping decode. Use [Relaxed Parsing] to continue."); | ./CrossVul/dataset_final_sorted/CWE-369/cpp/bad_2528_0 |
crossvul-cpp_data_bad_153_1 | /*
* rdbmp.c
*
* This file was part of the Independent JPEG Group's software:
* Copyright (C) 1994-1996, Thomas G. Lane.
* Modified 2009-2010 by Guido Vollbeding.
* libjpeg-turbo Modifications:
* Modified 2011 by Siarhei Siamashka.
* Copyright (C) 2015, 2017, D. R. Commander.
* For conditions of distribution and use, see the accompanying README.ijg
* file.
*
* This file contains routines to read input images in Microsoft "BMP"
* format (MS Windows 3.x, OS/2 1.x, and OS/2 2.x flavors).
* Currently, only 8-bit and 24-bit images are supported, not 1-bit or
* 4-bit (feeding such low-depth images into JPEG would be silly anyway).
* Also, we don't support RLE-compressed files.
*
* These routines may need modification for non-Unix environments or
* specialized applications. As they stand, they assume input from
* an ordinary stdio stream. They further assume that reading begins
* at the start of the file; start_input may need work if the
* user interface has already read some data (e.g., to determine that
* the file is indeed BMP format).
*
* This code contributed by James Arthur Boucher.
*/
#include "cmyk.h"
#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
#ifdef BMP_SUPPORTED
/* Macros to deal with unsigned chars as efficiently as compiler allows */
#ifdef HAVE_UNSIGNED_CHAR
typedef unsigned char U_CHAR;
#define UCH(x) ((int)(x))
#else /* !HAVE_UNSIGNED_CHAR */
#ifdef __CHAR_UNSIGNED__
typedef char U_CHAR;
#define UCH(x) ((int)(x))
#else
typedef char U_CHAR;
#define UCH(x) ((int)(x) & 0xFF)
#endif
#endif /* HAVE_UNSIGNED_CHAR */
#define ReadOK(file, buffer, len) \
(JFREAD(file, buffer, len) == ((size_t)(len)))
static int alpha_index[JPEG_NUMCS] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 3, 0, 0, -1
};
/* Private version of data source object */
typedef struct _bmp_source_struct *bmp_source_ptr;
typedef struct _bmp_source_struct {
struct cjpeg_source_struct pub; /* public fields */
j_compress_ptr cinfo; /* back link saves passing separate parm */
JSAMPARRAY colormap; /* BMP colormap (converted to my format) */
jvirt_sarray_ptr whole_image; /* Needed to reverse row order */
JDIMENSION source_row; /* Current source row number */
JDIMENSION row_width; /* Physical width of scanlines in file */
int bits_per_pixel; /* remembers 8- or 24-bit format */
boolean use_inversion_array; /* TRUE = preload the whole image, which is
stored in bottom-up order, and feed it to
the calling program in top-down order
FALSE = the calling program will maintain
its own image buffer and read the rows in
bottom-up order */
U_CHAR *iobuffer; /* I/O buffer (used to buffer a single row from
disk if use_inversion_array == FALSE) */
} bmp_source_struct;
LOCAL(int)
read_byte(bmp_source_ptr sinfo)
/* Read next byte from BMP file */
{
register FILE *infile = sinfo->pub.input_file;
register int c;
if ((c = getc(infile)) == EOF)
ERREXIT(sinfo->cinfo, JERR_INPUT_EOF);
return c;
}
LOCAL(void)
read_colormap(bmp_source_ptr sinfo, int cmaplen, int mapentrysize)
/* Read the colormap from a BMP file */
{
int i, gray = 1;
switch (mapentrysize) {
case 3:
/* BGR format (occurs in OS/2 files) */
for (i = 0; i < cmaplen; i++) {
sinfo->colormap[2][i] = (JSAMPLE)read_byte(sinfo);
sinfo->colormap[1][i] = (JSAMPLE)read_byte(sinfo);
sinfo->colormap[0][i] = (JSAMPLE)read_byte(sinfo);
if (sinfo->colormap[2][i] != sinfo->colormap[1][i] ||
sinfo->colormap[1][i] != sinfo->colormap[0][i])
gray = 0;
}
break;
case 4:
/* BGR0 format (occurs in MS Windows files) */
for (i = 0; i < cmaplen; i++) {
sinfo->colormap[2][i] = (JSAMPLE)read_byte(sinfo);
sinfo->colormap[1][i] = (JSAMPLE)read_byte(sinfo);
sinfo->colormap[0][i] = (JSAMPLE)read_byte(sinfo);
(void)read_byte(sinfo);
if (sinfo->colormap[2][i] != sinfo->colormap[1][i] ||
sinfo->colormap[1][i] != sinfo->colormap[0][i])
gray = 0;
}
break;
default:
ERREXIT(sinfo->cinfo, JERR_BMP_BADCMAP);
break;
}
if (sinfo->cinfo->in_color_space == JCS_UNKNOWN && gray)
sinfo->cinfo->in_color_space = JCS_GRAYSCALE;
if (sinfo->cinfo->in_color_space == JCS_GRAYSCALE && !gray)
ERREXIT(sinfo->cinfo, JERR_BAD_IN_COLORSPACE);
}
/*
* Read one row of pixels.
* The image has been read into the whole_image array, but is otherwise
* unprocessed. We must read it out in top-to-bottom row order, and if
* it is an 8-bit image, we must expand colormapped pixels to 24bit format.
*/
METHODDEF(JDIMENSION)
get_8bit_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading 8-bit colormap indexes */
{
bmp_source_ptr source = (bmp_source_ptr)sinfo;
register JSAMPARRAY colormap = source->colormap;
JSAMPARRAY image_ptr;
register int t;
register JSAMPROW inptr, outptr;
register JDIMENSION col;
if (source->use_inversion_array) {
/* Fetch next row from virtual array */
source->source_row--;
image_ptr = (*cinfo->mem->access_virt_sarray)
((j_common_ptr)cinfo, source->whole_image,
source->source_row, (JDIMENSION)1, FALSE);
inptr = image_ptr[0];
} else {
if (!ReadOK(source->pub.input_file, source->iobuffer, source->row_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
inptr = source->iobuffer;
}
/* Expand the colormap indexes to real data */
outptr = source->pub.buffer[0];
if (cinfo->in_color_space == JCS_GRAYSCALE) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
*outptr++ = colormap[0][t];
}
} else if (cinfo->in_color_space == JCS_CMYK) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
rgb_to_cmyk(colormap[0][t], colormap[1][t], colormap[2][t], outptr,
outptr + 1, outptr + 2, outptr + 3);
outptr += 4;
}
} else {
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
if (aindex >= 0) {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
outptr[rindex] = colormap[0][t];
outptr[gindex] = colormap[1][t];
outptr[bindex] = colormap[2][t];
outptr[aindex] = 0xFF;
outptr += ps;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
t = GETJSAMPLE(*inptr++);
outptr[rindex] = colormap[0][t];
outptr[gindex] = colormap[1][t];
outptr[bindex] = colormap[2][t];
outptr += ps;
}
}
}
return 1;
}
METHODDEF(JDIMENSION)
get_24bit_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading 24-bit pixels */
{
bmp_source_ptr source = (bmp_source_ptr)sinfo;
JSAMPARRAY image_ptr;
register JSAMPROW inptr, outptr;
register JDIMENSION col;
if (source->use_inversion_array) {
/* Fetch next row from virtual array */
source->source_row--;
image_ptr = (*cinfo->mem->access_virt_sarray)
((j_common_ptr)cinfo, source->whole_image,
source->source_row, (JDIMENSION)1, FALSE);
inptr = image_ptr[0];
} else {
if (!ReadOK(source->pub.input_file, source->iobuffer, source->row_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
inptr = source->iobuffer;
}
/* Transfer data. Note source values are in BGR order
* (even though Microsoft's own documents say the opposite).
*/
outptr = source->pub.buffer[0];
if (cinfo->in_color_space == JCS_EXT_BGR) {
MEMCOPY(outptr, inptr, source->row_width);
} else if (cinfo->in_color_space == JCS_CMYK) {
for (col = cinfo->image_width; col > 0; col--) {
/* can omit GETJSAMPLE() safely */
JSAMPLE b = *inptr++, g = *inptr++, r = *inptr++;
rgb_to_cmyk(r, g, b, outptr, outptr + 1, outptr + 2, outptr + 3);
outptr += 4;
}
} else {
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
if (aindex >= 0) {
for (col = cinfo->image_width; col > 0; col--) {
outptr[bindex] = *inptr++; /* can omit GETJSAMPLE() safely */
outptr[gindex] = *inptr++;
outptr[rindex] = *inptr++;
outptr[aindex] = 0xFF;
outptr += ps;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
outptr[bindex] = *inptr++; /* can omit GETJSAMPLE() safely */
outptr[gindex] = *inptr++;
outptr[rindex] = *inptr++;
outptr += ps;
}
}
}
return 1;
}
METHODDEF(JDIMENSION)
get_32bit_row(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
/* This version is for reading 32-bit pixels */
{
bmp_source_ptr source = (bmp_source_ptr)sinfo;
JSAMPARRAY image_ptr;
register JSAMPROW inptr, outptr;
register JDIMENSION col;
if (source->use_inversion_array) {
/* Fetch next row from virtual array */
source->source_row--;
image_ptr = (*cinfo->mem->access_virt_sarray)
((j_common_ptr)cinfo, source->whole_image,
source->source_row, (JDIMENSION)1, FALSE);
inptr = image_ptr[0];
} else {
if (!ReadOK(source->pub.input_file, source->iobuffer, source->row_width))
ERREXIT(cinfo, JERR_INPUT_EOF);
inptr = source->iobuffer;
}
/* Transfer data. Note source values are in BGR order
* (even though Microsoft's own documents say the opposite).
*/
outptr = source->pub.buffer[0];
if (cinfo->in_color_space == JCS_EXT_BGRX ||
cinfo->in_color_space == JCS_EXT_BGRA) {
MEMCOPY(outptr, inptr, source->row_width);
} else if (cinfo->in_color_space == JCS_CMYK) {
for (col = cinfo->image_width; col > 0; col--) {
/* can omit GETJSAMPLE() safely */
JSAMPLE b = *inptr++, g = *inptr++, r = *inptr++;
rgb_to_cmyk(r, g, b, outptr, outptr + 1, outptr + 2, outptr + 3);
inptr++; /* skip the 4th byte (Alpha channel) */
outptr += 4;
}
} else {
register int rindex = rgb_red[cinfo->in_color_space];
register int gindex = rgb_green[cinfo->in_color_space];
register int bindex = rgb_blue[cinfo->in_color_space];
register int aindex = alpha_index[cinfo->in_color_space];
register int ps = rgb_pixelsize[cinfo->in_color_space];
if (aindex >= 0) {
for (col = cinfo->image_width; col > 0; col--) {
outptr[bindex] = *inptr++; /* can omit GETJSAMPLE() safely */
outptr[gindex] = *inptr++;
outptr[rindex] = *inptr++;
outptr[aindex] = *inptr++;
outptr += ps;
}
} else {
for (col = cinfo->image_width; col > 0; col--) {
outptr[bindex] = *inptr++; /* can omit GETJSAMPLE() safely */
outptr[gindex] = *inptr++;
outptr[rindex] = *inptr++;
inptr++; /* skip the 4th byte (Alpha channel) */
outptr += ps;
}
}
}
return 1;
}
/*
* This method loads the image into whole_image during the first call on
* get_pixel_rows. The get_pixel_rows pointer is then adjusted to call
* get_8bit_row, get_24bit_row, or get_32bit_row on subsequent calls.
*/
METHODDEF(JDIMENSION)
preload_image(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
bmp_source_ptr source = (bmp_source_ptr)sinfo;
register FILE *infile = source->pub.input_file;
register JSAMPROW out_ptr;
JSAMPARRAY image_ptr;
JDIMENSION row;
cd_progress_ptr progress = (cd_progress_ptr)cinfo->progress;
/* Read the data into a virtual array in input-file row order. */
for (row = 0; row < cinfo->image_height; row++) {
if (progress != NULL) {
progress->pub.pass_counter = (long)row;
progress->pub.pass_limit = (long)cinfo->image_height;
(*progress->pub.progress_monitor) ((j_common_ptr)cinfo);
}
image_ptr = (*cinfo->mem->access_virt_sarray)
((j_common_ptr)cinfo, source->whole_image, row, (JDIMENSION)1, TRUE);
out_ptr = image_ptr[0];
if (fread(out_ptr, 1, source->row_width, infile) != source->row_width) {
if (feof(infile))
ERREXIT(cinfo, JERR_INPUT_EOF);
else
ERREXIT(cinfo, JERR_FILE_READ);
}
}
if (progress != NULL)
progress->completed_extra_passes++;
/* Set up to read from the virtual array in top-to-bottom order */
switch (source->bits_per_pixel) {
case 8:
source->pub.get_pixel_rows = get_8bit_row;
break;
case 24:
source->pub.get_pixel_rows = get_24bit_row;
break;
case 32:
source->pub.get_pixel_rows = get_32bit_row;
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
}
source->source_row = cinfo->image_height;
/* And read the first row */
return (*source->pub.get_pixel_rows) (cinfo, sinfo);
}
/*
* Read the file header; return image size and component count.
*/
METHODDEF(void)
start_input_bmp(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
bmp_source_ptr source = (bmp_source_ptr)sinfo;
U_CHAR bmpfileheader[14];
U_CHAR bmpinfoheader[64];
#define GET_2B(array, offset) \
((unsigned short)UCH(array[offset]) + \
(((unsigned short)UCH(array[offset + 1])) << 8))
#define GET_4B(array, offset) \
((unsigned int)UCH(array[offset]) + \
(((unsigned int)UCH(array[offset + 1])) << 8) + \
(((unsigned int)UCH(array[offset + 2])) << 16) + \
(((unsigned int)UCH(array[offset + 3])) << 24))
unsigned int bfOffBits;
unsigned int headerSize;
int biWidth;
int biHeight;
unsigned short biPlanes;
unsigned int biCompression;
int biXPelsPerMeter, biYPelsPerMeter;
unsigned int biClrUsed = 0;
int mapentrysize = 0; /* 0 indicates no colormap */
int bPad;
JDIMENSION row_width = 0;
/* Read and verify the bitmap file header */
if (!ReadOK(source->pub.input_file, bmpfileheader, 14))
ERREXIT(cinfo, JERR_INPUT_EOF);
if (GET_2B(bmpfileheader, 0) != 0x4D42) /* 'BM' */
ERREXIT(cinfo, JERR_BMP_NOT);
bfOffBits = GET_4B(bmpfileheader, 10);
/* We ignore the remaining fileheader fields */
/* The infoheader might be 12 bytes (OS/2 1.x), 40 bytes (Windows),
* or 64 bytes (OS/2 2.x). Check the first 4 bytes to find out which.
*/
if (!ReadOK(source->pub.input_file, bmpinfoheader, 4))
ERREXIT(cinfo, JERR_INPUT_EOF);
headerSize = GET_4B(bmpinfoheader, 0);
if (headerSize < 12 || headerSize > 64)
ERREXIT(cinfo, JERR_BMP_BADHEADER);
if (!ReadOK(source->pub.input_file, bmpinfoheader + 4, headerSize - 4))
ERREXIT(cinfo, JERR_INPUT_EOF);
switch (headerSize) {
case 12:
/* Decode OS/2 1.x header (Microsoft calls this a BITMAPCOREHEADER) */
biWidth = (int)GET_2B(bmpinfoheader, 4);
biHeight = (int)GET_2B(bmpinfoheader, 6);
biPlanes = GET_2B(bmpinfoheader, 8);
source->bits_per_pixel = (int)GET_2B(bmpinfoheader, 10);
switch (source->bits_per_pixel) {
case 8: /* colormapped image */
mapentrysize = 3; /* OS/2 uses RGBTRIPLE colormap */
TRACEMS2(cinfo, 1, JTRC_BMP_OS2_MAPPED, biWidth, biHeight);
break;
case 24: /* RGB image */
TRACEMS2(cinfo, 1, JTRC_BMP_OS2, biWidth, biHeight);
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
break;
}
break;
case 40:
case 64:
/* Decode Windows 3.x header (Microsoft calls this a BITMAPINFOHEADER) */
/* or OS/2 2.x header, which has additional fields that we ignore */
biWidth = (int)GET_4B(bmpinfoheader, 4);
biHeight = (int)GET_4B(bmpinfoheader, 8);
biPlanes = GET_2B(bmpinfoheader, 12);
source->bits_per_pixel = (int)GET_2B(bmpinfoheader, 14);
biCompression = GET_4B(bmpinfoheader, 16);
biXPelsPerMeter = (int)GET_4B(bmpinfoheader, 24);
biYPelsPerMeter = (int)GET_4B(bmpinfoheader, 28);
biClrUsed = GET_4B(bmpinfoheader, 32);
/* biSizeImage, biClrImportant fields are ignored */
switch (source->bits_per_pixel) {
case 8: /* colormapped image */
mapentrysize = 4; /* Windows uses RGBQUAD colormap */
TRACEMS2(cinfo, 1, JTRC_BMP_MAPPED, biWidth, biHeight);
break;
case 24: /* RGB image */
TRACEMS2(cinfo, 1, JTRC_BMP, biWidth, biHeight);
break;
case 32: /* RGB image + Alpha channel */
TRACEMS2(cinfo, 1, JTRC_BMP, biWidth, biHeight);
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
break;
}
if (biCompression != 0)
ERREXIT(cinfo, JERR_BMP_COMPRESSED);
if (biXPelsPerMeter > 0 && biYPelsPerMeter > 0) {
/* Set JFIF density parameters from the BMP data */
cinfo->X_density = (UINT16)(biXPelsPerMeter / 100); /* 100 cm per meter */
cinfo->Y_density = (UINT16)(biYPelsPerMeter / 100);
cinfo->density_unit = 2; /* dots/cm */
}
break;
default:
ERREXIT(cinfo, JERR_BMP_BADHEADER);
return;
}
if (biWidth <= 0 || biHeight <= 0)
ERREXIT(cinfo, JERR_BMP_EMPTY);
if (biPlanes != 1)
ERREXIT(cinfo, JERR_BMP_BADPLANES);
/* Compute distance to bitmap data --- will adjust for colormap below */
bPad = bfOffBits - (headerSize + 14);
/* Read the colormap, if any */
if (mapentrysize > 0) {
if (biClrUsed <= 0)
biClrUsed = 256; /* assume it's 256 */
else if (biClrUsed > 256)
ERREXIT(cinfo, JERR_BMP_BADCMAP);
/* Allocate space to store the colormap */
source->colormap = (*cinfo->mem->alloc_sarray)
((j_common_ptr)cinfo, JPOOL_IMAGE, (JDIMENSION)biClrUsed, (JDIMENSION)3);
/* and read it from the file */
read_colormap(source, (int)biClrUsed, mapentrysize);
/* account for size of colormap */
bPad -= biClrUsed * mapentrysize;
}
/* Skip any remaining pad bytes */
if (bPad < 0) /* incorrect bfOffBits value? */
ERREXIT(cinfo, JERR_BMP_BADHEADER);
while (--bPad >= 0) {
(void)read_byte(source);
}
/* Compute row width in file, including padding to 4-byte boundary */
switch (source->bits_per_pixel) {
case 8:
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_EXT_RGB;
if (IsExtRGB(cinfo->in_color_space))
cinfo->input_components = rgb_pixelsize[cinfo->in_color_space];
else if (cinfo->in_color_space == JCS_GRAYSCALE)
cinfo->input_components = 1;
else if (cinfo->in_color_space == JCS_CMYK)
cinfo->input_components = 4;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
row_width = (JDIMENSION)biWidth;
break;
case 24:
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_EXT_BGR;
if (IsExtRGB(cinfo->in_color_space))
cinfo->input_components = rgb_pixelsize[cinfo->in_color_space];
else if (cinfo->in_color_space == JCS_CMYK)
cinfo->input_components = 4;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
row_width = (JDIMENSION)(biWidth * 3);
break;
case 32:
if (cinfo->in_color_space == JCS_UNKNOWN)
cinfo->in_color_space = JCS_EXT_BGRA;
if (IsExtRGB(cinfo->in_color_space))
cinfo->input_components = rgb_pixelsize[cinfo->in_color_space];
else if (cinfo->in_color_space == JCS_CMYK)
cinfo->input_components = 4;
else
ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
row_width = (JDIMENSION)(biWidth * 4);
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
}
while ((row_width & 3) != 0) row_width++;
source->row_width = row_width;
if (source->use_inversion_array) {
/* Allocate space for inversion array, prepare for preload pass */
source->whole_image = (*cinfo->mem->request_virt_sarray)
((j_common_ptr)cinfo, JPOOL_IMAGE, FALSE,
row_width, (JDIMENSION)biHeight, (JDIMENSION)1);
source->pub.get_pixel_rows = preload_image;
if (cinfo->progress != NULL) {
cd_progress_ptr progress = (cd_progress_ptr)cinfo->progress;
progress->total_extra_passes++; /* count file input as separate pass */
}
} else {
source->iobuffer = (U_CHAR *)
(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE, row_width);
switch (source->bits_per_pixel) {
case 8:
source->pub.get_pixel_rows = get_8bit_row;
break;
case 24:
source->pub.get_pixel_rows = get_24bit_row;
break;
case 32:
source->pub.get_pixel_rows = get_32bit_row;
break;
default:
ERREXIT(cinfo, JERR_BMP_BADDEPTH);
}
}
/* Allocate one-row buffer for returned data */
source->pub.buffer = (*cinfo->mem->alloc_sarray)
((j_common_ptr)cinfo, JPOOL_IMAGE,
(JDIMENSION)(biWidth * cinfo->input_components), (JDIMENSION)1);
source->pub.buffer_height = 1;
cinfo->data_precision = 8;
cinfo->image_width = (JDIMENSION)biWidth;
cinfo->image_height = (JDIMENSION)biHeight;
}
/*
* Finish up at the end of the file.
*/
METHODDEF(void)
finish_input_bmp(j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
{
/* no work */
}
/*
* The module selection routine for BMP format input.
*/
GLOBAL(cjpeg_source_ptr)
jinit_read_bmp(j_compress_ptr cinfo, boolean use_inversion_array)
{
bmp_source_ptr source;
/* Create module interface object */
source = (bmp_source_ptr)
(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
sizeof(bmp_source_struct));
source->cinfo = cinfo; /* make back link for subroutines */
/* Fill in method ptrs, except get_pixel_rows which start_input sets */
source->pub.start_input = start_input_bmp;
source->pub.finish_input = finish_input_bmp;
source->use_inversion_array = use_inversion_array;
return (cjpeg_source_ptr)source;
}
#endif /* BMP_SUPPORTED */
| ./CrossVul/dataset_final_sorted/CWE-369/c/bad_153_1 |
crossvul-cpp_data_good_5364_0 | /*
* Copyright (c) 1999-2000 Image Power, Inc. and the University of
* British Columbia.
* Copyright (c) 2001-2002 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__
*/
/*
* JPEG-2000 Code Stream Library
*
* $Id$
*/
/******************************************************************************\
* Includes.
\******************************************************************************/
#include <stdlib.h>
#include <assert.h>
#include <ctype.h>
#include "jasper/jas_malloc.h"
#include "jasper/jas_debug.h"
#include "jpc_cs.h"
/******************************************************************************\
* Types.
\******************************************************************************/
/* Marker segment table entry. */
typedef struct {
int id;
char *name;
jpc_msops_t ops;
} jpc_mstabent_t;
/******************************************************************************\
* Local prototypes.
\******************************************************************************/
static jpc_mstabent_t *jpc_mstab_lookup(int id);
static int jpc_poc_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_poc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_poc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static void jpc_poc_destroyparms(jpc_ms_t *ms);
static int jpc_unk_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_sot_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_cod_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_coc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_qcd_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_qcc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_rgn_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_sop_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_ppm_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_ppt_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_crg_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_com_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in);
static int jpc_sot_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_siz_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_cod_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_coc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_qcd_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_qcc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_rgn_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_unk_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_sop_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_ppt_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_crg_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_com_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out);
static int jpc_sot_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_siz_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_cod_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_coc_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_qcc_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_rgn_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_unk_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_sop_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_ppm_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_ppt_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_crg_dumpparms(jpc_ms_t *ms, FILE *out);
static int jpc_com_dumpparms(jpc_ms_t *ms, FILE *out);
static void jpc_siz_destroyparms(jpc_ms_t *ms);
static void jpc_qcd_destroyparms(jpc_ms_t *ms);
static void jpc_qcc_destroyparms(jpc_ms_t *ms);
static void jpc_cod_destroyparms(jpc_ms_t *ms);
static void jpc_coc_destroyparms(jpc_ms_t *ms);
static void jpc_unk_destroyparms(jpc_ms_t *ms);
static void jpc_ppm_destroyparms(jpc_ms_t *ms);
static void jpc_ppt_destroyparms(jpc_ms_t *ms);
static void jpc_crg_destroyparms(jpc_ms_t *ms);
static void jpc_com_destroyparms(jpc_ms_t *ms);
static void jpc_qcx_destroycompparms(jpc_qcxcp_t *compparms);
static int jpc_qcx_getcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
jas_stream_t *in, uint_fast16_t len);
static int jpc_qcx_putcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
jas_stream_t *out);
static void jpc_cox_destroycompparms(jpc_coxcp_t *compparms);
static int jpc_cox_getcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
jas_stream_t *in, int prtflag, jpc_coxcp_t *compparms);
static int jpc_cox_putcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
jas_stream_t *out, int prtflag, jpc_coxcp_t *compparms);
/******************************************************************************\
* Global data.
\******************************************************************************/
static jpc_mstabent_t jpc_mstab[] = {
{JPC_MS_SOC, "SOC", {0, 0, 0, 0}},
{JPC_MS_SOT, "SOT", {0, jpc_sot_getparms, jpc_sot_putparms,
jpc_sot_dumpparms}},
{JPC_MS_SOD, "SOD", {0, 0, 0, 0}},
{JPC_MS_EOC, "EOC", {0, 0, 0, 0}},
{JPC_MS_SIZ, "SIZ", {jpc_siz_destroyparms, jpc_siz_getparms,
jpc_siz_putparms, jpc_siz_dumpparms}},
{JPC_MS_COD, "COD", {jpc_cod_destroyparms, jpc_cod_getparms,
jpc_cod_putparms, jpc_cod_dumpparms}},
{JPC_MS_COC, "COC", {jpc_coc_destroyparms, jpc_coc_getparms,
jpc_coc_putparms, jpc_coc_dumpparms}},
{JPC_MS_RGN, "RGN", {0, jpc_rgn_getparms, jpc_rgn_putparms,
jpc_rgn_dumpparms}},
{JPC_MS_QCD, "QCD", {jpc_qcd_destroyparms, jpc_qcd_getparms,
jpc_qcd_putparms, jpc_qcd_dumpparms}},
{JPC_MS_QCC, "QCC", {jpc_qcc_destroyparms, jpc_qcc_getparms,
jpc_qcc_putparms, jpc_qcc_dumpparms}},
{JPC_MS_POC, "POC", {jpc_poc_destroyparms, jpc_poc_getparms,
jpc_poc_putparms, jpc_poc_dumpparms}},
{JPC_MS_TLM, "TLM", {0, jpc_unk_getparms, jpc_unk_putparms, 0}},
{JPC_MS_PLM, "PLM", {0, jpc_unk_getparms, jpc_unk_putparms, 0}},
{JPC_MS_PPM, "PPM", {jpc_ppm_destroyparms, jpc_ppm_getparms,
jpc_ppm_putparms, jpc_ppm_dumpparms}},
{JPC_MS_PPT, "PPT", {jpc_ppt_destroyparms, jpc_ppt_getparms,
jpc_ppt_putparms, jpc_ppt_dumpparms}},
{JPC_MS_SOP, "SOP", {0, jpc_sop_getparms, jpc_sop_putparms,
jpc_sop_dumpparms}},
{JPC_MS_EPH, "EPH", {0, 0, 0, 0}},
{JPC_MS_CRG, "CRG", {0, jpc_crg_getparms, jpc_crg_putparms,
jpc_crg_dumpparms}},
{JPC_MS_COM, "COM", {jpc_com_destroyparms, jpc_com_getparms,
jpc_com_putparms, jpc_com_dumpparms}},
{-1, "UNKNOWN", {jpc_unk_destroyparms, jpc_unk_getparms,
jpc_unk_putparms, jpc_unk_dumpparms}}
};
/******************************************************************************\
* Code stream manipulation functions.
\******************************************************************************/
/* Create a code stream state object. */
jpc_cstate_t *jpc_cstate_create()
{
jpc_cstate_t *cstate;
if (!(cstate = jas_malloc(sizeof(jpc_cstate_t)))) {
return 0;
}
cstate->numcomps = 0;
return cstate;
}
/* Destroy a code stream state object. */
void jpc_cstate_destroy(jpc_cstate_t *cstate)
{
jas_free(cstate);
}
/* Read a marker segment from a stream. */
jpc_ms_t *jpc_getms(jas_stream_t *in, jpc_cstate_t *cstate)
{
jpc_ms_t *ms;
jpc_mstabent_t *mstabent;
jas_stream_t *tmpstream;
if (!(ms = jpc_ms_create(0))) {
return 0;
}
/* Get the marker type. */
if (jpc_getuint16(in, &ms->id) || ms->id < JPC_MS_MIN ||
ms->id > JPC_MS_MAX) {
jpc_ms_destroy(ms);
return 0;
}
mstabent = jpc_mstab_lookup(ms->id);
ms->ops = &mstabent->ops;
/* Get the marker segment length and parameters if present. */
/* Note: It is tacitly assumed that a marker segment cannot have
parameters unless it has a length field. That is, there cannot
be a parameters field without a length field and vice versa. */
if (JPC_MS_HASPARMS(ms->id)) {
/* Get the length of the marker segment. */
if (jpc_getuint16(in, &ms->len) || ms->len < 3) {
jpc_ms_destroy(ms);
return 0;
}
/* Calculate the length of the marker segment parameters. */
ms->len -= 2;
/* Create and prepare a temporary memory stream from which to
read the marker segment parameters. */
/* Note: This approach provides a simple way of ensuring that
we never read beyond the end of the marker segment (even if
the marker segment length is errantly set too small). */
if (!(tmpstream = jas_stream_memopen(0, 0))) {
jpc_ms_destroy(ms);
return 0;
}
if (jas_stream_copy(tmpstream, in, ms->len) ||
jas_stream_seek(tmpstream, 0, SEEK_SET) < 0) {
jas_stream_close(tmpstream);
jpc_ms_destroy(ms);
return 0;
}
/* Get the marker segment parameters. */
if ((*ms->ops->getparms)(ms, cstate, tmpstream)) {
ms->ops = 0;
jpc_ms_destroy(ms);
jas_stream_close(tmpstream);
return 0;
}
if (jas_getdbglevel() > 0) {
jpc_ms_dump(ms, stderr);
}
if (JAS_CAST(ulong, jas_stream_tell(tmpstream)) != ms->len) {
jas_eprintf("warning: trailing garbage in marker segment (%ld bytes)\n",
ms->len - jas_stream_tell(tmpstream));
}
/* Close the temporary stream. */
jas_stream_close(tmpstream);
} else {
/* There are no marker segment parameters. */
ms->len = 0;
if (jas_getdbglevel() > 0) {
jpc_ms_dump(ms, stderr);
}
}
/* Update the code stream state information based on the type of
marker segment read. */
/* Note: This is a bit of a hack, but I'm not going to define another
type of virtual function for this one special case. */
if (ms->id == JPC_MS_SIZ) {
cstate->numcomps = ms->parms.siz.numcomps;
}
return ms;
}
/* Write a marker segment to a stream. */
int jpc_putms(jas_stream_t *out, jpc_cstate_t *cstate, jpc_ms_t *ms)
{
jas_stream_t *tmpstream;
int len;
/* Output the marker segment type. */
if (jpc_putuint16(out, ms->id)) {
return -1;
}
/* Output the marker segment length and parameters if necessary. */
if (ms->ops->putparms) {
/* Create a temporary stream in which to buffer the
parameter data. */
if (!(tmpstream = jas_stream_memopen(0, 0))) {
return -1;
}
if ((*ms->ops->putparms)(ms, cstate, tmpstream)) {
jas_stream_close(tmpstream);
return -1;
}
/* Get the number of bytes of parameter data written. */
if ((len = jas_stream_tell(tmpstream)) < 0) {
jas_stream_close(tmpstream);
return -1;
}
ms->len = len;
/* Write the marker segment length and parameter data to
the output stream. */
if (jas_stream_seek(tmpstream, 0, SEEK_SET) < 0 ||
jpc_putuint16(out, ms->len + 2) ||
jas_stream_copy(out, tmpstream, ms->len) < 0) {
jas_stream_close(tmpstream);
return -1;
}
/* Close the temporary stream. */
jas_stream_close(tmpstream);
}
/* This is a bit of a hack, but I'm not going to define another
type of virtual function for this one special case. */
if (ms->id == JPC_MS_SIZ) {
cstate->numcomps = ms->parms.siz.numcomps;
}
if (jas_getdbglevel() > 0) {
jpc_ms_dump(ms, stderr);
}
return 0;
}
/******************************************************************************\
* Marker segment operations.
\******************************************************************************/
/* Create a marker segment of the specified type. */
jpc_ms_t *jpc_ms_create(int type)
{
jpc_ms_t *ms;
jpc_mstabent_t *mstabent;
if (!(ms = jas_malloc(sizeof(jpc_ms_t)))) {
return 0;
}
ms->id = type;
ms->len = 0;
mstabent = jpc_mstab_lookup(ms->id);
ms->ops = &mstabent->ops;
memset(&ms->parms, 0, sizeof(jpc_msparms_t));
return ms;
}
/* Destroy a marker segment. */
void jpc_ms_destroy(jpc_ms_t *ms)
{
if (ms->ops && ms->ops->destroyparms) {
(*ms->ops->destroyparms)(ms);
}
jas_free(ms);
}
/* Dump a marker segment to a stream for debugging. */
void jpc_ms_dump(jpc_ms_t *ms, FILE *out)
{
jpc_mstabent_t *mstabent;
mstabent = jpc_mstab_lookup(ms->id);
fprintf(out, "type = 0x%04x (%s);", ms->id, mstabent->name);
if (JPC_MS_HASPARMS(ms->id)) {
fprintf(out, " len = %d;", ms->len + 2);
if (ms->ops->dumpparms) {
(*ms->ops->dumpparms)(ms, out);
} else {
fprintf(out, "\n");
}
} else {
fprintf(out, "\n");
}
}
/******************************************************************************\
* SOT marker segment operations.
\******************************************************************************/
static int jpc_sot_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_sot_t *sot = &ms->parms.sot;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (jpc_getuint16(in, &sot->tileno) ||
jpc_getuint32(in, &sot->len) ||
jpc_getuint8(in, &sot->partno) ||
jpc_getuint8(in, &sot->numparts)) {
return -1;
}
if (jas_stream_eof(in)) {
return -1;
}
return 0;
}
static int jpc_sot_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_sot_t *sot = &ms->parms.sot;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (jpc_putuint16(out, sot->tileno) ||
jpc_putuint32(out, sot->len) ||
jpc_putuint8(out, sot->partno) ||
jpc_putuint8(out, sot->numparts)) {
return -1;
}
return 0;
}
static int jpc_sot_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_sot_t *sot = &ms->parms.sot;
fprintf(out, "tileno = %d; len = %d; partno = %d; numparts = %d\n",
sot->tileno, sot->len, sot->partno, sot->numparts);
return 0;
}
/******************************************************************************\
* SIZ marker segment operations.
\******************************************************************************/
static void jpc_siz_destroyparms(jpc_ms_t *ms)
{
jpc_siz_t *siz = &ms->parms.siz;
if (siz->comps) {
jas_free(siz->comps);
}
}
static int jpc_siz_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
jas_stream_t *in)
{
jpc_siz_t *siz = &ms->parms.siz;
unsigned int i;
uint_fast8_t tmp;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (jpc_getuint16(in, &siz->caps) ||
jpc_getuint32(in, &siz->width) ||
jpc_getuint32(in, &siz->height) ||
jpc_getuint32(in, &siz->xoff) ||
jpc_getuint32(in, &siz->yoff) ||
jpc_getuint32(in, &siz->tilewidth) ||
jpc_getuint32(in, &siz->tileheight) ||
jpc_getuint32(in, &siz->tilexoff) ||
jpc_getuint32(in, &siz->tileyoff) ||
jpc_getuint16(in, &siz->numcomps)) {
return -1;
}
if (!siz->width || !siz->height || !siz->tilewidth ||
!siz->tileheight || !siz->numcomps) {
return -1;
}
if (!(siz->comps = jas_alloc2(siz->numcomps, sizeof(jpc_sizcomp_t)))) {
return -1;
}
for (i = 0; i < siz->numcomps; ++i) {
if (jpc_getuint8(in, &tmp) ||
jpc_getuint8(in, &siz->comps[i].hsamp) ||
jpc_getuint8(in, &siz->comps[i].vsamp)) {
jas_free(siz->comps);
return -1;
}
if (siz->comps[i].hsamp == 0 || siz->comps[i].hsamp > 255) {
jas_eprintf("invalid XRsiz value %d\n", siz->comps[i].hsamp);
jas_free(siz->comps);
return -1;
}
if (siz->comps[i].vsamp == 0 || siz->comps[i].vsamp > 255) {
jas_eprintf("invalid YRsiz value %d\n", siz->comps[i].vsamp);
jas_free(siz->comps);
return -1;
}
siz->comps[i].sgnd = (tmp >> 7) & 1;
siz->comps[i].prec = (tmp & 0x7f) + 1;
}
if (jas_stream_eof(in)) {
jas_free(siz->comps);
return -1;
}
return 0;
}
static int jpc_siz_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_siz_t *siz = &ms->parms.siz;
unsigned int i;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
assert(siz->width && siz->height && siz->tilewidth &&
siz->tileheight && siz->numcomps);
if (jpc_putuint16(out, siz->caps) ||
jpc_putuint32(out, siz->width) ||
jpc_putuint32(out, siz->height) ||
jpc_putuint32(out, siz->xoff) ||
jpc_putuint32(out, siz->yoff) ||
jpc_putuint32(out, siz->tilewidth) ||
jpc_putuint32(out, siz->tileheight) ||
jpc_putuint32(out, siz->tilexoff) ||
jpc_putuint32(out, siz->tileyoff) ||
jpc_putuint16(out, siz->numcomps)) {
return -1;
}
for (i = 0; i < siz->numcomps; ++i) {
if (jpc_putuint8(out, ((siz->comps[i].sgnd & 1) << 7) |
((siz->comps[i].prec - 1) & 0x7f)) ||
jpc_putuint8(out, siz->comps[i].hsamp) ||
jpc_putuint8(out, siz->comps[i].vsamp)) {
return -1;
}
}
return 0;
}
static int jpc_siz_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_siz_t *siz = &ms->parms.siz;
unsigned int i;
fprintf(out, "caps = 0x%02x;\n", siz->caps);
fprintf(out, "width = %d; height = %d; xoff = %d; yoff = %d;\n",
siz->width, siz->height, siz->xoff, siz->yoff);
fprintf(out, "tilewidth = %d; tileheight = %d; tilexoff = %d; "
"tileyoff = %d;\n", siz->tilewidth, siz->tileheight, siz->tilexoff,
siz->tileyoff);
for (i = 0; i < siz->numcomps; ++i) {
fprintf(out, "prec[%d] = %d; sgnd[%d] = %d; hsamp[%d] = %d; "
"vsamp[%d] = %d\n", i, siz->comps[i].prec, i,
siz->comps[i].sgnd, i, siz->comps[i].hsamp, i,
siz->comps[i].vsamp);
}
return 0;
}
/******************************************************************************\
* COD marker segment operations.
\******************************************************************************/
static void jpc_cod_destroyparms(jpc_ms_t *ms)
{
jpc_cod_t *cod = &ms->parms.cod;
jpc_cox_destroycompparms(&cod->compparms);
}
static int jpc_cod_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_cod_t *cod = &ms->parms.cod;
if (jpc_getuint8(in, &cod->csty)) {
return -1;
}
if (jpc_getuint8(in, &cod->prg) ||
jpc_getuint16(in, &cod->numlyrs) ||
jpc_getuint8(in, &cod->mctrans)) {
return -1;
}
if (jpc_cox_getcompparms(ms, cstate, in,
(cod->csty & JPC_COX_PRT) != 0, &cod->compparms)) {
return -1;
}
if (jas_stream_eof(in)) {
jpc_cod_destroyparms(ms);
return -1;
}
return 0;
}
static int jpc_cod_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_cod_t *cod = &ms->parms.cod;
assert(cod->numlyrs > 0 && cod->compparms.numdlvls <= 32);
assert(cod->compparms.numdlvls == cod->compparms.numrlvls - 1);
if (jpc_putuint8(out, cod->compparms.csty) ||
jpc_putuint8(out, cod->prg) ||
jpc_putuint16(out, cod->numlyrs) ||
jpc_putuint8(out, cod->mctrans)) {
return -1;
}
if (jpc_cox_putcompparms(ms, cstate, out,
(cod->csty & JPC_COX_PRT) != 0, &cod->compparms)) {
return -1;
}
return 0;
}
static int jpc_cod_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_cod_t *cod = &ms->parms.cod;
int i;
fprintf(out, "csty = 0x%02x;\n", cod->compparms.csty);
fprintf(out, "numdlvls = %d; qmfbid = %d; mctrans = %d\n",
cod->compparms.numdlvls, cod->compparms.qmfbid, cod->mctrans);
fprintf(out, "prg = %d; numlyrs = %d;\n",
cod->prg, cod->numlyrs);
fprintf(out, "cblkwidthval = %d; cblkheightval = %d; "
"cblksty = 0x%02x;\n", cod->compparms.cblkwidthval, cod->compparms.cblkheightval,
cod->compparms.cblksty);
if (cod->csty & JPC_COX_PRT) {
for (i = 0; i < cod->compparms.numrlvls; ++i) {
jas_eprintf("prcwidth[%d] = %d, prcheight[%d] = %d\n",
i, cod->compparms.rlvls[i].parwidthval,
i, cod->compparms.rlvls[i].parheightval);
}
}
return 0;
}
/******************************************************************************\
* COC marker segment operations.
\******************************************************************************/
static void jpc_coc_destroyparms(jpc_ms_t *ms)
{
jpc_coc_t *coc = &ms->parms.coc;
jpc_cox_destroycompparms(&coc->compparms);
}
static int jpc_coc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_coc_t *coc = &ms->parms.coc;
uint_fast8_t tmp;
if (cstate->numcomps <= 256) {
if (jpc_getuint8(in, &tmp)) {
return -1;
}
coc->compno = tmp;
} else {
if (jpc_getuint16(in, &coc->compno)) {
return -1;
}
}
if (jpc_getuint8(in, &coc->compparms.csty)) {
return -1;
}
if (jpc_cox_getcompparms(ms, cstate, in,
(coc->compparms.csty & JPC_COX_PRT) != 0, &coc->compparms)) {
return -1;
}
if (jas_stream_eof(in)) {
return -1;
}
return 0;
}
static int jpc_coc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_coc_t *coc = &ms->parms.coc;
assert(coc->compparms.numdlvls <= 32);
if (cstate->numcomps <= 256) {
if (jpc_putuint8(out, coc->compno)) {
return -1;
}
} else {
if (jpc_putuint16(out, coc->compno)) {
return -1;
}
}
if (jpc_putuint8(out, coc->compparms.csty)) {
return -1;
}
if (jpc_cox_putcompparms(ms, cstate, out,
(coc->compparms.csty & JPC_COX_PRT) != 0, &coc->compparms)) {
return -1;
}
return 0;
}
static int jpc_coc_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_coc_t *coc = &ms->parms.coc;
fprintf(out, "compno = %d; csty = 0x%02x; numdlvls = %d;\n",
coc->compno, coc->compparms.csty, coc->compparms.numdlvls);
fprintf(out, "cblkwidthval = %d; cblkheightval = %d; "
"cblksty = 0x%02x; qmfbid = %d;\n", coc->compparms.cblkwidthval,
coc->compparms.cblkheightval, coc->compparms.cblksty, coc->compparms.qmfbid);
return 0;
}
/******************************************************************************\
* COD/COC marker segment operation helper functions.
\******************************************************************************/
static void jpc_cox_destroycompparms(jpc_coxcp_t *compparms)
{
/* Eliminate compiler warning about unused variables. */
compparms = 0;
}
static int jpc_cox_getcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
jas_stream_t *in, int prtflag, jpc_coxcp_t *compparms)
{
uint_fast8_t tmp;
int i;
/* Eliminate compiler warning about unused variables. */
ms = 0;
cstate = 0;
if (jpc_getuint8(in, &compparms->numdlvls) ||
jpc_getuint8(in, &compparms->cblkwidthval) ||
jpc_getuint8(in, &compparms->cblkheightval) ||
jpc_getuint8(in, &compparms->cblksty) ||
jpc_getuint8(in, &compparms->qmfbid)) {
return -1;
}
compparms->numrlvls = compparms->numdlvls + 1;
if (prtflag) {
for (i = 0; i < compparms->numrlvls; ++i) {
if (jpc_getuint8(in, &tmp)) {
jpc_cox_destroycompparms(compparms);
return -1;
}
compparms->rlvls[i].parwidthval = tmp & 0xf;
compparms->rlvls[i].parheightval = (tmp >> 4) & 0xf;
}
/* Sigh. This bit should be in the same field in both COC and COD mrk segs. */
compparms->csty |= JPC_COX_PRT;
} else {
}
if (jas_stream_eof(in)) {
jpc_cox_destroycompparms(compparms);
return -1;
}
return 0;
}
static int jpc_cox_putcompparms(jpc_ms_t *ms, jpc_cstate_t *cstate,
jas_stream_t *out, int prtflag, jpc_coxcp_t *compparms)
{
int i;
assert(compparms->numdlvls <= 32);
/* Eliminate compiler warning about unused variables. */
ms = 0;
cstate = 0;
if (jpc_putuint8(out, compparms->numdlvls) ||
jpc_putuint8(out, compparms->cblkwidthval) ||
jpc_putuint8(out, compparms->cblkheightval) ||
jpc_putuint8(out, compparms->cblksty) ||
jpc_putuint8(out, compparms->qmfbid)) {
return -1;
}
if (prtflag) {
for (i = 0; i < compparms->numrlvls; ++i) {
if (jpc_putuint8(out,
((compparms->rlvls[i].parheightval & 0xf) << 4) |
(compparms->rlvls[i].parwidthval & 0xf))) {
return -1;
}
}
}
return 0;
}
/******************************************************************************\
* RGN marker segment operations.
\******************************************************************************/
static int jpc_rgn_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_rgn_t *rgn = &ms->parms.rgn;
uint_fast8_t tmp;
if (cstate->numcomps <= 256) {
if (jpc_getuint8(in, &tmp)) {
return -1;
}
rgn->compno = tmp;
} else {
if (jpc_getuint16(in, &rgn->compno)) {
return -1;
}
}
if (jpc_getuint8(in, &rgn->roisty) ||
jpc_getuint8(in, &rgn->roishift)) {
return -1;
}
return 0;
}
static int jpc_rgn_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_rgn_t *rgn = &ms->parms.rgn;
if (cstate->numcomps <= 256) {
if (jpc_putuint8(out, rgn->compno)) {
return -1;
}
} else {
if (jpc_putuint16(out, rgn->compno)) {
return -1;
}
}
if (jpc_putuint8(out, rgn->roisty) ||
jpc_putuint8(out, rgn->roishift)) {
return -1;
}
return 0;
}
static int jpc_rgn_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_rgn_t *rgn = &ms->parms.rgn;
fprintf(out, "compno = %d; roisty = %d; roishift = %d\n",
rgn->compno, rgn->roisty, rgn->roishift);
return 0;
}
/******************************************************************************\
* QCD marker segment operations.
\******************************************************************************/
static void jpc_qcd_destroyparms(jpc_ms_t *ms)
{
jpc_qcd_t *qcd = &ms->parms.qcd;
jpc_qcx_destroycompparms(&qcd->compparms);
}
static int jpc_qcd_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_qcxcp_t *compparms = &ms->parms.qcd.compparms;
return jpc_qcx_getcompparms(compparms, cstate, in, ms->len);
}
static int jpc_qcd_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_qcxcp_t *compparms = &ms->parms.qcd.compparms;
return jpc_qcx_putcompparms(compparms, cstate, out);
}
static int jpc_qcd_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_qcd_t *qcd = &ms->parms.qcd;
int i;
fprintf(out, "qntsty = %d; numguard = %d; numstepsizes = %d\n",
(int) qcd->compparms.qntsty, qcd->compparms.numguard, qcd->compparms.numstepsizes);
for (i = 0; i < qcd->compparms.numstepsizes; ++i) {
fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n",
i, (unsigned) JPC_QCX_GETEXPN(qcd->compparms.stepsizes[i]),
i, (unsigned) JPC_QCX_GETMANT(qcd->compparms.stepsizes[i]));
}
return 0;
}
/******************************************************************************\
* QCC marker segment operations.
\******************************************************************************/
static void jpc_qcc_destroyparms(jpc_ms_t *ms)
{
jpc_qcc_t *qcc = &ms->parms.qcc;
jpc_qcx_destroycompparms(&qcc->compparms);
}
static int jpc_qcc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_qcc_t *qcc = &ms->parms.qcc;
uint_fast8_t tmp;
int len;
len = ms->len;
if (cstate->numcomps <= 256) {
if (jpc_getuint8(in, &tmp)) {
return -1;
}
qcc->compno = tmp;
--len;
} else {
if (jpc_getuint16(in, &qcc->compno)) {
return -1;
}
len -= 2;
}
if (jpc_qcx_getcompparms(&qcc->compparms, cstate, in, len)) {
return -1;
}
if (jas_stream_eof(in)) {
jpc_qcc_destroyparms(ms);
return -1;
}
return 0;
}
static int jpc_qcc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_qcc_t *qcc = &ms->parms.qcc;
if (cstate->numcomps <= 256) {
if (jpc_putuint8(out, qcc->compno)) {
return -1;
}
} else {
if (jpc_putuint16(out, qcc->compno)) {
return -1;
}
}
if (jpc_qcx_putcompparms(&qcc->compparms, cstate, out)) {
return -1;
}
return 0;
}
static int jpc_qcc_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_qcc_t *qcc = &ms->parms.qcc;
int i;
fprintf(out, "compno = %d; qntsty = %d; numguard = %d; "
"numstepsizes = %d\n", qcc->compno, qcc->compparms.qntsty, qcc->compparms.numguard,
qcc->compparms.numstepsizes);
for (i = 0; i < qcc->compparms.numstepsizes; ++i) {
fprintf(out, "expn[%d] = 0x%04x; mant[%d] = 0x%04x;\n",
i, (unsigned) JPC_QCX_GETEXPN(qcc->compparms.stepsizes[i]),
i, (unsigned) JPC_QCX_GETMANT(qcc->compparms.stepsizes[i]));
}
return 0;
}
/******************************************************************************\
* QCD/QCC marker segment helper functions.
\******************************************************************************/
static void jpc_qcx_destroycompparms(jpc_qcxcp_t *compparms)
{
if (compparms->stepsizes) {
jas_free(compparms->stepsizes);
}
}
static int jpc_qcx_getcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
jas_stream_t *in, uint_fast16_t len)
{
uint_fast8_t tmp;
int n;
int i;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
n = 0;
if (jpc_getuint8(in, &tmp)) {
return -1;
}
++n;
compparms->qntsty = tmp & 0x1f;
compparms->numguard = (tmp >> 5) & 7;
switch (compparms->qntsty) {
case JPC_QCX_SIQNT:
compparms->numstepsizes = 1;
break;
case JPC_QCX_NOQNT:
compparms->numstepsizes = (len - n);
break;
case JPC_QCX_SEQNT:
/* XXX - this is a hack */
compparms->numstepsizes = (len - n) / 2;
break;
}
if (compparms->numstepsizes > 0) {
compparms->stepsizes = jas_alloc2(compparms->numstepsizes,
sizeof(uint_fast16_t));
assert(compparms->stepsizes);
for (i = 0; i < compparms->numstepsizes; ++i) {
if (compparms->qntsty == JPC_QCX_NOQNT) {
if (jpc_getuint8(in, &tmp)) {
return -1;
}
compparms->stepsizes[i] = JPC_QCX_EXPN(tmp >> 3);
} else {
if (jpc_getuint16(in, &compparms->stepsizes[i])) {
return -1;
}
}
}
} else {
compparms->stepsizes = 0;
}
if (jas_stream_error(in) || jas_stream_eof(in)) {
jpc_qcx_destroycompparms(compparms);
return -1;
}
return 0;
}
static int jpc_qcx_putcompparms(jpc_qcxcp_t *compparms, jpc_cstate_t *cstate,
jas_stream_t *out)
{
int i;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
jpc_putuint8(out, ((compparms->numguard & 7) << 5) | compparms->qntsty);
for (i = 0; i < compparms->numstepsizes; ++i) {
if (compparms->qntsty == JPC_QCX_NOQNT) {
if (jpc_putuint8(out, JPC_QCX_GETEXPN(
compparms->stepsizes[i]) << 3)) {
return -1;
}
} else {
if (jpc_putuint16(out, compparms->stepsizes[i])) {
return -1;
}
}
}
return 0;
}
/******************************************************************************\
* SOP marker segment operations.
\******************************************************************************/
static int jpc_sop_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_sop_t *sop = &ms->parms.sop;
/* Eliminate compiler warning about unused variable. */
cstate = 0;
if (jpc_getuint16(in, &sop->seqno)) {
return -1;
}
return 0;
}
static int jpc_sop_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_sop_t *sop = &ms->parms.sop;
/* Eliminate compiler warning about unused variable. */
cstate = 0;
if (jpc_putuint16(out, sop->seqno)) {
return -1;
}
return 0;
}
static int jpc_sop_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_sop_t *sop = &ms->parms.sop;
fprintf(out, "seqno = %d;\n", sop->seqno);
return 0;
}
/******************************************************************************\
* PPM marker segment operations.
\******************************************************************************/
static void jpc_ppm_destroyparms(jpc_ms_t *ms)
{
jpc_ppm_t *ppm = &ms->parms.ppm;
if (ppm->data) {
jas_free(ppm->data);
}
}
static int jpc_ppm_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_ppm_t *ppm = &ms->parms.ppm;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
ppm->data = 0;
if (ms->len < 1) {
goto error;
}
if (jpc_getuint8(in, &ppm->ind)) {
goto error;
}
ppm->len = ms->len - 1;
if (ppm->len > 0) {
if (!(ppm->data = jas_malloc(ppm->len))) {
goto error;
}
if (JAS_CAST(uint, jas_stream_read(in, ppm->data, ppm->len)) != ppm->len) {
goto error;
}
} else {
ppm->data = 0;
}
return 0;
error:
jpc_ppm_destroyparms(ms);
return -1;
}
static int jpc_ppm_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_ppm_t *ppm = &ms->parms.ppm;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (JAS_CAST(uint, jas_stream_write(out, (char *) ppm->data, ppm->len)) != ppm->len) {
return -1;
}
return 0;
}
static int jpc_ppm_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_ppm_t *ppm = &ms->parms.ppm;
fprintf(out, "ind=%d; len = %d;\n", ppm->ind, ppm->len);
if (ppm->len > 0) {
fprintf(out, "data =\n");
jas_memdump(out, ppm->data, ppm->len);
}
return 0;
}
/******************************************************************************\
* PPT marker segment operations.
\******************************************************************************/
static void jpc_ppt_destroyparms(jpc_ms_t *ms)
{
jpc_ppt_t *ppt = &ms->parms.ppt;
if (ppt->data) {
jas_free(ppt->data);
}
}
static int jpc_ppt_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_ppt_t *ppt = &ms->parms.ppt;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
ppt->data = 0;
if (ms->len < 1) {
goto error;
}
if (jpc_getuint8(in, &ppt->ind)) {
goto error;
}
ppt->len = ms->len - 1;
if (ppt->len > 0) {
if (!(ppt->data = jas_malloc(ppt->len))) {
goto error;
}
if (jas_stream_read(in, (char *) ppt->data, ppt->len) != JAS_CAST(int, ppt->len)) {
goto error;
}
} else {
ppt->data = 0;
}
return 0;
error:
jpc_ppt_destroyparms(ms);
return -1;
}
static int jpc_ppt_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_ppt_t *ppt = &ms->parms.ppt;
/* Eliminate compiler warning about unused variable. */
cstate = 0;
if (jpc_putuint8(out, ppt->ind)) {
return -1;
}
if (jas_stream_write(out, (char *) ppt->data, ppt->len) != JAS_CAST(int, ppt->len)) {
return -1;
}
return 0;
}
static int jpc_ppt_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_ppt_t *ppt = &ms->parms.ppt;
fprintf(out, "ind=%d; len = %d;\n", ppt->ind, ppt->len);
if (ppt->len > 0) {
fprintf(out, "data =\n");
jas_memdump(out, ppt->data, ppt->len);
}
return 0;
}
/******************************************************************************\
* POC marker segment operations.
\******************************************************************************/
static void jpc_poc_destroyparms(jpc_ms_t *ms)
{
jpc_poc_t *poc = &ms->parms.poc;
if (poc->pchgs) {
jas_free(poc->pchgs);
}
}
static int jpc_poc_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_poc_t *poc = &ms->parms.poc;
jpc_pocpchg_t *pchg;
int pchgno;
uint_fast8_t tmp;
poc->numpchgs = (cstate->numcomps > 256) ? (ms->len / 9) :
(ms->len / 7);
if (!(poc->pchgs = jas_alloc2(poc->numpchgs, sizeof(jpc_pocpchg_t)))) {
goto error;
}
for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs; ++pchgno,
++pchg) {
if (jpc_getuint8(in, &pchg->rlvlnostart)) {
goto error;
}
if (cstate->numcomps > 256) {
if (jpc_getuint16(in, &pchg->compnostart)) {
goto error;
}
} else {
if (jpc_getuint8(in, &tmp)) {
goto error;
};
pchg->compnostart = tmp;
}
if (jpc_getuint16(in, &pchg->lyrnoend) ||
jpc_getuint8(in, &pchg->rlvlnoend)) {
goto error;
}
if (cstate->numcomps > 256) {
if (jpc_getuint16(in, &pchg->compnoend)) {
goto error;
}
} else {
if (jpc_getuint8(in, &tmp)) {
goto error;
}
pchg->compnoend = tmp;
}
if (jpc_getuint8(in, &pchg->prgord)) {
goto error;
}
if (pchg->rlvlnostart > pchg->rlvlnoend ||
pchg->compnostart > pchg->compnoend) {
goto error;
}
}
return 0;
error:
jpc_poc_destroyparms(ms);
return -1;
}
static int jpc_poc_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_poc_t *poc = &ms->parms.poc;
jpc_pocpchg_t *pchg;
int pchgno;
for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs; ++pchgno,
++pchg) {
if (jpc_putuint8(out, pchg->rlvlnostart) ||
((cstate->numcomps > 256) ?
jpc_putuint16(out, pchg->compnostart) :
jpc_putuint8(out, pchg->compnostart)) ||
jpc_putuint16(out, pchg->lyrnoend) ||
jpc_putuint8(out, pchg->rlvlnoend) ||
((cstate->numcomps > 256) ?
jpc_putuint16(out, pchg->compnoend) :
jpc_putuint8(out, pchg->compnoend)) ||
jpc_putuint8(out, pchg->prgord)) {
return -1;
}
}
return 0;
}
static int jpc_poc_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_poc_t *poc = &ms->parms.poc;
jpc_pocpchg_t *pchg;
int pchgno;
for (pchgno = 0, pchg = poc->pchgs; pchgno < poc->numpchgs;
++pchgno, ++pchg) {
fprintf(out, "po[%d] = %d; ", pchgno, pchg->prgord);
fprintf(out, "cs[%d] = %d; ce[%d] = %d; ",
pchgno, pchg->compnostart, pchgno, pchg->compnoend);
fprintf(out, "rs[%d] = %d; re[%d] = %d; ",
pchgno, pchg->rlvlnostart, pchgno, pchg->rlvlnoend);
fprintf(out, "le[%d] = %d\n", pchgno, pchg->lyrnoend);
}
return 0;
}
/******************************************************************************\
* CRG marker segment operations.
\******************************************************************************/
static void jpc_crg_destroyparms(jpc_ms_t *ms)
{
jpc_crg_t *crg = &ms->parms.crg;
if (crg->comps) {
jas_free(crg->comps);
}
}
static int jpc_crg_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_crg_t *crg = &ms->parms.crg;
jpc_crgcomp_t *comp;
uint_fast16_t compno;
crg->numcomps = cstate->numcomps;
if (!(crg->comps = jas_alloc2(cstate->numcomps, sizeof(uint_fast16_t)))) {
return -1;
}
for (compno = 0, comp = crg->comps; compno < cstate->numcomps;
++compno, ++comp) {
if (jpc_getuint16(in, &comp->hoff) ||
jpc_getuint16(in, &comp->voff)) {
jpc_crg_destroyparms(ms);
return -1;
}
}
return 0;
}
static int jpc_crg_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_crg_t *crg = &ms->parms.crg;
int compno;
jpc_crgcomp_t *comp;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
for (compno = 0, comp = crg->comps; compno < crg->numcomps; ++compno,
++comp) {
if (jpc_putuint16(out, comp->hoff) ||
jpc_putuint16(out, comp->voff)) {
return -1;
}
}
return 0;
}
static int jpc_crg_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_crg_t *crg = &ms->parms.crg;
int compno;
jpc_crgcomp_t *comp;
for (compno = 0, comp = crg->comps; compno < crg->numcomps; ++compno,
++comp) {
fprintf(out, "hoff[%d] = %d; voff[%d] = %d\n", compno,
comp->hoff, compno, comp->voff);
}
return 0;
}
/******************************************************************************\
* Operations for COM marker segment.
\******************************************************************************/
static void jpc_com_destroyparms(jpc_ms_t *ms)
{
jpc_com_t *com = &ms->parms.com;
if (com->data) {
jas_free(com->data);
}
}
static int jpc_com_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_com_t *com = &ms->parms.com;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (jpc_getuint16(in, &com->regid)) {
return -1;
}
com->len = ms->len - 2;
if (com->len > 0) {
if (!(com->data = jas_malloc(com->len))) {
return -1;
}
if (jas_stream_read(in, com->data, com->len) != JAS_CAST(int, com->len)) {
return -1;
}
} else {
com->data = 0;
}
return 0;
}
static int jpc_com_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
jpc_com_t *com = &ms->parms.com;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (jpc_putuint16(out, com->regid)) {
return -1;
}
if (jas_stream_write(out, com->data, com->len) != JAS_CAST(int, com->len)) {
return -1;
}
return 0;
}
static int jpc_com_dumpparms(jpc_ms_t *ms, FILE *out)
{
jpc_com_t *com = &ms->parms.com;
unsigned int i;
int printable;
fprintf(out, "regid = %d;\n", com->regid);
printable = 1;
for (i = 0; i < com->len; ++i) {
if (!isprint(com->data[i])) {
printable = 0;
break;
}
}
if (printable) {
fprintf(out, "data = ");
fwrite(com->data, sizeof(char), com->len, out);
fprintf(out, "\n");
}
return 0;
}
/******************************************************************************\
* Operations for unknown types of marker segments.
\******************************************************************************/
static void jpc_unk_destroyparms(jpc_ms_t *ms)
{
jpc_unk_t *unk = &ms->parms.unk;
if (unk->data) {
jas_free(unk->data);
}
}
static int jpc_unk_getparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *in)
{
jpc_unk_t *unk = &ms->parms.unk;
/* Eliminate compiler warning about unused variables. */
cstate = 0;
if (ms->len > 0) {
if (!(unk->data = jas_alloc2(ms->len, sizeof(unsigned char)))) {
return -1;
}
if (jas_stream_read(in, (char *) unk->data, ms->len) != JAS_CAST(int, ms->len)) {
jas_free(unk->data);
return -1;
}
unk->len = ms->len;
} else {
unk->data = 0;
unk->len = 0;
}
return 0;
}
static int jpc_unk_putparms(jpc_ms_t *ms, jpc_cstate_t *cstate, jas_stream_t *out)
{
/* Eliminate compiler warning about unused variables. */
cstate = 0;
ms = 0;
out = 0;
/* If this function is called, we are trying to write an unsupported
type of marker segment. Return with an error indication. */
return -1;
}
static int jpc_unk_dumpparms(jpc_ms_t *ms, FILE *out)
{
unsigned int i;
jpc_unk_t *unk = &ms->parms.unk;
for (i = 0; i < unk->len; ++i) {
fprintf(out, "%02x ", unk->data[i]);
}
return 0;
}
/******************************************************************************\
* Primitive I/O operations.
\******************************************************************************/
int jpc_getuint8(jas_stream_t *in, uint_fast8_t *val)
{
int c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
if (val) {
*val = c;
}
return 0;
}
int jpc_putuint8(jas_stream_t *out, uint_fast8_t val)
{
if (jas_stream_putc(out, val & 0xff) == EOF) {
return -1;
}
return 0;
}
int jpc_getuint16(jas_stream_t *in, uint_fast16_t *val)
{
uint_fast16_t v;
int c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = (v << 8) | c;
if (val) {
*val = v;
}
return 0;
}
int jpc_putuint16(jas_stream_t *out, uint_fast16_t val)
{
if (jas_stream_putc(out, (val >> 8) & 0xff) == EOF ||
jas_stream_putc(out, val & 0xff) == EOF) {
return -1;
}
return 0;
}
int jpc_getuint32(jas_stream_t *in, uint_fast32_t *val)
{
uint_fast32_t v;
int c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = (v << 8) | c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = (v << 8) | c;
if ((c = jas_stream_getc(in)) == EOF) {
return -1;
}
v = (v << 8) | c;
if (val) {
*val = v;
}
return 0;
}
int jpc_putuint32(jas_stream_t *out, uint_fast32_t val)
{
if (jas_stream_putc(out, (val >> 24) & 0xff) == EOF ||
jas_stream_putc(out, (val >> 16) & 0xff) == EOF ||
jas_stream_putc(out, (val >> 8) & 0xff) == EOF ||
jas_stream_putc(out, val & 0xff) == EOF) {
return -1;
}
return 0;
}
/******************************************************************************\
* Miscellany
\******************************************************************************/
static jpc_mstabent_t *jpc_mstab_lookup(int id)
{
jpc_mstabent_t *mstabent;
for (mstabent = jpc_mstab;; ++mstabent) {
if (mstabent->id == id || mstabent->id < 0) {
return mstabent;
}
}
assert(0);
return 0;
}
int jpc_validate(jas_stream_t *in)
{
int n;
int i;
unsigned char buf[2];
assert(JAS_STREAM_MAXPUTBACK >= 2);
if ((n = jas_stream_read(in, (char *) buf, 2)) < 0) {
return -1;
}
for (i = n - 1; i >= 0; --i) {
if (jas_stream_ungetc(in, buf[i]) == EOF) {
return -1;
}
}
if (n < 2) {
return -1;
}
if (buf[0] == (JPC_MS_SOC >> 8) && buf[1] == (JPC_MS_SOC & 0xff)) {
return 0;
}
return -1;
}
int jpc_getdata(jas_stream_t *in, jas_stream_t *out, long len)
{
return jas_stream_copy(out, in, len);
}
int jpc_putdata(jas_stream_t *out, jas_stream_t *in, long len)
{
return jas_stream_copy(out, in, len);
}
| ./CrossVul/dataset_final_sorted/CWE-369/c/good_5364_0 |
crossvul-cpp_data_bad_5063_0 | /*
* The copyright in this software is being made available under the 2-clauses
* BSD License, included below. This software may be subject to other third
* party and contributor rights, including patent rights, and no such rights
* are granted under this license.
*
* Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium
* Copyright (c) 2002-2014, Professor Benoit Macq
* Copyright (c) 2001-2003, David Janssens
* Copyright (c) 2002-2003, Yannick Verschueren
* Copyright (c) 2003-2007, Francois-Olivier Devaux
* Copyright (c) 2003-2014, Antonin Descampe
* Copyright (c) 2005, Herve Drolon, FreeImage Team
* Copyright (c) 2006-2007, Parvatha Elangovan
* Copyright (c) 2008, 2011-2012, Centre National d'Etudes Spatiales (CNES), FR
* Copyright (c) 2012, CS Systemes d'Information, France
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS'
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "opj_includes.h"
/* ----------------------------------------------------------------------- */
/* TODO MSD: */
#ifdef TODO_MSD
void tcd_dump(FILE *fd, opj_tcd_t *tcd, opj_tcd_image_t * img) {
int tileno, compno, resno, bandno, precno;/*, cblkno;*/
fprintf(fd, "image {\n");
fprintf(fd, " tw=%d, th=%d x0=%d x1=%d y0=%d y1=%d\n",
img->tw, img->th, tcd->image->x0, tcd->image->x1, tcd->image->y0, tcd->image->y1);
for (tileno = 0; tileno < img->th * img->tw; tileno++) {
opj_tcd_tile_t *tile = &tcd->tcd_image->tiles[tileno];
fprintf(fd, " tile {\n");
fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, numcomps=%d\n",
tile->x0, tile->y0, tile->x1, tile->y1, tile->numcomps);
for (compno = 0; compno < tile->numcomps; compno++) {
opj_tcd_tilecomp_t *tilec = &tile->comps[compno];
fprintf(fd, " tilec {\n");
fprintf(fd,
" x0=%d, y0=%d, x1=%d, y1=%d, numresolutions=%d\n",
tilec->x0, tilec->y0, tilec->x1, tilec->y1, tilec->numresolutions);
for (resno = 0; resno < tilec->numresolutions; resno++) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
fprintf(fd, "\n res {\n");
fprintf(fd,
" x0=%d, y0=%d, x1=%d, y1=%d, pw=%d, ph=%d, numbands=%d\n",
res->x0, res->y0, res->x1, res->y1, res->pw, res->ph, res->numbands);
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
fprintf(fd, " band {\n");
fprintf(fd,
" x0=%d, y0=%d, x1=%d, y1=%d, stepsize=%f, numbps=%d\n",
band->x0, band->y0, band->x1, band->y1, band->stepsize, band->numbps);
for (precno = 0; precno < res->pw * res->ph; precno++) {
opj_tcd_precinct_t *prec = &band->precincts[precno];
fprintf(fd, " prec {\n");
fprintf(fd,
" x0=%d, y0=%d, x1=%d, y1=%d, cw=%d, ch=%d\n",
prec->x0, prec->y0, prec->x1, prec->y1, prec->cw, prec->ch);
/*
for (cblkno = 0; cblkno < prec->cw * prec->ch; cblkno++) {
opj_tcd_cblk_t *cblk = &prec->cblks[cblkno];
fprintf(fd, " cblk {\n");
fprintf(fd,
" x0=%d, y0=%d, x1=%d, y1=%d\n",
cblk->x0, cblk->y0, cblk->x1, cblk->y1);
fprintf(fd, " }\n");
}
*/
fprintf(fd, " }\n");
}
fprintf(fd, " }\n");
}
fprintf(fd, " }\n");
}
fprintf(fd, " }\n");
}
fprintf(fd, " }\n");
}
fprintf(fd, "}\n");
}
#endif
/**
* Initializes tile coding/decoding
*/
static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block, opj_event_mgr_t* manager);
/**
* Allocates memory for a decoding code block.
*/
static OPJ_BOOL opj_tcd_code_block_dec_allocate (opj_tcd_cblk_dec_t * p_code_block);
/**
* Deallocates the decoding data of the given precinct.
*/
static void opj_tcd_code_block_dec_deallocate (opj_tcd_precinct_t * p_precinct);
/**
* Allocates memory for an encoding code block (but not data).
*/
static OPJ_BOOL opj_tcd_code_block_enc_allocate (opj_tcd_cblk_enc_t * p_code_block);
/**
* Allocates data for an encoding code block
*/
static OPJ_BOOL opj_tcd_code_block_enc_allocate_data (opj_tcd_cblk_enc_t * p_code_block);
/**
* Deallocates the encoding data of the given precinct.
*/
static void opj_tcd_code_block_enc_deallocate (opj_tcd_precinct_t * p_precinct);
/**
Free the memory allocated for encoding
@param tcd TCD handle
*/
static void opj_tcd_free_tile(opj_tcd_t *tcd);
static OPJ_BOOL opj_tcd_t2_decode ( opj_tcd_t *p_tcd,
OPJ_BYTE * p_src_data,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_src_size,
opj_codestream_index_t *p_cstr_index,
opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_tcd_t1_decode (opj_tcd_t *p_tcd);
static OPJ_BOOL opj_tcd_dwt_decode (opj_tcd_t *p_tcd);
static OPJ_BOOL opj_tcd_mct_decode (opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager);
static OPJ_BOOL opj_tcd_dc_level_shift_decode (opj_tcd_t *p_tcd);
static OPJ_BOOL opj_tcd_dc_level_shift_encode ( opj_tcd_t *p_tcd );
static OPJ_BOOL opj_tcd_mct_encode ( opj_tcd_t *p_tcd );
static OPJ_BOOL opj_tcd_dwt_encode ( opj_tcd_t *p_tcd );
static OPJ_BOOL opj_tcd_t1_encode ( opj_tcd_t *p_tcd );
static OPJ_BOOL opj_tcd_t2_encode ( opj_tcd_t *p_tcd,
OPJ_BYTE * p_dest_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_max_dest_size,
opj_codestream_info_t *p_cstr_info );
static OPJ_BOOL opj_tcd_rate_allocate_encode( opj_tcd_t *p_tcd,
OPJ_BYTE * p_dest_data,
OPJ_UINT32 p_max_dest_size,
opj_codestream_info_t *p_cstr_info );
/* ----------------------------------------------------------------------- */
/**
Create a new TCD handle
*/
opj_tcd_t* opj_tcd_create(OPJ_BOOL p_is_decoder)
{
opj_tcd_t *l_tcd = 00;
/* create the tcd structure */
l_tcd = (opj_tcd_t*) opj_calloc(1,sizeof(opj_tcd_t));
if (!l_tcd) {
return 00;
}
l_tcd->m_is_decoder = p_is_decoder ? 1 : 0;
l_tcd->tcd_image = (opj_tcd_image_t*)opj_calloc(1,sizeof(opj_tcd_image_t));
if (!l_tcd->tcd_image) {
opj_free(l_tcd);
return 00;
}
return l_tcd;
}
/* ----------------------------------------------------------------------- */
void opj_tcd_rateallocate_fixed(opj_tcd_t *tcd) {
OPJ_UINT32 layno;
for (layno = 0; layno < tcd->tcp->numlayers; layno++) {
opj_tcd_makelayer_fixed(tcd, layno, 1);
}
}
void opj_tcd_makelayer( opj_tcd_t *tcd,
OPJ_UINT32 layno,
OPJ_FLOAT64 thresh,
OPJ_UINT32 final)
{
OPJ_UINT32 compno, resno, bandno, precno, cblkno;
OPJ_UINT32 passno;
opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles;
tcd_tile->distolayer[layno] = 0; /* fixed_quality */
for (compno = 0; compno < tcd_tile->numcomps; compno++) {
opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno];
for (resno = 0; resno < tilec->numresolutions; resno++) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
for (precno = 0; precno < res->pw * res->ph; precno++) {
opj_tcd_precinct_t *prc = &band->precincts[precno];
for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno];
opj_tcd_layer_t *layer = &cblk->layers[layno];
OPJ_UINT32 n;
if (layno == 0) {
cblk->numpassesinlayers = 0;
}
n = cblk->numpassesinlayers;
for (passno = cblk->numpassesinlayers; passno < cblk->totalpasses; passno++) {
OPJ_UINT32 dr;
OPJ_FLOAT64 dd;
opj_tcd_pass_t *pass = &cblk->passes[passno];
if (n == 0) {
dr = pass->rate;
dd = pass->distortiondec;
} else {
dr = pass->rate - cblk->passes[n - 1].rate;
dd = pass->distortiondec - cblk->passes[n - 1].distortiondec;
}
if (!dr) {
if (dd != 0)
n = passno + 1;
continue;
}
if (thresh - (dd / dr) < DBL_EPSILON) /* do not rely on float equality, check with DBL_EPSILON margin */
n = passno + 1;
}
layer->numpasses = n - cblk->numpassesinlayers;
if (!layer->numpasses) {
layer->disto = 0;
continue;
}
if (cblk->numpassesinlayers == 0) {
layer->len = cblk->passes[n - 1].rate;
layer->data = cblk->data;
layer->disto = cblk->passes[n - 1].distortiondec;
} else {
layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers - 1].rate;
layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate;
layer->disto = cblk->passes[n - 1].distortiondec - cblk->passes[cblk->numpassesinlayers - 1].distortiondec;
}
tcd_tile->distolayer[layno] += layer->disto; /* fixed_quality */
if (final)
cblk->numpassesinlayers = n;
}
}
}
}
}
}
void opj_tcd_makelayer_fixed(opj_tcd_t *tcd, OPJ_UINT32 layno, OPJ_UINT32 final) {
OPJ_UINT32 compno, resno, bandno, precno, cblkno;
OPJ_INT32 value; /*, matrice[tcd_tcp->numlayers][tcd_tile->comps[0].numresolutions][3]; */
OPJ_INT32 matrice[10][10][3];
OPJ_UINT32 i, j, k;
opj_cp_t *cp = tcd->cp;
opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles;
opj_tcp_t *tcd_tcp = tcd->tcp;
for (compno = 0; compno < tcd_tile->numcomps; compno++) {
opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno];
for (i = 0; i < tcd_tcp->numlayers; i++) {
for (j = 0; j < tilec->numresolutions; j++) {
for (k = 0; k < 3; k++) {
matrice[i][j][k] =
(OPJ_INT32) ((OPJ_FLOAT32)cp->m_specific_param.m_enc.m_matrice[i * tilec->numresolutions * 3 + j * 3 + k]
* (OPJ_FLOAT32) (tcd->image->comps[compno].prec / 16.0));
}
}
}
for (resno = 0; resno < tilec->numresolutions; resno++) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
for (precno = 0; precno < res->pw * res->ph; precno++) {
opj_tcd_precinct_t *prc = &band->precincts[precno];
for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno];
opj_tcd_layer_t *layer = &cblk->layers[layno];
OPJ_UINT32 n;
OPJ_INT32 imsb = (OPJ_INT32)(tcd->image->comps[compno].prec - cblk->numbps); /* number of bit-plan equal to zero */
/* Correction of the matrix of coefficient to include the IMSB information */
if (layno == 0) {
value = matrice[layno][resno][bandno];
if (imsb >= value) {
value = 0;
} else {
value -= imsb;
}
} else {
value = matrice[layno][resno][bandno] - matrice[layno - 1][resno][bandno];
if (imsb >= matrice[layno - 1][resno][bandno]) {
value -= (imsb - matrice[layno - 1][resno][bandno]);
if (value < 0) {
value = 0;
}
}
}
if (layno == 0) {
cblk->numpassesinlayers = 0;
}
n = cblk->numpassesinlayers;
if (cblk->numpassesinlayers == 0) {
if (value != 0) {
n = 3 * (OPJ_UINT32)value - 2 + cblk->numpassesinlayers;
} else {
n = cblk->numpassesinlayers;
}
} else {
n = 3 * (OPJ_UINT32)value + cblk->numpassesinlayers;
}
layer->numpasses = n - cblk->numpassesinlayers;
if (!layer->numpasses)
continue;
if (cblk->numpassesinlayers == 0) {
layer->len = cblk->passes[n - 1].rate;
layer->data = cblk->data;
} else {
layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers - 1].rate;
layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate;
}
if (final)
cblk->numpassesinlayers = n;
}
}
}
}
}
}
OPJ_BOOL opj_tcd_rateallocate( opj_tcd_t *tcd,
OPJ_BYTE *dest,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 len,
opj_codestream_info_t *cstr_info)
{
OPJ_UINT32 compno, resno, bandno, precno, cblkno, layno;
OPJ_UINT32 passno;
OPJ_FLOAT64 min, max;
OPJ_FLOAT64 cumdisto[100]; /* fixed_quality */
const OPJ_FLOAT64 K = 1; /* 1.1; fixed_quality */
OPJ_FLOAT64 maxSE = 0;
opj_cp_t *cp = tcd->cp;
opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles;
opj_tcp_t *tcd_tcp = tcd->tcp;
min = DBL_MAX;
max = 0;
tcd_tile->numpix = 0; /* fixed_quality */
for (compno = 0; compno < tcd_tile->numcomps; compno++) {
opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno];
tilec->numpix = 0;
for (resno = 0; resno < tilec->numresolutions; resno++) {
opj_tcd_resolution_t *res = &tilec->resolutions[resno];
for (bandno = 0; bandno < res->numbands; bandno++) {
opj_tcd_band_t *band = &res->bands[bandno];
for (precno = 0; precno < res->pw * res->ph; precno++) {
opj_tcd_precinct_t *prc = &band->precincts[precno];
for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) {
opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno];
for (passno = 0; passno < cblk->totalpasses; passno++) {
opj_tcd_pass_t *pass = &cblk->passes[passno];
OPJ_INT32 dr;
OPJ_FLOAT64 dd, rdslope;
if (passno == 0) {
dr = (OPJ_INT32)pass->rate;
dd = pass->distortiondec;
} else {
dr = (OPJ_INT32)(pass->rate - cblk->passes[passno - 1].rate);
dd = pass->distortiondec - cblk->passes[passno - 1].distortiondec;
}
if (dr == 0) {
continue;
}
rdslope = dd / dr;
if (rdslope < min) {
min = rdslope;
}
if (rdslope > max) {
max = rdslope;
}
} /* passno */
/* fixed_quality */
tcd_tile->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0));
tilec->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0));
} /* cbklno */
} /* precno */
} /* bandno */
} /* resno */
maxSE += (((OPJ_FLOAT64)(1 << tcd->image->comps[compno].prec) - 1.0)
* ((OPJ_FLOAT64)(1 << tcd->image->comps[compno].prec) -1.0))
* ((OPJ_FLOAT64)(tilec->numpix));
} /* compno */
/* index file */
if(cstr_info) {
opj_tile_info_t *tile_info = &cstr_info->tile[tcd->tcd_tileno];
tile_info->numpix = tcd_tile->numpix;
tile_info->distotile = tcd_tile->distotile;
tile_info->thresh = (OPJ_FLOAT64 *) opj_malloc(tcd_tcp->numlayers * sizeof(OPJ_FLOAT64));
if (!tile_info->thresh) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
}
for (layno = 0; layno < tcd_tcp->numlayers; layno++) {
OPJ_FLOAT64 lo = min;
OPJ_FLOAT64 hi = max;
OPJ_UINT32 maxlen = tcd_tcp->rates[layno] > 0.0f ? opj_uint_min(((OPJ_UINT32) ceil(tcd_tcp->rates[layno])), len) : len;
OPJ_FLOAT64 goodthresh = 0;
OPJ_FLOAT64 stable_thresh = 0;
OPJ_UINT32 i;
OPJ_FLOAT64 distotarget; /* fixed_quality */
/* fixed_quality */
distotarget = tcd_tile->distotile - ((K * maxSE) / pow((OPJ_FLOAT32)10, tcd_tcp->distoratio[layno] / 10));
/* Don't try to find an optimal threshold but rather take everything not included yet, if
-r xx,yy,zz,0 (disto_alloc == 1 and rates == 0)
-q xx,yy,zz,0 (fixed_quality == 1 and distoratio == 0)
==> possible to have some lossy layers and the last layer for sure lossless */
if ( ((cp->m_specific_param.m_enc.m_disto_alloc==1) && (tcd_tcp->rates[layno]>0.0f)) || ((cp->m_specific_param.m_enc.m_fixed_quality==1) && (tcd_tcp->distoratio[layno]>0.0))) {
opj_t2_t*t2 = opj_t2_create(tcd->image, cp);
OPJ_FLOAT64 thresh = 0;
if (t2 == 00) {
return OPJ_FALSE;
}
for (i = 0; i < 128; ++i) {
OPJ_FLOAT64 distoachieved = 0; /* fixed_quality */
thresh = (lo + hi) / 2;
opj_tcd_makelayer(tcd, layno, thresh, 0);
if (cp->m_specific_param.m_enc.m_fixed_quality) { /* fixed_quality */
if(OPJ_IS_CINEMA(cp->rsiz)){
if (! opj_t2_encode_packets(t2,tcd->tcd_tileno, tcd_tile, layno + 1, dest, p_data_written, maxlen, cstr_info,tcd->cur_tp_num,tcd->tp_pos,tcd->cur_pino,THRESH_CALC)) {
lo = thresh;
continue;
}
else {
distoachieved = layno == 0 ?
tcd_tile->distolayer[0] : cumdisto[layno - 1] + tcd_tile->distolayer[layno];
if (distoachieved < distotarget) {
hi=thresh;
stable_thresh = thresh;
continue;
}else{
lo=thresh;
}
}
}else{
distoachieved = (layno == 0) ?
tcd_tile->distolayer[0] : (cumdisto[layno - 1] + tcd_tile->distolayer[layno]);
if (distoachieved < distotarget) {
hi = thresh;
stable_thresh = thresh;
continue;
}
lo = thresh;
}
} else {
if (! opj_t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest,p_data_written, maxlen, cstr_info,tcd->cur_tp_num,tcd->tp_pos,tcd->cur_pino,THRESH_CALC))
{
/* TODO: what to do with l ??? seek / tell ??? */
/* opj_event_msg(tcd->cinfo, EVT_INFO, "rate alloc: len=%d, max=%d\n", l, maxlen); */
lo = thresh;
continue;
}
hi = thresh;
stable_thresh = thresh;
}
}
goodthresh = stable_thresh == 0? thresh : stable_thresh;
opj_t2_destroy(t2);
} else {
goodthresh = min;
}
if(cstr_info) { /* Threshold for Marcela Index */
cstr_info->tile[tcd->tcd_tileno].thresh[layno] = goodthresh;
}
opj_tcd_makelayer(tcd, layno, goodthresh, 1);
/* fixed_quality */
cumdisto[layno] = (layno == 0) ? tcd_tile->distolayer[0] : (cumdisto[layno - 1] + tcd_tile->distolayer[layno]);
}
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_init( opj_tcd_t *p_tcd,
opj_image_t * p_image,
opj_cp_t * p_cp )
{
p_tcd->image = p_image;
p_tcd->cp = p_cp;
p_tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_calloc(1,sizeof(opj_tcd_tile_t));
if (! p_tcd->tcd_image->tiles) {
return OPJ_FALSE;
}
p_tcd->tcd_image->tiles->comps = (opj_tcd_tilecomp_t *) opj_calloc(p_image->numcomps,sizeof(opj_tcd_tilecomp_t));
if (! p_tcd->tcd_image->tiles->comps ) {
return OPJ_FALSE;
}
p_tcd->tcd_image->tiles->numcomps = p_image->numcomps;
p_tcd->tp_pos = p_cp->m_specific_param.m_enc.m_tp_pos;
return OPJ_TRUE;
}
/**
Destroy a previously created TCD handle
*/
void opj_tcd_destroy(opj_tcd_t *tcd) {
if (tcd) {
opj_tcd_free_tile(tcd);
if (tcd->tcd_image) {
opj_free(tcd->tcd_image);
tcd->tcd_image = 00;
}
opj_free(tcd);
}
}
OPJ_BOOL opj_alloc_tile_component_data(opj_tcd_tilecomp_t *l_tilec)
{
if ((l_tilec->data == 00) || ((l_tilec->data_size_needed > l_tilec->data_size) && (l_tilec->ownsData == OPJ_FALSE))) {
l_tilec->data = (OPJ_INT32 *) opj_aligned_malloc(l_tilec->data_size_needed);
if (! l_tilec->data ) {
return OPJ_FALSE;
}
/*fprintf(stderr, "tAllocate data of tilec (int): %d x OPJ_UINT32n",l_data_size);*/
l_tilec->data_size = l_tilec->data_size_needed;
l_tilec->ownsData = OPJ_TRUE;
}
else if (l_tilec->data_size_needed > l_tilec->data_size) {
/* We don't need to keep old data */
opj_aligned_free(l_tilec->data);
l_tilec->data = (OPJ_INT32 *) opj_aligned_malloc(l_tilec->data_size_needed);
if (! l_tilec->data ) {
l_tilec->data_size = 0;
l_tilec->data_size_needed = 0;
l_tilec->ownsData = OPJ_FALSE;
return OPJ_FALSE;
}
/*fprintf(stderr, "tReallocate data of tilec (int): from %d to %d x OPJ_UINT32n", l_tilec->data_size, l_data_size);*/
l_tilec->data_size = l_tilec->data_size_needed;
l_tilec->ownsData = OPJ_TRUE;
}
return OPJ_TRUE;
}
/* ----------------------------------------------------------------------- */
static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block, opj_event_mgr_t* manager)
{
OPJ_UINT32 (*l_gain_ptr)(OPJ_UINT32) = 00;
OPJ_UINT32 compno, resno, bandno, precno, cblkno;
opj_tcp_t * l_tcp = 00;
opj_cp_t * l_cp = 00;
opj_tcd_tile_t * l_tile = 00;
opj_tccp_t *l_tccp = 00;
opj_tcd_tilecomp_t *l_tilec = 00;
opj_image_comp_t * l_image_comp = 00;
opj_tcd_resolution_t *l_res = 00;
opj_tcd_band_t *l_band = 00;
opj_stepsize_t * l_step_size = 00;
opj_tcd_precinct_t *l_current_precinct = 00;
opj_image_t *l_image = 00;
OPJ_UINT32 p,q;
OPJ_UINT32 l_level_no;
OPJ_UINT32 l_pdx, l_pdy;
OPJ_UINT32 l_gain;
OPJ_INT32 l_x0b, l_y0b;
OPJ_UINT32 l_tx0, l_ty0;
/* extent of precincts , top left, bottom right**/
OPJ_INT32 l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end, l_br_prc_y_end;
/* number of precinct for a resolution */
OPJ_UINT32 l_nb_precincts;
/* room needed to store l_nb_precinct precinct for a resolution */
OPJ_UINT32 l_nb_precinct_size;
/* number of code blocks for a precinct*/
OPJ_UINT32 l_nb_code_blocks;
/* room needed to store l_nb_code_blocks code blocks for a precinct*/
OPJ_UINT32 l_nb_code_blocks_size;
/* size of data for a tile */
OPJ_UINT32 l_data_size;
l_cp = p_tcd->cp;
l_tcp = &(l_cp->tcps[p_tile_no]);
l_tile = p_tcd->tcd_image->tiles;
l_tccp = l_tcp->tccps;
l_tilec = l_tile->comps;
l_image = p_tcd->image;
l_image_comp = p_tcd->image->comps;
p = p_tile_no % l_cp->tw; /* tile coordinates */
q = p_tile_no / l_cp->tw;
/*fprintf(stderr, "Tile coordinate = %d,%d\n", p, q);*/
/* 4 borders of the tile rescale on the image if necessary */
l_tx0 = l_cp->tx0 + p * l_cp->tdx; /* can't be greater than l_image->x1 so won't overflow */
l_tile->x0 = (OPJ_INT32)opj_uint_max(l_tx0, l_image->x0);
l_tile->x1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, l_cp->tdx), l_image->x1);
l_ty0 = l_cp->ty0 + q * l_cp->tdy; /* can't be greater than l_image->y1 so won't overflow */
l_tile->y0 = (OPJ_INT32)opj_uint_max(l_ty0, l_image->y0);
l_tile->y1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, l_cp->tdy), l_image->y1);
/* testcase 1888.pdf.asan.35.988 */
if (l_tccp->numresolutions == 0) {
opj_event_msg(manager, EVT_ERROR, "tiles require at least one resolution\n");
return OPJ_FALSE;
}
/*fprintf(stderr, "Tile border = %d,%d,%d,%d\n", l_tile->x0, l_tile->y0,l_tile->x1,l_tile->y1);*/
/*tile->numcomps = image->numcomps; */
for (compno = 0; compno < l_tile->numcomps; ++compno) {
/*fprintf(stderr, "compno = %d/%d\n", compno, l_tile->numcomps);*/
l_image_comp->resno_decoded = 0;
/* border of each l_tile component (global) */
l_tilec->x0 = opj_int_ceildiv(l_tile->x0, (OPJ_INT32)l_image_comp->dx);
l_tilec->y0 = opj_int_ceildiv(l_tile->y0, (OPJ_INT32)l_image_comp->dy);
l_tilec->x1 = opj_int_ceildiv(l_tile->x1, (OPJ_INT32)l_image_comp->dx);
l_tilec->y1 = opj_int_ceildiv(l_tile->y1, (OPJ_INT32)l_image_comp->dy);
/*fprintf(stderr, "\tTile compo border = %d,%d,%d,%d\n", l_tilec->x0, l_tilec->y0,l_tilec->x1,l_tilec->y1);*/
/* compute l_data_size with overflow check */
l_data_size = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0);
if ((((OPJ_UINT32)-1) / l_data_size) < (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0)) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_data_size = l_data_size * (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0);
if ((((OPJ_UINT32)-1) / (OPJ_UINT32)sizeof(OPJ_UINT32)) < l_data_size) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_data_size = l_data_size * (OPJ_UINT32)sizeof(OPJ_UINT32);
l_tilec->numresolutions = l_tccp->numresolutions;
if (l_tccp->numresolutions < l_cp->m_specific_param.m_dec.m_reduce) {
l_tilec->minimum_num_resolutions = 1;
}
else {
l_tilec->minimum_num_resolutions = l_tccp->numresolutions - l_cp->m_specific_param.m_dec.m_reduce;
}
l_tilec->data_size_needed = l_data_size;
if (p_tcd->m_is_decoder && !opj_alloc_tile_component_data(l_tilec)) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile data\n");
return OPJ_FALSE;
}
l_data_size = l_tilec->numresolutions * (OPJ_UINT32)sizeof(opj_tcd_resolution_t);
if (l_tilec->resolutions == 00) {
l_tilec->resolutions = (opj_tcd_resolution_t *) opj_malloc(l_data_size);
if (! l_tilec->resolutions ) {
return OPJ_FALSE;
}
/*fprintf(stderr, "\tAllocate resolutions of tilec (opj_tcd_resolution_t): %d\n",l_data_size);*/
l_tilec->resolutions_size = l_data_size;
memset(l_tilec->resolutions,0,l_data_size);
}
else if (l_data_size > l_tilec->resolutions_size) {
opj_tcd_resolution_t* new_resolutions = (opj_tcd_resolution_t *) opj_realloc(l_tilec->resolutions, l_data_size);
if (! new_resolutions) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory for tile resolutions\n");
opj_free(l_tilec->resolutions);
l_tilec->resolutions = NULL;
l_tilec->resolutions_size = 0;
return OPJ_FALSE;
}
l_tilec->resolutions = new_resolutions;
/*fprintf(stderr, "\tReallocate data of tilec (int): from %d to %d x OPJ_UINT32\n", l_tilec->resolutions_size, l_data_size);*/
memset(((OPJ_BYTE*) l_tilec->resolutions)+l_tilec->resolutions_size,0,l_data_size - l_tilec->resolutions_size);
l_tilec->resolutions_size = l_data_size;
}
l_level_no = l_tilec->numresolutions;
l_res = l_tilec->resolutions;
l_step_size = l_tccp->stepsizes;
if (l_tccp->qmfbid == 0) {
l_gain_ptr = &opj_dwt_getgain_real;
}
else {
l_gain_ptr = &opj_dwt_getgain;
}
/*fprintf(stderr, "\tlevel_no=%d\n",l_level_no);*/
for (resno = 0; resno < l_tilec->numresolutions; ++resno) {
/*fprintf(stderr, "\t\tresno = %d/%d\n", resno, l_tilec->numresolutions);*/
OPJ_INT32 tlcbgxstart, tlcbgystart /*, brcbgxend, brcbgyend*/;
OPJ_UINT32 cbgwidthexpn, cbgheightexpn;
OPJ_UINT32 cblkwidthexpn, cblkheightexpn;
--l_level_no;
/* border for each resolution level (global) */
l_res->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no);
l_res->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no);
l_res->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no);
l_res->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no);
/*fprintf(stderr, "\t\t\tres_x0= %d, res_y0 =%d, res_x1=%d, res_y1=%d\n", l_res->x0, l_res->y0, l_res->x1, l_res->y1);*/
/* p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000) */
l_pdx = l_tccp->prcw[resno];
l_pdy = l_tccp->prch[resno];
/*fprintf(stderr, "\t\t\tpdx=%d, pdy=%d\n", l_pdx, l_pdy);*/
/* p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000) */
l_tl_prc_x_start = opj_int_floordivpow2(l_res->x0, (OPJ_INT32)l_pdx) << l_pdx;
l_tl_prc_y_start = opj_int_floordivpow2(l_res->y0, (OPJ_INT32)l_pdy) << l_pdy;
l_br_prc_x_end = opj_int_ceildivpow2(l_res->x1, (OPJ_INT32)l_pdx) << l_pdx;
l_br_prc_y_end = opj_int_ceildivpow2(l_res->y1, (OPJ_INT32)l_pdy) << l_pdy;
/*fprintf(stderr, "\t\t\tprc_x_start=%d, prc_y_start=%d, br_prc_x_end=%d, br_prc_y_end=%d \n", l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end ,l_br_prc_y_end );*/
l_res->pw = (l_res->x0 == l_res->x1) ? 0 : (OPJ_UINT32)((l_br_prc_x_end - l_tl_prc_x_start) >> l_pdx);
l_res->ph = (l_res->y0 == l_res->y1) ? 0 : (OPJ_UINT32)((l_br_prc_y_end - l_tl_prc_y_start) >> l_pdy);
/*fprintf(stderr, "\t\t\tres_pw=%d, res_ph=%d\n", l_res->pw, l_res->ph );*/
l_nb_precincts = l_res->pw * l_res->ph;
l_nb_precinct_size = l_nb_precincts * (OPJ_UINT32)sizeof(opj_tcd_precinct_t);
if (resno == 0) {
tlcbgxstart = l_tl_prc_x_start;
tlcbgystart = l_tl_prc_y_start;
/*brcbgxend = l_br_prc_x_end;*/
/* brcbgyend = l_br_prc_y_end;*/
cbgwidthexpn = l_pdx;
cbgheightexpn = l_pdy;
l_res->numbands = 1;
}
else {
tlcbgxstart = opj_int_ceildivpow2(l_tl_prc_x_start, 1);
tlcbgystart = opj_int_ceildivpow2(l_tl_prc_y_start, 1);
/*brcbgxend = opj_int_ceildivpow2(l_br_prc_x_end, 1);*/
/*brcbgyend = opj_int_ceildivpow2(l_br_prc_y_end, 1);*/
cbgwidthexpn = l_pdx - 1;
cbgheightexpn = l_pdy - 1;
l_res->numbands = 3;
}
cblkwidthexpn = opj_uint_min(l_tccp->cblkw, cbgwidthexpn);
cblkheightexpn = opj_uint_min(l_tccp->cblkh, cbgheightexpn);
l_band = l_res->bands;
for (bandno = 0; bandno < l_res->numbands; ++bandno) {
OPJ_INT32 numbps;
/*fprintf(stderr, "\t\t\tband_no=%d/%d\n", bandno, l_res->numbands );*/
if (resno == 0) {
l_band->bandno = 0 ;
l_band->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no);
l_band->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no);
l_band->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no);
l_band->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no);
}
else {
l_band->bandno = bandno + 1;
/* x0b = 1 if bandno = 1 or 3 */
l_x0b = l_band->bandno&1;
/* y0b = 1 if bandno = 2 or 3 */
l_y0b = (OPJ_INT32)((l_band->bandno)>>1);
/* l_band border (global) */
l_band->x0 = opj_int64_ceildivpow2(l_tilec->x0 - ((OPJ_INT64)l_x0b << l_level_no), (OPJ_INT32)(l_level_no + 1));
l_band->y0 = opj_int64_ceildivpow2(l_tilec->y0 - ((OPJ_INT64)l_y0b << l_level_no), (OPJ_INT32)(l_level_no + 1));
l_band->x1 = opj_int64_ceildivpow2(l_tilec->x1 - ((OPJ_INT64)l_x0b << l_level_no), (OPJ_INT32)(l_level_no + 1));
l_band->y1 = opj_int64_ceildivpow2(l_tilec->y1 - ((OPJ_INT64)l_y0b << l_level_no), (OPJ_INT32)(l_level_no + 1));
}
/** avoid an if with storing function pointer */
l_gain = (*l_gain_ptr) (l_band->bandno);
numbps = (OPJ_INT32)(l_image_comp->prec + l_gain);
l_band->stepsize = (OPJ_FLOAT32)(((1.0 + l_step_size->mant / 2048.0) * pow(2.0, (OPJ_INT32) (numbps - l_step_size->expn)))) * fraction;
l_band->numbps = l_step_size->expn + (OPJ_INT32)l_tccp->numgbits - 1; /* WHY -1 ? */
if (!l_band->precincts && (l_nb_precincts > 0U)) {
l_band->precincts = (opj_tcd_precinct_t *) opj_malloc( /*3 * */ l_nb_precinct_size);
if (! l_band->precincts) {
return OPJ_FALSE;
}
/*fprintf(stderr, "\t\t\t\tAllocate precincts of a band (opj_tcd_precinct_t): %d\n",l_nb_precinct_size); */
memset(l_band->precincts,0,l_nb_precinct_size);
l_band->precincts_data_size = l_nb_precinct_size;
}
else if (l_band->precincts_data_size < l_nb_precinct_size) {
opj_tcd_precinct_t * new_precincts = (opj_tcd_precinct_t *) opj_realloc(l_band->precincts,/*3 * */ l_nb_precinct_size);
if (! new_precincts) {
opj_event_msg(manager, EVT_ERROR, "Not enough memory to handle band precints\n");
opj_free(l_band->precincts);
l_band->precincts = NULL;
l_band->precincts_data_size = 0;
return OPJ_FALSE;
}
l_band->precincts = new_precincts;
/*fprintf(stderr, "\t\t\t\tReallocate precincts of a band (opj_tcd_precinct_t): from %d to %d\n",l_band->precincts_data_size, l_nb_precinct_size);*/
memset(((OPJ_BYTE *) l_band->precincts) + l_band->precincts_data_size,0,l_nb_precinct_size - l_band->precincts_data_size);
l_band->precincts_data_size = l_nb_precinct_size;
}
l_current_precinct = l_band->precincts;
for (precno = 0; precno < l_nb_precincts; ++precno) {
OPJ_INT32 tlcblkxstart, tlcblkystart, brcblkxend, brcblkyend;
OPJ_INT32 cbgxstart = tlcbgxstart + (OPJ_INT32)(precno % l_res->pw) * (1 << cbgwidthexpn);
OPJ_INT32 cbgystart = tlcbgystart + (OPJ_INT32)(precno / l_res->pw) * (1 << cbgheightexpn);
OPJ_INT32 cbgxend = cbgxstart + (1 << cbgwidthexpn);
OPJ_INT32 cbgyend = cbgystart + (1 << cbgheightexpn);
/*fprintf(stderr, "\t precno=%d; bandno=%d, resno=%d; compno=%d\n", precno, bandno , resno, compno);*/
/*fprintf(stderr, "\t tlcbgxstart(=%d) + (precno(=%d) percent res->pw(=%d)) * (1 << cbgwidthexpn(=%d)) \n",tlcbgxstart,precno,l_res->pw,cbgwidthexpn);*/
/* precinct size (global) */
/*fprintf(stderr, "\t cbgxstart=%d, l_band->x0 = %d \n",cbgxstart, l_band->x0);*/
l_current_precinct->x0 = opj_int_max(cbgxstart, l_band->x0);
l_current_precinct->y0 = opj_int_max(cbgystart, l_band->y0);
l_current_precinct->x1 = opj_int_min(cbgxend, l_band->x1);
l_current_precinct->y1 = opj_int_min(cbgyend, l_band->y1);
/*fprintf(stderr, "\t prc_x0=%d; prc_y0=%d, prc_x1=%d; prc_y1=%d\n",l_current_precinct->x0, l_current_precinct->y0 ,l_current_precinct->x1, l_current_precinct->y1);*/
tlcblkxstart = opj_int_floordivpow2(l_current_precinct->x0, (OPJ_INT32)cblkwidthexpn) << cblkwidthexpn;
/*fprintf(stderr, "\t tlcblkxstart =%d\n",tlcblkxstart );*/
tlcblkystart = opj_int_floordivpow2(l_current_precinct->y0, (OPJ_INT32)cblkheightexpn) << cblkheightexpn;
/*fprintf(stderr, "\t tlcblkystart =%d\n",tlcblkystart );*/
brcblkxend = opj_int_ceildivpow2(l_current_precinct->x1, (OPJ_INT32)cblkwidthexpn) << cblkwidthexpn;
/*fprintf(stderr, "\t brcblkxend =%d\n",brcblkxend );*/
brcblkyend = opj_int_ceildivpow2(l_current_precinct->y1, (OPJ_INT32)cblkheightexpn) << cblkheightexpn;
/*fprintf(stderr, "\t brcblkyend =%d\n",brcblkyend );*/
l_current_precinct->cw = (OPJ_UINT32)((brcblkxend - tlcblkxstart) >> cblkwidthexpn);
l_current_precinct->ch = (OPJ_UINT32)((brcblkyend - tlcblkystart) >> cblkheightexpn);
l_nb_code_blocks = l_current_precinct->cw * l_current_precinct->ch;
/*fprintf(stderr, "\t\t\t\t precinct_cw = %d x recinct_ch = %d\n",l_current_precinct->cw, l_current_precinct->ch); */
l_nb_code_blocks_size = l_nb_code_blocks * (OPJ_UINT32)sizeof_block;
if (!l_current_precinct->cblks.blocks && (l_nb_code_blocks > 0U)) {
l_current_precinct->cblks.blocks = opj_malloc(l_nb_code_blocks_size);
if (! l_current_precinct->cblks.blocks ) {
return OPJ_FALSE;
}
/*fprintf(stderr, "\t\t\t\tAllocate cblks of a precinct (opj_tcd_cblk_dec_t): %d\n",l_nb_code_blocks_size);*/
memset(l_current_precinct->cblks.blocks,0,l_nb_code_blocks_size);
l_current_precinct->block_size = l_nb_code_blocks_size;
}
else if (l_nb_code_blocks_size > l_current_precinct->block_size) {
void *new_blocks = opj_realloc(l_current_precinct->cblks.blocks, l_nb_code_blocks_size);
if (! new_blocks) {
opj_free(l_current_precinct->cblks.blocks);
l_current_precinct->cblks.blocks = NULL;
l_current_precinct->block_size = 0;
opj_event_msg(manager, EVT_ERROR, "Not enough memory for current precinct codeblock element\n");
return OPJ_FALSE;
}
l_current_precinct->cblks.blocks = new_blocks;
/*fprintf(stderr, "\t\t\t\tReallocate cblks of a precinct (opj_tcd_cblk_dec_t): from %d to %d\n",l_current_precinct->block_size, l_nb_code_blocks_size); */
memset(((OPJ_BYTE *) l_current_precinct->cblks.blocks) + l_current_precinct->block_size
,0
,l_nb_code_blocks_size - l_current_precinct->block_size);
l_current_precinct->block_size = l_nb_code_blocks_size;
}
if (! l_current_precinct->incltree) {
l_current_precinct->incltree = opj_tgt_create(l_current_precinct->cw, l_current_precinct->ch, manager);
}
else{
l_current_precinct->incltree = opj_tgt_init(l_current_precinct->incltree, l_current_precinct->cw, l_current_precinct->ch, manager);
}
if (! l_current_precinct->incltree) {
opj_event_msg(manager, EVT_WARNING, "No incltree created.\n");
/*return OPJ_FALSE;*/
}
if (! l_current_precinct->imsbtree) {
l_current_precinct->imsbtree = opj_tgt_create(l_current_precinct->cw, l_current_precinct->ch, manager);
}
else {
l_current_precinct->imsbtree = opj_tgt_init(l_current_precinct->imsbtree, l_current_precinct->cw, l_current_precinct->ch, manager);
}
if (! l_current_precinct->imsbtree) {
opj_event_msg(manager, EVT_WARNING, "No imsbtree created.\n");
/*return OPJ_FALSE;*/
}
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
OPJ_INT32 cblkxstart = tlcblkxstart + (OPJ_INT32)(cblkno % l_current_precinct->cw) * (1 << cblkwidthexpn);
OPJ_INT32 cblkystart = tlcblkystart + (OPJ_INT32)(cblkno / l_current_precinct->cw) * (1 << cblkheightexpn);
OPJ_INT32 cblkxend = cblkxstart + (1 << cblkwidthexpn);
OPJ_INT32 cblkyend = cblkystart + (1 << cblkheightexpn);
if (isEncoder) {
opj_tcd_cblk_enc_t* l_code_block = l_current_precinct->cblks.enc + cblkno;
if (! opj_tcd_code_block_enc_allocate(l_code_block)) {
return OPJ_FALSE;
}
/* code-block size (global) */
l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0);
l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0);
l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1);
l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1);
if (! opj_tcd_code_block_enc_allocate_data(l_code_block)) {
return OPJ_FALSE;
}
} else {
opj_tcd_cblk_dec_t* l_code_block = l_current_precinct->cblks.dec + cblkno;
if (! opj_tcd_code_block_dec_allocate(l_code_block)) {
return OPJ_FALSE;
}
/* code-block size (global) */
l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0);
l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0);
l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1);
l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1);
}
}
++l_current_precinct;
} /* precno */
++l_band;
++l_step_size;
} /* bandno */
++l_res;
} /* resno */
++l_tccp;
++l_tilec;
++l_image_comp;
} /* compno */
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_init_encode_tile (opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, opj_event_mgr_t* p_manager)
{
return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_TRUE, 1.0F, sizeof(opj_tcd_cblk_enc_t), p_manager);
}
OPJ_BOOL opj_tcd_init_decode_tile (opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, opj_event_mgr_t* p_manager)
{
return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_FALSE, 0.5F, sizeof(opj_tcd_cblk_dec_t), p_manager);
}
/**
* Allocates memory for an encoding code block (but not data memory).
*/
static OPJ_BOOL opj_tcd_code_block_enc_allocate (opj_tcd_cblk_enc_t * p_code_block)
{
if (! p_code_block->layers) {
/* no memset since data */
p_code_block->layers = (opj_tcd_layer_t*) opj_calloc(100, sizeof(opj_tcd_layer_t));
if (! p_code_block->layers) {
return OPJ_FALSE;
}
}
if (! p_code_block->passes) {
p_code_block->passes = (opj_tcd_pass_t*) opj_calloc(100, sizeof(opj_tcd_pass_t));
if (! p_code_block->passes) {
return OPJ_FALSE;
}
}
return OPJ_TRUE;
}
/**
* Allocates data memory for an encoding code block.
*/
static OPJ_BOOL opj_tcd_code_block_enc_allocate_data (opj_tcd_cblk_enc_t * p_code_block)
{
OPJ_UINT32 l_data_size;
l_data_size = (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32));
if (l_data_size > p_code_block->data_size) {
if (p_code_block->data) {
opj_free(p_code_block->data - 1); /* again, why -1 */
}
p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size+1);
if(! p_code_block->data) {
p_code_block->data_size = 0U;
return OPJ_FALSE;
}
p_code_block->data_size = l_data_size;
p_code_block->data[0] = 0;
p_code_block->data+=1; /*why +1 ?*/
}
return OPJ_TRUE;
}
/**
* Allocates memory for a decoding code block.
*/
static OPJ_BOOL opj_tcd_code_block_dec_allocate (opj_tcd_cblk_dec_t * p_code_block)
{
if (! p_code_block->data) {
p_code_block->data = (OPJ_BYTE*) opj_malloc(OPJ_J2K_DEFAULT_CBLK_DATA_SIZE);
if (! p_code_block->data) {
return OPJ_FALSE;
}
p_code_block->data_max_size = OPJ_J2K_DEFAULT_CBLK_DATA_SIZE;
/*fprintf(stderr, "Allocate 8192 elements of code_block->data\n");*/
p_code_block->segs = (opj_tcd_seg_t *) opj_calloc(OPJ_J2K_DEFAULT_NB_SEGS,sizeof(opj_tcd_seg_t));
if (! p_code_block->segs) {
return OPJ_FALSE;
}
/*fprintf(stderr, "Allocate %d elements of code_block->data\n", OPJ_J2K_DEFAULT_NB_SEGS * sizeof(opj_tcd_seg_t));*/
p_code_block->m_current_max_segs = OPJ_J2K_DEFAULT_NB_SEGS;
/*fprintf(stderr, "m_current_max_segs of code_block->data = %d\n", p_code_block->m_current_max_segs);*/
} else {
/* sanitize */
OPJ_BYTE* l_data = p_code_block->data;
OPJ_UINT32 l_data_max_size = p_code_block->data_max_size;
opj_tcd_seg_t * l_segs = p_code_block->segs;
OPJ_UINT32 l_current_max_segs = p_code_block->m_current_max_segs;
memset(p_code_block, 0, sizeof(opj_tcd_cblk_dec_t));
p_code_block->data = l_data;
p_code_block->data_max_size = l_data_max_size;
p_code_block->segs = l_segs;
p_code_block->m_current_max_segs = l_current_max_segs;
}
return OPJ_TRUE;
}
OPJ_UINT32 opj_tcd_get_decoded_tile_size ( opj_tcd_t *p_tcd )
{
OPJ_UINT32 i;
OPJ_UINT32 l_data_size = 0;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_tilecomp_t * l_tile_comp = 00;
opj_tcd_resolution_t * l_res = 00;
OPJ_UINT32 l_size_comp, l_remaining;
l_tile_comp = p_tcd->tcd_image->tiles->comps;
l_img_comp = p_tcd->image->comps;
for (i=0;i<p_tcd->image->numcomps;++i) {
l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp->prec & 7; /* (%8) */
if(l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
l_res = l_tile_comp->resolutions + l_tile_comp->minimum_num_resolutions - 1;
l_data_size += l_size_comp * (OPJ_UINT32)((l_res->x1 - l_res->x0) * (l_res->y1 - l_res->y0));
++l_img_comp;
++l_tile_comp;
}
return l_data_size;
}
OPJ_BOOL opj_tcd_encode_tile( opj_tcd_t *p_tcd,
OPJ_UINT32 p_tile_no,
OPJ_BYTE *p_dest,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_max_length,
opj_codestream_info_t *p_cstr_info)
{
if (p_tcd->cur_tp_num == 0) {
p_tcd->tcd_tileno = p_tile_no;
p_tcd->tcp = &p_tcd->cp->tcps[p_tile_no];
/* INDEX >> "Precinct_nb_X et Precinct_nb_Y" */
if(p_cstr_info) {
OPJ_UINT32 l_num_packs = 0;
OPJ_UINT32 i;
opj_tcd_tilecomp_t *l_tilec_idx = &p_tcd->tcd_image->tiles->comps[0]; /* based on component 0 */
opj_tccp_t *l_tccp = p_tcd->tcp->tccps; /* based on component 0 */
for (i = 0; i < l_tilec_idx->numresolutions; i++) {
opj_tcd_resolution_t *l_res_idx = &l_tilec_idx->resolutions[i];
p_cstr_info->tile[p_tile_no].pw[i] = (int)l_res_idx->pw;
p_cstr_info->tile[p_tile_no].ph[i] = (int)l_res_idx->ph;
l_num_packs += l_res_idx->pw * l_res_idx->ph;
p_cstr_info->tile[p_tile_no].pdx[i] = (int)l_tccp->prcw[i];
p_cstr_info->tile[p_tile_no].pdy[i] = (int)l_tccp->prch[i];
}
p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t*) opj_calloc((size_t)p_cstr_info->numcomps * (size_t)p_cstr_info->numlayers * l_num_packs, sizeof(opj_packet_info_t));
if (!p_cstr_info->tile[p_tile_no].packet) {
/* FIXME event manager error callback */
return OPJ_FALSE;
}
}
/* << INDEX */
/* FIXME _ProfStart(PGROUP_DC_SHIFT); */
/*---------------TILE-------------------*/
if (! opj_tcd_dc_level_shift_encode(p_tcd)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_DC_SHIFT); */
/* FIXME _ProfStart(PGROUP_MCT); */
if (! opj_tcd_mct_encode(p_tcd)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_MCT); */
/* FIXME _ProfStart(PGROUP_DWT); */
if (! opj_tcd_dwt_encode(p_tcd)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_DWT); */
/* FIXME _ProfStart(PGROUP_T1); */
if (! opj_tcd_t1_encode(p_tcd)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_T1); */
/* FIXME _ProfStart(PGROUP_RATE); */
if (! opj_tcd_rate_allocate_encode(p_tcd,p_dest,p_max_length,p_cstr_info)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_RATE); */
}
/*--------------TIER2------------------*/
/* INDEX */
if (p_cstr_info) {
p_cstr_info->index_write = 1;
}
/* FIXME _ProfStart(PGROUP_T2); */
if (! opj_tcd_t2_encode(p_tcd,p_dest,p_data_written,p_max_length,p_cstr_info)) {
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_T2); */
/*---------------CLEAN-------------------*/
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_decode_tile( opj_tcd_t *p_tcd,
OPJ_BYTE *p_src,
OPJ_UINT32 p_max_length,
OPJ_UINT32 p_tile_no,
opj_codestream_index_t *p_cstr_index,
opj_event_mgr_t *p_manager
)
{
OPJ_UINT32 l_data_read;
p_tcd->tcd_tileno = p_tile_no;
p_tcd->tcp = &(p_tcd->cp->tcps[p_tile_no]);
#ifdef TODO_MSD /* FIXME */
/* INDEX >> */
if(p_cstr_info) {
OPJ_UINT32 resno, compno, numprec = 0;
for (compno = 0; compno < (OPJ_UINT32) p_cstr_info->numcomps; compno++) {
opj_tcp_t *tcp = &p_tcd->cp->tcps[0];
opj_tccp_t *tccp = &tcp->tccps[compno];
opj_tcd_tilecomp_t *tilec_idx = &p_tcd->tcd_image->tiles->comps[compno];
for (resno = 0; resno < tilec_idx->numresolutions; resno++) {
opj_tcd_resolution_t *res_idx = &tilec_idx->resolutions[resno];
p_cstr_info->tile[p_tile_no].pw[resno] = res_idx->pw;
p_cstr_info->tile[p_tile_no].ph[resno] = res_idx->ph;
numprec += res_idx->pw * res_idx->ph;
p_cstr_info->tile[p_tile_no].pdx[resno] = tccp->prcw[resno];
p_cstr_info->tile[p_tile_no].pdy[resno] = tccp->prch[resno];
}
}
p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t *) opj_malloc(p_cstr_info->numlayers * numprec * sizeof(opj_packet_info_t));
p_cstr_info->packno = 0;
}
/* << INDEX */
#endif
/*--------------TIER2------------------*/
/* FIXME _ProfStart(PGROUP_T2); */
l_data_read = 0;
if (! opj_tcd_t2_decode(p_tcd, p_src, &l_data_read, p_max_length, p_cstr_index, p_manager))
{
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_T2); */
/*------------------TIER1-----------------*/
/* FIXME _ProfStart(PGROUP_T1); */
if
(! opj_tcd_t1_decode(p_tcd))
{
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_T1); */
/*----------------DWT---------------------*/
/* FIXME _ProfStart(PGROUP_DWT); */
if
(! opj_tcd_dwt_decode(p_tcd))
{
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_DWT); */
/*----------------MCT-------------------*/
/* FIXME _ProfStart(PGROUP_MCT); */
if
(! opj_tcd_mct_decode(p_tcd, p_manager))
{
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_MCT); */
/* FIXME _ProfStart(PGROUP_DC_SHIFT); */
if
(! opj_tcd_dc_level_shift_decode(p_tcd))
{
return OPJ_FALSE;
}
/* FIXME _ProfStop(PGROUP_DC_SHIFT); */
/*---------------TILE-------------------*/
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_update_tile_data ( opj_tcd_t *p_tcd,
OPJ_BYTE * p_dest,
OPJ_UINT32 p_dest_length
)
{
OPJ_UINT32 i,j,k,l_data_size = 0;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_tilecomp_t * l_tilec = 00;
opj_tcd_resolution_t * l_res;
OPJ_UINT32 l_size_comp, l_remaining;
OPJ_UINT32 l_stride, l_width,l_height;
l_data_size = opj_tcd_get_decoded_tile_size(p_tcd);
if (l_data_size > p_dest_length) {
return OPJ_FALSE;
}
l_tilec = p_tcd->tcd_image->tiles->comps;
l_img_comp = p_tcd->image->comps;
for (i=0;i<p_tcd->image->numcomps;++i) {
l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp->prec & 7; /* (%8) */
l_res = l_tilec->resolutions + l_img_comp->resno_decoded;
l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0);
l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0);
l_stride = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0) - l_width;
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
switch (l_size_comp)
{
case 1:
{
OPJ_CHAR * l_dest_ptr = (OPJ_CHAR *) p_dest;
const OPJ_INT32 * l_src_ptr = l_tilec->data;
if (l_img_comp->sgnd) {
for (j=0;j<l_height;++j) {
for (k=0;k<l_width;++k) {
*(l_dest_ptr++) = (OPJ_CHAR) (*(l_src_ptr++));
}
l_src_ptr += l_stride;
}
}
else {
for (j=0;j<l_height;++j) {
for (k=0;k<l_width;++k) {
*(l_dest_ptr++) = (OPJ_CHAR) ((*(l_src_ptr++))&0xff);
}
l_src_ptr += l_stride;
}
}
p_dest = (OPJ_BYTE *)l_dest_ptr;
}
break;
case 2:
{
const OPJ_INT32 * l_src_ptr = l_tilec->data;
OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_dest;
if (l_img_comp->sgnd) {
for (j=0;j<l_height;++j) {
for (k=0;k<l_width;++k) {
*(l_dest_ptr++) = (OPJ_INT16) (*(l_src_ptr++));
}
l_src_ptr += l_stride;
}
}
else {
for (j=0;j<l_height;++j) {
for (k=0;k<l_width;++k) {
*(l_dest_ptr++) = (OPJ_INT16) ((*(l_src_ptr++))&0xffff);
}
l_src_ptr += l_stride;
}
}
p_dest = (OPJ_BYTE*) l_dest_ptr;
}
break;
case 4:
{
OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_dest;
OPJ_INT32 * l_src_ptr = l_tilec->data;
for (j=0;j<l_height;++j) {
for (k=0;k<l_width;++k) {
*(l_dest_ptr++) = (*(l_src_ptr++));
}
l_src_ptr += l_stride;
}
p_dest = (OPJ_BYTE*) l_dest_ptr;
}
break;
}
++l_img_comp;
++l_tilec;
}
return OPJ_TRUE;
}
static void opj_tcd_free_tile(opj_tcd_t *p_tcd)
{
OPJ_UINT32 compno, resno, bandno, precno;
opj_tcd_tile_t *l_tile = 00;
opj_tcd_tilecomp_t *l_tile_comp = 00;
opj_tcd_resolution_t *l_res = 00;
opj_tcd_band_t *l_band = 00;
opj_tcd_precinct_t *l_precinct = 00;
OPJ_UINT32 l_nb_resolutions, l_nb_precincts;
void (* l_tcd_code_block_deallocate) (opj_tcd_precinct_t *) = 00;
if (! p_tcd) {
return;
}
if (! p_tcd->tcd_image) {
return;
}
if (p_tcd->m_is_decoder) {
l_tcd_code_block_deallocate = opj_tcd_code_block_dec_deallocate;
}
else {
l_tcd_code_block_deallocate = opj_tcd_code_block_enc_deallocate;
}
l_tile = p_tcd->tcd_image->tiles;
if (! l_tile) {
return;
}
l_tile_comp = l_tile->comps;
for (compno = 0; compno < l_tile->numcomps; ++compno) {
l_res = l_tile_comp->resolutions;
if (l_res) {
l_nb_resolutions = l_tile_comp->resolutions_size / sizeof(opj_tcd_resolution_t);
for (resno = 0; resno < l_nb_resolutions; ++resno) {
l_band = l_res->bands;
for (bandno = 0; bandno < 3; ++bandno) {
l_precinct = l_band->precincts;
if (l_precinct) {
l_nb_precincts = l_band->precincts_data_size / sizeof(opj_tcd_precinct_t);
for (precno = 0; precno < l_nb_precincts; ++precno) {
opj_tgt_destroy(l_precinct->incltree);
l_precinct->incltree = 00;
opj_tgt_destroy(l_precinct->imsbtree);
l_precinct->imsbtree = 00;
(*l_tcd_code_block_deallocate) (l_precinct);
++l_precinct;
}
opj_free(l_band->precincts);
l_band->precincts = 00;
}
++l_band;
} /* for (resno */
++l_res;
}
opj_free(l_tile_comp->resolutions);
l_tile_comp->resolutions = 00;
}
if (l_tile_comp->ownsData && l_tile_comp->data) {
opj_aligned_free(l_tile_comp->data);
l_tile_comp->data = 00;
l_tile_comp->ownsData = 0;
l_tile_comp->data_size = 0;
l_tile_comp->data_size_needed = 0;
}
++l_tile_comp;
}
opj_free(l_tile->comps);
l_tile->comps = 00;
opj_free(p_tcd->tcd_image->tiles);
p_tcd->tcd_image->tiles = 00;
}
static OPJ_BOOL opj_tcd_t2_decode (opj_tcd_t *p_tcd,
OPJ_BYTE * p_src_data,
OPJ_UINT32 * p_data_read,
OPJ_UINT32 p_max_src_size,
opj_codestream_index_t *p_cstr_index,
opj_event_mgr_t *p_manager
)
{
opj_t2_t * l_t2;
l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp);
if (l_t2 == 00) {
return OPJ_FALSE;
}
if (! opj_t2_decode_packets(
l_t2,
p_tcd->tcd_tileno,
p_tcd->tcd_image->tiles,
p_src_data,
p_data_read,
p_max_src_size,
p_cstr_index,
p_manager)) {
opj_t2_destroy(l_t2);
return OPJ_FALSE;
}
opj_t2_destroy(l_t2);
/*---------------CLEAN-------------------*/
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_t1_decode ( opj_tcd_t *p_tcd )
{
OPJ_UINT32 compno;
opj_t1_t * l_t1;
opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
opj_tcd_tilecomp_t* l_tile_comp = l_tile->comps;
opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
l_t1 = opj_t1_create(OPJ_FALSE);
if (l_t1 == 00) {
return OPJ_FALSE;
}
for (compno = 0; compno < l_tile->numcomps; ++compno) {
/* The +3 is headroom required by the vectorized DWT */
if (OPJ_FALSE == opj_t1_decode_cblks(l_t1, l_tile_comp, l_tccp)) {
opj_t1_destroy(l_t1);
return OPJ_FALSE;
}
++l_tile_comp;
++l_tccp;
}
opj_t1_destroy(l_t1);
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_dwt_decode ( opj_tcd_t *p_tcd )
{
OPJ_UINT32 compno;
opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps;
opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
opj_image_comp_t * l_img_comp = p_tcd->image->comps;
for (compno = 0; compno < l_tile->numcomps; compno++) {
/*
if (tcd->cp->reduce != 0) {
tcd->image->comps[compno].resno_decoded =
tile->comps[compno].numresolutions - tcd->cp->reduce - 1;
if (tcd->image->comps[compno].resno_decoded < 0)
{
return false;
}
}
numres2decode = tcd->image->comps[compno].resno_decoded + 1;
if(numres2decode > 0){
*/
if (l_tccp->qmfbid == 1) {
if (! opj_dwt_decode(l_tile_comp, l_img_comp->resno_decoded+1)) {
return OPJ_FALSE;
}
}
else {
if (! opj_dwt_decode_real(l_tile_comp, l_img_comp->resno_decoded+1)) {
return OPJ_FALSE;
}
}
++l_tile_comp;
++l_img_comp;
++l_tccp;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_mct_decode ( opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager)
{
opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
opj_tcp_t * l_tcp = p_tcd->tcp;
opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps;
OPJ_UINT32 l_samples,i;
if (! l_tcp->mct) {
return OPJ_TRUE;
}
l_samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0));
if (l_tile->numcomps >= 3 ){
/* testcase 1336.pdf.asan.47.376 */
if ((l_tile->comps[0].x1 - l_tile->comps[0].x0) * (l_tile->comps[0].y1 - l_tile->comps[0].y0) < (OPJ_INT32)l_samples ||
(l_tile->comps[1].x1 - l_tile->comps[1].x0) * (l_tile->comps[1].y1 - l_tile->comps[1].y0) < (OPJ_INT32)l_samples ||
(l_tile->comps[2].x1 - l_tile->comps[2].x0) * (l_tile->comps[2].y1 - l_tile->comps[2].y0) < (OPJ_INT32)l_samples) {
opj_event_msg(p_manager, EVT_ERROR, "Tiles don't all have the same dimension. Skip the MCT step.\n");
return OPJ_FALSE;
}
else if (l_tcp->mct == 2) {
OPJ_BYTE ** l_data;
if (! l_tcp->m_mct_decoding_matrix) {
return OPJ_TRUE;
}
l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps*sizeof(OPJ_BYTE*));
if (! l_data) {
return OPJ_FALSE;
}
for (i=0;i<l_tile->numcomps;++i) {
l_data[i] = (OPJ_BYTE*) l_tile_comp->data;
++l_tile_comp;
}
if (! opj_mct_decode_custom(/* MCT data */
(OPJ_BYTE*) l_tcp->m_mct_decoding_matrix,
/* size of components */
l_samples,
/* components */
l_data,
/* nb of components (i.e. size of pData) */
l_tile->numcomps,
/* tells if the data is signed */
p_tcd->image->comps->sgnd)) {
opj_free(l_data);
return OPJ_FALSE;
}
opj_free(l_data);
}
else {
if (l_tcp->tccps->qmfbid == 1) {
opj_mct_decode( l_tile->comps[0].data,
l_tile->comps[1].data,
l_tile->comps[2].data,
l_samples);
}
else {
opj_mct_decode_real((OPJ_FLOAT32*)l_tile->comps[0].data,
(OPJ_FLOAT32*)l_tile->comps[1].data,
(OPJ_FLOAT32*)l_tile->comps[2].data,
l_samples);
}
}
}
else {
opj_event_msg(p_manager, EVT_ERROR, "Number of components (%d) is inconsistent with a MCT. Skip the MCT step.\n",l_tile->numcomps);
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_dc_level_shift_decode ( opj_tcd_t *p_tcd )
{
OPJ_UINT32 compno;
opj_tcd_tilecomp_t * l_tile_comp = 00;
opj_tccp_t * l_tccp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_resolution_t* l_res = 00;
opj_tcd_tile_t * l_tile;
OPJ_UINT32 l_width,l_height,i,j;
OPJ_INT32 * l_current_ptr;
OPJ_INT32 l_min, l_max;
OPJ_UINT32 l_stride;
l_tile = p_tcd->tcd_image->tiles;
l_tile_comp = l_tile->comps;
l_tccp = p_tcd->tcp->tccps;
l_img_comp = p_tcd->image->comps;
for (compno = 0; compno < l_tile->numcomps; compno++) {
l_res = l_tile_comp->resolutions + l_img_comp->resno_decoded;
l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0);
l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0);
l_stride = (OPJ_UINT32)(l_tile_comp->x1 - l_tile_comp->x0) - l_width;
assert(l_height == 0 || l_width + l_stride <= l_tile_comp->data_size / l_height); /*MUPDF*/
if (l_img_comp->sgnd) {
l_min = -(1 << (l_img_comp->prec - 1));
l_max = (1 << (l_img_comp->prec - 1)) - 1;
}
else {
l_min = 0;
l_max = (1 << l_img_comp->prec) - 1;
}
l_current_ptr = l_tile_comp->data;
if (l_tccp->qmfbid == 1) {
for (j=0;j<l_height;++j) {
for (i = 0; i < l_width; ++i) {
*l_current_ptr = opj_int_clamp(*l_current_ptr + l_tccp->m_dc_level_shift, l_min, l_max);
++l_current_ptr;
}
l_current_ptr += l_stride;
}
}
else {
for (j=0;j<l_height;++j) {
for (i = 0; i < l_width; ++i) {
OPJ_FLOAT32 l_value = *((OPJ_FLOAT32 *) l_current_ptr);
*l_current_ptr = opj_int_clamp((OPJ_INT32)opj_lrintf(l_value) + l_tccp->m_dc_level_shift, l_min, l_max); ;
++l_current_ptr;
}
l_current_ptr += l_stride;
}
}
++l_img_comp;
++l_tccp;
++l_tile_comp;
}
return OPJ_TRUE;
}
/**
* Deallocates the encoding data of the given precinct.
*/
static void opj_tcd_code_block_dec_deallocate (opj_tcd_precinct_t * p_precinct)
{
OPJ_UINT32 cblkno , l_nb_code_blocks;
opj_tcd_cblk_dec_t * l_code_block = p_precinct->cblks.dec;
if (l_code_block) {
/*fprintf(stderr,"deallocate codeblock:{\n");*/
/*fprintf(stderr,"\t x0=%d, y0=%d, x1=%d, y1=%d\n",l_code_block->x0, l_code_block->y0, l_code_block->x1, l_code_block->y1);*/
/*fprintf(stderr,"\t numbps=%d, numlenbits=%d, len=%d, numnewpasses=%d, real_num_segs=%d, m_current_max_segs=%d\n ",
l_code_block->numbps, l_code_block->numlenbits, l_code_block->len, l_code_block->numnewpasses, l_code_block->real_num_segs, l_code_block->m_current_max_segs );*/
l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_dec_t);
/*fprintf(stderr,"nb_code_blocks =%d\t}\n", l_nb_code_blocks);*/
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
if (l_code_block->data) {
opj_free(l_code_block->data);
l_code_block->data = 00;
}
if (l_code_block->segs) {
opj_free(l_code_block->segs );
l_code_block->segs = 00;
}
++l_code_block;
}
opj_free(p_precinct->cblks.dec);
p_precinct->cblks.dec = 00;
}
}
/**
* Deallocates the encoding data of the given precinct.
*/
static void opj_tcd_code_block_enc_deallocate (opj_tcd_precinct_t * p_precinct)
{
OPJ_UINT32 cblkno , l_nb_code_blocks;
opj_tcd_cblk_enc_t * l_code_block = p_precinct->cblks.enc;
if (l_code_block) {
l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_enc_t);
for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) {
if (l_code_block->data) {
opj_free(l_code_block->data - 1);
l_code_block->data = 00;
}
if (l_code_block->layers) {
opj_free(l_code_block->layers );
l_code_block->layers = 00;
}
if (l_code_block->passes) {
opj_free(l_code_block->passes );
l_code_block->passes = 00;
}
++l_code_block;
}
opj_free(p_precinct->cblks.enc);
p_precinct->cblks.enc = 00;
}
}
OPJ_UINT32 opj_tcd_get_encoded_tile_size ( opj_tcd_t *p_tcd )
{
OPJ_UINT32 i,l_data_size = 0;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_tilecomp_t * l_tilec = 00;
OPJ_UINT32 l_size_comp, l_remaining;
l_tilec = p_tcd->tcd_image->tiles->comps;
l_img_comp = p_tcd->image->comps;
for (i=0;i<p_tcd->image->numcomps;++i) {
l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp->prec & 7; /* (%8) */
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
l_data_size += l_size_comp * (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) * (l_tilec->y1 - l_tilec->y0));
++l_img_comp;
++l_tilec;
}
return l_data_size;
}
static OPJ_BOOL opj_tcd_dc_level_shift_encode ( opj_tcd_t *p_tcd )
{
OPJ_UINT32 compno;
opj_tcd_tilecomp_t * l_tile_comp = 00;
opj_tccp_t * l_tccp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_tile_t * l_tile;
OPJ_UINT32 l_nb_elem,i;
OPJ_INT32 * l_current_ptr;
l_tile = p_tcd->tcd_image->tiles;
l_tile_comp = l_tile->comps;
l_tccp = p_tcd->tcp->tccps;
l_img_comp = p_tcd->image->comps;
for (compno = 0; compno < l_tile->numcomps; compno++) {
l_current_ptr = l_tile_comp->data;
l_nb_elem = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0));
if (l_tccp->qmfbid == 1) {
for (i = 0; i < l_nb_elem; ++i) {
*l_current_ptr -= l_tccp->m_dc_level_shift ;
++l_current_ptr;
}
}
else {
for (i = 0; i < l_nb_elem; ++i) {
*l_current_ptr = (*l_current_ptr - l_tccp->m_dc_level_shift) * (1 << 11);
++l_current_ptr;
}
}
++l_img_comp;
++l_tccp;
++l_tile_comp;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_mct_encode ( opj_tcd_t *p_tcd )
{
opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps;
OPJ_UINT32 samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0));
OPJ_UINT32 i;
OPJ_BYTE ** l_data = 00;
opj_tcp_t * l_tcp = p_tcd->tcp;
if(!p_tcd->tcp->mct) {
return OPJ_TRUE;
}
if (p_tcd->tcp->mct == 2) {
if (! p_tcd->tcp->m_mct_coding_matrix) {
return OPJ_TRUE;
}
l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps*sizeof(OPJ_BYTE*));
if (! l_data) {
return OPJ_FALSE;
}
for (i=0;i<l_tile->numcomps;++i) {
l_data[i] = (OPJ_BYTE*) l_tile_comp->data;
++l_tile_comp;
}
if (! opj_mct_encode_custom(/* MCT data */
(OPJ_BYTE*) p_tcd->tcp->m_mct_coding_matrix,
/* size of components */
samples,
/* components */
l_data,
/* nb of components (i.e. size of pData) */
l_tile->numcomps,
/* tells if the data is signed */
p_tcd->image->comps->sgnd) )
{
opj_free(l_data);
return OPJ_FALSE;
}
opj_free(l_data);
}
else if (l_tcp->tccps->qmfbid == 0) {
opj_mct_encode_real(l_tile->comps[0].data, l_tile->comps[1].data, l_tile->comps[2].data, samples);
}
else {
opj_mct_encode(l_tile->comps[0].data, l_tile->comps[1].data, l_tile->comps[2].data, samples);
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_dwt_encode ( opj_tcd_t *p_tcd )
{
opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps;
opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
OPJ_UINT32 compno;
for (compno = 0; compno < l_tile->numcomps; ++compno) {
if (l_tccp->qmfbid == 1) {
if (! opj_dwt_encode(l_tile_comp)) {
return OPJ_FALSE;
}
}
else if (l_tccp->qmfbid == 0) {
if (! opj_dwt_encode_real(l_tile_comp)) {
return OPJ_FALSE;
}
}
++l_tile_comp;
++l_tccp;
}
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_t1_encode ( opj_tcd_t *p_tcd )
{
opj_t1_t * l_t1;
const OPJ_FLOAT64 * l_mct_norms;
OPJ_UINT32 l_mct_numcomps = 0U;
opj_tcp_t * l_tcp = p_tcd->tcp;
l_t1 = opj_t1_create(OPJ_TRUE);
if (l_t1 == 00) {
return OPJ_FALSE;
}
if (l_tcp->mct == 1) {
l_mct_numcomps = 3U;
/* irreversible encoding */
if (l_tcp->tccps->qmfbid == 0) {
l_mct_norms = opj_mct_get_mct_norms_real();
}
else {
l_mct_norms = opj_mct_get_mct_norms();
}
}
else {
l_mct_numcomps = p_tcd->image->numcomps;
l_mct_norms = (const OPJ_FLOAT64 *) (l_tcp->mct_norms);
}
if (! opj_t1_encode_cblks(l_t1, p_tcd->tcd_image->tiles , l_tcp, l_mct_norms, l_mct_numcomps)) {
opj_t1_destroy(l_t1);
return OPJ_FALSE;
}
opj_t1_destroy(l_t1);
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_t2_encode (opj_tcd_t *p_tcd,
OPJ_BYTE * p_dest_data,
OPJ_UINT32 * p_data_written,
OPJ_UINT32 p_max_dest_size,
opj_codestream_info_t *p_cstr_info )
{
opj_t2_t * l_t2;
l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp);
if (l_t2 == 00) {
return OPJ_FALSE;
}
if (! opj_t2_encode_packets(
l_t2,
p_tcd->tcd_tileno,
p_tcd->tcd_image->tiles,
p_tcd->tcp->numlayers,
p_dest_data,
p_data_written,
p_max_dest_size,
p_cstr_info,
p_tcd->tp_num,
p_tcd->tp_pos,
p_tcd->cur_pino,
FINAL_PASS))
{
opj_t2_destroy(l_t2);
return OPJ_FALSE;
}
opj_t2_destroy(l_t2);
/*---------------CLEAN-------------------*/
return OPJ_TRUE;
}
static OPJ_BOOL opj_tcd_rate_allocate_encode( opj_tcd_t *p_tcd,
OPJ_BYTE * p_dest_data,
OPJ_UINT32 p_max_dest_size,
opj_codestream_info_t *p_cstr_info )
{
opj_cp_t * l_cp = p_tcd->cp;
OPJ_UINT32 l_nb_written = 0;
if (p_cstr_info) {
p_cstr_info->index_write = 0;
}
if (l_cp->m_specific_param.m_enc.m_disto_alloc|| l_cp->m_specific_param.m_enc.m_fixed_quality) {
/* fixed_quality */
/* Normal Rate/distortion allocation */
if (! opj_tcd_rateallocate(p_tcd, p_dest_data,&l_nb_written, p_max_dest_size, p_cstr_info)) {
return OPJ_FALSE;
}
}
else {
/* Fixed layer allocation */
opj_tcd_rateallocate_fixed(p_tcd);
}
return OPJ_TRUE;
}
OPJ_BOOL opj_tcd_copy_tile_data ( opj_tcd_t *p_tcd,
OPJ_BYTE * p_src,
OPJ_UINT32 p_src_length )
{
OPJ_UINT32 i,j,l_data_size = 0;
opj_image_comp_t * l_img_comp = 00;
opj_tcd_tilecomp_t * l_tilec = 00;
OPJ_UINT32 l_size_comp, l_remaining;
OPJ_UINT32 l_nb_elem;
l_data_size = opj_tcd_get_encoded_tile_size(p_tcd);
if (l_data_size != p_src_length) {
return OPJ_FALSE;
}
l_tilec = p_tcd->tcd_image->tiles->comps;
l_img_comp = p_tcd->image->comps;
for (i=0;i<p_tcd->image->numcomps;++i) {
l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/
l_remaining = l_img_comp->prec & 7; /* (%8) */
l_nb_elem = (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) * (l_tilec->y1 - l_tilec->y0));
if (l_remaining) {
++l_size_comp;
}
if (l_size_comp == 3) {
l_size_comp = 4;
}
switch (l_size_comp) {
case 1:
{
OPJ_CHAR * l_src_ptr = (OPJ_CHAR *) p_src;
OPJ_INT32 * l_dest_ptr = l_tilec->data;
if (l_img_comp->sgnd) {
for (j=0;j<l_nb_elem;++j) {
*(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++));
}
}
else {
for (j=0;j<l_nb_elem;++j) {
*(l_dest_ptr++) = (*(l_src_ptr++))&0xff;
}
}
p_src = (OPJ_BYTE*) l_src_ptr;
}
break;
case 2:
{
OPJ_INT32 * l_dest_ptr = l_tilec->data;
OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_src;
if (l_img_comp->sgnd) {
for (j=0;j<l_nb_elem;++j) {
*(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++));
}
}
else {
for (j=0;j<l_nb_elem;++j) {
*(l_dest_ptr++) = (*(l_src_ptr++))&0xffff;
}
}
p_src = (OPJ_BYTE*) l_src_ptr;
}
break;
case 4:
{
OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_src;
OPJ_INT32 * l_dest_ptr = l_tilec->data;
for (j=0;j<l_nb_elem;++j) {
*(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++));
}
p_src = (OPJ_BYTE*) l_src_ptr;
}
break;
}
++l_img_comp;
++l_tilec;
}
return OPJ_TRUE;
}
| ./CrossVul/dataset_final_sorted/CWE-369/c/bad_5063_0 |
crossvul-cpp_data_good_4854_1 | /* $Id$ */
/* WARNING: The type of JPEG encapsulation defined by the TIFF Version 6.0
specification is now totally obsolete and deprecated for new applications and
images. This file was was created solely in order to read unconverted images
still present on some users' computer systems. It will never be extended
to write such files. Writing new-style JPEG compressed TIFFs is implemented
in tif_jpeg.c.
The code is carefully crafted to robustly read all gathered JPEG-in-TIFF
testfiles, and anticipate as much as possible all other... But still, it may
fail on some. If you encounter problems, please report them on the TIFF
mailing list and/or to Joris Van Damme <info@awaresystems.be>.
Please read the file called "TIFF Technical Note #2" if you need to be
convinced this compression scheme is bad and breaks TIFF. That document
is linked to from the LibTiff site <http://www.remotesensing.org/libtiff/>
and from AWare Systems' TIFF section
<http://www.awaresystems.be/imaging/tiff.html>. It is also absorbed
in Adobe's specification supplements, marked "draft" up to this day, but
supported by the TIFF community.
This file interfaces with Release 6B of the JPEG Library written by the
Independent JPEG Group. Previous versions of this file required a hack inside
the LibJpeg library. This version no longer requires that. Remember to
remove the hack if you update from the old version.
Copyright (c) Joris Van Damme <info@awaresystems.be>
Copyright (c) AWare Systems <http://www.awaresystems.be/>
The licence agreement for this file is the same as the rest of the LibTiff
library.
IN NO EVENT SHALL JORIS VAN DAMME OR AWARE SYSTEMS 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.
Joris Van Damme and/or AWare Systems may be available for custom
development. If you like what you see, and need anything similar or related,
contact <info@awaresystems.be>.
*/
/* What is what, and what is not?
This decoder starts with an input stream, that is essentially the JpegInterchangeFormat
stream, if any, followed by the strile data, if any. This stream is read in
OJPEGReadByte and related functions.
It analyzes the start of this stream, until it encounters non-marker data, i.e.
compressed image data. Some of the header markers it sees have no actual content,
like the SOI marker, and APP/COM markers that really shouldn't even be there. Some
other markers do have content, and the valuable bits and pieces of information
in these markers are saved, checking all to verify that the stream is more or
less within expected bounds. This happens inside the OJPEGReadHeaderInfoSecStreamXxx
functions.
Some OJPEG imagery contains no valid JPEG header markers. This situation is picked
up on if we've seen no SOF marker when we're at the start of the compressed image
data. In this case, the tables are read from JpegXxxTables tags, and the other
bits and pieces of information is initialized to its most basic value. This is
implemented in the OJPEGReadHeaderInfoSecTablesXxx functions.
When this is complete, a good and valid JPEG header can be assembled, and this is
passed through to LibJpeg. When that's done, the remainder of the input stream, i.e.
the compressed image data, can be passed through unchanged. This is done in
OJPEGWriteStream functions.
LibTiff rightly expects to know the subsampling values before decompression. Just like
in new-style JPEG-in-TIFF, though, or even more so, actually, the YCbCrsubsampling
tag is notoriously unreliable. To correct these tag values with the ones inside
the JPEG stream, the first part of the input stream is pre-scanned in
OJPEGSubsamplingCorrect, making no note of any other data, reporting no warnings
or errors, up to the point where either these values are read, or it's clear they
aren't there. This means that some of the data is read twice, but we feel speed
in correcting these values is important enough to warrant this sacrifice. Although
there is currently no define or other configuration mechanism to disable this behaviour,
the actual header scanning is build to robustly respond with error report if it
should encounter an uncorrected mismatch of subsampling values. See
OJPEGReadHeaderInfoSecStreamSof.
The restart interval and restart markers are the most tricky part... The restart
interval can be specified in a tag. It can also be set inside the input JPEG stream.
It can be used inside the input JPEG stream. If reading from strile data, we've
consistently discovered the need to insert restart markers in between the different
striles, as is also probably the most likely interpretation of the original TIFF 6.0
specification. With all this setting of interval, and actual use of markers that is not
predictable at the time of valid JPEG header assembly, the restart thing may turn
out the Achilles heel of this implementation. Fortunately, most OJPEG writer vendors
succeed in reading back what they write, which may be the reason why we've been able
to discover ways that seem to work.
Some special provision is made for planarconfig separate OJPEG files. These seem
to consistently contain header info, a SOS marker, a plane, SOS marker, plane, SOS,
and plane. This may or may not be a valid JPEG configuration, we don't know and don't
care. We want LibTiff to be able to access the planes individually, without huge
buffering inside LibJpeg, anyway. So we compose headers to feed to LibJpeg, in this
case, that allow us to pass a single plane such that LibJpeg sees a valid
single-channel JPEG stream. Locating subsequent SOS markers, and thus subsequent
planes, is done inside OJPEGReadSecondarySos.
The benefit of the scheme is... that it works, basically. We know of no other that
does. It works without checking software tag, or otherwise going about things in an
OJPEG flavor specific manner. Instead, it is a single scheme, that covers the cases
with and without JpegInterchangeFormat, with and without striles, with part of
the header in JpegInterchangeFormat and remainder in first strile, etc. It is forgiving
and robust, may likely work with OJPEG flavors we've not seen yet, and makes most out
of the data.
Another nice side-effect is that a complete JPEG single valid stream is build if
planarconfig is not separate (vast majority). We may one day use that to build
converters to JPEG, and/or to new-style JPEG compression inside TIFF.
A disadvantage is the lack of random access to the individual striles. This is the
reason for much of the complicated restart-and-position stuff inside OJPEGPreDecode.
Applications would do well accessing all striles in order, as this will result in
a single sequential scan of the input stream, and no restarting of LibJpeg decoding
session.
*/
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include "tiffiop.h"
#ifdef OJPEG_SUPPORT
/* Configuration defines here are:
* JPEG_ENCAP_EXTERNAL: The normal way to call libjpeg, uses longjump. In some environments,
* like eg LibTiffDelphi, this is not possible. For this reason, the actual calls to
* libjpeg, with longjump stuff, are encapsulated in dedicated functions. When
* JPEG_ENCAP_EXTERNAL is defined, these encapsulating functions are declared external
* to this unit, and can be defined elsewhere to use stuff other then longjump.
* The default mode, without JPEG_ENCAP_EXTERNAL, implements the call encapsulators
* here, internally, with normal longjump.
* SETJMP, LONGJMP, JMP_BUF: On some machines/environments a longjump equivalent is
* conveniently available, but still it may be worthwhile to use _setjmp or sigsetjmp
* in place of plain setjmp. These macros will make it easier. It is useless
* to fiddle with these if you define JPEG_ENCAP_EXTERNAL.
* OJPEG_BUFFER: Define the size of the desired buffer here. Should be small enough so as to guarantee
* instant processing, optimal streaming and optimal use of processor cache, but also big
* enough so as to not result in significant call overhead. It should be at least a few
* bytes to accommodate some structures (this is verified in asserts), but it would not be
* sensible to make it this small anyway, and it should be at most 64K since it is indexed
* with uint16. We recommend 2K.
* EGYPTIANWALK: You could also define EGYPTIANWALK here, but it is not used anywhere and has
* absolutely no effect. That is why most people insist the EGYPTIANWALK is a bit silly.
*/
/* define LIBJPEG_ENCAP_EXTERNAL */
#define SETJMP(jbuf) setjmp(jbuf)
#define LONGJMP(jbuf,code) longjmp(jbuf,code)
#define JMP_BUF jmp_buf
#define OJPEG_BUFFER 2048
/* define EGYPTIANWALK */
#define JPEG_MARKER_SOF0 0xC0
#define JPEG_MARKER_SOF1 0xC1
#define JPEG_MARKER_SOF3 0xC3
#define JPEG_MARKER_DHT 0xC4
#define JPEG_MARKER_RST0 0XD0
#define JPEG_MARKER_SOI 0xD8
#define JPEG_MARKER_EOI 0xD9
#define JPEG_MARKER_SOS 0xDA
#define JPEG_MARKER_DQT 0xDB
#define JPEG_MARKER_DRI 0xDD
#define JPEG_MARKER_APP0 0xE0
#define JPEG_MARKER_COM 0xFE
#define FIELD_OJPEG_JPEGINTERCHANGEFORMAT (FIELD_CODEC+0)
#define FIELD_OJPEG_JPEGINTERCHANGEFORMATLENGTH (FIELD_CODEC+1)
#define FIELD_OJPEG_JPEGQTABLES (FIELD_CODEC+2)
#define FIELD_OJPEG_JPEGDCTABLES (FIELD_CODEC+3)
#define FIELD_OJPEG_JPEGACTABLES (FIELD_CODEC+4)
#define FIELD_OJPEG_JPEGPROC (FIELD_CODEC+5)
#define FIELD_OJPEG_JPEGRESTARTINTERVAL (FIELD_CODEC+6)
static const TIFFField ojpegFields[] = {
{TIFFTAG_JPEGIFOFFSET,1,1,TIFF_LONG8,0,TIFF_SETGET_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGINTERCHANGEFORMAT,TRUE,FALSE,"JpegInterchangeFormat",NULL},
{TIFFTAG_JPEGIFBYTECOUNT,1,1,TIFF_LONG8,0,TIFF_SETGET_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGINTERCHANGEFORMATLENGTH,TRUE,FALSE,"JpegInterchangeFormatLength",NULL},
{TIFFTAG_JPEGQTABLES,TIFF_VARIABLE2,TIFF_VARIABLE2,TIFF_LONG8,0,TIFF_SETGET_C32_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGQTABLES,FALSE,TRUE,"JpegQTables",NULL},
{TIFFTAG_JPEGDCTABLES,TIFF_VARIABLE2,TIFF_VARIABLE2,TIFF_LONG8,0,TIFF_SETGET_C32_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGDCTABLES,FALSE,TRUE,"JpegDcTables",NULL},
{TIFFTAG_JPEGACTABLES,TIFF_VARIABLE2,TIFF_VARIABLE2,TIFF_LONG8,0,TIFF_SETGET_C32_UINT64,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGACTABLES,FALSE,TRUE,"JpegAcTables",NULL},
{TIFFTAG_JPEGPROC,1,1,TIFF_SHORT,0,TIFF_SETGET_UINT16,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGPROC,FALSE,FALSE,"JpegProc",NULL},
{TIFFTAG_JPEGRESTARTINTERVAL,1,1,TIFF_SHORT,0,TIFF_SETGET_UINT16,TIFF_SETGET_UNDEFINED,FIELD_OJPEG_JPEGRESTARTINTERVAL,FALSE,FALSE,"JpegRestartInterval",NULL},
};
#ifndef LIBJPEG_ENCAP_EXTERNAL
#include <setjmp.h>
#endif
/* We undefine FAR to avoid conflict with JPEG definition */
#ifdef FAR
#undef FAR
#endif
/*
Libjpeg's jmorecfg.h defines INT16 and INT32, but only if XMD_H is
not defined. Unfortunately, the MinGW and Borland compilers include
a typedef for INT32, which causes a conflict. MSVC does not include
a conflicting typedef given the headers which are included.
*/
#if defined(__BORLANDC__) || defined(__MINGW32__)
# define XMD_H 1
#endif
/* Define "boolean" as unsigned char, not int, per Windows custom. */
#if defined(__WIN32__) && !defined(__MINGW32__)
# ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
typedef unsigned char boolean;
# endif
# define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
#endif
#include "jpeglib.h"
#include "jerror.h"
typedef struct jpeg_error_mgr jpeg_error_mgr;
typedef struct jpeg_common_struct jpeg_common_struct;
typedef struct jpeg_decompress_struct jpeg_decompress_struct;
typedef struct jpeg_source_mgr jpeg_source_mgr;
typedef enum {
osibsNotSetYet,
osibsJpegInterchangeFormat,
osibsStrile,
osibsEof
} OJPEGStateInBufferSource;
typedef enum {
ososSoi,
ososQTable0,ososQTable1,ososQTable2,ososQTable3,
ososDcTable0,ososDcTable1,ososDcTable2,ososDcTable3,
ososAcTable0,ososAcTable1,ososAcTable2,ososAcTable3,
ososDri,
ososSof,
ososSos,
ososCompressed,
ososRst,
ososEoi
} OJPEGStateOutState;
typedef struct {
TIFF* tif;
int decoder_ok;
#ifndef LIBJPEG_ENCAP_EXTERNAL
JMP_BUF exit_jmpbuf;
#endif
TIFFVGetMethod vgetparent;
TIFFVSetMethod vsetparent;
TIFFPrintMethod printdir;
uint64 file_size;
uint32 image_width;
uint32 image_length;
uint32 strile_width;
uint32 strile_length;
uint32 strile_length_total;
uint8 samples_per_pixel;
uint8 plane_sample_offset;
uint8 samples_per_pixel_per_plane;
uint64 jpeg_interchange_format;
uint64 jpeg_interchange_format_length;
uint8 jpeg_proc;
uint8 subsamplingcorrect;
uint8 subsamplingcorrect_done;
uint8 subsampling_tag;
uint8 subsampling_hor;
uint8 subsampling_ver;
uint8 subsampling_force_desubsampling_inside_decompression;
uint8 qtable_offset_count;
uint8 dctable_offset_count;
uint8 actable_offset_count;
uint64 qtable_offset[3];
uint64 dctable_offset[3];
uint64 actable_offset[3];
uint8* qtable[4];
uint8* dctable[4];
uint8* actable[4];
uint16 restart_interval;
uint8 restart_index;
uint8 sof_log;
uint8 sof_marker_id;
uint32 sof_x;
uint32 sof_y;
uint8 sof_c[3];
uint8 sof_hv[3];
uint8 sof_tq[3];
uint8 sos_cs[3];
uint8 sos_tda[3];
struct {
uint8 log;
OJPEGStateInBufferSource in_buffer_source;
uint32 in_buffer_next_strile;
uint64 in_buffer_file_pos;
uint64 in_buffer_file_togo;
} sos_end[3];
uint8 readheader_done;
uint8 writeheader_done;
uint16 write_cursample;
uint32 write_curstrile;
uint8 libjpeg_session_active;
uint8 libjpeg_jpeg_query_style;
jpeg_error_mgr libjpeg_jpeg_error_mgr;
jpeg_decompress_struct libjpeg_jpeg_decompress_struct;
jpeg_source_mgr libjpeg_jpeg_source_mgr;
uint8 subsampling_convert_log;
uint32 subsampling_convert_ylinelen;
uint32 subsampling_convert_ylines;
uint32 subsampling_convert_clinelen;
uint32 subsampling_convert_clines;
uint32 subsampling_convert_ybuflen;
uint32 subsampling_convert_cbuflen;
uint32 subsampling_convert_ycbcrbuflen;
uint8* subsampling_convert_ycbcrbuf;
uint8* subsampling_convert_ybuf;
uint8* subsampling_convert_cbbuf;
uint8* subsampling_convert_crbuf;
uint32 subsampling_convert_ycbcrimagelen;
uint8** subsampling_convert_ycbcrimage;
uint32 subsampling_convert_clinelenout;
uint32 subsampling_convert_state;
uint32 bytes_per_line; /* if the codec outputs subsampled data, a 'line' in bytes_per_line */
uint32 lines_per_strile; /* and lines_per_strile means subsampling_ver desubsampled rows */
OJPEGStateInBufferSource in_buffer_source;
uint32 in_buffer_next_strile;
uint32 in_buffer_strile_count;
uint64 in_buffer_file_pos;
uint8 in_buffer_file_pos_log;
uint64 in_buffer_file_togo;
uint16 in_buffer_togo;
uint8* in_buffer_cur;
uint8 in_buffer[OJPEG_BUFFER];
OJPEGStateOutState out_state;
uint8 out_buffer[OJPEG_BUFFER];
uint8* skip_buffer;
} OJPEGState;
static int OJPEGVGetField(TIFF* tif, uint32 tag, va_list ap);
static int OJPEGVSetField(TIFF* tif, uint32 tag, va_list ap);
static void OJPEGPrintDir(TIFF* tif, FILE* fd, long flags);
static int OJPEGFixupTags(TIFF* tif);
static int OJPEGSetupDecode(TIFF* tif);
static int OJPEGPreDecode(TIFF* tif, uint16 s);
static int OJPEGPreDecodeSkipRaw(TIFF* tif);
static int OJPEGPreDecodeSkipScanlines(TIFF* tif);
static int OJPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
static int OJPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc);
static int OJPEGDecodeScanlines(TIFF* tif, uint8* buf, tmsize_t cc);
static void OJPEGPostDecode(TIFF* tif, uint8* buf, tmsize_t cc);
static int OJPEGSetupEncode(TIFF* tif);
static int OJPEGPreEncode(TIFF* tif, uint16 s);
static int OJPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s);
static int OJPEGPostEncode(TIFF* tif);
static void OJPEGCleanup(TIFF* tif);
static void OJPEGSubsamplingCorrect(TIFF* tif);
static int OJPEGReadHeaderInfo(TIFF* tif);
static int OJPEGReadSecondarySos(TIFF* tif, uint16 s);
static int OJPEGWriteHeaderInfo(TIFF* tif);
static void OJPEGLibjpegSessionAbort(TIFF* tif);
static int OJPEGReadHeaderInfoSec(TIFF* tif);
static int OJPEGReadHeaderInfoSecStreamDri(TIFF* tif);
static int OJPEGReadHeaderInfoSecStreamDqt(TIFF* tif);
static int OJPEGReadHeaderInfoSecStreamDht(TIFF* tif);
static int OJPEGReadHeaderInfoSecStreamSof(TIFF* tif, uint8 marker_id);
static int OJPEGReadHeaderInfoSecStreamSos(TIFF* tif);
static int OJPEGReadHeaderInfoSecTablesQTable(TIFF* tif);
static int OJPEGReadHeaderInfoSecTablesDcTable(TIFF* tif);
static int OJPEGReadHeaderInfoSecTablesAcTable(TIFF* tif);
static int OJPEGReadBufferFill(OJPEGState* sp);
static int OJPEGReadByte(OJPEGState* sp, uint8* byte);
static int OJPEGReadBytePeek(OJPEGState* sp, uint8* byte);
static void OJPEGReadByteAdvance(OJPEGState* sp);
static int OJPEGReadWord(OJPEGState* sp, uint16* word);
static int OJPEGReadBlock(OJPEGState* sp, uint16 len, void* mem);
static void OJPEGReadSkip(OJPEGState* sp, uint16 len);
static int OJPEGWriteStream(TIFF* tif, void** mem, uint32* len);
static void OJPEGWriteStreamSoi(TIFF* tif, void** mem, uint32* len);
static void OJPEGWriteStreamQTable(TIFF* tif, uint8 table_index, void** mem, uint32* len);
static void OJPEGWriteStreamDcTable(TIFF* tif, uint8 table_index, void** mem, uint32* len);
static void OJPEGWriteStreamAcTable(TIFF* tif, uint8 table_index, void** mem, uint32* len);
static void OJPEGWriteStreamDri(TIFF* tif, void** mem, uint32* len);
static void OJPEGWriteStreamSof(TIFF* tif, void** mem, uint32* len);
static void OJPEGWriteStreamSos(TIFF* tif, void** mem, uint32* len);
static int OJPEGWriteStreamCompressed(TIFF* tif, void** mem, uint32* len);
static void OJPEGWriteStreamRst(TIFF* tif, void** mem, uint32* len);
static void OJPEGWriteStreamEoi(TIFF* tif, void** mem, uint32* len);
#ifdef LIBJPEG_ENCAP_EXTERNAL
extern int jpeg_create_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo);
extern int jpeg_read_header_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, uint8 require_image);
extern int jpeg_start_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo);
extern int jpeg_read_scanlines_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* scanlines, uint32 max_lines);
extern int jpeg_read_raw_data_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* data, uint32 max_lines);
extern void jpeg_encap_unwind(TIFF* tif);
#else
static int jpeg_create_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* j);
static int jpeg_read_header_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, uint8 require_image);
static int jpeg_start_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo);
static int jpeg_read_scanlines_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* scanlines, uint32 max_lines);
static int jpeg_read_raw_data_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* data, uint32 max_lines);
static void jpeg_encap_unwind(TIFF* tif);
#endif
static void OJPEGLibjpegJpegErrorMgrOutputMessage(jpeg_common_struct* cinfo);
static void OJPEGLibjpegJpegErrorMgrErrorExit(jpeg_common_struct* cinfo);
static void OJPEGLibjpegJpegSourceMgrInitSource(jpeg_decompress_struct* cinfo);
static boolean OJPEGLibjpegJpegSourceMgrFillInputBuffer(jpeg_decompress_struct* cinfo);
static void OJPEGLibjpegJpegSourceMgrSkipInputData(jpeg_decompress_struct* cinfo, long num_bytes);
static boolean OJPEGLibjpegJpegSourceMgrResyncToRestart(jpeg_decompress_struct* cinfo, int desired);
static void OJPEGLibjpegJpegSourceMgrTermSource(jpeg_decompress_struct* cinfo);
int
TIFFInitOJPEG(TIFF* tif, int scheme)
{
static const char module[]="TIFFInitOJPEG";
OJPEGState* sp;
assert(scheme==COMPRESSION_OJPEG);
/*
* Merge codec-specific tag information.
*/
if (!_TIFFMergeFields(tif, ojpegFields, TIFFArrayCount(ojpegFields))) {
TIFFErrorExt(tif->tif_clientdata, module,
"Merging Old JPEG codec-specific tags failed");
return 0;
}
/* state block */
sp=_TIFFmalloc(sizeof(OJPEGState));
if (sp==NULL)
{
TIFFErrorExt(tif->tif_clientdata,module,"No space for OJPEG state block");
return(0);
}
_TIFFmemset(sp,0,sizeof(OJPEGState));
sp->tif=tif;
sp->jpeg_proc=1;
sp->subsampling_hor=2;
sp->subsampling_ver=2;
TIFFSetField(tif,TIFFTAG_YCBCRSUBSAMPLING,2,2);
/* tif codec methods */
tif->tif_fixuptags=OJPEGFixupTags;
tif->tif_setupdecode=OJPEGSetupDecode;
tif->tif_predecode=OJPEGPreDecode;
tif->tif_postdecode=OJPEGPostDecode;
tif->tif_decoderow=OJPEGDecode;
tif->tif_decodestrip=OJPEGDecode;
tif->tif_decodetile=OJPEGDecode;
tif->tif_setupencode=OJPEGSetupEncode;
tif->tif_preencode=OJPEGPreEncode;
tif->tif_postencode=OJPEGPostEncode;
tif->tif_encoderow=OJPEGEncode;
tif->tif_encodestrip=OJPEGEncode;
tif->tif_encodetile=OJPEGEncode;
tif->tif_cleanup=OJPEGCleanup;
tif->tif_data=(uint8*)sp;
/* tif tag methods */
sp->vgetparent=tif->tif_tagmethods.vgetfield;
tif->tif_tagmethods.vgetfield=OJPEGVGetField;
sp->vsetparent=tif->tif_tagmethods.vsetfield;
tif->tif_tagmethods.vsetfield=OJPEGVSetField;
sp->printdir=tif->tif_tagmethods.printdir;
tif->tif_tagmethods.printdir=OJPEGPrintDir;
/* Some OJPEG files don't have strip or tile offsets or bytecounts tags.
Some others do, but have totally meaningless or corrupt values
in these tags. In these cases, the JpegInterchangeFormat stream is
reliable. In any case, this decoder reads the compressed data itself,
from the most reliable locations, and we need to notify encapsulating
LibTiff not to read raw strips or tiles for us. */
tif->tif_flags|=TIFF_NOREADRAW;
return(1);
}
static int
OJPEGVGetField(TIFF* tif, uint32 tag, va_list ap)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
switch(tag)
{
case TIFFTAG_JPEGIFOFFSET:
*va_arg(ap,uint64*)=(uint64)sp->jpeg_interchange_format;
break;
case TIFFTAG_JPEGIFBYTECOUNT:
*va_arg(ap,uint64*)=(uint64)sp->jpeg_interchange_format_length;
break;
case TIFFTAG_YCBCRSUBSAMPLING:
if (sp->subsamplingcorrect_done==0)
OJPEGSubsamplingCorrect(tif);
*va_arg(ap,uint16*)=(uint16)sp->subsampling_hor;
*va_arg(ap,uint16*)=(uint16)sp->subsampling_ver;
break;
case TIFFTAG_JPEGQTABLES:
*va_arg(ap,uint32*)=(uint32)sp->qtable_offset_count;
*va_arg(ap,void**)=(void*)sp->qtable_offset;
break;
case TIFFTAG_JPEGDCTABLES:
*va_arg(ap,uint32*)=(uint32)sp->dctable_offset_count;
*va_arg(ap,void**)=(void*)sp->dctable_offset;
break;
case TIFFTAG_JPEGACTABLES:
*va_arg(ap,uint32*)=(uint32)sp->actable_offset_count;
*va_arg(ap,void**)=(void*)sp->actable_offset;
break;
case TIFFTAG_JPEGPROC:
*va_arg(ap,uint16*)=(uint16)sp->jpeg_proc;
break;
case TIFFTAG_JPEGRESTARTINTERVAL:
*va_arg(ap,uint16*)=sp->restart_interval;
break;
default:
return (*sp->vgetparent)(tif,tag,ap);
}
return (1);
}
static int
OJPEGVSetField(TIFF* tif, uint32 tag, va_list ap)
{
static const char module[]="OJPEGVSetField";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint32 ma;
uint64* mb;
uint32 n;
const TIFFField* fip;
switch(tag)
{
case TIFFTAG_JPEGIFOFFSET:
sp->jpeg_interchange_format=(uint64)va_arg(ap,uint64);
break;
case TIFFTAG_JPEGIFBYTECOUNT:
sp->jpeg_interchange_format_length=(uint64)va_arg(ap,uint64);
break;
case TIFFTAG_YCBCRSUBSAMPLING:
sp->subsampling_tag=1;
sp->subsampling_hor=(uint8)va_arg(ap,uint16_vap);
sp->subsampling_ver=(uint8)va_arg(ap,uint16_vap);
tif->tif_dir.td_ycbcrsubsampling[0]=sp->subsampling_hor;
tif->tif_dir.td_ycbcrsubsampling[1]=sp->subsampling_ver;
break;
case TIFFTAG_JPEGQTABLES:
ma=(uint32)va_arg(ap,uint32);
if (ma!=0)
{
if (ma>3)
{
TIFFErrorExt(tif->tif_clientdata,module,"JpegQTables tag has incorrect count");
return(0);
}
sp->qtable_offset_count=(uint8)ma;
mb=(uint64*)va_arg(ap,uint64*);
for (n=0; n<ma; n++)
sp->qtable_offset[n]=mb[n];
}
break;
case TIFFTAG_JPEGDCTABLES:
ma=(uint32)va_arg(ap,uint32);
if (ma!=0)
{
if (ma>3)
{
TIFFErrorExt(tif->tif_clientdata,module,"JpegDcTables tag has incorrect count");
return(0);
}
sp->dctable_offset_count=(uint8)ma;
mb=(uint64*)va_arg(ap,uint64*);
for (n=0; n<ma; n++)
sp->dctable_offset[n]=mb[n];
}
break;
case TIFFTAG_JPEGACTABLES:
ma=(uint32)va_arg(ap,uint32);
if (ma!=0)
{
if (ma>3)
{
TIFFErrorExt(tif->tif_clientdata,module,"JpegAcTables tag has incorrect count");
return(0);
}
sp->actable_offset_count=(uint8)ma;
mb=(uint64*)va_arg(ap,uint64*);
for (n=0; n<ma; n++)
sp->actable_offset[n]=mb[n];
}
break;
case TIFFTAG_JPEGPROC:
sp->jpeg_proc=(uint8)va_arg(ap,uint16_vap);
break;
case TIFFTAG_JPEGRESTARTINTERVAL:
sp->restart_interval=(uint16)va_arg(ap,uint16_vap);
break;
default:
return (*sp->vsetparent)(tif,tag,ap);
}
fip = TIFFFieldWithTag(tif,tag);
if( fip == NULL ) /* shouldn't happen */
return(0);
TIFFSetFieldBit(tif,fip->field_bit);
tif->tif_flags|=TIFF_DIRTYDIRECT;
return(1);
}
static void
OJPEGPrintDir(TIFF* tif, FILE* fd, long flags)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint8 m;
(void)flags;
assert(sp!=NULL);
if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGINTERCHANGEFORMAT))
fprintf(fd," JpegInterchangeFormat: " TIFF_UINT64_FORMAT "\n",(TIFF_UINT64_T)sp->jpeg_interchange_format);
if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGINTERCHANGEFORMATLENGTH))
fprintf(fd," JpegInterchangeFormatLength: " TIFF_UINT64_FORMAT "\n",(TIFF_UINT64_T)sp->jpeg_interchange_format_length);
if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGQTABLES))
{
fprintf(fd," JpegQTables:");
for (m=0; m<sp->qtable_offset_count; m++)
fprintf(fd," " TIFF_UINT64_FORMAT,(TIFF_UINT64_T)sp->qtable_offset[m]);
fprintf(fd,"\n");
}
if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGDCTABLES))
{
fprintf(fd," JpegDcTables:");
for (m=0; m<sp->dctable_offset_count; m++)
fprintf(fd," " TIFF_UINT64_FORMAT,(TIFF_UINT64_T)sp->dctable_offset[m]);
fprintf(fd,"\n");
}
if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGACTABLES))
{
fprintf(fd," JpegAcTables:");
for (m=0; m<sp->actable_offset_count; m++)
fprintf(fd," " TIFF_UINT64_FORMAT,(TIFF_UINT64_T)sp->actable_offset[m]);
fprintf(fd,"\n");
}
if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGPROC))
fprintf(fd," JpegProc: %u\n",(unsigned int)sp->jpeg_proc);
if (TIFFFieldSet(tif,FIELD_OJPEG_JPEGRESTARTINTERVAL))
fprintf(fd," JpegRestartInterval: %u\n",(unsigned int)sp->restart_interval);
if (sp->printdir)
(*sp->printdir)(tif, fd, flags);
}
static int
OJPEGFixupTags(TIFF* tif)
{
(void) tif;
return(1);
}
static int
OJPEGSetupDecode(TIFF* tif)
{
static const char module[]="OJPEGSetupDecode";
TIFFWarningExt(tif->tif_clientdata,module,"Depreciated and troublesome old-style JPEG compression mode, please convert to new-style JPEG compression and notify vendor of writing software");
return(1);
}
static int
OJPEGPreDecode(TIFF* tif, uint16 s)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint32 m;
if (sp->subsamplingcorrect_done==0)
OJPEGSubsamplingCorrect(tif);
if (sp->readheader_done==0)
{
if (OJPEGReadHeaderInfo(tif)==0)
return(0);
}
if (sp->sos_end[s].log==0)
{
if (OJPEGReadSecondarySos(tif,s)==0)
return(0);
}
if isTiled(tif)
m=tif->tif_curtile;
else
m=tif->tif_curstrip;
if ((sp->writeheader_done!=0) && ((sp->write_cursample!=s) || (sp->write_curstrile>m)))
{
if (sp->libjpeg_session_active!=0)
OJPEGLibjpegSessionAbort(tif);
sp->writeheader_done=0;
}
if (sp->writeheader_done==0)
{
sp->plane_sample_offset=(uint8)s;
sp->write_cursample=s;
sp->write_curstrile=s*tif->tif_dir.td_stripsperimage;
if ((sp->in_buffer_file_pos_log==0) ||
(sp->in_buffer_file_pos-sp->in_buffer_togo!=sp->sos_end[s].in_buffer_file_pos))
{
sp->in_buffer_source=sp->sos_end[s].in_buffer_source;
sp->in_buffer_next_strile=sp->sos_end[s].in_buffer_next_strile;
sp->in_buffer_file_pos=sp->sos_end[s].in_buffer_file_pos;
sp->in_buffer_file_pos_log=0;
sp->in_buffer_file_togo=sp->sos_end[s].in_buffer_file_togo;
sp->in_buffer_togo=0;
sp->in_buffer_cur=0;
}
if (OJPEGWriteHeaderInfo(tif)==0)
return(0);
}
while (sp->write_curstrile<m)
{
if (sp->libjpeg_jpeg_query_style==0)
{
if (OJPEGPreDecodeSkipRaw(tif)==0)
return(0);
}
else
{
if (OJPEGPreDecodeSkipScanlines(tif)==0)
return(0);
}
sp->write_curstrile++;
}
sp->decoder_ok = 1;
return(1);
}
static int
OJPEGPreDecodeSkipRaw(TIFF* tif)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint32 m;
m=sp->lines_per_strile;
if (sp->subsampling_convert_state!=0)
{
if (sp->subsampling_convert_clines-sp->subsampling_convert_state>=m)
{
sp->subsampling_convert_state+=m;
if (sp->subsampling_convert_state==sp->subsampling_convert_clines)
sp->subsampling_convert_state=0;
return(1);
}
m-=sp->subsampling_convert_clines-sp->subsampling_convert_state;
sp->subsampling_convert_state=0;
}
while (m>=sp->subsampling_convert_clines)
{
if (jpeg_read_raw_data_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),sp->subsampling_convert_ycbcrimage,sp->subsampling_ver*8)==0)
return(0);
m-=sp->subsampling_convert_clines;
}
if (m>0)
{
if (jpeg_read_raw_data_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),sp->subsampling_convert_ycbcrimage,sp->subsampling_ver*8)==0)
return(0);
sp->subsampling_convert_state=m;
}
return(1);
}
static int
OJPEGPreDecodeSkipScanlines(TIFF* tif)
{
static const char module[]="OJPEGPreDecodeSkipScanlines";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint32 m;
if (sp->skip_buffer==NULL)
{
sp->skip_buffer=_TIFFmalloc(sp->bytes_per_line);
if (sp->skip_buffer==NULL)
{
TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
return(0);
}
}
for (m=0; m<sp->lines_per_strile; m++)
{
if (jpeg_read_scanlines_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),&sp->skip_buffer,1)==0)
return(0);
}
return(1);
}
static int
OJPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
{
static const char module[]="OJPEGDecode";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
(void)s;
if( !sp->decoder_ok )
{
TIFFErrorExt(tif->tif_clientdata,module,"Cannot decode: decoder not correctly initialized");
return 0;
}
if (sp->libjpeg_jpeg_query_style==0)
{
if (OJPEGDecodeRaw(tif,buf,cc)==0)
return(0);
}
else
{
if (OJPEGDecodeScanlines(tif,buf,cc)==0)
return(0);
}
return(1);
}
static int
OJPEGDecodeRaw(TIFF* tif, uint8* buf, tmsize_t cc)
{
static const char module[]="OJPEGDecodeRaw";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint8* m;
tmsize_t n;
uint8* oy;
uint8* ocb;
uint8* ocr;
uint8* p;
uint32 q;
uint8* r;
uint8 sx,sy;
if (cc%sp->bytes_per_line!=0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Fractional scanline not read");
return(0);
}
assert(cc>0);
m=buf;
n=cc;
do
{
if (sp->subsampling_convert_state==0)
{
if (jpeg_read_raw_data_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),sp->subsampling_convert_ycbcrimage,sp->subsampling_ver*8)==0)
return(0);
}
oy=sp->subsampling_convert_ybuf+sp->subsampling_convert_state*sp->subsampling_ver*sp->subsampling_convert_ylinelen;
ocb=sp->subsampling_convert_cbbuf+sp->subsampling_convert_state*sp->subsampling_convert_clinelen;
ocr=sp->subsampling_convert_crbuf+sp->subsampling_convert_state*sp->subsampling_convert_clinelen;
p=m;
for (q=0; q<sp->subsampling_convert_clinelenout; q++)
{
r=oy;
for (sy=0; sy<sp->subsampling_ver; sy++)
{
for (sx=0; sx<sp->subsampling_hor; sx++)
*p++=*r++;
r+=sp->subsampling_convert_ylinelen-sp->subsampling_hor;
}
oy+=sp->subsampling_hor;
*p++=*ocb++;
*p++=*ocr++;
}
sp->subsampling_convert_state++;
if (sp->subsampling_convert_state==sp->subsampling_convert_clines)
sp->subsampling_convert_state=0;
m+=sp->bytes_per_line;
n-=sp->bytes_per_line;
} while(n>0);
return(1);
}
static int
OJPEGDecodeScanlines(TIFF* tif, uint8* buf, tmsize_t cc)
{
static const char module[]="OJPEGDecodeScanlines";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint8* m;
tmsize_t n;
if (cc%sp->bytes_per_line!=0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Fractional scanline not read");
return(0);
}
assert(cc>0);
m=buf;
n=cc;
do
{
if (jpeg_read_scanlines_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),&m,1)==0)
return(0);
m+=sp->bytes_per_line;
n-=sp->bytes_per_line;
} while(n>0);
return(1);
}
static void
OJPEGPostDecode(TIFF* tif, uint8* buf, tmsize_t cc)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
(void)buf;
(void)cc;
sp->write_curstrile++;
if (sp->write_curstrile%tif->tif_dir.td_stripsperimage==0)
{
assert(sp->libjpeg_session_active!=0);
OJPEGLibjpegSessionAbort(tif);
sp->writeheader_done=0;
}
}
static int
OJPEGSetupEncode(TIFF* tif)
{
static const char module[]="OJPEGSetupEncode";
TIFFErrorExt(tif->tif_clientdata,module,"OJPEG encoding not supported; use new-style JPEG compression instead");
return(0);
}
static int
OJPEGPreEncode(TIFF* tif, uint16 s)
{
static const char module[]="OJPEGPreEncode";
(void)s;
TIFFErrorExt(tif->tif_clientdata,module,"OJPEG encoding not supported; use new-style JPEG compression instead");
return(0);
}
static int
OJPEGEncode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
{
static const char module[]="OJPEGEncode";
(void)buf;
(void)cc;
(void)s;
TIFFErrorExt(tif->tif_clientdata,module,"OJPEG encoding not supported; use new-style JPEG compression instead");
return(0);
}
static int
OJPEGPostEncode(TIFF* tif)
{
static const char module[]="OJPEGPostEncode";
TIFFErrorExt(tif->tif_clientdata,module,"OJPEG encoding not supported; use new-style JPEG compression instead");
return(0);
}
static void
OJPEGCleanup(TIFF* tif)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
if (sp!=0)
{
tif->tif_tagmethods.vgetfield=sp->vgetparent;
tif->tif_tagmethods.vsetfield=sp->vsetparent;
tif->tif_tagmethods.printdir=sp->printdir;
if (sp->qtable[0]!=0)
_TIFFfree(sp->qtable[0]);
if (sp->qtable[1]!=0)
_TIFFfree(sp->qtable[1]);
if (sp->qtable[2]!=0)
_TIFFfree(sp->qtable[2]);
if (sp->qtable[3]!=0)
_TIFFfree(sp->qtable[3]);
if (sp->dctable[0]!=0)
_TIFFfree(sp->dctable[0]);
if (sp->dctable[1]!=0)
_TIFFfree(sp->dctable[1]);
if (sp->dctable[2]!=0)
_TIFFfree(sp->dctable[2]);
if (sp->dctable[3]!=0)
_TIFFfree(sp->dctable[3]);
if (sp->actable[0]!=0)
_TIFFfree(sp->actable[0]);
if (sp->actable[1]!=0)
_TIFFfree(sp->actable[1]);
if (sp->actable[2]!=0)
_TIFFfree(sp->actable[2]);
if (sp->actable[3]!=0)
_TIFFfree(sp->actable[3]);
if (sp->libjpeg_session_active!=0)
OJPEGLibjpegSessionAbort(tif);
if (sp->subsampling_convert_ycbcrbuf!=0)
_TIFFfree(sp->subsampling_convert_ycbcrbuf);
if (sp->subsampling_convert_ycbcrimage!=0)
_TIFFfree(sp->subsampling_convert_ycbcrimage);
if (sp->skip_buffer!=0)
_TIFFfree(sp->skip_buffer);
_TIFFfree(sp);
tif->tif_data=NULL;
_TIFFSetDefaultCompressionState(tif);
}
}
static void
OJPEGSubsamplingCorrect(TIFF* tif)
{
static const char module[]="OJPEGSubsamplingCorrect";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint8 mh;
uint8 mv;
_TIFFFillStriles( tif );
assert(sp->subsamplingcorrect_done==0);
if ((tif->tif_dir.td_samplesperpixel!=3) || ((tif->tif_dir.td_photometric!=PHOTOMETRIC_YCBCR) &&
(tif->tif_dir.td_photometric!=PHOTOMETRIC_ITULAB)))
{
if (sp->subsampling_tag!=0)
TIFFWarningExt(tif->tif_clientdata,module,"Subsampling tag not appropriate for this Photometric and/or SamplesPerPixel");
sp->subsampling_hor=1;
sp->subsampling_ver=1;
sp->subsampling_force_desubsampling_inside_decompression=0;
}
else
{
sp->subsamplingcorrect_done=1;
mh=sp->subsampling_hor;
mv=sp->subsampling_ver;
sp->subsamplingcorrect=1;
OJPEGReadHeaderInfoSec(tif);
if (sp->subsampling_force_desubsampling_inside_decompression!=0)
{
sp->subsampling_hor=1;
sp->subsampling_ver=1;
}
sp->subsamplingcorrect=0;
if (((sp->subsampling_hor!=mh) || (sp->subsampling_ver!=mv)) && (sp->subsampling_force_desubsampling_inside_decompression==0))
{
if (sp->subsampling_tag==0)
TIFFWarningExt(tif->tif_clientdata,module,"Subsampling tag is not set, yet subsampling inside JPEG data [%d,%d] does not match default values [2,2]; assuming subsampling inside JPEG data is correct",sp->subsampling_hor,sp->subsampling_ver);
else
TIFFWarningExt(tif->tif_clientdata,module,"Subsampling inside JPEG data [%d,%d] does not match subsampling tag values [%d,%d]; assuming subsampling inside JPEG data is correct",sp->subsampling_hor,sp->subsampling_ver,mh,mv);
}
if (sp->subsampling_force_desubsampling_inside_decompression!=0)
{
if (sp->subsampling_tag==0)
TIFFWarningExt(tif->tif_clientdata,module,"Subsampling tag is not set, yet subsampling inside JPEG data does not match default values [2,2] (nor any other values allowed in TIFF); assuming subsampling inside JPEG data is correct and desubsampling inside JPEG decompression");
else
TIFFWarningExt(tif->tif_clientdata,module,"Subsampling inside JPEG data does not match subsampling tag values [%d,%d] (nor any other values allowed in TIFF); assuming subsampling inside JPEG data is correct and desubsampling inside JPEG decompression",mh,mv);
}
if (sp->subsampling_force_desubsampling_inside_decompression==0)
{
if (sp->subsampling_hor<sp->subsampling_ver)
TIFFWarningExt(tif->tif_clientdata,module,"Subsampling values [%d,%d] are not allowed in TIFF",sp->subsampling_hor,sp->subsampling_ver);
}
}
sp->subsamplingcorrect_done=1;
}
static int
OJPEGReadHeaderInfo(TIFF* tif)
{
static const char module[]="OJPEGReadHeaderInfo";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
assert(sp->readheader_done==0);
sp->image_width=tif->tif_dir.td_imagewidth;
sp->image_length=tif->tif_dir.td_imagelength;
if isTiled(tif)
{
sp->strile_width=tif->tif_dir.td_tilewidth;
sp->strile_length=tif->tif_dir.td_tilelength;
sp->strile_length_total=((sp->image_length+sp->strile_length-1)/sp->strile_length)*sp->strile_length;
}
else
{
sp->strile_width=sp->image_width;
sp->strile_length=tif->tif_dir.td_rowsperstrip;
sp->strile_length_total=sp->image_length;
}
if (tif->tif_dir.td_samplesperpixel==1)
{
sp->samples_per_pixel=1;
sp->plane_sample_offset=0;
sp->samples_per_pixel_per_plane=sp->samples_per_pixel;
sp->subsampling_hor=1;
sp->subsampling_ver=1;
}
else
{
if (tif->tif_dir.td_samplesperpixel!=3)
{
TIFFErrorExt(tif->tif_clientdata,module,"SamplesPerPixel %d not supported for this compression scheme",sp->samples_per_pixel);
return(0);
}
sp->samples_per_pixel=3;
sp->plane_sample_offset=0;
if (tif->tif_dir.td_planarconfig==PLANARCONFIG_CONTIG)
sp->samples_per_pixel_per_plane=3;
else
sp->samples_per_pixel_per_plane=1;
}
if (sp->strile_length<sp->image_length)
{
if (sp->strile_length%(sp->subsampling_ver*8)!=0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Incompatible vertical subsampling and image strip/tile length");
return(0);
}
sp->restart_interval=(uint16)(((sp->strile_width+sp->subsampling_hor*8-1)/(sp->subsampling_hor*8))*(sp->strile_length/(sp->subsampling_ver*8)));
}
if (OJPEGReadHeaderInfoSec(tif)==0)
return(0);
sp->sos_end[0].log=1;
sp->sos_end[0].in_buffer_source=sp->in_buffer_source;
sp->sos_end[0].in_buffer_next_strile=sp->in_buffer_next_strile;
sp->sos_end[0].in_buffer_file_pos=sp->in_buffer_file_pos-sp->in_buffer_togo;
sp->sos_end[0].in_buffer_file_togo=sp->in_buffer_file_togo+sp->in_buffer_togo;
sp->readheader_done=1;
return(1);
}
static int
OJPEGReadSecondarySos(TIFF* tif, uint16 s)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint8 m;
assert(s>0);
assert(s<3);
assert(sp->sos_end[0].log!=0);
assert(sp->sos_end[s].log==0);
sp->plane_sample_offset=(uint8)(s-1);
while(sp->sos_end[sp->plane_sample_offset].log==0)
sp->plane_sample_offset--;
sp->in_buffer_source=sp->sos_end[sp->plane_sample_offset].in_buffer_source;
sp->in_buffer_next_strile=sp->sos_end[sp->plane_sample_offset].in_buffer_next_strile;
sp->in_buffer_file_pos=sp->sos_end[sp->plane_sample_offset].in_buffer_file_pos;
sp->in_buffer_file_pos_log=0;
sp->in_buffer_file_togo=sp->sos_end[sp->plane_sample_offset].in_buffer_file_togo;
sp->in_buffer_togo=0;
sp->in_buffer_cur=0;
while(sp->plane_sample_offset<s)
{
do
{
if (OJPEGReadByte(sp,&m)==0)
return(0);
if (m==255)
{
do
{
if (OJPEGReadByte(sp,&m)==0)
return(0);
if (m!=255)
break;
} while(1);
if (m==JPEG_MARKER_SOS)
break;
}
} while(1);
sp->plane_sample_offset++;
if (OJPEGReadHeaderInfoSecStreamSos(tif)==0)
return(0);
sp->sos_end[sp->plane_sample_offset].log=1;
sp->sos_end[sp->plane_sample_offset].in_buffer_source=sp->in_buffer_source;
sp->sos_end[sp->plane_sample_offset].in_buffer_next_strile=sp->in_buffer_next_strile;
sp->sos_end[sp->plane_sample_offset].in_buffer_file_pos=sp->in_buffer_file_pos-sp->in_buffer_togo;
sp->sos_end[sp->plane_sample_offset].in_buffer_file_togo=sp->in_buffer_file_togo+sp->in_buffer_togo;
}
return(1);
}
static int
OJPEGWriteHeaderInfo(TIFF* tif)
{
static const char module[]="OJPEGWriteHeaderInfo";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint8** m;
uint32 n;
/* if a previous attempt failed, don't try again */
if (sp->libjpeg_session_active != 0)
return 0;
sp->out_state=ososSoi;
sp->restart_index=0;
jpeg_std_error(&(sp->libjpeg_jpeg_error_mgr));
sp->libjpeg_jpeg_error_mgr.output_message=OJPEGLibjpegJpegErrorMgrOutputMessage;
sp->libjpeg_jpeg_error_mgr.error_exit=OJPEGLibjpegJpegErrorMgrErrorExit;
sp->libjpeg_jpeg_decompress_struct.err=&(sp->libjpeg_jpeg_error_mgr);
sp->libjpeg_jpeg_decompress_struct.client_data=(void*)tif;
if (jpeg_create_decompress_encap(sp,&(sp->libjpeg_jpeg_decompress_struct))==0)
return(0);
sp->libjpeg_session_active=1;
sp->libjpeg_jpeg_source_mgr.bytes_in_buffer=0;
sp->libjpeg_jpeg_source_mgr.init_source=OJPEGLibjpegJpegSourceMgrInitSource;
sp->libjpeg_jpeg_source_mgr.fill_input_buffer=OJPEGLibjpegJpegSourceMgrFillInputBuffer;
sp->libjpeg_jpeg_source_mgr.skip_input_data=OJPEGLibjpegJpegSourceMgrSkipInputData;
sp->libjpeg_jpeg_source_mgr.resync_to_restart=OJPEGLibjpegJpegSourceMgrResyncToRestart;
sp->libjpeg_jpeg_source_mgr.term_source=OJPEGLibjpegJpegSourceMgrTermSource;
sp->libjpeg_jpeg_decompress_struct.src=&(sp->libjpeg_jpeg_source_mgr);
if (jpeg_read_header_encap(sp,&(sp->libjpeg_jpeg_decompress_struct),1)==0)
return(0);
if ((sp->subsampling_force_desubsampling_inside_decompression==0) && (sp->samples_per_pixel_per_plane>1))
{
sp->libjpeg_jpeg_decompress_struct.raw_data_out=1;
#if JPEG_LIB_VERSION >= 70
sp->libjpeg_jpeg_decompress_struct.do_fancy_upsampling=FALSE;
#endif
sp->libjpeg_jpeg_query_style=0;
if (sp->subsampling_convert_log==0)
{
assert(sp->subsampling_convert_ycbcrbuf==0);
assert(sp->subsampling_convert_ycbcrimage==0);
sp->subsampling_convert_ylinelen=((sp->strile_width+sp->subsampling_hor*8-1)/(sp->subsampling_hor*8)*sp->subsampling_hor*8);
sp->subsampling_convert_ylines=sp->subsampling_ver*8;
sp->subsampling_convert_clinelen=sp->subsampling_convert_ylinelen/sp->subsampling_hor;
sp->subsampling_convert_clines=8;
sp->subsampling_convert_ybuflen=sp->subsampling_convert_ylinelen*sp->subsampling_convert_ylines;
sp->subsampling_convert_cbuflen=sp->subsampling_convert_clinelen*sp->subsampling_convert_clines;
sp->subsampling_convert_ycbcrbuflen=sp->subsampling_convert_ybuflen+2*sp->subsampling_convert_cbuflen;
sp->subsampling_convert_ycbcrbuf=_TIFFmalloc(sp->subsampling_convert_ycbcrbuflen);
if (sp->subsampling_convert_ycbcrbuf==0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
return(0);
}
sp->subsampling_convert_ybuf=sp->subsampling_convert_ycbcrbuf;
sp->subsampling_convert_cbbuf=sp->subsampling_convert_ybuf+sp->subsampling_convert_ybuflen;
sp->subsampling_convert_crbuf=sp->subsampling_convert_cbbuf+sp->subsampling_convert_cbuflen;
sp->subsampling_convert_ycbcrimagelen=3+sp->subsampling_convert_ylines+2*sp->subsampling_convert_clines;
sp->subsampling_convert_ycbcrimage=_TIFFmalloc(sp->subsampling_convert_ycbcrimagelen*sizeof(uint8*));
if (sp->subsampling_convert_ycbcrimage==0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
return(0);
}
m=sp->subsampling_convert_ycbcrimage;
*m++=(uint8*)(sp->subsampling_convert_ycbcrimage+3);
*m++=(uint8*)(sp->subsampling_convert_ycbcrimage+3+sp->subsampling_convert_ylines);
*m++=(uint8*)(sp->subsampling_convert_ycbcrimage+3+sp->subsampling_convert_ylines+sp->subsampling_convert_clines);
for (n=0; n<sp->subsampling_convert_ylines; n++)
*m++=sp->subsampling_convert_ybuf+n*sp->subsampling_convert_ylinelen;
for (n=0; n<sp->subsampling_convert_clines; n++)
*m++=sp->subsampling_convert_cbbuf+n*sp->subsampling_convert_clinelen;
for (n=0; n<sp->subsampling_convert_clines; n++)
*m++=sp->subsampling_convert_crbuf+n*sp->subsampling_convert_clinelen;
sp->subsampling_convert_clinelenout=((sp->strile_width+sp->subsampling_hor-1)/sp->subsampling_hor);
sp->subsampling_convert_state=0;
sp->bytes_per_line=sp->subsampling_convert_clinelenout*(sp->subsampling_ver*sp->subsampling_hor+2);
sp->lines_per_strile=((sp->strile_length+sp->subsampling_ver-1)/sp->subsampling_ver);
sp->subsampling_convert_log=1;
}
}
else
{
sp->libjpeg_jpeg_decompress_struct.jpeg_color_space=JCS_UNKNOWN;
sp->libjpeg_jpeg_decompress_struct.out_color_space=JCS_UNKNOWN;
sp->libjpeg_jpeg_query_style=1;
sp->bytes_per_line=sp->samples_per_pixel_per_plane*sp->strile_width;
sp->lines_per_strile=sp->strile_length;
}
if (jpeg_start_decompress_encap(sp,&(sp->libjpeg_jpeg_decompress_struct))==0)
return(0);
sp->writeheader_done=1;
return(1);
}
static void
OJPEGLibjpegSessionAbort(TIFF* tif)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
assert(sp->libjpeg_session_active!=0);
jpeg_destroy((jpeg_common_struct*)(&(sp->libjpeg_jpeg_decompress_struct)));
sp->libjpeg_session_active=0;
}
static int
OJPEGReadHeaderInfoSec(TIFF* tif)
{
static const char module[]="OJPEGReadHeaderInfoSec";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint8 m;
uint16 n;
uint8 o;
if (sp->file_size==0)
sp->file_size=TIFFGetFileSize(tif);
if (sp->jpeg_interchange_format!=0)
{
if (sp->jpeg_interchange_format>=sp->file_size)
{
sp->jpeg_interchange_format=0;
sp->jpeg_interchange_format_length=0;
}
else
{
if ((sp->jpeg_interchange_format_length==0) || (sp->jpeg_interchange_format+sp->jpeg_interchange_format_length>sp->file_size))
sp->jpeg_interchange_format_length=sp->file_size-sp->jpeg_interchange_format;
}
}
sp->in_buffer_source=osibsNotSetYet;
sp->in_buffer_next_strile=0;
sp->in_buffer_strile_count=tif->tif_dir.td_nstrips;
sp->in_buffer_file_togo=0;
sp->in_buffer_togo=0;
do
{
if (OJPEGReadBytePeek(sp,&m)==0)
return(0);
if (m!=255)
break;
OJPEGReadByteAdvance(sp);
do
{
if (OJPEGReadByte(sp,&m)==0)
return(0);
} while(m==255);
switch(m)
{
case JPEG_MARKER_SOI:
/* this type of marker has no data, and should be skipped */
break;
case JPEG_MARKER_COM:
case JPEG_MARKER_APP0:
case JPEG_MARKER_APP0+1:
case JPEG_MARKER_APP0+2:
case JPEG_MARKER_APP0+3:
case JPEG_MARKER_APP0+4:
case JPEG_MARKER_APP0+5:
case JPEG_MARKER_APP0+6:
case JPEG_MARKER_APP0+7:
case JPEG_MARKER_APP0+8:
case JPEG_MARKER_APP0+9:
case JPEG_MARKER_APP0+10:
case JPEG_MARKER_APP0+11:
case JPEG_MARKER_APP0+12:
case JPEG_MARKER_APP0+13:
case JPEG_MARKER_APP0+14:
case JPEG_MARKER_APP0+15:
/* this type of marker has data, but it has no use to us (and no place here) and should be skipped */
if (OJPEGReadWord(sp,&n)==0)
return(0);
if (n<2)
{
if (sp->subsamplingcorrect==0)
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JPEG data");
return(0);
}
if (n>2)
OJPEGReadSkip(sp,n-2);
break;
case JPEG_MARKER_DRI:
if (OJPEGReadHeaderInfoSecStreamDri(tif)==0)
return(0);
break;
case JPEG_MARKER_DQT:
if (OJPEGReadHeaderInfoSecStreamDqt(tif)==0)
return(0);
break;
case JPEG_MARKER_DHT:
if (OJPEGReadHeaderInfoSecStreamDht(tif)==0)
return(0);
break;
case JPEG_MARKER_SOF0:
case JPEG_MARKER_SOF1:
case JPEG_MARKER_SOF3:
if (OJPEGReadHeaderInfoSecStreamSof(tif,m)==0)
return(0);
if (sp->subsamplingcorrect!=0)
return(1);
break;
case JPEG_MARKER_SOS:
if (sp->subsamplingcorrect!=0)
return(1);
assert(sp->plane_sample_offset==0);
if (OJPEGReadHeaderInfoSecStreamSos(tif)==0)
return(0);
break;
default:
TIFFErrorExt(tif->tif_clientdata,module,"Unknown marker type %d in JPEG data",m);
return(0);
}
} while(m!=JPEG_MARKER_SOS);
if (sp->subsamplingcorrect)
return(1);
if (sp->sof_log==0)
{
if (OJPEGReadHeaderInfoSecTablesQTable(tif)==0)
return(0);
sp->sof_marker_id=JPEG_MARKER_SOF0;
for (o=0; o<sp->samples_per_pixel; o++)
sp->sof_c[o]=o;
sp->sof_hv[0]=((sp->subsampling_hor<<4)|sp->subsampling_ver);
for (o=1; o<sp->samples_per_pixel; o++)
sp->sof_hv[o]=17;
sp->sof_x=sp->strile_width;
sp->sof_y=sp->strile_length_total;
sp->sof_log=1;
if (OJPEGReadHeaderInfoSecTablesDcTable(tif)==0)
return(0);
if (OJPEGReadHeaderInfoSecTablesAcTable(tif)==0)
return(0);
for (o=1; o<sp->samples_per_pixel; o++)
sp->sos_cs[o]=o;
}
return(1);
}
static int
OJPEGReadHeaderInfoSecStreamDri(TIFF* tif)
{
/* This could easily cause trouble in some cases... but no such cases have
occurred so far */
static const char module[]="OJPEGReadHeaderInfoSecStreamDri";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint16 m;
if (OJPEGReadWord(sp,&m)==0)
return(0);
if (m!=4)
{
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DRI marker in JPEG data");
return(0);
}
if (OJPEGReadWord(sp,&m)==0)
return(0);
sp->restart_interval=m;
return(1);
}
static int
OJPEGReadHeaderInfoSecStreamDqt(TIFF* tif)
{
/* this is a table marker, and it is to be saved as a whole for exact pushing on the jpeg stream later on */
static const char module[]="OJPEGReadHeaderInfoSecStreamDqt";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint16 m;
uint32 na;
uint8* nb;
uint8 o;
if (OJPEGReadWord(sp,&m)==0)
return(0);
if (m<=2)
{
if (sp->subsamplingcorrect==0)
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DQT marker in JPEG data");
return(0);
}
if (sp->subsamplingcorrect!=0)
OJPEGReadSkip(sp,m-2);
else
{
m-=2;
do
{
if (m<65)
{
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DQT marker in JPEG data");
return(0);
}
na=sizeof(uint32)+69;
nb=_TIFFmalloc(na);
if (nb==0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
return(0);
}
*(uint32*)nb=na;
nb[sizeof(uint32)]=255;
nb[sizeof(uint32)+1]=JPEG_MARKER_DQT;
nb[sizeof(uint32)+2]=0;
nb[sizeof(uint32)+3]=67;
if (OJPEGReadBlock(sp,65,&nb[sizeof(uint32)+4])==0) {
_TIFFfree(nb);
return(0);
}
o=nb[sizeof(uint32)+4]&15;
if (3<o)
{
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DQT marker in JPEG data");
_TIFFfree(nb);
return(0);
}
if (sp->qtable[o]!=0)
_TIFFfree(sp->qtable[o]);
sp->qtable[o]=nb;
m-=65;
} while(m>0);
}
return(1);
}
static int
OJPEGReadHeaderInfoSecStreamDht(TIFF* tif)
{
/* this is a table marker, and it is to be saved as a whole for exact pushing on the jpeg stream later on */
/* TODO: the following assumes there is only one table in this marker... but i'm not quite sure that assumption is guaranteed correct */
static const char module[]="OJPEGReadHeaderInfoSecStreamDht";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint16 m;
uint32 na;
uint8* nb;
uint8 o;
if (OJPEGReadWord(sp,&m)==0)
return(0);
if (m<=2)
{
if (sp->subsamplingcorrect==0)
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
return(0);
}
if (sp->subsamplingcorrect!=0)
{
OJPEGReadSkip(sp,m-2);
}
else
{
na=sizeof(uint32)+2+m;
nb=_TIFFmalloc(na);
if (nb==0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
return(0);
}
*(uint32*)nb=na;
nb[sizeof(uint32)]=255;
nb[sizeof(uint32)+1]=JPEG_MARKER_DHT;
nb[sizeof(uint32)+2]=(m>>8);
nb[sizeof(uint32)+3]=(m&255);
if (OJPEGReadBlock(sp,m-2,&nb[sizeof(uint32)+4])==0) {
_TIFFfree(nb);
return(0);
}
o=nb[sizeof(uint32)+4];
if ((o&240)==0)
{
if (3<o)
{
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
_TIFFfree(nb);
return(0);
}
if (sp->dctable[o]!=0)
_TIFFfree(sp->dctable[o]);
sp->dctable[o]=nb;
}
else
{
if ((o&240)!=16)
{
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
_TIFFfree(nb);
return(0);
}
o&=15;
if (3<o)
{
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
_TIFFfree(nb);
return(0);
}
if (sp->actable[o]!=0)
_TIFFfree(sp->actable[o]);
sp->actable[o]=nb;
}
}
return(1);
}
static int
OJPEGReadHeaderInfoSecStreamSof(TIFF* tif, uint8 marker_id)
{
/* this marker needs to be checked, and part of its data needs to be saved for regeneration later on */
static const char module[]="OJPEGReadHeaderInfoSecStreamSof";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint16 m;
uint16 n;
uint8 o;
uint16 p;
uint16 q;
if (sp->sof_log!=0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JPEG data");
return(0);
}
if (sp->subsamplingcorrect==0)
sp->sof_marker_id=marker_id;
/* Lf: data length */
if (OJPEGReadWord(sp,&m)==0)
return(0);
if (m<11)
{
if (sp->subsamplingcorrect==0)
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOF marker in JPEG data");
return(0);
}
m-=8;
if (m%3!=0)
{
if (sp->subsamplingcorrect==0)
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOF marker in JPEG data");
return(0);
}
n=m/3;
if (sp->subsamplingcorrect==0)
{
if (n!=sp->samples_per_pixel)
{
TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected number of samples");
return(0);
}
}
/* P: Sample precision */
if (OJPEGReadByte(sp,&o)==0)
return(0);
if (o!=8)
{
if (sp->subsamplingcorrect==0)
TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected number of bits per sample");
return(0);
}
/* Y: Number of lines, X: Number of samples per line */
if (sp->subsamplingcorrect)
OJPEGReadSkip(sp,4);
else
{
/* Y: Number of lines */
if (OJPEGReadWord(sp,&p)==0)
return(0);
if (((uint32)p<sp->image_length) && ((uint32)p<sp->strile_length_total))
{
TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected height");
return(0);
}
sp->sof_y=p;
/* X: Number of samples per line */
if (OJPEGReadWord(sp,&p)==0)
return(0);
if (((uint32)p<sp->image_width) && ((uint32)p<sp->strile_width))
{
TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected width");
return(0);
}
if ((uint32)p>sp->strile_width)
{
TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data image width exceeds expected image width");
return(0);
}
sp->sof_x=p;
}
/* Nf: Number of image components in frame */
if (OJPEGReadByte(sp,&o)==0)
return(0);
if (o!=n)
{
if (sp->subsamplingcorrect==0)
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOF marker in JPEG data");
return(0);
}
/* per component stuff */
/* TODO: double-check that flow implies that n cannot be as big as to make us overflow sof_c, sof_hv and sof_tq arrays */
for (q=0; q<n; q++)
{
/* C: Component identifier */
if (OJPEGReadByte(sp,&o)==0)
return(0);
if (sp->subsamplingcorrect==0)
sp->sof_c[q]=o;
/* H: Horizontal sampling factor, and V: Vertical sampling factor */
if (OJPEGReadByte(sp,&o)==0)
return(0);
if (sp->subsamplingcorrect!=0)
{
if (q==0)
{
sp->subsampling_hor=(o>>4);
sp->subsampling_ver=(o&15);
if (((sp->subsampling_hor!=1) && (sp->subsampling_hor!=2) && (sp->subsampling_hor!=4)) ||
((sp->subsampling_ver!=1) && (sp->subsampling_ver!=2) && (sp->subsampling_ver!=4)))
sp->subsampling_force_desubsampling_inside_decompression=1;
}
else
{
if (o!=17)
sp->subsampling_force_desubsampling_inside_decompression=1;
}
}
else
{
sp->sof_hv[q]=o;
if (sp->subsampling_force_desubsampling_inside_decompression==0)
{
if (q==0)
{
if (o!=((sp->subsampling_hor<<4)|sp->subsampling_ver))
{
TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected subsampling values");
return(0);
}
}
else
{
if (o!=17)
{
TIFFErrorExt(tif->tif_clientdata,module,"JPEG compressed data indicates unexpected subsampling values");
return(0);
}
}
}
}
/* Tq: Quantization table destination selector */
if (OJPEGReadByte(sp,&o)==0)
return(0);
if (sp->subsamplingcorrect==0)
sp->sof_tq[q]=o;
}
if (sp->subsamplingcorrect==0)
sp->sof_log=1;
return(1);
}
static int
OJPEGReadHeaderInfoSecStreamSos(TIFF* tif)
{
/* this marker needs to be checked, and part of its data needs to be saved for regeneration later on */
static const char module[]="OJPEGReadHeaderInfoSecStreamSos";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint16 m;
uint8 n;
uint8 o;
assert(sp->subsamplingcorrect==0);
if (sp->sof_log==0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOS marker in JPEG data");
return(0);
}
/* Ls */
if (OJPEGReadWord(sp,&m)==0)
return(0);
if (m!=6+sp->samples_per_pixel_per_plane*2)
{
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOS marker in JPEG data");
return(0);
}
/* Ns */
if (OJPEGReadByte(sp,&n)==0)
return(0);
if (n!=sp->samples_per_pixel_per_plane)
{
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt SOS marker in JPEG data");
return(0);
}
/* Cs, Td, and Ta */
for (o=0; o<sp->samples_per_pixel_per_plane; o++)
{
/* Cs */
if (OJPEGReadByte(sp,&n)==0)
return(0);
sp->sos_cs[sp->plane_sample_offset+o]=n;
/* Td and Ta */
if (OJPEGReadByte(sp,&n)==0)
return(0);
sp->sos_tda[sp->plane_sample_offset+o]=n;
}
/* skip Ss, Se, Ah, en Al -> no check, as per Tom Lane recommendation, as per LibJpeg source */
OJPEGReadSkip(sp,3);
return(1);
}
static int
OJPEGReadHeaderInfoSecTablesQTable(TIFF* tif)
{
static const char module[]="OJPEGReadHeaderInfoSecTablesQTable";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint8 m;
uint8 n;
uint32 oa;
uint8* ob;
uint32 p;
if (sp->qtable_offset[0]==0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Missing JPEG tables");
return(0);
}
sp->in_buffer_file_pos_log=0;
for (m=0; m<sp->samples_per_pixel; m++)
{
if ((sp->qtable_offset[m]!=0) && ((m==0) || (sp->qtable_offset[m]!=sp->qtable_offset[m-1])))
{
for (n=0; n<m-1; n++)
{
if (sp->qtable_offset[m]==sp->qtable_offset[n])
{
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JpegQTables tag value");
return(0);
}
}
oa=sizeof(uint32)+69;
ob=_TIFFmalloc(oa);
if (ob==0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
return(0);
}
*(uint32*)ob=oa;
ob[sizeof(uint32)]=255;
ob[sizeof(uint32)+1]=JPEG_MARKER_DQT;
ob[sizeof(uint32)+2]=0;
ob[sizeof(uint32)+3]=67;
ob[sizeof(uint32)+4]=m;
TIFFSeekFile(tif,sp->qtable_offset[m],SEEK_SET);
p=(uint32)TIFFReadFile(tif,&ob[sizeof(uint32)+5],64);
if (p!=64)
return(0);
sp->qtable[m]=ob;
sp->sof_tq[m]=m;
}
else
sp->sof_tq[m]=sp->sof_tq[m-1];
}
return(1);
}
static int
OJPEGReadHeaderInfoSecTablesDcTable(TIFF* tif)
{
static const char module[]="OJPEGReadHeaderInfoSecTablesDcTable";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint8 m;
uint8 n;
uint8 o[16];
uint32 p;
uint32 q;
uint32 ra;
uint8* rb;
if (sp->dctable_offset[0]==0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Missing JPEG tables");
return(0);
}
sp->in_buffer_file_pos_log=0;
for (m=0; m<sp->samples_per_pixel; m++)
{
if ((sp->dctable_offset[m]!=0) && ((m==0) || (sp->dctable_offset[m]!=sp->dctable_offset[m-1])))
{
for (n=0; n<m-1; n++)
{
if (sp->dctable_offset[m]==sp->dctable_offset[n])
{
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JpegDcTables tag value");
return(0);
}
}
TIFFSeekFile(tif,sp->dctable_offset[m],SEEK_SET);
p=(uint32)TIFFReadFile(tif,o,16);
if (p!=16)
return(0);
q=0;
for (n=0; n<16; n++)
q+=o[n];
ra=sizeof(uint32)+21+q;
rb=_TIFFmalloc(ra);
if (rb==0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
return(0);
}
*(uint32*)rb=ra;
rb[sizeof(uint32)]=255;
rb[sizeof(uint32)+1]=JPEG_MARKER_DHT;
rb[sizeof(uint32)+2]=(uint8)((19+q)>>8);
rb[sizeof(uint32)+3]=((19+q)&255);
rb[sizeof(uint32)+4]=m;
for (n=0; n<16; n++)
rb[sizeof(uint32)+5+n]=o[n];
p=(uint32)TIFFReadFile(tif,&(rb[sizeof(uint32)+21]),q);
if (p!=q)
return(0);
sp->dctable[m]=rb;
sp->sos_tda[m]=(m<<4);
}
else
sp->sos_tda[m]=sp->sos_tda[m-1];
}
return(1);
}
static int
OJPEGReadHeaderInfoSecTablesAcTable(TIFF* tif)
{
static const char module[]="OJPEGReadHeaderInfoSecTablesAcTable";
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint8 m;
uint8 n;
uint8 o[16];
uint32 p;
uint32 q;
uint32 ra;
uint8* rb;
if (sp->actable_offset[0]==0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Missing JPEG tables");
return(0);
}
sp->in_buffer_file_pos_log=0;
for (m=0; m<sp->samples_per_pixel; m++)
{
if ((sp->actable_offset[m]!=0) && ((m==0) || (sp->actable_offset[m]!=sp->actable_offset[m-1])))
{
for (n=0; n<m-1; n++)
{
if (sp->actable_offset[m]==sp->actable_offset[n])
{
TIFFErrorExt(tif->tif_clientdata,module,"Corrupt JpegAcTables tag value");
return(0);
}
}
TIFFSeekFile(tif,sp->actable_offset[m],SEEK_SET);
p=(uint32)TIFFReadFile(tif,o,16);
if (p!=16)
return(0);
q=0;
for (n=0; n<16; n++)
q+=o[n];
ra=sizeof(uint32)+21+q;
rb=_TIFFmalloc(ra);
if (rb==0)
{
TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
return(0);
}
*(uint32*)rb=ra;
rb[sizeof(uint32)]=255;
rb[sizeof(uint32)+1]=JPEG_MARKER_DHT;
rb[sizeof(uint32)+2]=(uint8)((19+q)>>8);
rb[sizeof(uint32)+3]=((19+q)&255);
rb[sizeof(uint32)+4]=(16|m);
for (n=0; n<16; n++)
rb[sizeof(uint32)+5+n]=o[n];
p=(uint32)TIFFReadFile(tif,&(rb[sizeof(uint32)+21]),q);
if (p!=q)
return(0);
sp->actable[m]=rb;
sp->sos_tda[m]=(sp->sos_tda[m]|m);
}
else
sp->sos_tda[m]=(sp->sos_tda[m]|(sp->sos_tda[m-1]&15));
}
return(1);
}
static int
OJPEGReadBufferFill(OJPEGState* sp)
{
uint16 m;
tmsize_t n;
/* TODO: double-check: when subsamplingcorrect is set, no call to TIFFErrorExt or TIFFWarningExt should be made
* in any other case, seek or read errors should be passed through */
do
{
if (sp->in_buffer_file_togo!=0)
{
if (sp->in_buffer_file_pos_log==0)
{
TIFFSeekFile(sp->tif,sp->in_buffer_file_pos,SEEK_SET);
sp->in_buffer_file_pos_log=1;
}
m=OJPEG_BUFFER;
if ((uint64)m>sp->in_buffer_file_togo)
m=(uint16)sp->in_buffer_file_togo;
n=TIFFReadFile(sp->tif,sp->in_buffer,(tmsize_t)m);
if (n==0)
return(0);
assert(n>0);
assert(n<=OJPEG_BUFFER);
assert(n<65536);
assert((uint64)n<=sp->in_buffer_file_togo);
m=(uint16)n;
sp->in_buffer_togo=m;
sp->in_buffer_cur=sp->in_buffer;
sp->in_buffer_file_togo-=m;
sp->in_buffer_file_pos+=m;
break;
}
sp->in_buffer_file_pos_log=0;
switch(sp->in_buffer_source)
{
case osibsNotSetYet:
if (sp->jpeg_interchange_format!=0)
{
sp->in_buffer_file_pos=sp->jpeg_interchange_format;
sp->in_buffer_file_togo=sp->jpeg_interchange_format_length;
}
sp->in_buffer_source=osibsJpegInterchangeFormat;
break;
case osibsJpegInterchangeFormat:
sp->in_buffer_source=osibsStrile;
break;
case osibsStrile:
if (!_TIFFFillStriles( sp->tif )
|| sp->tif->tif_dir.td_stripoffset == NULL
|| sp->tif->tif_dir.td_stripbytecount == NULL)
return 0;
if (sp->in_buffer_next_strile==sp->in_buffer_strile_count)
sp->in_buffer_source=osibsEof;
else
{
sp->in_buffer_file_pos=sp->tif->tif_dir.td_stripoffset[sp->in_buffer_next_strile];
if (sp->in_buffer_file_pos!=0)
{
if (sp->in_buffer_file_pos>=sp->file_size)
sp->in_buffer_file_pos=0;
else if (sp->tif->tif_dir.td_stripbytecount==NULL)
sp->in_buffer_file_togo=sp->file_size-sp->in_buffer_file_pos;
else
{
if (sp->tif->tif_dir.td_stripbytecount == 0) {
TIFFErrorExt(sp->tif->tif_clientdata,sp->tif->tif_name,"Strip byte counts are missing");
return(0);
}
sp->in_buffer_file_togo=sp->tif->tif_dir.td_stripbytecount[sp->in_buffer_next_strile];
if (sp->in_buffer_file_togo==0)
sp->in_buffer_file_pos=0;
else if (sp->in_buffer_file_pos+sp->in_buffer_file_togo>sp->file_size)
sp->in_buffer_file_togo=sp->file_size-sp->in_buffer_file_pos;
}
}
sp->in_buffer_next_strile++;
}
break;
default:
return(0);
}
} while (1);
return(1);
}
static int
OJPEGReadByte(OJPEGState* sp, uint8* byte)
{
if (sp->in_buffer_togo==0)
{
if (OJPEGReadBufferFill(sp)==0)
return(0);
assert(sp->in_buffer_togo>0);
}
*byte=*(sp->in_buffer_cur);
sp->in_buffer_cur++;
sp->in_buffer_togo--;
return(1);
}
static int
OJPEGReadBytePeek(OJPEGState* sp, uint8* byte)
{
if (sp->in_buffer_togo==0)
{
if (OJPEGReadBufferFill(sp)==0)
return(0);
assert(sp->in_buffer_togo>0);
}
*byte=*(sp->in_buffer_cur);
return(1);
}
static void
OJPEGReadByteAdvance(OJPEGState* sp)
{
assert(sp->in_buffer_togo>0);
sp->in_buffer_cur++;
sp->in_buffer_togo--;
}
static int
OJPEGReadWord(OJPEGState* sp, uint16* word)
{
uint8 m;
if (OJPEGReadByte(sp,&m)==0)
return(0);
*word=(m<<8);
if (OJPEGReadByte(sp,&m)==0)
return(0);
*word|=m;
return(1);
}
static int
OJPEGReadBlock(OJPEGState* sp, uint16 len, void* mem)
{
uint16 mlen;
uint8* mmem;
uint16 n;
assert(len>0);
mlen=len;
mmem=mem;
do
{
if (sp->in_buffer_togo==0)
{
if (OJPEGReadBufferFill(sp)==0)
return(0);
assert(sp->in_buffer_togo>0);
}
n=mlen;
if (n>sp->in_buffer_togo)
n=sp->in_buffer_togo;
_TIFFmemcpy(mmem,sp->in_buffer_cur,n);
sp->in_buffer_cur+=n;
sp->in_buffer_togo-=n;
mlen-=n;
mmem+=n;
} while(mlen>0);
return(1);
}
static void
OJPEGReadSkip(OJPEGState* sp, uint16 len)
{
uint16 m;
uint16 n;
m=len;
n=m;
if (n>sp->in_buffer_togo)
n=sp->in_buffer_togo;
sp->in_buffer_cur+=n;
sp->in_buffer_togo-=n;
m-=n;
if (m>0)
{
assert(sp->in_buffer_togo==0);
n=m;
if ((uint64)n>sp->in_buffer_file_togo)
n=(uint16)sp->in_buffer_file_togo;
sp->in_buffer_file_pos+=n;
sp->in_buffer_file_togo-=n;
sp->in_buffer_file_pos_log=0;
/* we don't skip past jpeginterchangeformat/strile block...
* if that is asked from us, we're dealing with totally bazurk
* data anyway, and we've not seen this happening on any
* testfile, so we might as well likely cause some other
* meaningless error to be passed at some later time
*/
}
}
static int
OJPEGWriteStream(TIFF* tif, void** mem, uint32* len)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
*len=0;
do
{
assert(sp->out_state<=ososEoi);
switch(sp->out_state)
{
case ososSoi:
OJPEGWriteStreamSoi(tif,mem,len);
break;
case ososQTable0:
OJPEGWriteStreamQTable(tif,0,mem,len);
break;
case ososQTable1:
OJPEGWriteStreamQTable(tif,1,mem,len);
break;
case ososQTable2:
OJPEGWriteStreamQTable(tif,2,mem,len);
break;
case ososQTable3:
OJPEGWriteStreamQTable(tif,3,mem,len);
break;
case ososDcTable0:
OJPEGWriteStreamDcTable(tif,0,mem,len);
break;
case ososDcTable1:
OJPEGWriteStreamDcTable(tif,1,mem,len);
break;
case ososDcTable2:
OJPEGWriteStreamDcTable(tif,2,mem,len);
break;
case ososDcTable3:
OJPEGWriteStreamDcTable(tif,3,mem,len);
break;
case ososAcTable0:
OJPEGWriteStreamAcTable(tif,0,mem,len);
break;
case ososAcTable1:
OJPEGWriteStreamAcTable(tif,1,mem,len);
break;
case ososAcTable2:
OJPEGWriteStreamAcTable(tif,2,mem,len);
break;
case ososAcTable3:
OJPEGWriteStreamAcTable(tif,3,mem,len);
break;
case ososDri:
OJPEGWriteStreamDri(tif,mem,len);
break;
case ososSof:
OJPEGWriteStreamSof(tif,mem,len);
break;
case ososSos:
OJPEGWriteStreamSos(tif,mem,len);
break;
case ososCompressed:
if (OJPEGWriteStreamCompressed(tif,mem,len)==0)
return(0);
break;
case ososRst:
OJPEGWriteStreamRst(tif,mem,len);
break;
case ososEoi:
OJPEGWriteStreamEoi(tif,mem,len);
break;
}
} while (*len==0);
return(1);
}
static void
OJPEGWriteStreamSoi(TIFF* tif, void** mem, uint32* len)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
assert(OJPEG_BUFFER>=2);
sp->out_buffer[0]=255;
sp->out_buffer[1]=JPEG_MARKER_SOI;
*len=2;
*mem=(void*)sp->out_buffer;
sp->out_state++;
}
static void
OJPEGWriteStreamQTable(TIFF* tif, uint8 table_index, void** mem, uint32* len)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
if (sp->qtable[table_index]!=0)
{
*mem=(void*)(sp->qtable[table_index]+sizeof(uint32));
*len=*((uint32*)sp->qtable[table_index])-sizeof(uint32);
}
sp->out_state++;
}
static void
OJPEGWriteStreamDcTable(TIFF* tif, uint8 table_index, void** mem, uint32* len)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
if (sp->dctable[table_index]!=0)
{
*mem=(void*)(sp->dctable[table_index]+sizeof(uint32));
*len=*((uint32*)sp->dctable[table_index])-sizeof(uint32);
}
sp->out_state++;
}
static void
OJPEGWriteStreamAcTable(TIFF* tif, uint8 table_index, void** mem, uint32* len)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
if (sp->actable[table_index]!=0)
{
*mem=(void*)(sp->actable[table_index]+sizeof(uint32));
*len=*((uint32*)sp->actable[table_index])-sizeof(uint32);
}
sp->out_state++;
}
static void
OJPEGWriteStreamDri(TIFF* tif, void** mem, uint32* len)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
assert(OJPEG_BUFFER>=6);
if (sp->restart_interval!=0)
{
sp->out_buffer[0]=255;
sp->out_buffer[1]=JPEG_MARKER_DRI;
sp->out_buffer[2]=0;
sp->out_buffer[3]=4;
sp->out_buffer[4]=(sp->restart_interval>>8);
sp->out_buffer[5]=(sp->restart_interval&255);
*len=6;
*mem=(void*)sp->out_buffer;
}
sp->out_state++;
}
static void
OJPEGWriteStreamSof(TIFF* tif, void** mem, uint32* len)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint8 m;
assert(OJPEG_BUFFER>=2+8+sp->samples_per_pixel_per_plane*3);
assert(255>=8+sp->samples_per_pixel_per_plane*3);
sp->out_buffer[0]=255;
sp->out_buffer[1]=sp->sof_marker_id;
/* Lf */
sp->out_buffer[2]=0;
sp->out_buffer[3]=8+sp->samples_per_pixel_per_plane*3;
/* P */
sp->out_buffer[4]=8;
/* Y */
sp->out_buffer[5]=(uint8)(sp->sof_y>>8);
sp->out_buffer[6]=(sp->sof_y&255);
/* X */
sp->out_buffer[7]=(uint8)(sp->sof_x>>8);
sp->out_buffer[8]=(sp->sof_x&255);
/* Nf */
sp->out_buffer[9]=sp->samples_per_pixel_per_plane;
for (m=0; m<sp->samples_per_pixel_per_plane; m++)
{
/* C */
sp->out_buffer[10+m*3]=sp->sof_c[sp->plane_sample_offset+m];
/* H and V */
sp->out_buffer[10+m*3+1]=sp->sof_hv[sp->plane_sample_offset+m];
/* Tq */
sp->out_buffer[10+m*3+2]=sp->sof_tq[sp->plane_sample_offset+m];
}
*len=10+sp->samples_per_pixel_per_plane*3;
*mem=(void*)sp->out_buffer;
sp->out_state++;
}
static void
OJPEGWriteStreamSos(TIFF* tif, void** mem, uint32* len)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
uint8 m;
assert(OJPEG_BUFFER>=2+6+sp->samples_per_pixel_per_plane*2);
assert(255>=6+sp->samples_per_pixel_per_plane*2);
sp->out_buffer[0]=255;
sp->out_buffer[1]=JPEG_MARKER_SOS;
/* Ls */
sp->out_buffer[2]=0;
sp->out_buffer[3]=6+sp->samples_per_pixel_per_plane*2;
/* Ns */
sp->out_buffer[4]=sp->samples_per_pixel_per_plane;
for (m=0; m<sp->samples_per_pixel_per_plane; m++)
{
/* Cs */
sp->out_buffer[5+m*2]=sp->sos_cs[sp->plane_sample_offset+m];
/* Td and Ta */
sp->out_buffer[5+m*2+1]=sp->sos_tda[sp->plane_sample_offset+m];
}
/* Ss */
sp->out_buffer[5+sp->samples_per_pixel_per_plane*2]=0;
/* Se */
sp->out_buffer[5+sp->samples_per_pixel_per_plane*2+1]=63;
/* Ah and Al */
sp->out_buffer[5+sp->samples_per_pixel_per_plane*2+2]=0;
*len=8+sp->samples_per_pixel_per_plane*2;
*mem=(void*)sp->out_buffer;
sp->out_state++;
}
static int
OJPEGWriteStreamCompressed(TIFF* tif, void** mem, uint32* len)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
if (sp->in_buffer_togo==0)
{
if (OJPEGReadBufferFill(sp)==0)
return(0);
assert(sp->in_buffer_togo>0);
}
*len=sp->in_buffer_togo;
*mem=(void*)sp->in_buffer_cur;
sp->in_buffer_togo=0;
if (sp->in_buffer_file_togo==0)
{
switch(sp->in_buffer_source)
{
case osibsStrile:
if (sp->in_buffer_next_strile<sp->in_buffer_strile_count)
sp->out_state=ososRst;
else
sp->out_state=ososEoi;
break;
case osibsEof:
sp->out_state=ososEoi;
break;
default:
break;
}
}
return(1);
}
static void
OJPEGWriteStreamRst(TIFF* tif, void** mem, uint32* len)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
assert(OJPEG_BUFFER>=2);
sp->out_buffer[0]=255;
sp->out_buffer[1]=JPEG_MARKER_RST0+sp->restart_index;
sp->restart_index++;
if (sp->restart_index==8)
sp->restart_index=0;
*len=2;
*mem=(void*)sp->out_buffer;
sp->out_state=ososCompressed;
}
static void
OJPEGWriteStreamEoi(TIFF* tif, void** mem, uint32* len)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
assert(OJPEG_BUFFER>=2);
sp->out_buffer[0]=255;
sp->out_buffer[1]=JPEG_MARKER_EOI;
*len=2;
*mem=(void*)sp->out_buffer;
}
#ifndef LIBJPEG_ENCAP_EXTERNAL
static int
jpeg_create_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo)
{
if( SETJMP(sp->exit_jmpbuf) )
return 0;
else {
jpeg_create_decompress(cinfo);
return 1;
}
}
#endif
#ifndef LIBJPEG_ENCAP_EXTERNAL
static int
jpeg_read_header_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, uint8 require_image)
{
if( SETJMP(sp->exit_jmpbuf) )
return 0;
else {
jpeg_read_header(cinfo,require_image);
return 1;
}
}
#endif
#ifndef LIBJPEG_ENCAP_EXTERNAL
static int
jpeg_start_decompress_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo)
{
if( SETJMP(sp->exit_jmpbuf) )
return 0;
else {
jpeg_start_decompress(cinfo);
return 1;
}
}
#endif
#ifndef LIBJPEG_ENCAP_EXTERNAL
static int
jpeg_read_scanlines_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* scanlines, uint32 max_lines)
{
if( SETJMP(sp->exit_jmpbuf) )
return 0;
else {
jpeg_read_scanlines(cinfo,scanlines,max_lines);
return 1;
}
}
#endif
#ifndef LIBJPEG_ENCAP_EXTERNAL
static int
jpeg_read_raw_data_encap(OJPEGState* sp, jpeg_decompress_struct* cinfo, void* data, uint32 max_lines)
{
if( SETJMP(sp->exit_jmpbuf) )
return 0;
else {
jpeg_read_raw_data(cinfo,data,max_lines);
return 1;
}
}
#endif
#ifndef LIBJPEG_ENCAP_EXTERNAL
static void
jpeg_encap_unwind(TIFF* tif)
{
OJPEGState* sp=(OJPEGState*)tif->tif_data;
LONGJMP(sp->exit_jmpbuf,1);
}
#endif
static void
OJPEGLibjpegJpegErrorMgrOutputMessage(jpeg_common_struct* cinfo)
{
char buffer[JMSG_LENGTH_MAX];
(*cinfo->err->format_message)(cinfo,buffer);
TIFFWarningExt(((TIFF*)(cinfo->client_data))->tif_clientdata,"LibJpeg","%s",buffer);
}
static void
OJPEGLibjpegJpegErrorMgrErrorExit(jpeg_common_struct* cinfo)
{
char buffer[JMSG_LENGTH_MAX];
(*cinfo->err->format_message)(cinfo,buffer);
TIFFErrorExt(((TIFF*)(cinfo->client_data))->tif_clientdata,"LibJpeg","%s",buffer);
jpeg_encap_unwind((TIFF*)(cinfo->client_data));
}
static void
OJPEGLibjpegJpegSourceMgrInitSource(jpeg_decompress_struct* cinfo)
{
(void)cinfo;
}
static boolean
OJPEGLibjpegJpegSourceMgrFillInputBuffer(jpeg_decompress_struct* cinfo)
{
TIFF* tif=(TIFF*)cinfo->client_data;
OJPEGState* sp=(OJPEGState*)tif->tif_data;
void* mem=0;
uint32 len=0U;
if (OJPEGWriteStream(tif,&mem,&len)==0)
{
TIFFErrorExt(tif->tif_clientdata,"LibJpeg","Premature end of JPEG data");
jpeg_encap_unwind(tif);
}
sp->libjpeg_jpeg_source_mgr.bytes_in_buffer=len;
sp->libjpeg_jpeg_source_mgr.next_input_byte=mem;
return(1);
}
static void
OJPEGLibjpegJpegSourceMgrSkipInputData(jpeg_decompress_struct* cinfo, long num_bytes)
{
TIFF* tif=(TIFF*)cinfo->client_data;
(void)num_bytes;
TIFFErrorExt(tif->tif_clientdata,"LibJpeg","Unexpected error");
jpeg_encap_unwind(tif);
}
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 4702 ) /* unreachable code */
#endif
static boolean
OJPEGLibjpegJpegSourceMgrResyncToRestart(jpeg_decompress_struct* cinfo, int desired)
{
TIFF* tif=(TIFF*)cinfo->client_data;
(void)desired;
TIFFErrorExt(tif->tif_clientdata,"LibJpeg","Unexpected error");
jpeg_encap_unwind(tif);
return(0);
}
#ifdef _MSC_VER
#pragma warning( pop )
#endif
static void
OJPEGLibjpegJpegSourceMgrTermSource(jpeg_decompress_struct* cinfo)
{
(void)cinfo;
}
#endif
/*
* Local Variables:
* mode: c
* c-basic-offset: 8
* fill-column: 78
* End:
*/
| ./CrossVul/dataset_final_sorted/CWE-369/c/good_4854_1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.